@sma1lboy/rove 0.9.310-nightly.20261128 → 0.9.310

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 (250) hide show
  1. package/dist/cli/{chunk-rrtbrnsm.js → chunk-06cpc990.js} +1 -1
  2. package/dist/cli/chunk-0ccgkp9z.js +2 -0
  3. package/dist/cli/{chunk-qjq62kcb.js → chunk-0mdzphdz.js} +1 -1
  4. package/dist/cli/chunk-0rfd9c8r.js +9 -0
  5. package/dist/cli/{chunk-n7wa2g9g.js → chunk-0rfkgmns.js} +1 -1
  6. package/dist/cli/{chunk-0gdrrkeb.js → chunk-0x3vfkz9.js} +1 -1
  7. package/dist/cli/chunk-0xn13zhr.js +2 -0
  8. package/dist/cli/{chunk-aw9y2ecv.js → chunk-11vgtrm4.js} +1 -1
  9. package/dist/cli/{chunk-7akh6mpq.js → chunk-12qq8r81.js} +1 -1
  10. package/dist/cli/chunk-140pf8yx.js +77 -0
  11. package/dist/cli/chunk-152tg65q.js +2 -0
  12. package/dist/cli/chunk-17b3wpdk.js +2 -0
  13. package/dist/cli/chunk-1thazzyj.js +2 -0
  14. package/dist/cli/chunk-1wpwxcg9.js +3 -0
  15. package/dist/cli/chunk-22knrp3g.js +2 -0
  16. package/dist/cli/{chunk-xpf5znba.js → chunk-29ftjs96.js} +1 -1
  17. package/dist/cli/{chunk-v73jr6d3.js → chunk-2vk65d66.js} +1 -1
  18. package/dist/cli/{chunk-0pd79pqm.js → chunk-361acgxq.js} +1 -1
  19. package/dist/cli/{chunk-7qqg543d.js → chunk-36qsn2v8.js} +1 -1
  20. package/dist/cli/{chunk-8vhda57t.js → chunk-39txvrcs.js} +1 -1
  21. package/dist/cli/{chunk-ndjs6pfx.js → chunk-3d6caevx.js} +1 -1
  22. package/dist/cli/chunk-3fzrgjxr.js +13 -0
  23. package/dist/cli/{chunk-vr3hz387.js → chunk-3kraw5fh.js} +1 -1
  24. package/dist/cli/chunk-3vhhs2ye.js +2 -0
  25. package/dist/cli/chunk-3wkjeqt5.js +19 -0
  26. package/dist/cli/{chunk-th94kgx8.js → chunk-3yd8nyv6.js} +2 -2
  27. package/dist/cli/chunk-451z1265.js +19 -0
  28. package/dist/cli/chunk-4csg29es.js +3 -0
  29. package/dist/cli/chunk-4g1466qe.js +2 -0
  30. package/dist/cli/{chunk-d527kp0a.js → chunk-4y536nwm.js} +1 -1
  31. package/dist/cli/chunk-599msv9a.js +2 -0
  32. package/dist/cli/{chunk-94v7fkbx.js → chunk-5jevazzh.js} +2 -2
  33. package/dist/cli/chunk-5p2hhjje.js +3 -0
  34. package/dist/cli/{chunk-e5rhtk39.js → chunk-5sb5cgsx.js} +1 -1
  35. package/dist/cli/{chunk-7za2saew.js → chunk-65nm1v5h.js} +1 -1
  36. package/dist/cli/{chunk-bccq9wmd.js → chunk-69cqwz53.js} +1 -1
  37. package/dist/cli/{chunk-t0m58ycm.js → chunk-6f6b9zxx.js} +1 -1
  38. package/dist/cli/{chunk-f3bfy4jj.js → chunk-6qp32yje.js} +1 -1
  39. package/dist/cli/{chunk-zren8xsj.js → chunk-6t1yxx9x.js} +1 -1
  40. package/dist/cli/{chunk-nsscv6nb.js → chunk-76snhsy7.js} +1 -1
  41. package/dist/cli/{chunk-9avew3w0.js → chunk-7709m234.js} +1 -1
  42. package/dist/cli/{chunk-br2ehnve.js → chunk-7fw390kp.js} +1 -1
  43. package/dist/cli/{chunk-9h9kbx1m.js → chunk-7vassnhs.js} +3 -3
  44. package/dist/cli/chunk-887ysmy5.js +2 -0
  45. package/dist/cli/{chunk-bp4wst6z.js → chunk-89xz7kc8.js} +1 -1
  46. package/dist/cli/chunk-8akyzrjc.js +2 -0
  47. package/dist/cli/chunk-8byrmc70.js +3 -0
  48. package/dist/cli/{chunk-ys6md651.js → chunk-8ca4esh6.js} +1 -1
  49. package/dist/cli/{chunk-vf138rbf.js → chunk-8y9de8mg.js} +2 -2
  50. package/dist/cli/chunk-96wm6gt4.js +7 -0
  51. package/dist/cli/{chunk-2d0yz3mg.js → chunk-97fhq6zk.js} +1 -1
  52. package/dist/cli/chunk-9qye1syf.js +3 -0
  53. package/dist/cli/{chunk-e6wjt3e2.js → chunk-a2m6sk0n.js} +1 -1
  54. package/dist/cli/chunk-a2rxzyy4.js +2 -0
  55. package/dist/cli/chunk-asnjgz5a.js +4 -0
  56. package/dist/cli/chunk-aterhn60.js +3 -0
  57. package/dist/cli/chunk-ay3c35g5.js +2 -0
  58. package/dist/cli/{chunk-1kf56h0r.js → chunk-b3nrywgm.js} +1 -1
  59. package/dist/cli/{chunk-fg8d4z6c.js → chunk-bche07fb.js} +1 -1
  60. package/dist/cli/{chunk-5nwcwk6x.js → chunk-bsprr76b.js} +1 -1
  61. package/dist/cli/{chunk-jpc5yh8e.js → chunk-bwgtbaex.js} +1 -1
  62. package/dist/cli/chunk-bxabhkaq.js +21 -0
  63. package/dist/cli/{chunk-se483mcw.js → chunk-bz3p5vp1.js} +3 -3
  64. package/dist/cli/chunk-bzqjk9fb.js +3 -0
  65. package/dist/cli/chunk-c4c03wnz.js +3 -0
  66. package/dist/cli/{chunk-kqb8dd6n.js → chunk-cjzyc7cn.js} +12 -10
  67. package/dist/cli/{chunk-b550dwkd.js → chunk-cq4fym60.js} +1 -1
  68. package/dist/cli/{chunk-6d49rhme.js → chunk-cqazrkzw.js} +1 -1
  69. package/dist/cli/{chunk-vnp1k7ek.js → chunk-d3sgpjj6.js} +1 -1
  70. package/dist/cli/{chunk-rzem07e4.js → chunk-d5gtdecq.js} +1 -1
  71. package/dist/cli/chunk-de89aagk.js +6 -0
  72. package/dist/cli/chunk-ecdnw5xe.js +70 -0
  73. package/dist/cli/{chunk-sgnm8v1a.js → chunk-ehssspvr.js} +1 -1
  74. package/dist/cli/{chunk-ytrktnmv.js → chunk-emzt8crt.js} +1 -1
  75. package/dist/cli/{chunk-pnv7anct.js → chunk-ene2k7kb.js} +1 -1
  76. package/dist/cli/{chunk-a5p8fvpv.js → chunk-ep7abg35.js} +1 -1
  77. package/dist/cli/{chunk-7h5xfs5r.js → chunk-etj5h8hg.js} +2 -2
  78. package/dist/cli/chunk-ex2qtjt3.js +3 -0
  79. package/dist/cli/chunk-expgczbc.js +2 -0
  80. package/dist/cli/{chunk-9bq5e4fm.js → chunk-ez623zqp.js} +1 -1
  81. package/dist/cli/chunk-fads90r0.js +2 -0
  82. package/dist/cli/chunk-fdajxdht.js +2 -0
  83. package/dist/cli/{chunk-rbfah7j1.js → chunk-fwrpg1q9.js} +1 -1
  84. package/dist/cli/{chunk-mq9ng0qf.js → chunk-fyxfgkrw.js} +1 -1
  85. package/dist/cli/{chunk-b8xsf17w.js → chunk-fzc40zx7.js} +1 -1
  86. package/dist/cli/{chunk-s2wr6rc2.js → chunk-fzkq16qb.js} +1 -1
  87. package/dist/cli/chunk-g9qssqb7.js +2 -0
  88. package/dist/cli/{chunk-ekp98v7y.js → chunk-gf37e6ty.js} +1 -1
  89. package/dist/cli/chunk-gfsgk1n8.js +2 -0
  90. package/dist/cli/{chunk-8gy5m5s9.js → chunk-gvxchzch.js} +2 -2
  91. package/dist/cli/chunk-gxwy1r9a.js +382 -0
  92. package/dist/cli/{chunk-0ceg9qrt.js → chunk-hedp76tw.js} +1 -1
  93. package/dist/cli/{chunk-xttwk07t.js → chunk-hvz45y6d.js} +1 -1
  94. package/dist/cli/chunk-hwckecfa.js +2 -0
  95. package/dist/cli/{chunk-r987rn4r.js → chunk-j0s13v56.js} +1 -1
  96. package/dist/cli/chunk-j25b1ggg.js +2 -0
  97. package/dist/cli/{chunk-mapwzp5d.js → chunk-j6g8jmke.js} +2 -2
  98. package/dist/cli/chunk-j8r8q5z8.js +8 -0
  99. package/dist/cli/chunk-jgkjfqm9.js +4 -0
  100. package/dist/cli/{chunk-fexbzt63.js → chunk-jpa26n83.js} +1 -1
  101. package/dist/cli/chunk-jx3zndsh.js +2 -0
  102. package/dist/cli/chunk-jykxdtad.js +3 -0
  103. package/dist/cli/{chunk-73a9kk03.js → chunk-jyrmdx8f.js} +1 -1
  104. package/dist/cli/{chunk-fkz86c53.js → chunk-k1pk159f.js} +1 -1
  105. package/dist/cli/{chunk-4q5gbyhd.js → chunk-kmfas00z.js} +1 -1
  106. package/dist/cli/{chunk-szdzakrk.js → chunk-kpq28cbh.js} +1 -1
  107. package/dist/cli/chunk-kzcd7vdj.js +189 -0
  108. package/dist/cli/chunk-m0kprsxc.js +2 -0
  109. package/dist/cli/chunk-m932h3dx.js +30 -0
  110. package/dist/cli/{chunk-r5c51qqp.js → chunk-mp535p99.js} +1 -1
  111. package/dist/cli/chunk-mpmsc9s5.js +2 -0
  112. package/dist/cli/{chunk-dmb3y33d.js → chunk-n9d40jze.js} +1 -1
  113. package/dist/cli/{chunk-0b9dhq9b.js → chunk-navavqt2.js} +1 -1
  114. package/dist/cli/chunk-nf7pks44.js +2 -0
  115. package/dist/cli/chunk-pgaf0wqj.js +2 -0
  116. package/dist/cli/chunk-pp771snb.js +3 -0
  117. package/dist/cli/{chunk-3k56eqyb.js → chunk-pw0fvd64.js} +2 -2
  118. package/dist/cli/{chunk-55h581rc.js → chunk-qbmdpbdg.js} +1 -1
  119. package/dist/cli/chunk-qe7m3bwf.js +2 -0
  120. package/dist/cli/{chunk-6x4h80aw.js → chunk-qsfc7q9h.js} +1 -1
  121. package/dist/cli/chunk-r9n3asjx.js +2 -0
  122. package/dist/cli/{chunk-7v2m50tf.js → chunk-rr97z89e.js} +1 -1
  123. package/dist/cli/{chunk-sae6zcnq.js → chunk-rt4bsvd5.js} +1 -1
  124. package/dist/cli/chunk-sd3e5htq.js +2 -0
  125. package/dist/cli/{chunk-rzskspr8.js → chunk-spr6z826.js} +1 -1
  126. package/dist/cli/{chunk-jmx0vbra.js → chunk-t2f0xqyk.js} +2 -2
  127. package/dist/cli/chunk-t9vpmnbc.js +7 -0
  128. package/dist/cli/{chunk-mwnx6dk0.js → chunk-teq8p5rp.js} +4 -4
  129. package/dist/cli/{chunk-ebd4hnwk.js → chunk-tswzvtsy.js} +1 -1
  130. package/dist/cli/chunk-tzhfek18.js +34 -0
  131. package/dist/cli/{chunk-b4fqpvf8.js → chunk-v29v0cgd.js} +1 -1
  132. package/dist/cli/chunk-v2vs5nzx.js +2 -0
  133. package/dist/cli/{chunk-brk45qrp.js → chunk-v72qzktg.js} +1 -1
  134. package/dist/cli/chunk-vg3tyctk.js +2 -0
  135. package/dist/cli/chunk-vpy8tvfy.js +6 -0
  136. package/dist/cli/{chunk-eh7gh2nd.js → chunk-w3dpq6aj.js} +3 -3
  137. package/dist/cli/chunk-w70anvs6.js +3 -0
  138. package/dist/cli/chunk-wcjpanrw.js +51 -0
  139. package/dist/cli/{chunk-ay4k354s.js → chunk-wjmte4f0.js} +1 -1
  140. package/dist/cli/chunk-wth84cjn.js +3 -0
  141. package/dist/cli/chunk-wx3pr38x.js +2 -0
  142. package/dist/cli/{chunk-zw0k97mj.js → chunk-xc2zndmb.js} +1 -1
  143. package/dist/cli/chunk-xff3eqbv.js +2 -0
  144. package/dist/cli/chunk-xq2tazj5.js +2 -0
  145. package/dist/cli/{chunk-wdsbprdp.js → chunk-y4bhq88n.js} +1 -1
  146. package/dist/cli/{chunk-a833bpk3.js → chunk-y6eqz5pa.js} +1 -1
  147. package/dist/cli/{chunk-mm9rcced.js → chunk-ydxq51g3.js} +1 -1
  148. package/dist/cli/{chunk-nkgfr338.js → chunk-yg74j7kp.js} +1 -1
  149. package/dist/cli/{chunk-gpsj28xq.js → chunk-ygdxgp8r.js} +1 -1
  150. package/dist/cli/{chunk-h9hve3q0.js → chunk-ymmzwv5w.js} +2 -2
  151. package/dist/cli/{chunk-g883a7np.js → chunk-yn7y3epg.js} +1 -1
  152. package/dist/cli/chunk-ynwk3ep3.js +2 -0
  153. package/dist/cli/chunk-ypbh8ra4.js +8 -0
  154. package/dist/cli/{chunk-243dk7qd.js → chunk-z343ngx6.js} +1 -1
  155. package/dist/cli/{chunk-tdxr7vsr.js → chunk-z3cje8hk.js} +1 -1
  156. package/dist/cli/{chunk-q11wjx9d.js → chunk-z4nk2g47.js} +1 -1
  157. package/dist/cli/{chunk-18jk12bw.js → chunk-z6k53zqj.js} +1 -1
  158. package/dist/cli/chunk-z7dzpnyt.js +2 -0
  159. package/dist/cli/{chunk-h3fhg0k6.js → chunk-z98zs1h3.js} +2 -2
  160. package/dist/cli/chunk-z9c475xb.js +1 -0
  161. package/dist/cli/chunk-zg76y0bt.js +2 -0
  162. package/dist/cli/{chunk-sxpb2rv2.js → chunk-zgmnse5q.js} +1 -1
  163. package/dist/cli/chunk-zknvzer3.js +3 -0
  164. package/dist/cli/{chunk-1tqdxper.js → chunk-zpwg3eh0.js} +1 -1
  165. package/dist/cli/{chunk-e62x3fgv.js → chunk-zswn8skz.js} +1 -1
  166. package/dist/cli/index.js +7 -7
  167. package/dist/cli/pty-host-node.mjs +1 -1
  168. package/dist/cli/rove-run.js +1 -1
  169. package/dist/cli/rove.js +5 -5
  170. package/dist/completions/rove.bash +5 -3
  171. package/dist/completions/rove.fish +6 -2
  172. package/dist/completions/rove.zsh +5 -3
  173. package/dist/skills/rove/SKILL.md +21 -1
  174. package/dist/skills/rove/references/api-flags.md +21 -7
  175. package/dist/web/assets/index-BWayUsdy.css +1 -0
  176. package/dist/web/assets/index-D7OcIn1Q.js +113 -0
  177. package/dist/web/assets/term-mount-CSGanVNa.js +94 -0
  178. package/dist/web/index.html +2 -2
  179. package/dist/web/relay/index.html +12 -12
  180. package/dist/web/relay-client/assets/index-B307rVpU.js +264 -0
  181. package/dist/web/relay-client/assets/index-T6nIyGrP.css +1 -0
  182. package/dist/web/relay-client/index.html +2 -2
  183. package/package.json +7 -7
  184. package/dist/cli/chunk-0ft14bvv.js +0 -2
  185. package/dist/cli/chunk-0fymskqv.js +0 -2
  186. package/dist/cli/chunk-0x5c0fps.js +0 -2
  187. package/dist/cli/chunk-1z684jqw.js +0 -7
  188. package/dist/cli/chunk-22zaracj.js +0 -2
  189. package/dist/cli/chunk-35bm2hhp.js +0 -3
  190. package/dist/cli/chunk-43z1kjw1.js +0 -34
  191. package/dist/cli/chunk-452h1mje.js +0 -4
  192. package/dist/cli/chunk-4bje4rs5.js +0 -2
  193. package/dist/cli/chunk-4nwydt5r.js +0 -70
  194. package/dist/cli/chunk-5fn27ykb.js +0 -3
  195. package/dist/cli/chunk-686h761b.js +0 -2
  196. package/dist/cli/chunk-6ev3tb6p.js +0 -2
  197. package/dist/cli/chunk-6rpzvsp9.js +0 -2
  198. package/dist/cli/chunk-6rtxkaq4.js +0 -62
  199. package/dist/cli/chunk-7q0tgnka.js +0 -2
  200. package/dist/cli/chunk-7xzsssdb.js +0 -2
  201. package/dist/cli/chunk-7yx30m9p.js +0 -2
  202. package/dist/cli/chunk-88c4frwd.js +0 -2
  203. package/dist/cli/chunk-8jp0h0cb.js +0 -3
  204. package/dist/cli/chunk-9hkf3fxt.js +0 -2
  205. package/dist/cli/chunk-9tfh7fm8.js +0 -2
  206. package/dist/cli/chunk-a1cdvvjj.js +0 -3
  207. package/dist/cli/chunk-b926z6ts.js +0 -3
  208. package/dist/cli/chunk-c9c6yczz.js +0 -3
  209. package/dist/cli/chunk-cq5bvzpw.js +0 -2
  210. package/dist/cli/chunk-dsqcwtw5.js +0 -5
  211. package/dist/cli/chunk-e3d8k6yn.js +0 -173
  212. package/dist/cli/chunk-ea6nmvhb.js +0 -6
  213. package/dist/cli/chunk-en31v4c6.js +0 -2
  214. package/dist/cli/chunk-ex4q79hw.js +0 -4
  215. package/dist/cli/chunk-f7h3mzk0.js +0 -3
  216. package/dist/cli/chunk-feq3nytk.js +0 -3
  217. package/dist/cli/chunk-g2brwxbt.js +0 -2
  218. package/dist/cli/chunk-g6wzch69.js +0 -162
  219. package/dist/cli/chunk-gpdrhahv.js +0 -2
  220. package/dist/cli/chunk-h0yvntcq.js +0 -3
  221. package/dist/cli/chunk-hy1pkmfa.js +0 -2
  222. package/dist/cli/chunk-jrrq9k1b.js +0 -212
  223. package/dist/cli/chunk-khfwvz0g.js +0 -2
  224. package/dist/cli/chunk-kknejavp.js +0 -2
  225. package/dist/cli/chunk-m00ftggk.js +0 -11
  226. package/dist/cli/chunk-mktg22yf.js +0 -13
  227. package/dist/cli/chunk-mxr7n23g.js +0 -2
  228. package/dist/cli/chunk-nr7gk1r6.js +0 -2
  229. package/dist/cli/chunk-p90ne1pc.js +0 -4
  230. package/dist/cli/chunk-pmfkzjj4.js +0 -2
  231. package/dist/cli/chunk-qwkgksrt.js +0 -2
  232. package/dist/cli/chunk-r1zy756y.js +0 -2
  233. package/dist/cli/chunk-rf82fyrx.js +0 -2
  234. package/dist/cli/chunk-rv0c3aje.js +0 -2
  235. package/dist/cli/chunk-s0y3qw79.js +0 -2
  236. package/dist/cli/chunk-tm6vvy5t.js +0 -3
  237. package/dist/cli/chunk-tsyz1xr8.js +0 -2
  238. package/dist/cli/chunk-vfc9k4b9.js +0 -5
  239. package/dist/cli/chunk-wgyhtgeq.js +0 -2
  240. package/dist/cli/chunk-yecvqy0c.js +0 -2
  241. package/dist/cli/chunk-yz9erpjc.js +0 -2
  242. package/dist/cli/chunk-zhjd9pvc.js +0 -2
  243. package/dist/cli/chunk-zmk4q05h.js +0 -2
  244. package/dist/cli/chunk-zwbnsf1p.js +0 -8
  245. package/dist/cli/chunk-zy7m8fm9.js +0 -2
  246. package/dist/web/assets/index-BJEFhpXi.css +0 -1
  247. package/dist/web/assets/index-D7VnKpGY.js +0 -100
  248. package/dist/web/assets/term-mount-DBU4rcMr.js +0 -94
  249. package/dist/web/relay-client/assets/index-D9PRsWzW.js +0 -251
  250. package/dist/web/relay-client/assets/index-Dk042dEU.css +0 -1
@@ -0,0 +1,51 @@
1
+ // @bun
2
+ import{serialized,writeJsonAtomic}from"./chunk-5mhvjytn.js";import{ROVE_STATE_DIR_BASENAME,readRoveHomeDirEnv}from"./chunk-nc46gddg.js";import{__export}from"./chunk-91sykzqq.js";import{createHash,randomBytes as randomBytes6}from"crypto";import{readFile}from"fs/promises";import{homedir}from"os";import{join}from"path";function isBytes(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in a&&a.BYTES_PER_ELEMENT===1}var atitle=(title)=>title?`"${title}" `:"";function anumber(n,title=""){if(typeof n!=="number")throw TypeError(atitle(title)+"expected number, got "+typeof n);if(!Number.isSafeInteger(n)||n<0)throw RangeError(atitle(title)+"expected integer >= 0, got "+n);return n}function abytes(value,length,title=""){if(isBytes(value)&&(length===void 0||value.length===length))return value;if(length!==void 0)anumber(length,"length");let bytes=isBytes(value),ofLen=length!==void 0?` of length ${length}`:"",got=bytes?`length=${value.length}`:`type=${typeof value}`,message=atitle(title)+"expected Uint8Array"+ofLen+", got "+got;if(!bytes)throw TypeError(message);throw RangeError(message)}function ahash(h){if(typeof h!=="function"||typeof h.create!=="function")throw TypeError("expected hash wrapped by utils.createHasher");if(anumber(h.outputLen),anumber(h.blockLen),h.outputLen<1||h.blockLen<1)throw Error("hash blockLen / outputLen must be >= 1")}var aobject=(value,label)=>{if(value===null||typeof value!=="object"||Array.isArray(value))throw TypeError((label==="object"?"":`"${label}" `)+"expected object, got type="+typeof value)},aopts=(value,label)=>{aobject(value,label);let proto=Object.getPrototypeOf(value);if(proto!==Object.prototype&&proto!==null)throw TypeError(`"${label}" expected plain object`);if(Object.hasOwn(value,"__proto__"))throw TypeError(`"${label}.__proto__" is not allowed`)};function aexists(instance,checkFinished=!0){if(instance.destroyed)throw Error("hash was destroyed");if(checkFinished&&instance.finished)throw Error("digest() was already called")}function aoutput(out,instance){abytes(out,void 0,"output");let min=instance.outputLen;if(!(out.length>=min))throw RangeError('"output" expected length >= '+min)}function u32(arr){return new Uint32Array(arr.buffer,arr.byteOffset,Math.floor(arr.byteLength/4))}function clean(...arrays){for(let i=0;i<arrays.length;i++)arrays[i].fill(0)}function createView(arr){return new DataView(arr.buffer,arr.byteOffset,arr.byteLength)}function rotr(word,shift){return word<<32-shift|word>>>shift}function rotl(word,shift){return word<<shift|word>>>32-shift>>>0}var isLE=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function byteSwap(word){return word<<24&4278190080|word<<8&16711680|word>>>8&65280|word>>>24&255}function byteSwap32(arr){for(let i=0;i<arr.length;i++)arr[i]=byteSwap(arr[i]);return arr}var swap32IfBE=isLE?(u)=>u:byteSwap32,hasHexBuiltin=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),hexes=Array.from({length:256},(_,i)=>i.toString(16).padStart(2,"0"));function bytesToHex(bytes){if(abytes(bytes),hasHexBuiltin)return bytes.toHex();let hex="";for(let i=0;i<bytes.length;i++)hex+=hexes[bytes[i]];return hex}function asciiToBase16(ch){return ch>=48&&ch<=57?ch-48:ch>=65&&ch<=70?ch-55:ch>=97&&ch<=102?ch-87:void 0}function hexToBytes(hex){if(typeof hex!=="string")throw TypeError("hex string expected, got "+typeof hex);if(hasHexBuiltin)try{return Uint8Array.fromHex(hex)}catch(error){if(error instanceof SyntaxError)throw RangeError(error.message);throw error}let hl=hex.length,al=hl/2;if(hl%2)throw RangeError("hex string expected, got unpadded hex of length "+hl);let array=new Uint8Array(al);for(let ai=0,hi=0;ai<al;ai++,hi+=2){let n1=asciiToBase16(hex.charCodeAt(hi)),n2=asciiToBase16(hex.charCodeAt(hi+1));if(n1===void 0||n2===void 0){let char=hex[hi]+hex[hi+1];throw RangeError('hex string expected, got non-hex character "'+char+'" at index '+hi)}array[ai]=n1*16+n2}return array}function utf8ToBytes(str){if(typeof str!=="string")throw TypeError("string expected");let encoded=new TextEncoder().encode(str);try{return new Uint8Array(encoded)}finally{clean(encoded)}}function kdfInputToBytes(data,errorTitle=""){if(typeof data==="string")return utf8ToBytes(data);return abytes(data,void 0,errorTitle)}function concatBytes(...arrays){let sum=0;for(let i=0;i<arrays.length;i++){let a=arrays[i];abytes(a),sum+=a.length}let res=new Uint8Array(sum);for(let i=0,pad=0;i<arrays.length;i++){let a=arrays[i];res.set(a,pad),pad+=a.length}return res}function checkOpts(defaults,opts,title="opts"){if(aopts(defaults,"defaults"),opts!==void 0)aopts(opts,title);return Object.assign(Object.create(null),defaults,opts)}function createHasher(hashCons,info={}){if(typeof hashCons!=="function")throw TypeError('"hashCons" expected function, got type='+typeof hashCons);info=checkOpts({},info,"info");let hashC=(msg,opts)=>hashCons(opts).update(msg).digest(),tmp=hashCons(void 0);return hashC.outputLen=tmp.outputLen,hashC.blockLen=tmp.blockLen,hashC.canXOF=tmp.canXOF,hashC.create=(opts)=>hashCons(opts),Object.assign(hashC,info),Object.freeze(hashC)}function randomBytes(bytesLength=32){anumber(bytesLength,"bytesLength");let cr=typeof globalThis==="object"?globalThis.crypto:null;if(typeof cr?.getRandomValues!=="function")throw Error("crypto.getRandomValues must be defined");if(bytesLength>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);return cr.getRandomValues(new Uint8Array(bytesLength))}var oidNist=(suffix)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,suffix])});class _HMAC{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(hash,key){if(ahash(hash),abytes(key,void 0,"key"),this.iHash=hash.create(),typeof this.iHash.update!=="function")throw Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let blockLen=this.blockLen,pad=new Uint8Array(blockLen);pad.set(key.length>blockLen?hash.create().update(key).digest():key);for(let i=0;i<pad.length;i++)pad[i]^=54;this.iHash.update(pad),this.oHash=hash.create();for(let i=0;i<pad.length;i++)pad[i]^=106;this.oHash.update(pad),clean(pad)}update(buf){return aexists(this),this.iHash.update(buf),this}digestInto(out){aexists(this),aoutput(out,this),this.finished=!0;let buf=out.subarray(0,this.outputLen);this.iHash.digestInto(buf),this.oHash.update(buf),this.oHash.digestInto(buf),this.destroy()}digest(){let out=new Uint8Array(this.oHash.outputLen);return this.digestInto(out),out}_cloneInto(to){to||=Object.create(Object.getPrototypeOf(this),{});let{oHash,iHash,finished,destroyed,blockLen,outputLen,canXOF}=this;return to=to,to.finished=finished,to.destroyed=destroyed,to.blockLen=blockLen,to.outputLen=outputLen,to.canXOF=canXOF,to.oHash=oHash._cloneInto(to.oHash),to.iHash=iHash._cloneInto(to.iHash),to}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var hmac=(()=>{let hmac_=(hash,key,message)=>new _HMAC(hash,key).update(message).digest();return hmac_.create=(hash,key)=>new _HMAC(hash,key),hmac_})();function extract(hash,ikm,salt){if(ahash(hash),salt===void 0)salt=new Uint8Array(hash.outputLen);return hmac(hash,salt,ikm)}var HKDF_COUNTER=Uint8Array.of(0),EMPTY_BUFFER=Uint8Array.of();function expand(hash,prk,info,length=32,_recycled){ahash(hash),anumber(length,"length"),abytes(prk,void 0,"prk");let olen=hash.outputLen;if(prk.length<olen)throw Error('"prk" must be at least HashLen octets');if(length>255*olen)throw Error("Length must be <= 255*HashLen");let blocks=Math.ceil(length/olen);if(info===void 0)info=EMPTY_BUFFER;else abytes(info,void 0,"info");if(!blocks){if(_recycled)clean(prk);return new Uint8Array}let okm=_recycled&&blocks===1?prk:new Uint8Array(blocks*olen),{iHash,oHash}=hmac.create(hash,prk),T=_recycled?prk:new Uint8Array(olen),worker=blocks>1?_recycled?.iHash||hash.create():void 0;for(let counter=0;counter<blocks-1;counter++){HKDF_COUNTER[0]=counter+1;let iWork=iHash._cloneInto(worker);if(counter)iWork.update(T);iWork.update(info).update(HKDF_COUNTER).digestInto(T),oHash._cloneInto(worker).update(T).digestInto(T),okm.set(T,olen*counter)}if(HKDF_COUNTER[0]=blocks,blocks>1)iHash.update(T);if(iHash.update(info).update(HKDF_COUNTER).digestInto(T),oHash.update(T).digestInto(T),okm.set(T,olen*(blocks-1)),iHash.destroy(),oHash.destroy(),worker?.destroy(),T!==okm)clean(T);if(clean(HKDF_COUNTER),length===okm.length)return okm;let res=okm.slice(0,length);return clean(okm),res}var hkdf=(hash,ikm,salt,info,length)=>{if(ahash(hash),salt===void 0)salt=new Uint8Array(hash.outputLen);let HMAC=hmac.create(hash,salt).update(ikm);return expand(hash,HMAC.digest(),info,length,HMAC)};var fromNumH=(n)=>n/4294967296|0,fromNumL=(n)=>n>>>0;function setU64FromNum(view,byteOffset,n,isLE2){let h=fromNumH(n),l=fromNumL(n);view.setUint32(byteOffset,isLE2?l:h,isLE2),view.setUint32(byteOffset+4,isLE2?h:l,isLE2)}function Chi(a,b,c){return a&b^~a&c}function Maj(a,b,c){return a&b^a&c^b&c}class HashMD{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(blockLen,outputLen,padOffset,isLE2){this.blockLen=blockLen,this.outputLen=outputLen,this.padOffset=padOffset,this.isLE=isLE2,this.buffer=new Uint8Array(blockLen),this.view=createView(this.buffer)}update(data){aexists(this),abytes(data);let{view,buffer,blockLen}=this,len=data.length,processed=!1;for(let pos=0;pos<len;){let take=Math.min(blockLen-this.pos,len-pos);if(take===blockLen){let dataView=createView(data);for(;blockLen<=len-pos;pos+=blockLen)this.process(dataView,pos);processed=!0;continue}if(buffer.set(pos===0&&take===len?data:data.subarray(pos,pos+take),this.pos),this.pos+=take,pos+=take,this.pos===blockLen)this.process(view,0),this.pos=0,processed=!0}if(this.length+=data.length,processed)this.roundClean();return this}digestInto(out){aexists(this),aoutput(out,this),this.finished=!0;let{buffer,view,blockLen,isLE:isLE2}=this,{pos}=this;if(buffer[pos++]=128,buffer.fill(0,pos),this.padOffset>blockLen-pos)this.process(view,0),buffer.fill(0);setU64FromNum(view,blockLen-8,this.length*8,isLE2),this.process(view,0),this.roundClean();let oview=out===buffer?view:createView(out),len=this.outputLen,outLen=len/4,state=this.get();if(len%4||outLen>state.length)throw Error("invalid outputLen");for(let i=0;i<outLen;i++)oview.setUint32(4*i,state[i],isLE2)}digest(){let{buffer,outputLen}=this;this.digestInto(buffer);let res=buffer.slice(0,outputLen);return this.destroy(),res}_cloneIntoMeta(to){let{buffer,length,finished,destroyed,pos}=this;if(to.destroyed=destroyed,to.finished=finished,to.length=length,to.pos=pos,pos)to.buffer.set(buffer);return to}clone(){return this._cloneInto()}}var SHA256_IV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var SHA256_K=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]),SHA256_W=new Uint32Array(64);class SHA2_32B extends HashMD{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(outputLen,IV){super(64,outputLen,8,!1);this.A=IV[0]|0,this.B=IV[1]|0,this.C=IV[2]|0,this.D=IV[3]|0,this.E=IV[4]|0,this.F=IV[5]|0,this.G=IV[6]|0,this.H=IV[7]|0}get(){let{A,B,C,D,E,F,G,H}=this;return[A,B,C,D,E,F,G,H]}set(A,B,C,D,E,F,G,H){this.A=A|0,this.B=B|0,this.C=C|0,this.D=D|0,this.E=E|0,this.F=F|0,this.G=G|0,this.H=H|0}_cloneInto(to){return(to||=new this.constructor).set(...this.get()),this._cloneIntoMeta(to)}process(view,offset){for(let i=0;i<16;i++,offset+=4)SHA256_W[i]=view.getUint32(offset,!1);for(let i=16;i<64;i++){let W15=SHA256_W[i-15],W2=SHA256_W[i-2],s0=rotr(W15,7)^rotr(W15,18)^W15>>>3,s1=rotr(W2,17)^rotr(W2,19)^W2>>>10;SHA256_W[i]=s1+SHA256_W[i-7]+s0+SHA256_W[i-16]|0}let{A,B,C,D,E,F,G,H}=this;for(let i=0;i<64;i++){let sigma1=rotr(E,6)^rotr(E,11)^rotr(E,25),T1=H+sigma1+Chi(E,F,G)+SHA256_K[i]+SHA256_W[i]|0,T2=(rotr(A,2)^rotr(A,13)^rotr(A,22))+Maj(A,B,C)|0;H=G,G=F,F=E,E=D+T1|0,D=C,C=B,B=A,A=T1+T2|0}A=A+this.A|0,B=B+this.B|0,C=C+this.C|0,D=D+this.D|0,E=E+this.E|0,F=F+this.F|0,G=G+this.G|0,H=H+this.H|0,this.set(A,B,C,D,E,F,G,H)}roundClean(){clean(SHA256_W)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),clean(this.buffer)}}class _SHA256 extends SHA2_32B{constructor(){super(32,SHA256_IV)}}var sha256=createHasher(()=>new _SHA256,oidNist(1));/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */var freeze=(fn)=>Object.freeze(fn());function isBytes2(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in a&&a.BYTES_PER_ELEMENT===1}function abytes2(b){if(!isBytes2(b))throw TypeError("Uint8Array expected")}function isArrayOf(isString,arr){if(!Array.isArray(arr))return!1;if(arr.length===0)return!0;if(isString)return arr.every((item)=>typeof item==="string");else return arr.every((item)=>Number.isSafeInteger(item))}function afn(input){if(typeof input!=="function")throw TypeError("function expected");return!0}function astr(label,input){if(typeof input!=="string")throw TypeError(`${label}: string expected`);return!0}function anumber2(n,title="number"){if(typeof n!=="number")throw TypeError(`${title}: expected number, got ${typeof n}`);if(!Number.isSafeInteger(n))throw RangeError(`${title}: expected safe integer, got ${n}`)}function anumArr(label,input){if(!isArrayOf(!1,input))throw TypeError(`${label}: array of numbers expected`)}function chain(...args){let id=(a)=>a,wrap=(a,b)=>(c)=>a(b(c)),encode=args.map((x)=>x.encode).reduceRight(wrap,id),decode=args.map((x)=>x.decode).reduce(wrap,id);return{encode,decode}}var powers=(()=>{let res=[];for(let i=0;i<40;i++)res.push(2**i);return res})();function u8ToNumArr(u8,len=u8.length){let res=Array(len);for(let i=0;i<len;i++)res[i]=u8[i];return res}var asciiDecoder=(()=>{try{let decoder=new TextDecoder;return decoder.decode(Uint8Array.of(65,48,43,127))==="A0+\x7F"?decoder:void 0}catch(e){return}})(),B2S_CHUNK=8192;function charcodesToString(codes){let len=codes.length;if(asciiDecoder!==void 0&&len>=12)return asciiDecoder.decode(codes);if(len<=B2S_CHUNK)return String.fromCharCode.apply(null,codes);let res="";for(let i=0;i<len;i+=B2S_CHUNK)res+=String.fromCharCode.apply(null,codes.subarray(i,i+B2S_CHUNK));return res}function radix2(bits){if(anumber2(bits),bits<=0||bits>8)throw RangeError("radix2: bits should be in (0..8]");let mask=powers[bits]-1;return{encode:(bytes)=>{abytes2(bytes);let len=bytes.length,res=new Uint8Array(Math.ceil(len*8/bits)),carry=0,pos=0,j=0;for(let i=0;i<len;){if(i+2<len)carry=carry<<24|bytes[i]<<16|bytes[i+1]<<8|bytes[i+2],pos+=24,i+=3;else carry=(carry<<8|bytes[i])&65535,pos+=8,i++;for(;;)if(pos-=bits,res[j++]=carry>>pos&mask,pos<bits)break}if(pos>0)res[j]=carry<<bits-pos&mask;return res},decode:(digits)=>{let len=digits.length,res=new Uint8Array(Math.floor(len*bits/8)),carry=0,pos=0,j=0;for(let i=0;i<len;i++){carry=(carry<<bits|digits[i])&65535,pos+=bits;for(;pos>=8;pos-=8)res[j++]=carry>>pos-8&255}if(carry=carry<<8-pos&255,pos>=bits)throw Error("Excess padding");if(carry>0)throw Error(`Non-zero padding: ${carry}`);return res}}}function alphabet(letters,aliases){let len=letters.length;if(len>128)throw Error("alphabet: max 128 letters");let encTable=new Uint8Array(len),decTable=new Int8Array(128).fill(-1);for(let i=0;i<len;i++){let code=letters.charCodeAt(i);if(letters.codePointAt(i)!==code||code>127)throw Error("alphabet: single-char ASCII letters only");encTable[i]=code,decTable[code]=i}if(aliases!==void 0)for(let alias of Object.keys(aliases)){let code=alias.charCodeAt(0),target=decTable[aliases[alias].charCodeAt(0)];if(alias.length!==1||code>127||target===void 0||target===-1)throw Error(`alphabet: invalid alias ${alias}`);decTable[code]=target}return{encode:(digits)=>{let codes=new Uint8Array(digits.length);for(let i=0;i<digits.length;i++){let d=digits[i],code=encTable[d];if(code===void 0)throw Error(`alphabet.encode: invalid digit ${d}`);codes[i]=code}return charcodesToString(codes)},decode:(input)=>{astr("decode",input);let slen=input.length,digits=new Uint8Array(slen);for(let i=0;i<slen;i++){let code=input.charCodeAt(i),digit=code<128?decTable[code]:-1;if(digit===-1)throw Error(`Unknown letter "${input[i]}". Allowed: ${letters}`);digits[i]=digit}return digits}}}function padding(bits,chr="="){return anumber2(bits),astr("padding",chr),{encode(data){while(data.length*bits%8)data+=chr;return data},decode(input){astr("decode",input);let end=input.length;if(end*bits%8)throw Error("padding: invalid length");for(;end>0&&input[end-1]===chr;end--)if((end-1)*bits%8===0)throw Error("padding: excess padding");return input.slice(0,end)}}}function unsafeWrapper(fn){return afn(fn),function(...args){try{return fn.apply(null,args)}catch(e){}}}var hasBase64Builtin=(()=>typeof Uint8Array.from([]).toBase64==="function"&&typeof Uint8Array.fromBase64==="function")(),ASCII_WHITESPACE=/[\t\n\f\r ]/,decodeBase64Builtin=(s,isUrl)=>{astr("base64",s);let alphabet2=isUrl?"base64url":"base64";if(s.length>0&&ASCII_WHITESPACE.test(s))throw Error("invalid base64");return Uint8Array.fromBase64(s,{alphabet:alphabet2,lastChunkHandling:"strict"})},base64Fallback=freeze(()=>chain(radix2(6),alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),padding(6)));var base64=freeze(()=>hasBase64Builtin?{encode(b){return abytes2(b),b.toBase64()},decode(s){return decodeBase64Builtin(s,!1)}}:base64Fallback),base64nopad=freeze(()=>chain(radix2(6),alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")));var BECH_ALPHABET=alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),BECH_UPPERCASE_PRINTABLE=/^[\x21-\x60\x7b-\x7e]+$/;function assertBech32Printable(label,value){for(let i=0;i<value.length;i++){let c=value.charCodeAt(i);if(c<33||c>126)throw Error(`${label}: printable ASCII expected`)}}function wordsToU8(words){let len=words.length,res=new Uint8Array(len);for(let i=0;i<len;i++){let w=words[i];if(w<0||w>=32)throw Error(`alphabet.encode: invalid digit ${w}`);res[i]=w}return res}var POLYMOD_GENERATORS=[996825010,642813549,513874426,1027748829,705979059];function bech32Polymod(pre){let b=pre>>25,chk=(pre&33554431)<<5;for(let i=0;i<POLYMOD_GENERATORS.length;i++)if((b>>i&1)===1)chk^=POLYMOD_GENERATORS[i];return chk}function bechChecksum(prefix,words,encodingConst=1){let len=prefix.length,chk=1;for(let i=0;i<len;i++){let c=prefix.charCodeAt(i);if(c<33||c>126)throw Error(`Invalid prefix (${prefix})`);chk=bech32Polymod(chk)^c>>5}chk=bech32Polymod(chk);for(let i=0;i<len;i++)chk=bech32Polymod(chk)^prefix.charCodeAt(i)&31;for(let v of words)chk=bech32Polymod(chk)^v;for(let i=0;i<6;i++)chk=bech32Polymod(chk);chk^=encodingConst;let sum=new Uint8Array(6);for(let i=0;i<6;i++)sum[i]=chk>>>5*(5-i)&31;return BECH_ALPHABET.encode(sum)}function genBech32(encoding){let ENCODING_CONST=encoding==="bech32"?1:734539939,_words=radix2(5),toWords=(from)=>{abytes2(from);let len=from.length,res=Array(Math.ceil(len*8/5)),carry=0,pos=0,j=0;for(let i=0;i<len;i++){carry=carry<<8|from[i],pos+=8;for(;pos>=5;pos-=5)res[j++]=carry>>pos-5&31}if(pos>0)res[j]=carry<<5-pos&31;return res},fromWords=(to)=>{anumArr("radix2.decode",to);let len=to.length,digits=new Uint8Array(len);for(let i=0;i<len;i++){let w=to[i];if(w<0||w>=32)throw Error(`convertRadix2: invalid word=${w}`);digits[i]=w}return _words.decode(digits)},fromWordsUnsafe=unsafeWrapper(fromWords);function encode(prefix,words,limit=90){if(astr("bech32.encode prefix",prefix),limit!==!1)anumber2(limit,"limit");if(isBytes2(words))words=u8ToNumArr(words);anumArr("bech32.encode",words);let plen=prefix.length;if(plen===0)throw TypeError(`Invalid prefix length ${plen}`);let actualLength=plen+7+words.length;if(limit!==!1&&actualLength>limit)throw TypeError(`Length ${actualLength} exceeds limit ${limit}`);assertBech32Printable("bech32.encode prefix",prefix);let lowered=prefix.toLowerCase(),sum=bechChecksum(lowered,words,ENCODING_CONST);return`${lowered}1${BECH_ALPHABET.encode(wordsToU8(words))}${sum}`}function decode(str,limit=90){if(astr("bech32.decode input",str),limit!==!1)anumber2(limit,"limit");let slen=str.length;if(slen<8||limit!==!1&&slen>limit)throw TypeError(`invalid string length ${slen}, expected (8..${limit})`);let lowered=str.toLowerCase();if(str!==lowered){if(!BECH_UPPERCASE_PRINTABLE.test(str))throw assertBech32Printable("bech32.decode input",str),Error("mixed-case string not allowed")}let sepIndex=lowered.lastIndexOf("1");if(sepIndex===0||sepIndex===-1)throw Error('invalid separator "1"');let prefix=lowered.slice(0,sepIndex),data=lowered.slice(sepIndex+1);if(data.length<6)throw Error("invalid data length");let digits=BECH_ALPHABET.decode(data),words=u8ToNumArr(digits,digits.length-6),sum=bechChecksum(prefix,words,ENCODING_CONST);if(!data.endsWith(sum))throw Error(`Invalid checksum in ${str}`);return{prefix,words}}let decodeUnsafe=unsafeWrapper(decode);function decodeToBytes(str,limit=90){let{prefix,words}=decode(str,limit);return{prefix,words,bytes:fromWords(words)}}function encodeFromBytes(prefix,bytes){return encode(prefix,toWords(bytes))}return{encode,decode,encodeFromBytes,decodeToBytes,decodeUnsafe,fromWords,fromWordsUnsafe,toWords}}var bech32=freeze(()=>genBech32("bech32"));function pbkdf2Init(hash,_password,_salt,_opts){ahash(hash);let opts=checkOpts({dkLen:32,asyncTick:10},_opts),{c,dkLen,asyncTick}=opts;if(anumber(c,"c"),anumber(dkLen,"dkLen"),anumber(asyncTick,"asyncTick"),c<1)throw Error('"c" (iterations) must be >= 1');if(dkLen<1)throw Error('"dkLen" must be >= 1');if(dkLen>4294967295*hash.outputLen)throw Error("derived key too long");let p=kdfInputToBytes(_password,"password");try{let s=kdfInputToBytes(_salt,"salt");try{let DK=new Uint8Array(dkLen),{iHash,oHash,outputLen}=hmac.create(hash,p),u=new Uint8Array(outputLen),eng=pbkdf2Engine(iHash,oHash,s,u);return{c,dkLen,asyncTick,DK,outputLen,eng}}finally{if(typeof _salt==="string")clean(s)}}finally{if(typeof _password==="string")clean(p)}}function pbkdf2Engine(iHash,oHash,salt,u){let counter=new Uint8Array(4),view=createView(counter),salted=iHash._cloneInto().update(salt),work=oHash._cloneInto(),iClone=iHash._cloneInto,oClone=oHash._cloneInto;return{u1:(ti,Ti)=>{view.setInt32(0,ti,!1),salted._cloneInto(work).update(counter).digestInto(u),oHash._cloneInto(work).update(u).digestInto(u),Ti.set(u.subarray(0,Ti.length))},rounds:(c,Ti)=>{for(let ui=1;ui<c;ui++){iClone.call(iHash,work).update(u).digestInto(u),oClone.call(oHash,work).update(u).digestInto(u);for(let i=0;i<Ti.length;i++)Ti[i]^=u[i]}},output:(DK)=>{return iHash.destroy(),oHash.destroy(),salted.destroy(),work.destroy(),clean(u),DK}}}function pbkdf2(hash,password,salt,opts){let{c,dkLen,DK,outputLen,eng}=pbkdf2Init(hash,password,salt,opts);for(let ti=1,pos=0;pos<dkLen;ti++,pos+=outputLen){let Ti=DK.subarray(pos,pos+outputLen);eng.u1(ti,Ti),eng.rounds(c,Ti)}return eng.output(DK)}function XorAndSalsa(prev,pi,input,ii,out,oi){let y00=prev[pi++]^input[ii++],y01=prev[pi++]^input[ii++],y02=prev[pi++]^input[ii++],y03=prev[pi++]^input[ii++],y04=prev[pi++]^input[ii++],y05=prev[pi++]^input[ii++],y06=prev[pi++]^input[ii++],y07=prev[pi++]^input[ii++],y08=prev[pi++]^input[ii++],y09=prev[pi++]^input[ii++],y10=prev[pi++]^input[ii++],y11=prev[pi++]^input[ii++],y12=prev[pi++]^input[ii++],y13=prev[pi++]^input[ii++],y14=prev[pi++]^input[ii++],y15=prev[pi++]^input[ii++],x00=y00,x01=y01,x02=y02,x03=y03,x04=y04,x05=y05,x06=y06,x07=y07,x08=y08,x09=y09,x10=y10,x11=y11,x12=y12,x13=y13,x14=y14,x15=y15;for(let i=0;i<8;i+=2)x04^=rotl(x00+x12|0,7),x08^=rotl(x04+x00|0,9),x12^=rotl(x08+x04|0,13),x00^=rotl(x12+x08|0,18),x09^=rotl(x05+x01|0,7),x13^=rotl(x09+x05|0,9),x01^=rotl(x13+x09|0,13),x05^=rotl(x01+x13|0,18),x14^=rotl(x10+x06|0,7),x02^=rotl(x14+x10|0,9),x06^=rotl(x02+x14|0,13),x10^=rotl(x06+x02|0,18),x03^=rotl(x15+x11|0,7),x07^=rotl(x03+x15|0,9),x11^=rotl(x07+x03|0,13),x15^=rotl(x11+x07|0,18),x01^=rotl(x00+x03|0,7),x02^=rotl(x01+x00|0,9),x03^=rotl(x02+x01|0,13),x00^=rotl(x03+x02|0,18),x06^=rotl(x05+x04|0,7),x07^=rotl(x06+x05|0,9),x04^=rotl(x07+x06|0,13),x05^=rotl(x04+x07|0,18),x11^=rotl(x10+x09|0,7),x08^=rotl(x11+x10|0,9),x09^=rotl(x08+x11|0,13),x10^=rotl(x09+x08|0,18),x12^=rotl(x15+x14|0,7),x13^=rotl(x12+x15|0,9),x14^=rotl(x13+x12|0,13),x15^=rotl(x14+x13|0,18);out[oi++]=y00+x00|0,out[oi++]=y01+x01|0,out[oi++]=y02+x02|0,out[oi++]=y03+x03|0,out[oi++]=y04+x04|0,out[oi++]=y05+x05|0,out[oi++]=y06+x06|0,out[oi++]=y07+x07|0,out[oi++]=y08+x08|0,out[oi++]=y09+x09|0,out[oi++]=y10+x10|0,out[oi++]=y11+x11|0,out[oi++]=y12+x12|0,out[oi++]=y13+x13|0,out[oi++]=y14+x14|0,out[oi++]=y15+x15|0}function BlockMix(input,ii,out,oi,r){let head=oi+0,tail=oi+16*r;for(let i=0;i<16;i++)out[tail+i]=input[ii+(2*r-1)*16+i];for(let i=0;i<r;i++,head+=16,ii+=16){if(XorAndSalsa(out,tail,input,ii,out,head),i>0)tail+=16;XorAndSalsa(out,head,input,ii+=16,out,tail)}}var SCRYPT_DEFAULT_MAXMEM=1073743872;function scryptInit(password,salt,_opts){let opts=checkOpts({dkLen:32,asyncTick:10,maxmem:SCRYPT_DEFAULT_MAXMEM},_opts),{N,r,p,dkLen,asyncTick,maxmem,onProgress}=opts;if(anumber(N,"N"),anumber(r,"r"),anumber(p,"p"),anumber(dkLen,"dkLen"),anumber(asyncTick,"asyncTick"),anumber(maxmem,"maxmem"),onProgress!==void 0&&typeof onProgress!=="function")throw Error('"onProgress" must be a function');if(r<1)throw Error('"r" expected integer >= 1');let blockSize=128*r,blockSize32=blockSize/4,pow32=Math.pow(2,32);if(N<=1||(N&N-1)!==0||N>pow32)throw Error('"N" expected a power of 2, and 2^1 <= N <= 2^32');if(p<1||p>(pow32-1)*32/blockSize)throw Error('"p" expected integer 1..((2^32 - 1) * 32) / (128 * r)');if(dkLen<1||dkLen>(pow32-1)*32)throw Error('"dkLen" expected integer 1..(2^32 - 1) * 32');let memUsed=blockSize*(N+p+1);if(memUsed>maxmem)throw Error('"maxmem" limit was hit: memUsed(128*r*(N+p+1))='+memUsed+", maxmem="+maxmem);let B=pbkdf2(sha256,password,salt,{c:1,dkLen:blockSize*p}),B32=u32(B),V=u32(new Uint8Array(blockSize*N)),tmp=u32(new Uint8Array(blockSize)),blockMixCb=()=>{};if(onProgress){let totalBlockMix=2*N*p,callbackPer=Math.max(Math.floor(totalBlockMix/1e4),1),blockMixCnt=0;blockMixCb=()=>{if(blockMixCnt++,onProgress&&(!(blockMixCnt%callbackPer)||blockMixCnt===totalBlockMix))try{onProgress(blockMixCnt/totalBlockMix)}catch(e){throw clean(B,V,tmp),e}}}return{N,r,p,dkLen,blockSize32,V,B32,B,tmp,blockMixCb,asyncTick}}function scryptOutput(password,dkLen,B,V,tmp){let res=pbkdf2(sha256,password,B,{c:1,dkLen});return clean(B,V,tmp),res}function scrypt(password,salt,opts){let{N,r,p,dkLen,blockSize32,V,B32,B,tmp,blockMixCb}=scryptInit(password,salt,opts);swap32IfBE(B32);for(let pi=0;pi<p;pi++){let Pi=blockSize32*pi;for(let i=0;i<blockSize32;i++)V[i]=B32[Pi+i];for(let i=0,pos=0;i<N-1;i++)BlockMix(V,pos,V,pos+=blockSize32,r),blockMixCb();BlockMix(V,(N-1)*blockSize32,B32,Pi,r),blockMixCb();for(let i=0;i<N;i++){let j=(B32[Pi+blockSize32-16]&N-1)>>>0;for(let k=0;k<blockSize32;k++)tmp[k]=B32[Pi+k]^V[j*blockSize32+k];BlockMix(tmp,0,B32,Pi,r),blockMixCb()}}return swap32IfBE(B32),scryptOutput(password,dkLen,B,V,tmp)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function isBytes3(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in a&&a.BYTES_PER_ELEMENT===1}var atitle2=(title)=>title?`"${title}" `:"";function abool(value,title=""){if(typeof value!=="boolean")throw TypeError(atitle2(title)+"expected boolean, got type="+typeof value);return value}function anumber3(n,title=""){if(typeof n!=="number")throw TypeError(atitle2(title)+"expected number, got "+typeof n);if(!Number.isSafeInteger(n)||n<0)throw RangeError(atitle2(title)+"expected integer >= 0, got "+n);return n}function abytes3(value,length,title=""){if(isBytes3(value)&&(length===void 0||value.length===length))return value;if(length!==void 0)anumber3(length,"length");let bytes=isBytes3(value),ofLen=length!==void 0?` of length ${length}`:"",got=bytes?`length=${value.length}`:`type=${typeof value}`,message=atitle2(title)+"expected Uint8Array"+ofLen+", got "+got;if(!bytes)throw TypeError(message);throw RangeError(message)}var aobject2=(value,label)=>{if(value===null||typeof value!=="object"||Array.isArray(value))throw TypeError(label==="object"?"expected valid options object":`"${label}" expected object, got type=${typeof value}`)};function aexists2(instance,checkFinished=!0){if(instance.destroyed)throw Error("hash was destroyed");if(checkFinished&&instance.finished)throw Error("digest() was already called")}function aoutput2(out,instance){abytes3(out,void 0,"output");let min=instance.outputLen;if(!(out.length>=min))throw RangeError('"output" expected length >= '+min)}function u322(arr){return new Uint32Array(arr.buffer,arr.byteOffset,Math.floor(arr.byteLength/4))}function clean2(...arrays){for(let i=0;i<arrays.length;i++)arrays[i].fill(0)}function createView2(arr){return new DataView(arr.buffer,arr.byteOffset,arr.byteLength)}var isLE2=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function byteSwap2(word){return word<<24&4278190080|word<<8&16711680|word>>>8&65280|word>>>24&255}function byteSwap322(arr){for(let i=0;i<arr.length;i++)arr[i]=byteSwap2(arr[i]);return arr}var swap32IfBE2=isLE2?(u)=>u:byteSwap322;function overlapBytes(a,b){if(!a.byteLength||!b.byteLength)return!1;return a.buffer===b.buffer&&a.byteOffset<b.byteOffset+b.byteLength&&b.byteOffset<a.byteOffset+a.byteLength}function complexOverlapBytes(input,output){if(overlapBytes(input,output)&&input.byteOffset<output.byteOffset)throw Error("complex overlap of input and output is not supported")}function checkOpts2(defaults,opts){return aobject2(defaults,"defaults"),aobject2(opts,"opts"),Object.assign(defaults,opts)}function equalBytes(a,b){if(a=abytes3(a),b=abytes3(b),a.length!==b.length)return!1;let diff=0;for(let i=0;i<a.length;i++)diff|=a[i]^b[i];return diff===0}function wrapMacConstructor(keyLen,macCons,fromMsg){let mac=macCons,getArgs=fromMsg||(()=>[]),macC=(msg,key)=>mac(key,...getArgs(msg)).update(msg).digest(),tmp=mac(new Uint8Array(keyLen),...getArgs(new Uint8Array(0)));return macC.outputLen=tmp.outputLen,macC.blockLen=tmp.blockLen,macC.create=(key,...args)=>mac(key,...args),macC}var wrapCipher=(params,constructor)=>{function wrappedCipher(key,...args){if(abytes3(key,void 0,"key"),params.nonceLength!==void 0){let nonce=args[0];abytes3(nonce,params.varSizeNonce?void 0:params.nonceLength,"nonce")}let tagl=params.tagLength,aadStart=params.nonceLength!==void 0?1:0;if(!params.withAAD){for(let i=aadStart;i<args.length;i++)if(isBytes3(args[i]))throw Error("AAD not supported")}if(params.withAAD&&args[aadStart]!==void 0)abytes3(args[aadStart],void 0,"AAD");let cipher=constructor(key,...args),checkOutput=(fnLength,output)=>{if(output!==void 0){if(fnLength!==2)throw Error("cipher output not supported");abytes3(output,void 0,"output")}},called=!1;return{encrypt(data,output){if(called)throw Error("cannot encrypt() twice with same key + nonce");return called=!0,abytes3(data,void 0,"data"),checkOutput(cipher.encrypt.length,output),cipher.encrypt(data,output)},decrypt(data,output){if(abytes3(data,void 0,"data"),tagl&&data.length<tagl)throw Error('"ciphertext" expected length >= tagLength='+tagl);return checkOutput(cipher.decrypt.length,output),cipher.decrypt(data,output)}}}return Object.assign(wrappedCipher,params),wrappedCipher};function getOutput(expectedLength,out,onlyAligned=!0){if(out===void 0)return new Uint8Array(expectedLength);if(abytes3(out,expectedLength,"output"),onlyAligned&&!isAligned32(out))throw Error("invalid output, must be aligned");return out}function u64Lengths(dataLength,aadLength,isLE3){anumber3(dataLength),anumber3(aadLength),abool(isLE3);let num=new Uint8Array(16),view=createView2(num);return view.setBigUint64(0,BigInt(aadLength),isLE3),view.setBigUint64(8,BigInt(dataLength),isLE3),num}function isAligned32(bytes){return bytes.byteOffset%4===0}function copyBytes(bytes){return Uint8Array.from(abytes3(bytes))}var encodeStr=(str)=>Uint8Array.from(str.split(""),(c)=>c.charCodeAt(0)),sigma16_32=(()=>swap32IfBE2(u322(encodeStr("expand 16-byte k"))))(),sigma32_32=(()=>swap32IfBE2(u322(encodeStr("expand 32-byte k"))))();function rotl2(a,b){return a<<b|a>>>32-b}var BLOCK_LEN=64,BLOCK_LEN32=16,MAX_COUNTER=(()=>4294967295)(),U32_EMPTY=Uint32Array.of();function runCipher(core,sigma,key,nonce,data,output,counter,rounds){let len=data.length,block=new Uint8Array(BLOCK_LEN),b32=u322(block),isAligned=isLE2&&isAligned32(data)&&isAligned32(output),d32=isAligned?u322(data):U32_EMPTY,o32=isAligned?u322(output):U32_EMPTY;if(!isLE2){for(let pos=0;pos<len;counter++){if(core(sigma,key,nonce,b32,counter,rounds),swap32IfBE2(b32),counter>=MAX_COUNTER)throw Error("arx: counter overflow");let take=Math.min(BLOCK_LEN,len-pos);for(let j=0,posj;j<take;j++)posj=pos+j,output[posj]=data[posj]^block[j];pos+=take}return}for(let pos=0;pos<len;counter++){if(core(sigma,key,nonce,b32,counter,rounds),counter>=MAX_COUNTER)throw Error("arx: counter overflow");let take=Math.min(BLOCK_LEN,len-pos);if(isAligned&&take===BLOCK_LEN){let pos32=pos/4;if(pos%4!==0)throw Error("arx: invalid block position");for(let j=0,posj;j<BLOCK_LEN32;j++)posj=pos32+j,o32[posj]=d32[posj]^b32[j];pos+=BLOCK_LEN;continue}for(let j=0,posj;j<take;j++)posj=pos+j,output[posj]=data[posj]^block[j];pos+=take}}function createCipher(core,opts){let{allowShortKeys,extendNonceFn,counterLength,counterRight,rounds}=checkOpts2({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},opts);if(typeof core!=="function")throw Error("core must be a function");return anumber3(counterLength),anumber3(rounds),abool(counterRight),abool(allowShortKeys),(key,nonce,data,output,counter=0)=>{abytes3(key,void 0,"key"),abytes3(nonce,void 0,"nonce"),abytes3(data,void 0,"data");let len=data.length,hasOutput=output!==void 0;if(output=getOutput(len,output,!1),hasOutput)complexOverlapBytes(data,output);if(anumber3(counter),counter<0||counter>=MAX_COUNTER)throw Error("arx: counter overflow");let toClean=[],l=key.length,k,sigma;if(l===32)toClean.push(k=copyBytes(key)),sigma=sigma32_32;else if(l===16&&allowShortKeys)k=new Uint8Array(32),k.set(key),k.set(key,16),sigma=sigma16_32,toClean.push(k);else throw abytes3(key,32,"arx key"),Error("invalid key size");if(!isLE2||!isAligned32(nonce))toClean.push(nonce=copyBytes(nonce));let k32=u322(k);if(extendNonceFn){if(nonce.length!==24)throw Error("arx: extended nonce must be 24 bytes");let n16=nonce.subarray(0,16);if(isLE2)extendNonceFn(sigma,k32,u322(n16),k32);else{let sigmaRaw=swap32IfBE2(Uint32Array.from(sigma));extendNonceFn(sigmaRaw,k32,u322(n16),k32),clean2(sigmaRaw),swap32IfBE2(k32)}nonce=nonce.subarray(16)}else if(!isLE2)swap32IfBE2(k32);let nonceNcLen=16-counterLength;if(nonceNcLen!==nonce.length)throw Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);if(nonceNcLen!==12){let nc=new Uint8Array(12);nc.set(nonce,counterRight?0:12-nonce.length),nonce=nc,toClean.push(nonce)}let n32=swap32IfBE2(u322(nonce));try{return runCipher(core,sigma,k32,n32,data,output,counter,rounds),output}finally{clean2(...toClean)}}}function u8to16(a,i){return a[i++]&255|(a[i++]&255)<<8}class Poly1305{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(key){key=copyBytes(abytes3(key,32,"key"));let t0=u8to16(key,0),t1=u8to16(key,2),t2=u8to16(key,4),t3=u8to16(key,6),t4=u8to16(key,8),t5=u8to16(key,10),t6=u8to16(key,12),t7=u8to16(key,14);this.r[0]=t0&8191,this.r[1]=(t0>>>13|t1<<3)&8191,this.r[2]=(t1>>>10|t2<<6)&7939,this.r[3]=(t2>>>7|t3<<9)&8191,this.r[4]=(t3>>>4|t4<<12)&255,this.r[5]=t4>>>1&8190,this.r[6]=(t4>>>14|t5<<2)&8191,this.r[7]=(t5>>>11|t6<<5)&8065,this.r[8]=(t6>>>8|t7<<8)&8191,this.r[9]=t7>>>5&127;for(let i=0;i<8;i++)this.pad[i]=u8to16(key,16+2*i)}process(data,offset,isLast=!1){let hibit=isLast?0:2048,{h,r}=this,r0=r[0],r1=r[1],r2=r[2],r3=r[3],r4=r[4],r5=r[5],r6=r[6],r7=r[7],r8=r[8],r9=r[9],t0=u8to16(data,offset+0),t1=u8to16(data,offset+2),t2=u8to16(data,offset+4),t3=u8to16(data,offset+6),t4=u8to16(data,offset+8),t5=u8to16(data,offset+10),t6=u8to16(data,offset+12),t7=u8to16(data,offset+14),h0=h[0]+(t0&8191),h1=h[1]+((t0>>>13|t1<<3)&8191),h2=h[2]+((t1>>>10|t2<<6)&8191),h3=h[3]+((t2>>>7|t3<<9)&8191),h4=h[4]+((t3>>>4|t4<<12)&8191),h5=h[5]+(t4>>>1&8191),h6=h[6]+((t4>>>14|t5<<2)&8191),h7=h[7]+((t5>>>11|t6<<5)&8191),h8=h[8]+((t6>>>8|t7<<8)&8191),h9=h[9]+(t7>>>5|hibit),c=0,d0=c+h0*r0+h1*(5*r9)+h2*(5*r8)+h3*(5*r7)+h4*(5*r6);c=d0>>>13,d0&=8191,d0+=h5*(5*r5)+h6*(5*r4)+h7*(5*r3)+h8*(5*r2)+h9*(5*r1),c+=d0>>>13,d0&=8191;let d1=c+h0*r1+h1*r0+h2*(5*r9)+h3*(5*r8)+h4*(5*r7);c=d1>>>13,d1&=8191,d1+=h5*(5*r6)+h6*(5*r5)+h7*(5*r4)+h8*(5*r3)+h9*(5*r2),c+=d1>>>13,d1&=8191;let d2=c+h0*r2+h1*r1+h2*r0+h3*(5*r9)+h4*(5*r8);c=d2>>>13,d2&=8191,d2+=h5*(5*r7)+h6*(5*r6)+h7*(5*r5)+h8*(5*r4)+h9*(5*r3),c+=d2>>>13,d2&=8191;let d3=c+h0*r3+h1*r2+h2*r1+h3*r0+h4*(5*r9);c=d3>>>13,d3&=8191,d3+=h5*(5*r8)+h6*(5*r7)+h7*(5*r6)+h8*(5*r5)+h9*(5*r4),c+=d3>>>13,d3&=8191;let d4=c+h0*r4+h1*r3+h2*r2+h3*r1+h4*r0;c=d4>>>13,d4&=8191,d4+=h5*(5*r9)+h6*(5*r8)+h7*(5*r7)+h8*(5*r6)+h9*(5*r5),c+=d4>>>13,d4&=8191;let d5=c+h0*r5+h1*r4+h2*r3+h3*r2+h4*r1;c=d5>>>13,d5&=8191,d5+=h5*r0+h6*(5*r9)+h7*(5*r8)+h8*(5*r7)+h9*(5*r6),c+=d5>>>13,d5&=8191;let d6=c+h0*r6+h1*r5+h2*r4+h3*r3+h4*r2;c=d6>>>13,d6&=8191,d6+=h5*r1+h6*r0+h7*(5*r9)+h8*(5*r8)+h9*(5*r7),c+=d6>>>13,d6&=8191;let d7=c+h0*r7+h1*r6+h2*r5+h3*r4+h4*r3;c=d7>>>13,d7&=8191,d7+=h5*r2+h6*r1+h7*r0+h8*(5*r9)+h9*(5*r8),c+=d7>>>13,d7&=8191;let d8=c+h0*r8+h1*r7+h2*r6+h3*r5+h4*r4;c=d8>>>13,d8&=8191,d8+=h5*r3+h6*r2+h7*r1+h8*r0+h9*(5*r9),c+=d8>>>13,d8&=8191;let d9=c+h0*r9+h1*r8+h2*r7+h3*r6+h4*r5;c=d9>>>13,d9&=8191,d9+=h5*r4+h6*r3+h7*r2+h8*r1+h9*r0,c+=d9>>>13,d9&=8191,c=(c<<2)+c|0,c=c+d0|0,d0=c&8191,c=c>>>13,d1+=c,h[0]=d0,h[1]=d1,h[2]=d2,h[3]=d3,h[4]=d4,h[5]=d5,h[6]=d6,h[7]=d7,h[8]=d8,h[9]=d9}finalize(){let{h,pad}=this,g=new Uint16Array(10),c=h[1]>>>13;h[1]&=8191;for(let i=2;i<10;i++)h[i]+=c,c=h[i]>>>13,h[i]&=8191;h[0]+=c*5,c=h[0]>>>13,h[0]&=8191,h[1]+=c,c=h[1]>>>13,h[1]&=8191,h[2]+=c,g[0]=h[0]+5,c=g[0]>>>13,g[0]&=8191;for(let i=1;i<10;i++)g[i]=h[i]+c,c=g[i]>>>13,g[i]&=8191;g[9]-=8192;let mask=(c^1)-1;for(let i=0;i<10;i++)g[i]&=mask;mask=~mask;for(let i=0;i<10;i++)h[i]=h[i]&mask|g[i];h[0]=(h[0]|h[1]<<13)&65535,h[1]=(h[1]>>>3|h[2]<<10)&65535,h[2]=(h[2]>>>6|h[3]<<7)&65535,h[3]=(h[3]>>>9|h[4]<<4)&65535,h[4]=(h[4]>>>12|h[5]<<1|h[6]<<14)&65535,h[5]=(h[6]>>>2|h[7]<<11)&65535,h[6]=(h[7]>>>5|h[8]<<8)&65535,h[7]=(h[8]>>>8|h[9]<<5)&65535;let f=h[0]+pad[0];h[0]=f&65535;for(let i=1;i<8;i++)f=(h[i]+pad[i]|0)+(f>>>16)|0,h[i]=f&65535;clean2(g)}update(data){aexists2(this),abytes3(data),data=copyBytes(data);let{buffer,blockLen}=this,len=data.length;for(let pos=0;pos<len;){let take=Math.min(blockLen-this.pos,len-pos);if(take===blockLen){for(;blockLen<=len-pos;pos+=blockLen)this.process(data,pos);continue}if(buffer.set(data.subarray(pos,pos+take),this.pos),this.pos+=take,pos+=take,this.pos===blockLen)this.process(buffer,0,!1),this.pos=0}return this}destroy(){this.destroyed=!0,clean2(this.h,this.r,this.buffer,this.pad)}digestInto(out){aexists2(this),aoutput2(out,this),this.finished=!0;let{buffer,h}=this,{pos}=this;if(pos){buffer[pos++]=1;for(;pos<16;pos++)buffer[pos]=0;this.process(buffer,0,!0)}this.finalize();let opos=0;for(let i=0;i<8;i++)out[opos++]=h[i]>>>0,out[opos++]=h[i]>>>8}digest(){let{buffer,outputLen}=this;this.digestInto(buffer);let res=buffer.slice(0,outputLen);return this.destroy(),res}}var poly1305=wrapMacConstructor(32,(key)=>new Poly1305(key));function chachaCore(s,k,n,out,cnt,rounds=20){let y00=s[0],y01=s[1],y02=s[2],y03=s[3],y04=k[0],y05=k[1],y06=k[2],y07=k[3],y08=k[4],y09=k[5],y10=k[6],y11=k[7],y12=cnt,y13=n[0],y14=n[1],y15=n[2],x00=y00,x01=y01,x02=y02,x03=y03,x04=y04,x05=y05,x06=y06,x07=y07,x08=y08,x09=y09,x10=y10,x11=y11,x12=y12,x13=y13,x14=y14,x15=y15;for(let r=0;r<rounds;r+=2)x00=x00+x04|0,x12=rotl2(x12^x00,16),x08=x08+x12|0,x04=rotl2(x04^x08,12),x00=x00+x04|0,x12=rotl2(x12^x00,8),x08=x08+x12|0,x04=rotl2(x04^x08,7),x01=x01+x05|0,x13=rotl2(x13^x01,16),x09=x09+x13|0,x05=rotl2(x05^x09,12),x01=x01+x05|0,x13=rotl2(x13^x01,8),x09=x09+x13|0,x05=rotl2(x05^x09,7),x02=x02+x06|0,x14=rotl2(x14^x02,16),x10=x10+x14|0,x06=rotl2(x06^x10,12),x02=x02+x06|0,x14=rotl2(x14^x02,8),x10=x10+x14|0,x06=rotl2(x06^x10,7),x03=x03+x07|0,x15=rotl2(x15^x03,16),x11=x11+x15|0,x07=rotl2(x07^x11,12),x03=x03+x07|0,x15=rotl2(x15^x03,8),x11=x11+x15|0,x07=rotl2(x07^x11,7),x00=x00+x05|0,x15=rotl2(x15^x00,16),x10=x10+x15|0,x05=rotl2(x05^x10,12),x00=x00+x05|0,x15=rotl2(x15^x00,8),x10=x10+x15|0,x05=rotl2(x05^x10,7),x01=x01+x06|0,x12=rotl2(x12^x01,16),x11=x11+x12|0,x06=rotl2(x06^x11,12),x01=x01+x06|0,x12=rotl2(x12^x01,8),x11=x11+x12|0,x06=rotl2(x06^x11,7),x02=x02+x07|0,x13=rotl2(x13^x02,16),x08=x08+x13|0,x07=rotl2(x07^x08,12),x02=x02+x07|0,x13=rotl2(x13^x02,8),x08=x08+x13|0,x07=rotl2(x07^x08,7),x03=x03+x04|0,x14=rotl2(x14^x03,16),x09=x09+x14|0,x04=rotl2(x04^x09,12),x03=x03+x04|0,x14=rotl2(x14^x03,8),x09=x09+x14|0,x04=rotl2(x04^x09,7);let oi=0;out[oi++]=y00+x00|0,out[oi++]=y01+x01|0,out[oi++]=y02+x02|0,out[oi++]=y03+x03|0,out[oi++]=y04+x04|0,out[oi++]=y05+x05|0,out[oi++]=y06+x06|0,out[oi++]=y07+x07|0,out[oi++]=y08+x08|0,out[oi++]=y09+x09|0,out[oi++]=y10+x10|0,out[oi++]=y11+x11|0,out[oi++]=y12+x12|0,out[oi++]=y13+x13|0,out[oi++]=y14+x14|0,out[oi++]=y15+x15|0}var chacha20=createCipher(chachaCore,{counterRight:!1,counterLength:4,allowShortKeys:!1});var ZEROS16=new Uint8Array(16),updatePadded=(h,msg)=>{h.update(msg);let leftover=msg.length%16;if(leftover)h.update(ZEROS16.subarray(leftover))},ZEROS32=new Uint8Array(32);function computeTag(fn,key,nonce,ciphertext,AAD){if(AAD!==void 0)abytes3(AAD,void 0,"AAD");let authKey=fn(key,nonce,ZEROS32),lengths=u64Lengths(ciphertext.length,AAD?AAD.length:0,!0),h=poly1305.create(authKey);if(AAD)updatePadded(h,AAD);updatePadded(h,ciphertext),h.update(lengths);let res=h.digest();return clean2(authKey,lengths),res}var _poly1305_aead=(xorStream)=>(key,nonce,AAD)=>{return{encrypt(plaintext,output){let plength=plaintext.length;output=getOutput(plength+16,output,!1),output.set(plaintext);let oPlain=output.subarray(0,-16);xorStream(key,nonce,oPlain,oPlain,1);let tag=computeTag(xorStream,key,nonce,oPlain,AAD);return output.set(tag,plength),clean2(tag),output},decrypt(ciphertext,output){output=getOutput(ciphertext.length-16,output,!1);let data=ciphertext.subarray(0,-16),passedTag=ciphertext.subarray(-16),tag=computeTag(xorStream,key,nonce,data,AAD);if(!equalBytes(passedTag,tag))throw clean2(tag),Error("invalid tag");return output.set(ciphertext.subarray(0,-16)),xorStream(key,nonce,output,output,1),clean2(tag),output}}},chacha20poly1305=wrapCipher({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},_poly1305_aead(chacha20));/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function isBytes4(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"}function anumber4(n,title=""){if(!Number.isSafeInteger(n)||n<0){let prefix=title&&`"${title}" `;throw Error(`${prefix}expected integer >= 0, got ${n}`)}}function abytes4(value,length,title=""){let bytes=isBytes4(value),len=value?.length,needsLen=length!==void 0;if(!bytes||needsLen&&len!==length){let prefix=title&&`"${title}" `,ofLen=needsLen?` of length ${length}`:"",got=bytes?`length=${len}`:`type=${typeof value}`;throw Error(prefix+"expected Uint8Array"+ofLen+", got "+got)}return value}function ahash2(h){if(typeof h!=="function"||typeof h.create!=="function")throw Error("Hash must wrapped by utils.createHasher");anumber4(h.outputLen),anumber4(h.blockLen)}function aexists3(instance,checkFinished=!0){if(instance.destroyed)throw Error("Hash instance has been destroyed");if(checkFinished&&instance.finished)throw Error("Hash#digest() has already been called")}function aoutput3(out,instance){abytes4(out,void 0,"digestInto() output");let min=instance.outputLen;if(out.length<min)throw Error('"digestInto() output" expected to be of length >='+min)}function u323(arr){return new Uint32Array(arr.buffer,arr.byteOffset,Math.floor(arr.byteLength/4))}function clean3(...arrays){for(let i=0;i<arrays.length;i++)arrays[i].fill(0)}function createView3(arr){return new DataView(arr.buffer,arr.byteOffset,arr.byteLength)}function rotr2(word,shift){return word<<32-shift|word>>>shift}var isLE3=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function byteSwap3(word){return word<<24&4278190080|word<<8&16711680|word>>>8&65280|word>>>24&255}function byteSwap323(arr){for(let i=0;i<arr.length;i++)arr[i]=byteSwap3(arr[i]);return arr}var swap32IfBE3=isLE3?(u)=>u:byteSwap323,hasHexBuiltin2=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),hexes2=Array.from({length:256},(_,i)=>i.toString(16).padStart(2,"0"));function bytesToHex2(bytes){if(abytes4(bytes),hasHexBuiltin2)return bytes.toHex();let hex="";for(let i=0;i<bytes.length;i++)hex+=hexes2[bytes[i]];return hex}var asciis={_0:48,_9:57,A:65,F:70,a:97,f:102};function asciiToBase162(ch){if(ch>=asciis._0&&ch<=asciis._9)return ch-asciis._0;if(ch>=asciis.A&&ch<=asciis.F)return ch-(asciis.A-10);if(ch>=asciis.a&&ch<=asciis.f)return ch-(asciis.a-10);return}function hexToBytes2(hex){if(typeof hex!=="string")throw Error("hex string expected, got "+typeof hex);if(hasHexBuiltin2)return Uint8Array.fromHex(hex);let hl=hex.length,al=hl/2;if(hl%2)throw Error("hex string expected, got unpadded hex of length "+hl);let array=new Uint8Array(al);for(let ai=0,hi=0;ai<al;ai++,hi+=2){let n1=asciiToBase162(hex.charCodeAt(hi)),n2=asciiToBase162(hex.charCodeAt(hi+1));if(n1===void 0||n2===void 0){let char=hex[hi]+hex[hi+1];throw Error('hex string expected, got non-hex character "'+char+'" at index '+hi)}array[ai]=n1*16+n2}return array}function concatBytes2(...arrays){let sum=0;for(let i=0;i<arrays.length;i++){let a=arrays[i];abytes4(a),sum+=a.length}let res=new Uint8Array(sum);for(let i=0,pad=0;i<arrays.length;i++){let a=arrays[i];res.set(a,pad),pad+=a.length}return res}function createHasher2(hashCons,info={}){let hashC=(msg,opts)=>hashCons(opts).update(msg).digest(),tmp=hashCons(void 0);return hashC.outputLen=tmp.outputLen,hashC.blockLen=tmp.blockLen,hashC.create=(opts)=>hashCons(opts),Object.assign(hashC,info),Object.freeze(hashC)}function randomBytes3(bytesLength=32){let cr=typeof globalThis==="object"?globalThis.crypto:null;if(typeof cr?.getRandomValues!=="function")throw Error("crypto.getRandomValues must be defined");return cr.getRandomValues(new Uint8Array(bytesLength))}var oidNist2=(suffix)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,suffix])});/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var _0n=BigInt(0),_1n=BigInt(1);function abool2(value,title=""){if(typeof value!=="boolean"){let prefix=title&&`"${title}" `;throw Error(prefix+"expected boolean, got type="+typeof value)}return value}function abignumber(n){if(typeof n==="bigint"){if(!isPosBig(n))throw Error("positive bigint expected, got "+n)}else anumber4(n);return n}function numberToHexUnpadded(num){let hex=abignumber(num).toString(16);return hex.length&1?"0"+hex:hex}function hexToNumber(hex){if(typeof hex!=="string")throw Error("hex string expected, got "+typeof hex);return hex===""?_0n:BigInt("0x"+hex)}function bytesToNumberBE(bytes){return hexToNumber(bytesToHex2(bytes))}function bytesToNumberLE(bytes){return hexToNumber(bytesToHex2(copyBytes2(abytes4(bytes)).reverse()))}function numberToBytesBE(n,len){anumber4(len),n=abignumber(n);let res=hexToBytes2(n.toString(16).padStart(len*2,"0"));if(res.length!==len)throw Error("number too large");return res}function numberToBytesLE(n,len){return numberToBytesBE(n,len).reverse()}function copyBytes2(bytes){return Uint8Array.from(bytes)}function asciiToBytes(ascii){return Uint8Array.from(ascii,(c,i)=>{let charCode=c.charCodeAt(0);if(c.length!==1||charCode>127)throw Error(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);return charCode})}var isPosBig=(n)=>typeof n==="bigint"&&_0n<=n;function inRange(n,min,max){return isPosBig(n)&&isPosBig(min)&&isPosBig(max)&&min<=n&&n<max}function aInRange(title,n,min,max){if(!inRange(n,min,max))throw Error("expected valid "+title+": "+min+" <= n < "+max+", got "+n)}function bitLen(n){let len;for(len=0;n>_0n;n>>=_1n,len+=1);return len}var bitMask=(n)=>(_1n<<BigInt(n))-_1n;function createHmacDrbg(hashLen,qByteLen,hmacFn){if(anumber4(hashLen,"hashLen"),anumber4(qByteLen,"qByteLen"),typeof hmacFn!=="function")throw Error("hmacFn must be a function");let u8n=(len)=>new Uint8Array(len),NULL=Uint8Array.of(),byte0=Uint8Array.of(0),byte1=Uint8Array.of(1),_maxDrbgIters=1000,v=u8n(hashLen),k=u8n(hashLen),i=0,reset=()=>{v.fill(1),k.fill(0),i=0},h=(...msgs)=>hmacFn(k,concatBytes2(v,...msgs)),reseed=(seed=NULL)=>{if(k=h(byte0,seed),v=h(),seed.length===0)return;k=h(byte1,seed),v=h()},gen=()=>{if(i++>=_maxDrbgIters)throw Error("drbg: tried max amount of iterations");let len=0,out=[];while(len<qByteLen){v=h();let sl=v.slice();out.push(sl),len+=v.length}return concatBytes2(...out)};return(seed,pred)=>{reset(),reseed(seed);let res=void 0;while(!(res=pred(gen())))reseed();return reset(),res}}function validateObject(object,fields={},optFields={}){if(!object||typeof object!=="object")throw Error("expected valid options object");function checkField(fieldName,expectedType,isOpt){let val=object[fieldName];if(isOpt&&val===void 0)return;let current=typeof val;if(current!==expectedType||val===null)throw Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`)}let iter=(f,isOpt)=>Object.entries(f).forEach(([k,v])=>checkField(k,v,isOpt));iter(fields,!1),iter(optFields,!0)}function memoized(fn){let map=new WeakMap;return(arg,...args)=>{let val=map.get(arg);if(val!==void 0)return val;let computed=fn(arg,...args);return map.set(arg,computed),computed}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var _0n2=BigInt(0),_1n2=BigInt(1),_2n=BigInt(2),_3n=BigInt(3),_4n=BigInt(4),_5n=BigInt(5),_7n=BigInt(7),_8n=BigInt(8),_9n=BigInt(9),_16n=BigInt(16);function mod(a,b){let result=a%b;return result>=_0n2?result:b+result}function pow2(x,power,modulo){let res=x;while(power-- >_0n2)res*=res,res%=modulo;return res}function invert(number,modulo){if(number===_0n2)throw Error("invert: expected non-zero number");if(modulo<=_0n2)throw Error("invert: expected positive modulus, got "+modulo);let a=mod(number,modulo),b=modulo,x=_0n2,y=_1n2,u=_1n2,v=_0n2;while(a!==_0n2){let q=b/a,r=b%a,m=x-u*q,n=y-v*q;b=a,a=r,x=u,y=v,u=m,v=n}if(b!==_1n2)throw Error("invert: does not exist");return mod(x,modulo)}function assertIsSquare(Fp,root,n){if(!Fp.eql(Fp.sqr(root),n))throw Error("Cannot find square root")}function sqrt3mod4(Fp,n){let p1div4=(Fp.ORDER+_1n2)/_4n,root=Fp.pow(n,p1div4);return assertIsSquare(Fp,root,n),root}function sqrt5mod8(Fp,n){let p5div8=(Fp.ORDER-_5n)/_8n,n2=Fp.mul(n,_2n),v=Fp.pow(n2,p5div8),nv=Fp.mul(n,v),i=Fp.mul(Fp.mul(nv,_2n),v),root=Fp.mul(nv,Fp.sub(i,Fp.ONE));return assertIsSquare(Fp,root,n),root}function sqrt9mod16(P){let Fp_=Field(P),tn=tonelliShanks(P),c1=tn(Fp_,Fp_.neg(Fp_.ONE)),c2=tn(Fp_,c1),c3=tn(Fp_,Fp_.neg(c1)),c4=(P+_7n)/_16n;return(Fp,n)=>{let tv1=Fp.pow(n,c4),tv2=Fp.mul(tv1,c1),tv3=Fp.mul(tv1,c2),tv4=Fp.mul(tv1,c3),e1=Fp.eql(Fp.sqr(tv2),n),e2=Fp.eql(Fp.sqr(tv3),n);tv1=Fp.cmov(tv1,tv2,e1),tv2=Fp.cmov(tv4,tv3,e2);let e3=Fp.eql(Fp.sqr(tv2),n),root=Fp.cmov(tv1,tv2,e3);return assertIsSquare(Fp,root,n),root}}function tonelliShanks(P){if(P<_3n)throw Error("sqrt is not defined for small field");let Q=P-_1n2,S=0;while(Q%_2n===_0n2)Q/=_2n,S++;let Z=_2n,_Fp=Field(P);while(FpLegendre(_Fp,Z)===1)if(Z++>1000)throw Error("Cannot find square root: probably non-prime P");if(S===1)return sqrt3mod4;let cc=_Fp.pow(Z,Q),Q1div2=(Q+_1n2)/_2n;return function(Fp,n){if(Fp.is0(n))return n;if(FpLegendre(Fp,n)!==1)throw Error("Cannot find square root");let M=S,c=Fp.mul(Fp.ONE,cc),t=Fp.pow(n,Q),R=Fp.pow(n,Q1div2);while(!Fp.eql(t,Fp.ONE)){if(Fp.is0(t))return Fp.ZERO;let i=1,t_tmp=Fp.sqr(t);while(!Fp.eql(t_tmp,Fp.ONE))if(i++,t_tmp=Fp.sqr(t_tmp),i===M)throw Error("Cannot find square root");let exponent=_1n2<<BigInt(M-i-1),b=Fp.pow(c,exponent);M=i,c=Fp.sqr(b),t=Fp.mul(t,c),R=Fp.mul(R,b)}return R}}function FpSqrt(P){if(P%_4n===_3n)return sqrt3mod4;if(P%_8n===_5n)return sqrt5mod8;if(P%_16n===_9n)return sqrt9mod16(P);return tonelliShanks(P)}var FIELD_FIELDS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function validateField(field){let initial={ORDER:"bigint",BYTES:"number",BITS:"number"},opts=FIELD_FIELDS.reduce((map,val)=>{return map[val]="function",map},initial);return validateObject(field,opts),field}function FpPow(Fp,num,power){if(power<_0n2)throw Error("invalid exponent, negatives unsupported");if(power===_0n2)return Fp.ONE;if(power===_1n2)return num;let p=Fp.ONE,d=num;while(power>_0n2){if(power&_1n2)p=Fp.mul(p,d);d=Fp.sqr(d),power>>=_1n2}return p}function FpInvertBatch(Fp,nums,passZero=!1){let inverted=Array(nums.length).fill(passZero?Fp.ZERO:void 0),multipliedAcc=nums.reduce((acc,num,i)=>{if(Fp.is0(num))return acc;return inverted[i]=acc,Fp.mul(acc,num)},Fp.ONE),invertedAcc=Fp.inv(multipliedAcc);return nums.reduceRight((acc,num,i)=>{if(Fp.is0(num))return acc;return inverted[i]=Fp.mul(acc,inverted[i]),Fp.mul(acc,num)},invertedAcc),inverted}function FpLegendre(Fp,n){let p1mod2=(Fp.ORDER-_1n2)/_2n,powered=Fp.pow(n,p1mod2),yes=Fp.eql(powered,Fp.ONE),zero=Fp.eql(powered,Fp.ZERO),no=Fp.eql(powered,Fp.neg(Fp.ONE));if(!yes&&!zero&&!no)throw Error("invalid Legendre symbol result");return yes?1:zero?0:-1}function nLength(n,nBitLength){if(nBitLength!==void 0)anumber4(nBitLength);let _nBitLength=nBitLength!==void 0?nBitLength:n.toString(2).length,nByteLength=Math.ceil(_nBitLength/8);return{nBitLength:_nBitLength,nByteLength}}class _Field{ORDER;BITS;BYTES;isLE;ZERO=_0n2;ONE=_1n2;_lengths;_sqrt;_mod;constructor(ORDER,opts={}){if(ORDER<=_0n2)throw Error("invalid field: expected ORDER > 0, got "+ORDER);let _nbitLength=void 0;if(this.isLE=!1,opts!=null&&typeof opts==="object"){if(typeof opts.BITS==="number")_nbitLength=opts.BITS;if(typeof opts.sqrt==="function")this.sqrt=opts.sqrt;if(typeof opts.isLE==="boolean")this.isLE=opts.isLE;if(opts.allowedLengths)this._lengths=opts.allowedLengths?.slice();if(typeof opts.modFromBytes==="boolean")this._mod=opts.modFromBytes}let{nBitLength,nByteLength}=nLength(ORDER,_nbitLength);if(nByteLength>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=ORDER,this.BITS=nBitLength,this.BYTES=nByteLength,this._sqrt=void 0,Object.preventExtensions(this)}create(num){return mod(num,this.ORDER)}isValid(num){if(typeof num!=="bigint")throw Error("invalid field element: expected bigint, got "+typeof num);return _0n2<=num&&num<this.ORDER}is0(num){return num===_0n2}isValidNot0(num){return!this.is0(num)&&this.isValid(num)}isOdd(num){return(num&_1n2)===_1n2}neg(num){return mod(-num,this.ORDER)}eql(lhs,rhs){return lhs===rhs}sqr(num){return mod(num*num,this.ORDER)}add(lhs,rhs){return mod(lhs+rhs,this.ORDER)}sub(lhs,rhs){return mod(lhs-rhs,this.ORDER)}mul(lhs,rhs){return mod(lhs*rhs,this.ORDER)}pow(num,power){return FpPow(this,num,power)}div(lhs,rhs){return mod(lhs*invert(rhs,this.ORDER),this.ORDER)}sqrN(num){return num*num}addN(lhs,rhs){return lhs+rhs}subN(lhs,rhs){return lhs-rhs}mulN(lhs,rhs){return lhs*rhs}inv(num){return invert(num,this.ORDER)}sqrt(num){if(!this._sqrt)this._sqrt=FpSqrt(this.ORDER);return this._sqrt(this,num)}toBytes(num){return this.isLE?numberToBytesLE(num,this.BYTES):numberToBytesBE(num,this.BYTES)}fromBytes(bytes,skipValidation=!1){abytes4(bytes);let{_lengths:allowedLengths,BYTES,isLE:isLE4,ORDER,_mod:modFromBytes}=this;if(allowedLengths){if(!allowedLengths.includes(bytes.length)||bytes.length>BYTES)throw Error("Field.fromBytes: expected "+allowedLengths+" bytes, got "+bytes.length);let padded=new Uint8Array(BYTES);padded.set(bytes,isLE4?0:padded.length-bytes.length),bytes=padded}if(bytes.length!==BYTES)throw Error("Field.fromBytes: expected "+BYTES+" bytes, got "+bytes.length);let scalar=isLE4?bytesToNumberLE(bytes):bytesToNumberBE(bytes);if(modFromBytes)scalar=mod(scalar,ORDER);if(!skipValidation){if(!this.isValid(scalar))throw Error("invalid field element: outside of range 0..ORDER")}return scalar}invertBatch(lst){return FpInvertBatch(this,lst)}cmov(a,b,condition){return condition?b:a}}function Field(ORDER,opts={}){return new _Field(ORDER,opts)}function getFieldBytesLength(fieldOrder){if(typeof fieldOrder!=="bigint")throw Error("field order must be bigint");let bitLength=fieldOrder.toString(2).length;return Math.ceil(bitLength/8)}function getMinHashLength(fieldOrder){let length=getFieldBytesLength(fieldOrder);return length+Math.ceil(length/2)}function mapHashToField(key,fieldOrder,isLE4=!1){abytes4(key);let len=key.length,fieldLen=getFieldBytesLength(fieldOrder),minLen=getMinHashLength(fieldOrder);if(len<16||len<minLen||len>1024)throw Error("expected "+minLen+"-1024 bytes of input, got "+len);let num=isLE4?bytesToNumberLE(key):bytesToNumberBE(key),reduced=mod(num,fieldOrder-_1n2)+_1n2;return isLE4?numberToBytesLE(reduced,fieldLen):numberToBytesBE(reduced,fieldLen)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var _0n3=BigInt(0),_1n3=BigInt(1);function negateCt(condition,item){let neg=item.negate();return condition?neg:item}function normalizeZ(c,points){let invertedZs=FpInvertBatch(c.Fp,points.map((p)=>p.Z));return points.map((p,i)=>c.fromAffine(p.toAffine(invertedZs[i])))}function validateW(W,bits){if(!Number.isSafeInteger(W)||W<=0||W>bits)throw Error("invalid window size, expected [1.."+bits+"], got W="+W)}function calcWOpts(W,scalarBits){validateW(W,scalarBits);let windows=Math.ceil(scalarBits/W)+1,windowSize=2**(W-1),maxNumber=2**W,mask=bitMask(W),shiftBy=BigInt(W);return{windows,windowSize,mask,maxNumber,shiftBy}}function calcOffsets(n,window2,wOpts){let{windowSize,mask,maxNumber,shiftBy}=wOpts,wbits=Number(n&mask),nextN=n>>shiftBy;if(wbits>windowSize)wbits-=maxNumber,nextN+=_1n3;let offsetStart=window2*windowSize,offset=offsetStart+Math.abs(wbits)-1,isZero=wbits===0,isNeg=wbits<0,isNegF=window2%2!==0;return{nextN,offset,isZero,isNeg,isNegF,offsetF:offsetStart}}var pointPrecomputes=new WeakMap,pointWindowSizes=new WeakMap;function getW(P){return pointWindowSizes.get(P)||1}function assert0(n){if(n!==_0n3)throw Error("invalid wNAF")}class wNAF{BASE;ZERO;Fn;bits;constructor(Point,bits){this.BASE=Point.BASE,this.ZERO=Point.ZERO,this.Fn=Point.Fn,this.bits=bits}_unsafeLadder(elm,n,p=this.ZERO){let d=elm;while(n>_0n3){if(n&_1n3)p=p.add(d);d=d.double(),n>>=_1n3}return p}precomputeWindow(point,W){let{windows,windowSize}=calcWOpts(W,this.bits),points=[],p=point,base=p;for(let window2=0;window2<windows;window2++){base=p,points.push(base);for(let i=1;i<windowSize;i++)base=base.add(p),points.push(base);p=base.double()}return points}wNAF(W,precomputes,n){if(!this.Fn.isValid(n))throw Error("invalid scalar");let p=this.ZERO,f=this.BASE,wo=calcWOpts(W,this.bits);for(let window2=0;window2<wo.windows;window2++){let{nextN,offset,isZero,isNeg,isNegF,offsetF}=calcOffsets(n,window2,wo);if(n=nextN,isZero)f=f.add(negateCt(isNegF,precomputes[offsetF]));else p=p.add(negateCt(isNeg,precomputes[offset]))}return assert0(n),{p,f}}wNAFUnsafe(W,precomputes,n,acc=this.ZERO){let wo=calcWOpts(W,this.bits);for(let window2=0;window2<wo.windows;window2++){if(n===_0n3)break;let{nextN,offset,isZero,isNeg}=calcOffsets(n,window2,wo);if(n=nextN,isZero)continue;else{let item=precomputes[offset];acc=acc.add(isNeg?item.negate():item)}}return assert0(n),acc}getPrecomputes(W,point,transform){let comp=pointPrecomputes.get(point);if(!comp){if(comp=this.precomputeWindow(point,W),W!==1){if(typeof transform==="function")comp=transform(comp);pointPrecomputes.set(point,comp)}}return comp}cached(point,scalar,transform){let W=getW(point);return this.wNAF(W,this.getPrecomputes(W,point,transform),scalar)}unsafe(point,scalar,transform,prev){let W=getW(point);if(W===1)return this._unsafeLadder(point,scalar,prev);return this.wNAFUnsafe(W,this.getPrecomputes(W,point,transform),scalar,prev)}createCache(P,W){validateW(W,this.bits),pointWindowSizes.set(P,W),pointPrecomputes.delete(P)}hasCache(elm){return getW(elm)!==1}}function mulEndoUnsafe(Point,point,k1,k2){let acc=point,p1=Point.ZERO,p2=Point.ZERO;while(k1>_0n3||k2>_0n3){if(k1&_1n3)p1=p1.add(acc);if(k2&_1n3)p2=p2.add(acc);acc=acc.double(),k1>>=_1n3,k2>>=_1n3}return{p1,p2}}function createField(order,field,isLE4){if(field){if(field.ORDER!==order)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return validateField(field),field}else return Field(order,{isLE:isLE4})}function createCurveFields(type,CURVE,curveOpts={},FpFnLE){if(FpFnLE===void 0)FpFnLE=type==="edwards";if(!CURVE||typeof CURVE!=="object")throw Error(`expected valid ${type} CURVE object`);for(let p of["p","n","h"]){let val=CURVE[p];if(!(typeof val==="bigint"&&val>_0n3))throw Error(`CURVE.${p} must be positive bigint`)}let Fp=createField(CURVE.p,curveOpts.Fp,FpFnLE),Fn=createField(CURVE.n,curveOpts.Fn,FpFnLE),params=["Gx","Gy","a",type==="weierstrass"?"b":"d"];for(let p of params)if(!Fp.isValid(CURVE[p]))throw Error(`CURVE.${p} must be valid field element of CURVE.Fp`);return CURVE=Object.freeze(Object.assign({},CURVE)),{CURVE,Fp,Fn}}function createKeygen(randomSecretKey,getPublicKey){return function(seed){let secretKey=randomSecretKey(seed);return{secretKey,publicKey:getPublicKey(secretKey)}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var _0n4=BigInt(0),_1n4=BigInt(1),_2n2=BigInt(2);function validateOpts(curve){return validateObject(curve,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...curve})}function montgomery(curveDef){let CURVE=validateOpts(curveDef),{P,type,adjustScalarBytes,powPminus2,randomBytes:rand}=CURVE,is25519=type==="x25519";if(!is25519&&type!=="x448")throw Error("invalid type");let randomBytes_=rand||randomBytes3,montgomeryBits=is25519?255:448,fieldLen=is25519?32:56,Gu=is25519?BigInt(9):BigInt(5),a24=is25519?BigInt(121665):BigInt(39081),minScalar=is25519?_2n2**BigInt(254):_2n2**BigInt(447),maxAdded=is25519?BigInt(8)*_2n2**BigInt(251)-_1n4:BigInt(4)*_2n2**BigInt(445)-_1n4,maxScalar=minScalar+maxAdded+_1n4,modP=(n)=>mod(n,P),GuBytes=encodeU(Gu);function encodeU(u){return numberToBytesLE(modP(u),fieldLen)}function decodeU(u){let _u=copyBytes2(abytes4(u,fieldLen,"uCoordinate"));if(is25519)_u[31]&=127;return modP(bytesToNumberLE(_u))}function decodeScalar(scalar){return bytesToNumberLE(adjustScalarBytes(copyBytes2(abytes4(scalar,fieldLen,"scalar"))))}function scalarMult(scalar,u){let pu=montgomeryLadder(decodeU(u),decodeScalar(scalar));if(pu===_0n4)throw Error("invalid private or public key received");return encodeU(pu)}function scalarMultBase(scalar){return scalarMult(scalar,GuBytes)}let getPublicKey=scalarMultBase,getSharedSecret=scalarMult;function cswap(swap,x_2,x_3){let dummy=modP(swap*(x_2-x_3));return x_2=modP(x_2-dummy),x_3=modP(x_3+dummy),{x_2,x_3}}function montgomeryLadder(u,scalar){aInRange("u",u,_0n4,P),aInRange("scalar",scalar,minScalar,maxScalar);let k=scalar,x_1=u,x_2=_1n4,z_2=_0n4,x_3=u,z_3=_1n4,swap=_0n4;for(let t=BigInt(montgomeryBits-1);t>=_0n4;t--){let k_t=k>>t&_1n4;swap^=k_t,{x_2,x_3}=cswap(swap,x_2,x_3),{x_2:z_2,x_3:z_3}=cswap(swap,z_2,z_3),swap=k_t;let A=x_2+z_2,AA=modP(A*A),B=x_2-z_2,BB=modP(B*B),E=AA-BB,C=x_3+z_3,D=x_3-z_3,DA=modP(D*A),CB=modP(C*B),dacb=DA+CB,da_cb=DA-CB;x_3=modP(dacb*dacb),z_3=modP(x_1*modP(da_cb*da_cb)),x_2=modP(AA*BB),z_2=modP(E*(AA+modP(a24*E)))}({x_2,x_3}=cswap(swap,x_2,x_3)),{x_2:z_2,x_3:z_3}=cswap(swap,z_2,z_3);let z2=powPminus2(z_2);return modP(x_2*z2)}let lengths={secretKey:fieldLen,publicKey:fieldLen,seed:fieldLen},randomSecretKey=(seed=randomBytes_(fieldLen))=>{return abytes4(seed,lengths.seed,"seed"),seed},utils={randomSecretKey};return Object.freeze({keygen:createKeygen(randomSecretKey,getPublicKey),getSharedSecret,getPublicKey,scalarMult,scalarMultBase,utils,GuBytes:GuBytes.slice(),lengths})}class _HMAC2{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(hash,key){if(ahash2(hash),abytes4(key,void 0,"key"),this.iHash=hash.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let blockLen=this.blockLen,pad=new Uint8Array(blockLen);pad.set(key.length>blockLen?hash.create().update(key).digest():key);for(let i=0;i<pad.length;i++)pad[i]^=54;this.iHash.update(pad),this.oHash=hash.create();for(let i=0;i<pad.length;i++)pad[i]^=106;this.oHash.update(pad),clean3(pad)}update(buf){return aexists3(this),this.iHash.update(buf),this}digestInto(out){aexists3(this),abytes4(out,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(out),this.oHash.update(out),this.oHash.digestInto(out),this.destroy()}digest(){let out=new Uint8Array(this.oHash.outputLen);return this.digestInto(out),out}_cloneInto(to){to||=Object.create(Object.getPrototypeOf(this),{});let{oHash,iHash,finished,destroyed,blockLen,outputLen}=this;return to=to,to.finished=finished,to.destroyed=destroyed,to.blockLen=blockLen,to.outputLen=outputLen,to.oHash=oHash._cloneInto(to.oHash),to.iHash=iHash._cloneInto(to.iHash),to}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var hmac2=(hash,key,message)=>new _HMAC2(hash,key).update(message).digest();hmac2.create=(hash,key)=>new _HMAC2(hash,key);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var divNearest=(num,den)=>(num+(num>=0?den:-den)/_2n3)/den;function _splitEndoScalar(k,basis,n){let[[a1,b1],[a2,b2]]=basis,c1=divNearest(b2*k,n),c2=divNearest(-b1*k,n),k1=k-c1*a1-c2*a2,k2=-c1*b1-c2*b2,k1neg=k1<_0n5,k2neg=k2<_0n5;if(k1neg)k1=-k1;if(k2neg)k2=-k2;let MAX_NUM=bitMask(Math.ceil(bitLen(n)/2))+_1n5;if(k1<_0n5||k1>=MAX_NUM||k2<_0n5||k2>=MAX_NUM)throw Error("splitScalar (endomorphism): failed, k="+k);return{k1neg,k1,k2neg,k2}}function validateSigFormat(format){if(!["compact","recovered","der"].includes(format))throw Error('Signature format must be "compact", "recovered", or "der"');return format}function validateSigOpts(opts,def){let optsn={};for(let optName of Object.keys(def))optsn[optName]=opts[optName]===void 0?def[optName]:opts[optName];if(abool2(optsn.lowS,"lowS"),abool2(optsn.prehash,"prehash"),optsn.format!==void 0)validateSigFormat(optsn.format);return optsn}class DERErr extends Error{constructor(m=""){super(m)}}var DER={Err:DERErr,_tlv:{encode:(tag,data)=>{let{Err:E}=DER;if(tag<0||tag>256)throw new E("tlv.encode: wrong tag");if(data.length&1)throw new E("tlv.encode: unpadded data");let dataLen=data.length/2,len=numberToHexUnpadded(dataLen);if(len.length/2&128)throw new E("tlv.encode: long form length too big");let lenLen=dataLen>127?numberToHexUnpadded(len.length/2|128):"";return numberToHexUnpadded(tag)+lenLen+len+data},decode(tag,data){let{Err:E}=DER,pos=0;if(tag<0||tag>256)throw new E("tlv.encode: wrong tag");if(data.length<2||data[pos++]!==tag)throw new E("tlv.decode: wrong tlv");let first=data[pos++],isLong=!!(first&128),length=0;if(!isLong)length=first;else{let lenLen=first&127;if(!lenLen)throw new E("tlv.decode(long): indefinite length not supported");if(lenLen>4)throw new E("tlv.decode(long): byte length is too big");let lengthBytes=data.subarray(pos,pos+lenLen);if(lengthBytes.length!==lenLen)throw new E("tlv.decode: length bytes not complete");if(lengthBytes[0]===0)throw new E("tlv.decode(long): zero leftmost byte");for(let b of lengthBytes)length=length<<8|b;if(pos+=lenLen,length<128)throw new E("tlv.decode(long): not minimal encoding")}let v=data.subarray(pos,pos+length);if(v.length!==length)throw new E("tlv.decode: wrong value length");return{v,l:data.subarray(pos+length)}}},_int:{encode(num){let{Err:E}=DER;if(num<_0n5)throw new E("integer: negative integers are not allowed");let hex=numberToHexUnpadded(num);if(Number.parseInt(hex[0],16)&8)hex="00"+hex;if(hex.length&1)throw new E("unexpected DER parsing assertion: unpadded hex");return hex},decode(data){let{Err:E}=DER;if(data[0]&128)throw new E("invalid signature integer: negative");if(data[0]===0&&!(data[1]&128))throw new E("invalid signature integer: unnecessary leading zero");return bytesToNumberBE(data)}},toSig(bytes){let{Err:E,_int:int,_tlv:tlv}=DER,data=abytes4(bytes,void 0,"signature"),{v:seqBytes,l:seqLeftBytes}=tlv.decode(48,data);if(seqLeftBytes.length)throw new E("invalid signature: left bytes after parsing");let{v:rBytes,l:rLeftBytes}=tlv.decode(2,seqBytes),{v:sBytes,l:sLeftBytes}=tlv.decode(2,rLeftBytes);if(sLeftBytes.length)throw new E("invalid signature: left bytes after parsing");return{r:int.decode(rBytes),s:int.decode(sBytes)}},hexFromSig(sig){let{_tlv:tlv,_int:int}=DER,rs=tlv.encode(2,int.encode(sig.r)),ss=tlv.encode(2,int.encode(sig.s)),seq=rs+ss;return tlv.encode(48,seq)}},_0n5=BigInt(0),_1n5=BigInt(1),_2n3=BigInt(2),_3n2=BigInt(3),_4n2=BigInt(4);function weierstrass(params,extraOpts={}){let validated=createCurveFields("weierstrass",params,extraOpts),{Fp,Fn}=validated,CURVE=validated.CURVE,{h:cofactor,n:CURVE_ORDER}=CURVE;validateObject(extraOpts,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo}=extraOpts;if(endo){if(!Fp.is0(CURVE.a)||typeof endo.beta!=="bigint"||!Array.isArray(endo.basises))throw Error('invalid endo: expected "beta": bigint and "basises": array')}let lengths=getWLengths(Fp,Fn);function assertCompressionIsSupported(){if(!Fp.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}function pointToBytes(_c,point,isCompressed){let{x,y}=point.toAffine(),bx=Fp.toBytes(x);if(abool2(isCompressed,"isCompressed"),isCompressed){assertCompressionIsSupported();let hasEvenY=!Fp.isOdd(y);return concatBytes2(pprefix(hasEvenY),bx)}else return concatBytes2(Uint8Array.of(4),bx,Fp.toBytes(y))}function pointFromBytes(bytes){abytes4(bytes,void 0,"Point");let{publicKey:comp,publicKeyUncompressed:uncomp}=lengths,length=bytes.length,head=bytes[0],tail=bytes.subarray(1);if(length===comp&&(head===2||head===3)){let x=Fp.fromBytes(tail);if(!Fp.isValid(x))throw Error("bad point: is not on curve, wrong x");let y2=weierstrassEquation(x),y;try{y=Fp.sqrt(y2)}catch(sqrtError){let err=sqrtError instanceof Error?": "+sqrtError.message:"";throw Error("bad point: is not on curve, sqrt error"+err)}assertCompressionIsSupported();let evenY=Fp.isOdd(y);if((head&1)===1!==evenY)y=Fp.neg(y);return{x,y}}else if(length===uncomp&&head===4){let L=Fp.BYTES,x=Fp.fromBytes(tail.subarray(0,L)),y=Fp.fromBytes(tail.subarray(L,L*2));if(!isValidXY(x,y))throw Error("bad point: is not on curve");return{x,y}}else throw Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`)}let encodePoint=extraOpts.toBytes||pointToBytes,decodePoint=extraOpts.fromBytes||pointFromBytes;function weierstrassEquation(x){let x2=Fp.sqr(x),x3=Fp.mul(x2,x);return Fp.add(Fp.add(x3,Fp.mul(x,CURVE.a)),CURVE.b)}function isValidXY(x,y){let left=Fp.sqr(y),right=weierstrassEquation(x);return Fp.eql(left,right)}if(!isValidXY(CURVE.Gx,CURVE.Gy))throw Error("bad curve params: generator point");let _4a3=Fp.mul(Fp.pow(CURVE.a,_3n2),_4n2),_27b2=Fp.mul(Fp.sqr(CURVE.b),BigInt(27));if(Fp.is0(Fp.add(_4a3,_27b2)))throw Error("bad curve params: a or b");function acoord(title,n,banZero=!1){if(!Fp.isValid(n)||banZero&&Fp.is0(n))throw Error(`bad point coordinate ${title}`);return n}function aprjpoint(other){if(!(other instanceof Point))throw Error("Weierstrass Point expected")}function splitEndoScalarN(k){if(!endo||!endo.basises)throw Error("no endo");return _splitEndoScalar(k,endo.basises,Fn.ORDER)}let toAffineMemo=memoized((p,iz)=>{let{X,Y,Z}=p;if(Fp.eql(Z,Fp.ONE))return{x:X,y:Y};let is0=p.is0();if(iz==null)iz=is0?Fp.ONE:Fp.inv(Z);let x=Fp.mul(X,iz),y=Fp.mul(Y,iz),zz=Fp.mul(Z,iz);if(is0)return{x:Fp.ZERO,y:Fp.ZERO};if(!Fp.eql(zz,Fp.ONE))throw Error("invZ was invalid");return{x,y}}),assertValidMemo=memoized((p)=>{if(p.is0()){if(extraOpts.allowInfinityPoint&&!Fp.is0(p.Y))return;throw Error("bad point: ZERO")}let{x,y}=p.toAffine();if(!Fp.isValid(x)||!Fp.isValid(y))throw Error("bad point: x or y not field elements");if(!isValidXY(x,y))throw Error("bad point: equation left != right");if(!p.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});function finishEndo(endoBeta,k1p,k2p,k1neg,k2neg){return k2p=new Point(Fp.mul(k2p.X,endoBeta),k2p.Y,k2p.Z),k1p=negateCt(k1neg,k1p),k2p=negateCt(k2neg,k2p),k1p.add(k2p)}class Point{static BASE=new Point(CURVE.Gx,CURVE.Gy,Fp.ONE);static ZERO=new Point(Fp.ZERO,Fp.ONE,Fp.ZERO);static Fp=Fp;static Fn=Fn;X;Y;Z;constructor(X,Y,Z){this.X=acoord("x",X),this.Y=acoord("y",Y,!0),this.Z=acoord("z",Z),Object.freeze(this)}static CURVE(){return CURVE}static fromAffine(p){let{x,y}=p||{};if(!p||!Fp.isValid(x)||!Fp.isValid(y))throw Error("invalid affine point");if(p instanceof Point)throw Error("projective point not allowed");if(Fp.is0(x)&&Fp.is0(y))return Point.ZERO;return new Point(x,y,Fp.ONE)}static fromBytes(bytes){let P=Point.fromAffine(decodePoint(abytes4(bytes,void 0,"point")));return P.assertValidity(),P}static fromHex(hex){return Point.fromBytes(hexToBytes2(hex))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(windowSize=8,isLazy=!0){if(wnaf.createCache(this,windowSize),!isLazy)this.multiply(_3n2);return this}assertValidity(){assertValidMemo(this)}hasEvenY(){let{y}=this.toAffine();if(!Fp.isOdd)throw Error("Field doesn't support isOdd");return!Fp.isOdd(y)}equals(other){aprjpoint(other);let{X:X1,Y:Y1,Z:Z1}=this,{X:X2,Y:Y2,Z:Z2}=other,U1=Fp.eql(Fp.mul(X1,Z2),Fp.mul(X2,Z1)),U2=Fp.eql(Fp.mul(Y1,Z2),Fp.mul(Y2,Z1));return U1&&U2}negate(){return new Point(this.X,Fp.neg(this.Y),this.Z)}double(){let{a,b}=CURVE,b3=Fp.mul(b,_3n2),{X:X1,Y:Y1,Z:Z1}=this,X3=Fp.ZERO,Y3=Fp.ZERO,Z3=Fp.ZERO,t0=Fp.mul(X1,X1),t1=Fp.mul(Y1,Y1),t2=Fp.mul(Z1,Z1),t3=Fp.mul(X1,Y1);return t3=Fp.add(t3,t3),Z3=Fp.mul(X1,Z1),Z3=Fp.add(Z3,Z3),X3=Fp.mul(a,Z3),Y3=Fp.mul(b3,t2),Y3=Fp.add(X3,Y3),X3=Fp.sub(t1,Y3),Y3=Fp.add(t1,Y3),Y3=Fp.mul(X3,Y3),X3=Fp.mul(t3,X3),Z3=Fp.mul(b3,Z3),t2=Fp.mul(a,t2),t3=Fp.sub(t0,t2),t3=Fp.mul(a,t3),t3=Fp.add(t3,Z3),Z3=Fp.add(t0,t0),t0=Fp.add(Z3,t0),t0=Fp.add(t0,t2),t0=Fp.mul(t0,t3),Y3=Fp.add(Y3,t0),t2=Fp.mul(Y1,Z1),t2=Fp.add(t2,t2),t0=Fp.mul(t2,t3),X3=Fp.sub(X3,t0),Z3=Fp.mul(t2,t1),Z3=Fp.add(Z3,Z3),Z3=Fp.add(Z3,Z3),new Point(X3,Y3,Z3)}add(other){aprjpoint(other);let{X:X1,Y:Y1,Z:Z1}=this,{X:X2,Y:Y2,Z:Z2}=other,X3=Fp.ZERO,Y3=Fp.ZERO,Z3=Fp.ZERO,a=CURVE.a,b3=Fp.mul(CURVE.b,_3n2),t0=Fp.mul(X1,X2),t1=Fp.mul(Y1,Y2),t2=Fp.mul(Z1,Z2),t3=Fp.add(X1,Y1),t4=Fp.add(X2,Y2);t3=Fp.mul(t3,t4),t4=Fp.add(t0,t1),t3=Fp.sub(t3,t4),t4=Fp.add(X1,Z1);let t5=Fp.add(X2,Z2);return t4=Fp.mul(t4,t5),t5=Fp.add(t0,t2),t4=Fp.sub(t4,t5),t5=Fp.add(Y1,Z1),X3=Fp.add(Y2,Z2),t5=Fp.mul(t5,X3),X3=Fp.add(t1,t2),t5=Fp.sub(t5,X3),Z3=Fp.mul(a,t4),X3=Fp.mul(b3,t2),Z3=Fp.add(X3,Z3),X3=Fp.sub(t1,Z3),Z3=Fp.add(t1,Z3),Y3=Fp.mul(X3,Z3),t1=Fp.add(t0,t0),t1=Fp.add(t1,t0),t2=Fp.mul(a,t2),t4=Fp.mul(b3,t4),t1=Fp.add(t1,t2),t2=Fp.sub(t0,t2),t2=Fp.mul(a,t2),t4=Fp.add(t4,t2),t0=Fp.mul(t1,t4),Y3=Fp.add(Y3,t0),t0=Fp.mul(t5,t4),X3=Fp.mul(t3,X3),X3=Fp.sub(X3,t0),t0=Fp.mul(t3,t1),Z3=Fp.mul(t5,Z3),Z3=Fp.add(Z3,t0),new Point(X3,Y3,Z3)}subtract(other){return this.add(other.negate())}is0(){return this.equals(Point.ZERO)}multiply(scalar){let{endo:endo2}=extraOpts;if(!Fn.isValidNot0(scalar))throw Error("invalid scalar: out of range");let point,fake,mul=(n)=>wnaf.cached(this,n,(p)=>normalizeZ(Point,p));if(endo2){let{k1neg,k1,k2neg,k2}=splitEndoScalarN(scalar),{p:k1p,f:k1f}=mul(k1),{p:k2p,f:k2f}=mul(k2);fake=k1f.add(k2f),point=finishEndo(endo2.beta,k1p,k2p,k1neg,k2neg)}else{let{p,f}=mul(scalar);point=p,fake=f}return normalizeZ(Point,[point,fake])[0]}multiplyUnsafe(sc){let{endo:endo2}=extraOpts,p=this;if(!Fn.isValid(sc))throw Error("invalid scalar: out of range");if(sc===_0n5||p.is0())return Point.ZERO;if(sc===_1n5)return p;if(wnaf.hasCache(this))return this.multiply(sc);if(endo2){let{k1neg,k1,k2neg,k2}=splitEndoScalarN(sc),{p1,p2}=mulEndoUnsafe(Point,p,k1,k2);return finishEndo(endo2.beta,p1,p2,k1neg,k2neg)}else return wnaf.unsafe(p,sc)}toAffine(invertedZ){return toAffineMemo(this,invertedZ)}isTorsionFree(){let{isTorsionFree}=extraOpts;if(cofactor===_1n5)return!0;if(isTorsionFree)return isTorsionFree(Point,this);return wnaf.unsafe(this,CURVE_ORDER).is0()}clearCofactor(){let{clearCofactor}=extraOpts;if(cofactor===_1n5)return this;if(clearCofactor)return clearCofactor(Point,this);return this.multiplyUnsafe(cofactor)}isSmallOrder(){return this.multiplyUnsafe(cofactor).is0()}toBytes(isCompressed=!0){return abool2(isCompressed,"isCompressed"),this.assertValidity(),encodePoint(Point,this,isCompressed)}toHex(isCompressed=!0){return bytesToHex2(this.toBytes(isCompressed))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let bits=Fn.BITS,wnaf=new wNAF(Point,extraOpts.endo?Math.ceil(bits/2):bits);return Point.BASE.precompute(8),Point}function pprefix(hasEvenY){return Uint8Array.of(hasEvenY?2:3)}function getWLengths(Fp,Fn){return{secretKey:Fn.BYTES,publicKey:1+Fp.BYTES,publicKeyUncompressed:1+2*Fp.BYTES,publicKeyHasPrefix:!0,signature:2*Fn.BYTES}}function ecdh(Point,ecdhOpts={}){let{Fn}=Point,randomBytes_=ecdhOpts.randomBytes||randomBytes3,lengths=Object.assign(getWLengths(Point.Fp,Fn),{seed:getMinHashLength(Fn.ORDER)});function isValidSecretKey(secretKey){try{let num=Fn.fromBytes(secretKey);return Fn.isValidNot0(num)}catch(error){return!1}}function isValidPublicKey(publicKey,isCompressed){let{publicKey:comp,publicKeyUncompressed}=lengths;try{let l=publicKey.length;if(isCompressed===!0&&l!==comp)return!1;if(isCompressed===!1&&l!==publicKeyUncompressed)return!1;return!!Point.fromBytes(publicKey)}catch(error){return!1}}function randomSecretKey(seed=randomBytes_(lengths.seed)){return mapHashToField(abytes4(seed,lengths.seed,"seed"),Fn.ORDER)}function getPublicKey(secretKey,isCompressed=!0){return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed)}function isProbPub(item){let{secretKey,publicKey,publicKeyUncompressed}=lengths;if(!isBytes4(item))return;if("_lengths"in Fn&&Fn._lengths||secretKey===publicKey)return;let l=abytes4(item,void 0,"key").length;return l===publicKey||l===publicKeyUncompressed}function getSharedSecret(secretKeyA,publicKeyB,isCompressed=!0){if(isProbPub(secretKeyA)===!0)throw Error("first arg must be private key");if(isProbPub(publicKeyB)===!1)throw Error("second arg must be public key");let s=Fn.fromBytes(secretKeyA);return Point.fromBytes(publicKeyB).multiply(s).toBytes(isCompressed)}let utils={isValidSecretKey,isValidPublicKey,randomSecretKey},keygen=createKeygen(randomSecretKey,getPublicKey);return Object.freeze({getPublicKey,getSharedSecret,keygen,Point,utils,lengths})}function ecdsa(Point,hash,ecdsaOpts={}){ahash2(hash),validateObject(ecdsaOpts,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),ecdsaOpts=Object.assign({},ecdsaOpts);let randomBytes4=ecdsaOpts.randomBytes||randomBytes3,hmac3=ecdsaOpts.hmac||((key,msg)=>hmac2(hash,key,msg)),{Fp,Fn}=Point,{ORDER:CURVE_ORDER,BITS:fnBits}=Fn,{keygen,getPublicKey,getSharedSecret,utils,lengths}=ecdh(Point,ecdsaOpts),defaultSigOpts={prehash:!0,lowS:typeof ecdsaOpts.lowS==="boolean"?ecdsaOpts.lowS:!0,format:"compact",extraEntropy:!1},hasLargeCofactor=CURVE_ORDER*_2n3<Fp.ORDER;function isBiggerThanHalfOrder(number){let HALF=CURVE_ORDER>>_1n5;return number>HALF}function validateRS(title,num){if(!Fn.isValidNot0(num))throw Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);return num}function assertSmallCofactor(){if(hasLargeCofactor)throw Error('"recovered" sig type is not supported for cofactor >2 curves')}function validateSigLength(bytes,format){validateSigFormat(format);let size=lengths.signature,sizer=format==="compact"?size:format==="recovered"?size+1:void 0;return abytes4(bytes,sizer)}class Signature{r;s;recovery;constructor(r,s,recovery){if(this.r=validateRS("r",r),this.s=validateRS("s",s),recovery!=null){if(assertSmallCofactor(),![0,1,2,3].includes(recovery))throw Error("invalid recovery id");this.recovery=recovery}Object.freeze(this)}static fromBytes(bytes,format=defaultSigOpts.format){validateSigLength(bytes,format);let recid;if(format==="der"){let{r:r2,s:s2}=DER.toSig(abytes4(bytes));return new Signature(r2,s2)}if(format==="recovered")recid=bytes[0],format="compact",bytes=bytes.subarray(1);let L=lengths.signature/2,r=bytes.subarray(0,L),s=bytes.subarray(L,L*2);return new Signature(Fn.fromBytes(r),Fn.fromBytes(s),recid)}static fromHex(hex,format){return this.fromBytes(hexToBytes2(hex),format)}assertRecovery(){let{recovery}=this;if(recovery==null)throw Error("invalid recovery id: must be present");return recovery}addRecoveryBit(recovery){return new Signature(this.r,this.s,recovery)}recoverPublicKey(messageHash){let{r,s}=this,recovery=this.assertRecovery(),radj=recovery===2||recovery===3?r+CURVE_ORDER:r;if(!Fp.isValid(radj))throw Error("invalid recovery id: sig.r+curve.n != R.x");let x=Fp.toBytes(radj),R=Point.fromBytes(concatBytes2(pprefix((recovery&1)===0),x)),ir=Fn.inv(radj),h=bits2int_modN(abytes4(messageHash,void 0,"msgHash")),u1=Fn.create(-h*ir),u2=Fn.create(s*ir),Q=Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));if(Q.is0())throw Error("invalid recovery: point at infinify");return Q.assertValidity(),Q}hasHighS(){return isBiggerThanHalfOrder(this.s)}toBytes(format=defaultSigOpts.format){if(validateSigFormat(format),format==="der")return hexToBytes2(DER.hexFromSig(this));let{r,s}=this,rb=Fn.toBytes(r),sb=Fn.toBytes(s);if(format==="recovered")return assertSmallCofactor(),concatBytes2(Uint8Array.of(this.assertRecovery()),rb,sb);return concatBytes2(rb,sb)}toHex(format){return bytesToHex2(this.toBytes(format))}}let bits2int=ecdsaOpts.bits2int||function(bytes){if(bytes.length>8192)throw Error("input is too large");let num=bytesToNumberBE(bytes),delta=bytes.length*8-fnBits;return delta>0?num>>BigInt(delta):num},bits2int_modN=ecdsaOpts.bits2int_modN||function(bytes){return Fn.create(bits2int(bytes))},ORDER_MASK=bitMask(fnBits);function int2octets(num){return aInRange("num < 2^"+fnBits,num,_0n5,ORDER_MASK),Fn.toBytes(num)}function validateMsgAndHash(message,prehash){return abytes4(message,void 0,"message"),prehash?abytes4(hash(message),void 0,"prehashed message"):message}function prepSig(message,secretKey,opts){let{lowS,prehash,extraEntropy}=validateSigOpts(opts,defaultSigOpts);message=validateMsgAndHash(message,prehash);let h1int=bits2int_modN(message),d=Fn.fromBytes(secretKey);if(!Fn.isValidNot0(d))throw Error("invalid private key");let seedArgs=[int2octets(d),int2octets(h1int)];if(extraEntropy!=null&&extraEntropy!==!1){let e=extraEntropy===!0?randomBytes4(lengths.secretKey):extraEntropy;seedArgs.push(abytes4(e,void 0,"extraEntropy"))}let seed=concatBytes2(...seedArgs),m=h1int;function k2sig(kBytes){let k=bits2int(kBytes);if(!Fn.isValidNot0(k))return;let ik=Fn.inv(k),q=Point.BASE.multiply(k).toAffine(),r=Fn.create(q.x);if(r===_0n5)return;let s=Fn.create(ik*Fn.create(m+r*d));if(s===_0n5)return;let recovery=(q.x===r?0:2)|Number(q.y&_1n5),normS=s;if(lowS&&isBiggerThanHalfOrder(s))normS=Fn.neg(s),recovery^=1;return new Signature(r,normS,hasLargeCofactor?void 0:recovery)}return{seed,k2sig}}function sign(message,secretKey,opts={}){let{seed,k2sig}=prepSig(message,secretKey,opts);return createHmacDrbg(hash.outputLen,Fn.BYTES,hmac3)(seed,k2sig).toBytes(opts.format)}function verify(signature,message,publicKey,opts={}){let{lowS,prehash,format}=validateSigOpts(opts,defaultSigOpts);if(publicKey=abytes4(publicKey,void 0,"publicKey"),message=validateMsgAndHash(message,prehash),!isBytes4(signature)){let end=signature instanceof Signature?", use sig.toBytes()":"";throw Error("verify expects Uint8Array signature"+end)}validateSigLength(signature,format);try{let sig=Signature.fromBytes(signature,format),P=Point.fromBytes(publicKey);if(lowS&&sig.hasHighS())return!1;let{r,s}=sig,h=bits2int_modN(message),is=Fn.inv(s),u1=Fn.create(h*is),u2=Fn.create(r*is),R=Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));if(R.is0())return!1;return Fn.create(R.x)===r}catch(e){return!1}}function recoverPublicKey(signature,message,opts={}){let{prehash}=validateSigOpts(opts,defaultSigOpts);return message=validateMsgAndHash(message,prehash),Signature.fromBytes(signature,"recovered").recoverPublicKey(message).toBytes()}return Object.freeze({keygen,getPublicKey,getSharedSecret,utils,lengths,Point,sign,verify,recoverPublicKey,Signature,hash})}function Chi2(a,b,c){return a&b^~a&c}function Maj2(a,b,c){return a&b^a&c^b&c}class HashMD2{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(blockLen,outputLen,padOffset,isLE4){this.blockLen=blockLen,this.outputLen=outputLen,this.padOffset=padOffset,this.isLE=isLE4,this.buffer=new Uint8Array(blockLen),this.view=createView3(this.buffer)}update(data){aexists3(this),abytes4(data);let{view,buffer,blockLen}=this,len=data.length;for(let pos=0;pos<len;){let take=Math.min(blockLen-this.pos,len-pos);if(take===blockLen){let dataView=createView3(data);for(;blockLen<=len-pos;pos+=blockLen)this.process(dataView,pos);continue}if(buffer.set(data.subarray(pos,pos+take),this.pos),this.pos+=take,pos+=take,this.pos===blockLen)this.process(view,0),this.pos=0}return this.length+=data.length,this.roundClean(),this}digestInto(out){aexists3(this),aoutput3(out,this),this.finished=!0;let{buffer,view,blockLen,isLE:isLE4}=this,{pos}=this;if(buffer[pos++]=128,clean3(this.buffer.subarray(pos)),this.padOffset>blockLen-pos)this.process(view,0),pos=0;for(let i=pos;i<blockLen;i++)buffer[i]=0;view.setBigUint64(blockLen-8,BigInt(this.length*8),isLE4),this.process(view,0);let oview=createView3(out),len=this.outputLen;if(len%4)throw Error("_sha2: outputLen must be aligned to 32bit");let outLen=len/4,state=this.get();if(outLen>state.length)throw Error("_sha2: outputLen bigger than state");for(let i=0;i<outLen;i++)oview.setUint32(4*i,state[i],isLE4)}digest(){let{buffer,outputLen}=this;this.digestInto(buffer);let res=buffer.slice(0,outputLen);return this.destroy(),res}_cloneInto(to){to||=new this.constructor,to.set(...this.get());let{blockLen,buffer,length,finished,destroyed,pos}=this;if(to.destroyed=destroyed,to.finished=finished,to.length=length,to.pos=pos,length%blockLen)to.buffer.set(buffer);return to}clone(){return this._cloneInto()}}var SHA256_IV2=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SHA224_IV2=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]),SHA384_IV2=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),SHA512_IV2=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var U32_MASK64=BigInt(4294967295),_32n=BigInt(32);function fromBig(n,le=!1){if(le)return{h:Number(n&U32_MASK64),l:Number(n>>_32n&U32_MASK64)};return{h:Number(n>>_32n&U32_MASK64)|0,l:Number(n&U32_MASK64)|0}}function split(lst,le=!1){let len=lst.length,Ah=new Uint32Array(len),Al=new Uint32Array(len);for(let i=0;i<len;i++){let{h,l}=fromBig(lst[i],le);[Ah[i],Al[i]]=[h,l]}return[Ah,Al]}var shrSH=(h,_l,s)=>h>>>s,shrSL=(h,l,s)=>h<<32-s|l>>>s,rotrSH=(h,l,s)=>h>>>s|l<<32-s,rotrSL=(h,l,s)=>h<<32-s|l>>>s,rotrBH=(h,l,s)=>h<<64-s|l>>>s-32,rotrBL=(h,l,s)=>h>>>s-32|l<<64-s;var rotlSH=(h,l,s)=>h<<s|l>>>32-s,rotlSL=(h,l,s)=>l<<s|h>>>32-s,rotlBH=(h,l,s)=>l<<s-32|h>>>64-s,rotlBL=(h,l,s)=>h<<s-32|l>>>64-s;function add(Ah,Al,Bh,Bl){let l=(Al>>>0)+(Bl>>>0);return{h:Ah+Bh+(l/4294967296|0)|0,l:l|0}}var add3L=(Al,Bl,Cl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0),add3H=(low,Ah,Bh,Ch)=>Ah+Bh+Ch+(low/4294967296|0)|0,add4L=(Al,Bl,Cl,Dl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0),add4H=(low,Ah,Bh,Ch,Dh)=>Ah+Bh+Ch+Dh+(low/4294967296|0)|0,add5L=(Al,Bl,Cl,Dl,El)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0)+(El>>>0),add5H=(low,Ah,Bh,Ch,Dh,Eh)=>Ah+Bh+Ch+Dh+Eh+(low/4294967296|0)|0;var SHA256_K2=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]),SHA256_W2=new Uint32Array(64);class SHA2_32B2 extends HashMD2{constructor(outputLen){super(64,outputLen,8,!1)}get(){let{A,B,C,D,E,F,G,H}=this;return[A,B,C,D,E,F,G,H]}set(A,B,C,D,E,F,G,H){this.A=A|0,this.B=B|0,this.C=C|0,this.D=D|0,this.E=E|0,this.F=F|0,this.G=G|0,this.H=H|0}process(view,offset){for(let i=0;i<16;i++,offset+=4)SHA256_W2[i]=view.getUint32(offset,!1);for(let i=16;i<64;i++){let W15=SHA256_W2[i-15],W2=SHA256_W2[i-2],s0=rotr2(W15,7)^rotr2(W15,18)^W15>>>3,s1=rotr2(W2,17)^rotr2(W2,19)^W2>>>10;SHA256_W2[i]=s1+SHA256_W2[i-7]+s0+SHA256_W2[i-16]|0}let{A,B,C,D,E,F,G,H}=this;for(let i=0;i<64;i++){let sigma1=rotr2(E,6)^rotr2(E,11)^rotr2(E,25),T1=H+sigma1+Chi2(E,F,G)+SHA256_K2[i]+SHA256_W2[i]|0,T2=(rotr2(A,2)^rotr2(A,13)^rotr2(A,22))+Maj2(A,B,C)|0;H=G,G=F,F=E,E=D+T1|0,D=C,C=B,B=A,A=T1+T2|0}A=A+this.A|0,B=B+this.B|0,C=C+this.C|0,D=D+this.D|0,E=E+this.E|0,F=F+this.F|0,G=G+this.G|0,H=H+this.H|0,this.set(A,B,C,D,E,F,G,H)}roundClean(){clean3(SHA256_W2)}destroy(){this.set(0,0,0,0,0,0,0,0),clean3(this.buffer)}}class _SHA2562 extends SHA2_32B2{A=SHA256_IV2[0]|0;B=SHA256_IV2[1]|0;C=SHA256_IV2[2]|0;D=SHA256_IV2[3]|0;E=SHA256_IV2[4]|0;F=SHA256_IV2[5]|0;G=SHA256_IV2[6]|0;H=SHA256_IV2[7]|0;constructor(){super(32)}}class _SHA224 extends SHA2_32B2{A=SHA224_IV2[0]|0;B=SHA224_IV2[1]|0;C=SHA224_IV2[2]|0;D=SHA224_IV2[3]|0;E=SHA224_IV2[4]|0;F=SHA224_IV2[5]|0;G=SHA224_IV2[6]|0;H=SHA224_IV2[7]|0;constructor(){super(28)}}var K512=(()=>split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((n)=>BigInt(n))))(),SHA512_Kh=(()=>K512[0])(),SHA512_Kl=(()=>K512[1])(),SHA512_W_H=new Uint32Array(80),SHA512_W_L=new Uint32Array(80);class SHA2_64B extends HashMD2{constructor(outputLen){super(128,outputLen,16,!1)}get(){let{Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl}=this;return[Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl]}set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl){this.Ah=Ah|0,this.Al=Al|0,this.Bh=Bh|0,this.Bl=Bl|0,this.Ch=Ch|0,this.Cl=Cl|0,this.Dh=Dh|0,this.Dl=Dl|0,this.Eh=Eh|0,this.El=El|0,this.Fh=Fh|0,this.Fl=Fl|0,this.Gh=Gh|0,this.Gl=Gl|0,this.Hh=Hh|0,this.Hl=Hl|0}process(view,offset){for(let i=0;i<16;i++,offset+=4)SHA512_W_H[i]=view.getUint32(offset),SHA512_W_L[i]=view.getUint32(offset+=4);for(let i=16;i<80;i++){let W15h=SHA512_W_H[i-15]|0,W15l=SHA512_W_L[i-15]|0,s0h=rotrSH(W15h,W15l,1)^rotrSH(W15h,W15l,8)^shrSH(W15h,W15l,7),s0l=rotrSL(W15h,W15l,1)^rotrSL(W15h,W15l,8)^shrSL(W15h,W15l,7),W2h=SHA512_W_H[i-2]|0,W2l=SHA512_W_L[i-2]|0,s1h=rotrSH(W2h,W2l,19)^rotrBH(W2h,W2l,61)^shrSH(W2h,W2l,6),s1l=rotrSL(W2h,W2l,19)^rotrBL(W2h,W2l,61)^shrSL(W2h,W2l,6),SUMl=add4L(s0l,s1l,SHA512_W_L[i-7],SHA512_W_L[i-16]),SUMh=add4H(SUMl,s0h,s1h,SHA512_W_H[i-7],SHA512_W_H[i-16]);SHA512_W_H[i]=SUMh|0,SHA512_W_L[i]=SUMl|0}let{Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl}=this;for(let i=0;i<80;i++){let sigma1h=rotrSH(Eh,El,14)^rotrSH(Eh,El,18)^rotrBH(Eh,El,41),sigma1l=rotrSL(Eh,El,14)^rotrSL(Eh,El,18)^rotrBL(Eh,El,41),CHIh=Eh&Fh^~Eh&Gh,CHIl=El&Fl^~El&Gl,T1ll=add5L(Hl,sigma1l,CHIl,SHA512_Kl[i],SHA512_W_L[i]),T1h=add5H(T1ll,Hh,sigma1h,CHIh,SHA512_Kh[i],SHA512_W_H[i]),T1l=T1ll|0,sigma0h=rotrSH(Ah,Al,28)^rotrBH(Ah,Al,34)^rotrBH(Ah,Al,39),sigma0l=rotrSL(Ah,Al,28)^rotrBL(Ah,Al,34)^rotrBL(Ah,Al,39),MAJh=Ah&Bh^Ah&Ch^Bh&Ch,MAJl=Al&Bl^Al&Cl^Bl&Cl;Hh=Gh|0,Hl=Gl|0,Gh=Fh|0,Gl=Fl|0,Fh=Eh|0,Fl=El|0,{h:Eh,l:El}=add(Dh|0,Dl|0,T1h|0,T1l|0),Dh=Ch|0,Dl=Cl|0,Ch=Bh|0,Cl=Bl|0,Bh=Ah|0,Bl=Al|0;let All=add3L(T1l,sigma0l,MAJl);Ah=add3H(All,T1h,sigma0h,MAJh),Al=All|0}({h:Ah,l:Al}=add(this.Ah|0,this.Al|0,Ah|0,Al|0)),{h:Bh,l:Bl}=add(this.Bh|0,this.Bl|0,Bh|0,Bl|0),{h:Ch,l:Cl}=add(this.Ch|0,this.Cl|0,Ch|0,Cl|0),{h:Dh,l:Dl}=add(this.Dh|0,this.Dl|0,Dh|0,Dl|0),{h:Eh,l:El}=add(this.Eh|0,this.El|0,Eh|0,El|0),{h:Fh,l:Fl}=add(this.Fh|0,this.Fl|0,Fh|0,Fl|0),{h:Gh,l:Gl}=add(this.Gh|0,this.Gl|0,Gh|0,Gl|0),{h:Hh,l:Hl}=add(this.Hh|0,this.Hl|0,Hh|0,Hl|0),this.set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl)}roundClean(){clean3(SHA512_W_H,SHA512_W_L)}destroy(){clean3(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class _SHA512 extends SHA2_64B{Ah=SHA512_IV2[0]|0;Al=SHA512_IV2[1]|0;Bh=SHA512_IV2[2]|0;Bl=SHA512_IV2[3]|0;Ch=SHA512_IV2[4]|0;Cl=SHA512_IV2[5]|0;Dh=SHA512_IV2[6]|0;Dl=SHA512_IV2[7]|0;Eh=SHA512_IV2[8]|0;El=SHA512_IV2[9]|0;Fh=SHA512_IV2[10]|0;Fl=SHA512_IV2[11]|0;Gh=SHA512_IV2[12]|0;Gl=SHA512_IV2[13]|0;Hh=SHA512_IV2[14]|0;Hl=SHA512_IV2[15]|0;constructor(){super(64)}}class _SHA384 extends SHA2_64B{Ah=SHA384_IV2[0]|0;Al=SHA384_IV2[1]|0;Bh=SHA384_IV2[2]|0;Bl=SHA384_IV2[3]|0;Ch=SHA384_IV2[4]|0;Cl=SHA384_IV2[5]|0;Dh=SHA384_IV2[6]|0;Dl=SHA384_IV2[7]|0;Eh=SHA384_IV2[8]|0;El=SHA384_IV2[9]|0;Fh=SHA384_IV2[10]|0;Fl=SHA384_IV2[11]|0;Gh=SHA384_IV2[12]|0;Gl=SHA384_IV2[13]|0;Hh=SHA384_IV2[14]|0;Hl=SHA384_IV2[15]|0;constructor(){super(48)}}var T224_IV=Uint32Array.from([2352822216,424955298,1944164710,2312950998,502970286,855612546,1738396948,1479516111,258812777,2077511080,2011393907,79989058,1067287976,1780299464,286451373,2446758561]),T256_IV=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class _SHA512_224 extends SHA2_64B{Ah=T224_IV[0]|0;Al=T224_IV[1]|0;Bh=T224_IV[2]|0;Bl=T224_IV[3]|0;Ch=T224_IV[4]|0;Cl=T224_IV[5]|0;Dh=T224_IV[6]|0;Dl=T224_IV[7]|0;Eh=T224_IV[8]|0;El=T224_IV[9]|0;Fh=T224_IV[10]|0;Fl=T224_IV[11]|0;Gh=T224_IV[12]|0;Gl=T224_IV[13]|0;Hh=T224_IV[14]|0;Hl=T224_IV[15]|0;constructor(){super(28)}}class _SHA512_256 extends SHA2_64B{Ah=T256_IV[0]|0;Al=T256_IV[1]|0;Bh=T256_IV[2]|0;Bl=T256_IV[3]|0;Ch=T256_IV[4]|0;Cl=T256_IV[5]|0;Dh=T256_IV[6]|0;Dl=T256_IV[7]|0;Eh=T256_IV[8]|0;El=T256_IV[9]|0;Fh=T256_IV[10]|0;Fl=T256_IV[11]|0;Gh=T256_IV[12]|0;Gl=T256_IV[13]|0;Hh=T256_IV[14]|0;Hl=T256_IV[15]|0;constructor(){super(32)}}var sha2562=createHasher2(()=>new _SHA2562,oidNist2(1));var sha384=createHasher2(()=>new _SHA384,oidNist2(2));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var _1n6=BigInt(1),_2n4=BigInt(2),_3n3=BigInt(3),_5n2=BigInt(5),_8n2=BigInt(8),ed25519_CURVE_p=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");function ed25519_pow_2_252_3(x){let _10n=BigInt(10),_20n=BigInt(20),_40n=BigInt(40),_80n=BigInt(80),P=ed25519_CURVE_p,b2=x*x%P*x%P,b4=pow2(b2,_2n4,P)*b2%P,b5=pow2(b4,_1n6,P)*x%P,b10=pow2(b5,_5n2,P)*b5%P,b20=pow2(b10,_10n,P)*b10%P,b40=pow2(b20,_20n,P)*b20%P,b80=pow2(b40,_40n,P)*b40%P,b160=pow2(b80,_80n,P)*b80%P,b240=pow2(b160,_80n,P)*b80%P,b250=pow2(b240,_10n,P)*b10%P;return{pow_p_5_8:pow2(b250,_2n4,P)*x%P,b2}}function adjustScalarBytes(bytes){return bytes[0]&=248,bytes[31]&=127,bytes[31]|=64,bytes}var x25519=(()=>{let P=ed25519_CURVE_p;return montgomery({P,type:"x25519",powPminus2:(x)=>{let{pow_p_5_8,b2}=ed25519_pow_2_252_3(x);return mod(pow2(pow_p_5_8,_3n3,P)*b2,P)},adjustScalarBytes})})();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var p256_CURVE=(()=>({p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")}))(),p384_CURVE=(()=>({p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")}))();var p256_Point=weierstrass(p256_CURVE),p256=ecdsa(p256_Point,sha2562);var p384_Point=weierstrass(p384_CURVE),p384=ecdsa(p384_Point,sha384);function extract2(hash,ikm,salt){if(ahash2(hash),salt===void 0)salt=new Uint8Array(hash.outputLen);return hmac2(hash,salt,ikm)}var HKDF_COUNTER2=Uint8Array.of(0),EMPTY_BUFFER2=Uint8Array.of();function expand2(hash,prk,info,length=32){ahash2(hash),anumber4(length,"length");let olen=hash.outputLen;if(length>255*olen)throw Error("Length must be <= 255*HashLen");let blocks=Math.ceil(length/olen);if(info===void 0)info=EMPTY_BUFFER2;else abytes4(info,void 0,"info");let okm=new Uint8Array(blocks*olen),HMAC=hmac2.create(hash,prk),HMACTmp=HMAC._cloneInto(),T=new Uint8Array(HMAC.outputLen);for(let counter=0;counter<blocks;counter++)HKDF_COUNTER2[0]=counter+1,HMACTmp.update(counter===0?EMPTY_BUFFER2:T).update(info).update(HKDF_COUNTER2).digestInto(T),okm.set(T,olen*counter),HMAC._cloneInto(HMACTmp);return HMAC.destroy(),HMACTmp.destroy(),clean3(T,HKDF_COUNTER2),okm.slice(0,length)}var _0n6=BigInt(0),_1n7=BigInt(1),_2n5=BigInt(2),_7n2=BigInt(7),_256n=BigInt(256),_0x71n=BigInt(113),SHA3_PI=[],SHA3_ROTL=[],_SHA3_IOTA=[];for(let round=0,R=_1n7,x=1,y=0;round<24;round++){[x,y]=[y,(2*x+3*y)%5],SHA3_PI.push(2*(5*y+x)),SHA3_ROTL.push((round+1)*(round+2)/2%64);let t=_0n6;for(let j=0;j<7;j++)if(R=(R<<_1n7^(R>>_7n2)*_0x71n)%_256n,R&_2n5)t^=_1n7<<(_1n7<<BigInt(j))-_1n7;_SHA3_IOTA.push(t)}var IOTAS=split(_SHA3_IOTA,!0),SHA3_IOTA_H=IOTAS[0],SHA3_IOTA_L=IOTAS[1],rotlH=(h,l,s)=>s>32?rotlBH(h,l,s):rotlSH(h,l,s),rotlL=(h,l,s)=>s>32?rotlBL(h,l,s):rotlSL(h,l,s);function keccakP(s,rounds=24){let B=new Uint32Array(10);for(let round=24-rounds;round<24;round++){for(let x=0;x<10;x++)B[x]=s[x]^s[x+10]^s[x+20]^s[x+30]^s[x+40];for(let x=0;x<10;x+=2){let idx1=(x+8)%10,idx0=(x+2)%10,B0=B[idx0],B1=B[idx0+1],Th=rotlH(B0,B1,1)^B[idx1],Tl=rotlL(B0,B1,1)^B[idx1+1];for(let y=0;y<50;y+=10)s[x+y]^=Th,s[x+y+1]^=Tl}let curH=s[2],curL=s[3];for(let t=0;t<24;t++){let shift=SHA3_ROTL[t],Th=rotlH(curH,curL,shift),Tl=rotlL(curH,curL,shift),PI=SHA3_PI[t];curH=s[PI],curL=s[PI+1],s[PI]=Th,s[PI+1]=Tl}for(let y=0;y<50;y+=10){for(let x=0;x<10;x++)B[x]=s[y+x];for(let x=0;x<10;x++)s[y+x]^=~B[(x+2)%10]&B[(x+4)%10]}s[0]^=SHA3_IOTA_H[round],s[1]^=SHA3_IOTA_L[round]}clean3(B)}class Keccak{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;enableXOF=!1;rounds;constructor(blockLen,suffix,outputLen,enableXOF=!1,rounds=24){if(this.blockLen=blockLen,this.suffix=suffix,this.outputLen=outputLen,this.enableXOF=enableXOF,this.rounds=rounds,anumber4(outputLen,"outputLen"),!(0<blockLen&&blockLen<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=u323(this.state)}clone(){return this._cloneInto()}keccak(){swap32IfBE3(this.state32),keccakP(this.state32,this.rounds),swap32IfBE3(this.state32),this.posOut=0,this.pos=0}update(data){aexists3(this),abytes4(data);let{blockLen,state}=this,len=data.length;for(let pos=0;pos<len;){let take=Math.min(blockLen-this.pos,len-pos);for(let i=0;i<take;i++)state[this.pos++]^=data[pos++];if(this.pos===blockLen)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state,suffix,pos,blockLen}=this;if(state[pos]^=suffix,(suffix&128)!==0&&pos===blockLen-1)this.keccak();state[blockLen-1]^=128,this.keccak()}writeInto(out){aexists3(this,!1),abytes4(out),this.finish();let bufferOut=this.state,{blockLen}=this;for(let pos=0,len=out.length;pos<len;){if(this.posOut>=blockLen)this.keccak();let take=Math.min(blockLen-this.posOut,len-pos);out.set(bufferOut.subarray(this.posOut,this.posOut+take),pos),this.posOut+=take,pos+=take}return out}xofInto(out){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(out)}xof(bytes){return anumber4(bytes),this.xofInto(new Uint8Array(bytes))}digestInto(out){if(aoutput3(out,this),this.finished)throw Error("digest() was already called");return this.writeInto(out),this.destroy(),out}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,clean3(this.state)}_cloneInto(to){let{blockLen,suffix,outputLen,rounds,enableXOF}=this;return to||=new Keccak(blockLen,suffix,outputLen,enableXOF,rounds),to.state32.set(this.state32),to.pos=this.pos,to.posOut=this.posOut,to.finished=this.finished,to.rounds=rounds,to.suffix=suffix,to.outputLen=outputLen,to.enableXOF=enableXOF,to.destroyed=this.destroyed,to}}var genKeccak=(suffix,blockLen,outputLen,info={})=>createHasher2(()=>new Keccak(blockLen,suffix,outputLen),info);var sha3_256=genKeccak(6,136,32,oidNist2(8));var sha3_512=genKeccak(6,72,64,oidNist2(10));var genShake=(suffix,blockLen,outputLen,info={})=>createHasher2((opts={})=>new Keccak(blockLen,suffix,opts.dkLen===void 0?outputLen:opts.dkLen,!0),info),shake128=genShake(31,168,16,oidNist2(11)),shake256=genShake(31,136,32,oidNist2(12));function checkU32(n){if(!Number.isSafeInteger(n)||n<0||n>4294967295)throw Error("wrong u32 integer:"+n);return n}function isPowerOfTwo(x){return checkU32(x),(x&x-1)===0&&x!==0}function reverseBits(n,bits){checkU32(n);let reversed=0;for(let i=0;i<bits;i++,n>>>=1)reversed=reversed<<1|n&1;return reversed}function log2(n){return checkU32(n),31-Math.clz32(n)}function bitReversalInplace(values){let n=values.length;if(n<2||!isPowerOfTwo(n))throw Error("n must be a power of 2 and greater than 1. Got "+n);let bits=log2(n);for(let i=0;i<n;i++){let j=reverseBits(i,bits);if(i<j){let tmp=values[i];values[i]=values[j],values[j]=tmp}}return values}var FFTCore=(F,coreOpts)=>{let{N,roots,dit,invertButterflies=!1,skipStages=0,brp=!0}=coreOpts,bits=log2(N);if(!isPowerOfTwo(N))throw Error("FFT: Polynomial size should be power of two");let isDit=dit!==invertButterflies;return(values)=>{if(values.length!==N)throw Error("FFT: wrong Polynomial length");if(dit&&brp)bitReversalInplace(values);for(let i=0,g=1;i<bits-skipStages;i++){let s=dit?i+1+skipStages:bits-i,m=1<<s,m2=m>>1,stride=N>>s;for(let k=0;k<N;k+=m)for(let j=0,grp=g++;j<m2;j++){let rootPos=invertButterflies?dit?N-grp:grp:j*stride,i0=k+j,i1=k+j+m2,omega=roots[rootPos],b=values[i1],a=values[i0];if(isDit){let t=F.mul(b,omega);values[i0]=F.add(a,t),values[i1]=F.sub(a,t)}else if(invertButterflies)values[i0]=F.add(b,a),values[i1]=F.mul(F.sub(b,a),omega);else values[i0]=F.add(a,b),values[i1]=F.mul(F.sub(a,b),omega)}}if(!dit&&brp)bitReversalInplace(values);return values}};/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */var randomBytes4=randomBytes3;function equalBytes2(a,b){if(a.length!==b.length)return!1;let diff=0;for(let i=0;i<a.length;i++)diff|=a[i]^b[i];return diff===0}function copyBytes3(bytes){return Uint8Array.from(bytes)}function splitCoder(label,...lengths){let getLength=(c)=>typeof c==="number"?c:c.bytesLen,bytesLen=lengths.reduce((sum,a)=>sum+getLength(a),0);return{bytesLen,encode:(bufs)=>{let res=new Uint8Array(bytesLen);for(let i=0,pos=0;i<lengths.length;i++){let c=lengths[i],l=getLength(c),b=typeof c==="number"?bufs[i]:c.encode(bufs[i]);if(abytes4(b,l,label),res.set(b,pos),typeof c!=="number")b.fill(0);pos+=l}return res},decode:(buf)=>{abytes4(buf,bytesLen,label);let res=[];for(let c of lengths){let l=getLength(c),b=buf.subarray(0,l);res.push(typeof c==="number"?b:c.decode(b)),buf=buf.subarray(l)}return res}}}function vecCoder(c,vecLen){let bytesLen=vecLen*c.bytesLen;return{bytesLen,encode:(u)=>{if(u.length!==vecLen)throw Error(`vecCoder.encode: wrong length=${u.length}. Expected: ${vecLen}`);let res=new Uint8Array(bytesLen);for(let i=0,pos=0;i<u.length;i++){let b=c.encode(u[i]);res.set(b,pos),b.fill(0),pos+=b.length}return res},decode:(a)=>{abytes4(a,bytesLen);let r=[];for(let i=0;i<a.length;i+=c.bytesLen)r.push(c.decode(a.subarray(i,i+c.bytesLen)));return r}}}function cleanBytes(...list){for(let t of list)if(Array.isArray(t))for(let b of t)b.fill(0);else t.fill(0)}function getMask(bits){return(1<<bits)-1}var EMPTY=Uint8Array.of();/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */var genCrystals=(opts)=>{let{newPoly,N,Q,F,ROOT_OF_UNITY,brvBits,isKyber}=opts,mod2=(a,modulo=Q)=>{let result=a%modulo|0;return(result>=0?result|0:modulo+result|0)|0},smod=(a,modulo=Q)=>{let r=mod2(a,modulo)|0;return(r>modulo>>1?r-modulo|0:r)|0};function getZettas(){let out=newPoly(N);for(let i=0;i<N;i++){let b=reverseBits(i,brvBits),p=BigInt(ROOT_OF_UNITY)**BigInt(b)%BigInt(Q);out[i]=Number(p)|0}return out}let nttZetas=getZettas(),field={add:(a,b)=>mod2((a|0)+(b|0))|0,sub:(a,b)=>mod2((a|0)-(b|0))|0,mul:(a,b)=>mod2((a|0)*(b|0))|0,inv:(_a)=>{throw Error("not implemented")}},nttOpts={N,roots:nttZetas,invertButterflies:!0,skipStages:isKyber?1:0,brp:!1},dif=FFTCore(field,{dit:!1,...nttOpts}),dit=FFTCore(field,{dit:!0,...nttOpts});return{mod:mod2,smod,nttZetas,NTT:{encode:(r)=>{return dif(r)},decode:(r)=>{dit(r);for(let i=0;i<r.length;i++)r[i]=mod2(F*r[i]);return r}},bitsCoder:(d,c)=>{let mask=getMask(d),bytesLen=d*(N/8);return{bytesLen,encode:(poly)=>{let r=new Uint8Array(bytesLen);for(let i=0,buf=0,bufLen=0,pos=0;i<poly.length;i++){buf|=(c.encode(poly[i])&mask)<<bufLen,bufLen+=d;for(;bufLen>=8;bufLen-=8,buf>>=8)r[pos++]=buf&getMask(bufLen)}return r},decode:(bytes)=>{let r=newPoly(N);for(let i=0,buf=0,bufLen=0,pos=0;i<bytes.length;i++){buf|=bytes[i]<<bufLen,bufLen+=8;for(;bufLen>=d;bufLen-=d,buf>>=d)r[pos++]=c.decode(buf&mask)}return r}}}}},createXofShake=(shake)=>(seed,blockLen)=>{if(!blockLen)blockLen=shake.blockLen;let _seed=new Uint8Array(seed.length+2);_seed.set(seed);let seedLen=seed.length,buf=new Uint8Array(blockLen),h=shake.create({}),calls=0,xofs=0;return{stats:()=>({calls,xofs}),get:(x,y)=>{return _seed[seedLen+0]=x,_seed[seedLen+1]=y,h.destroy(),h=shake.create({}).update(_seed),calls++,()=>{return xofs++,h.xofInto(buf)}},clean:()=>{h.destroy(),cleanBytes(buf,_seed)}}},XOF128=createXofShake(shake128);/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */var N=256,Q=3329,F=3303,ROOT_OF_UNITY=17,{mod:mod2,nttZetas,NTT,bitsCoder}=genCrystals({N,Q,F,ROOT_OF_UNITY,newPoly:(n)=>new Uint16Array(n),brvBits:7,isKyber:!0}),PARAMS={512:{N,Q,K:2,ETA1:3,ETA2:2,du:10,dv:4,RBGstrength:128},768:{N,Q,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192},1024:{N,Q,K:4,ETA1:2,ETA2:2,du:11,dv:5,RBGstrength:256}},compress=(d)=>{if(d>=12)return{encode:(i)=>i,decode:(i)=>i};let a=2**(d-1);return{encode:(i)=>((i<<d)+Q/2)/Q,decode:(i)=>i*Q+a>>>d}},polyCoder=(d)=>bitsCoder(d,compress(d));function polyAdd(a,b){for(let i=0;i<N;i++)a[i]=mod2(a[i]+b[i])}function polySub(a,b){for(let i=0;i<N;i++)a[i]=mod2(a[i]-b[i])}function BaseCaseMultiply(a0,a1,b0,b1,zeta){let c0=mod2(a1*b1*zeta+a0*b0),c1=mod2(a0*b1+a1*b0);return{c0,c1}}function MultiplyNTTs(f,g){for(let i=0;i<N/2;i++){let z=nttZetas[64+(i>>1)];if(i&1)z=-z;let{c0,c1}=BaseCaseMultiply(f[2*i+0],f[2*i+1],g[2*i+0],g[2*i+1],z);f[2*i+0]=c0,f[2*i+1]=c1}return f}function SampleNTT(xof){let r=new Uint16Array(N);for(let j=0;j<N;){let b=xof();if(b.length%3)throw Error("SampleNTT: unaligned block");for(let i=0;j<N&&i+3<=b.length;i+=3){let d1=(b[i+0]>>0|b[i+1]<<8)&4095,d2=(b[i+1]>>4|b[i+2]<<4)&4095;if(d1<Q)r[j++]=d1;if(j<N&&d2<Q)r[j++]=d2}}return r}function sampleCBD(PRF,seed,nonce,eta){let buf=PRF(eta*N/4,seed,nonce),r=new Uint16Array(N),b32=u323(buf),len=0;for(let i=0,p=0,bb=0,t0=0;i<b32.length;i++){let b=b32[i];for(let j=0;j<32;j++)if(bb+=b&1,b>>=1,len+=1,len===eta)t0=bb,bb=0;else if(len===2*eta)r[p++]=mod2(t0-bb),bb=0,len=0}if(len)throw Error(`sampleCBD: leftover bits: ${len}`);return r}var genKPKE=(opts)=>{let{K,PRF,XOF,HASH512,ETA1,ETA2,du,dv}=opts,poly1=polyCoder(1),polyV=polyCoder(dv),polyU=polyCoder(du),publicCoder=splitCoder("publicKey",vecCoder(polyCoder(12),K),32),secretCoder=vecCoder(polyCoder(12),K),cipherCoder=splitCoder("ciphertext",vecCoder(polyU,K),polyV),seedCoder=splitCoder("seed",32,32);return{secretCoder,lengths:{secretKey:secretCoder.bytesLen,publicKey:publicCoder.bytesLen,cipherText:cipherCoder.bytesLen},keygen:(seed)=>{abytes4(seed,32,"seed");let seedDst=new Uint8Array(33);seedDst.set(seed),seedDst[32]=K;let seedHash=HASH512(seedDst),[rho,sigma]=seedCoder.decode(seedHash),sHat=[],tHat=[];for(let i=0;i<K;i++)sHat.push(NTT.encode(sampleCBD(PRF,sigma,i,ETA1)));let x=XOF(rho);for(let i=0;i<K;i++){let e=NTT.encode(sampleCBD(PRF,sigma,K+i,ETA1));for(let j=0;j<K;j++){let aji=SampleNTT(x.get(j,i));polyAdd(e,MultiplyNTTs(aji,sHat[j]))}tHat.push(e)}x.clean();let res={publicKey:publicCoder.encode([tHat,rho]),secretKey:secretCoder.encode(sHat)};return cleanBytes(rho,sigma,sHat,tHat,seedDst,seedHash),res},encrypt:(publicKey,msg,seed)=>{let[tHat,rho]=publicCoder.decode(publicKey),rHat=[];for(let i=0;i<K;i++)rHat.push(NTT.encode(sampleCBD(PRF,seed,i,ETA1)));let x=XOF(rho),tmp2=new Uint16Array(N),u=[];for(let i=0;i<K;i++){let e1=sampleCBD(PRF,seed,K+i,ETA2),tmp=new Uint16Array(N);for(let j=0;j<K;j++){let aij=SampleNTT(x.get(i,j));polyAdd(tmp,MultiplyNTTs(aij,rHat[j]))}polyAdd(e1,NTT.decode(tmp)),u.push(e1),polyAdd(tmp2,MultiplyNTTs(tHat[i],rHat[i])),cleanBytes(tmp)}x.clean();let e2=sampleCBD(PRF,seed,2*K,ETA2);polyAdd(e2,NTT.decode(tmp2));let v=poly1.decode(msg);return polyAdd(v,e2),cleanBytes(tHat,rHat,tmp2,e2),cipherCoder.encode([u,v])},decrypt:(cipherText,privateKey)=>{let[u,v]=cipherCoder.decode(cipherText),sk=secretCoder.decode(privateKey),tmp=new Uint16Array(N);for(let i=0;i<K;i++)polyAdd(tmp,MultiplyNTTs(sk[i],NTT.encode(u[i])));return polySub(v,NTT.decode(tmp)),cleanBytes(tmp,sk,u),poly1.encode(v)}}};function createKyber(opts){let KPKE=genKPKE(opts),{HASH256,HASH512,KDF}=opts,{secretCoder:KPKESecretCoder,lengths}=KPKE,secretCoder=splitCoder("secretKey",lengths.secretKey,lengths.publicKey,32,32),msgLen=32,seedLen=64;return{info:{type:"ml-kem"},lengths:{...lengths,seed:64,msg:32,msgRand:32,secretKey:secretCoder.bytesLen},keygen:(seed=randomBytes4(64))=>{abytes4(seed,64,"seed");let{publicKey,secretKey:sk}=KPKE.keygen(seed.subarray(0,32)),publicKeyHash=HASH256(publicKey),secretKey=secretCoder.encode([sk,publicKey,publicKeyHash,seed.subarray(32)]);return cleanBytes(sk,publicKeyHash),{publicKey,secretKey}},getPublicKey:(secretKey)=>{let[_sk,publicKey,_publicKeyHash,_z]=secretCoder.decode(secretKey);return Uint8Array.from(publicKey)},encapsulate:(publicKey,msg=randomBytes4(32))=>{abytes4(publicKey,lengths.publicKey,"publicKey"),abytes4(msg,32,"message");let eke=publicKey.subarray(0,384*opts.K),ek=KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes3(eke)));if(!equalBytes2(ek,eke))throw cleanBytes(ek),Error("ML-KEM.encapsulate: wrong publicKey modulus");cleanBytes(ek);let kr=HASH512.create().update(msg).update(HASH256(publicKey)).digest(),cipherText=KPKE.encrypt(publicKey,msg,kr.subarray(32,64));return cleanBytes(kr.subarray(32)),{cipherText,sharedSecret:kr.subarray(0,32)}},decapsulate:(cipherText,secretKey)=>{abytes4(secretKey,secretCoder.bytesLen,"secretKey"),abytes4(cipherText,lengths.cipherText,"cipherText");let k768=secretCoder.bytesLen-96,start=k768+32,test=HASH256(secretKey.subarray(k768/2,start));if(!equalBytes2(test,secretKey.subarray(start,start+32)))throw Error("invalid secretKey: hash check failed");let[sk,publicKey,publicKeyHash,z]=secretCoder.decode(secretKey),msg=KPKE.decrypt(cipherText,sk),kr=HASH512.create().update(msg).update(publicKeyHash).digest(),Khat=kr.subarray(0,32),cipherText2=KPKE.encrypt(publicKey,msg,kr.subarray(32,64)),isValid=equalBytes2(cipherText,cipherText2),Kbar=KDF.create({dkLen:32}).update(z).update(cipherText).digest();return cleanBytes(msg,cipherText2,!isValid?Khat:Kbar),isValid?Khat:Kbar}}}function shakePRF(dkLen,key,nonce){return shake256.create({dkLen}).update(key).update(new Uint8Array([nonce])).digest()}var opts={HASH256:sha3_256,HASH512:sha3_512,KDF:shake256,XOF:XOF128,PRF:shakePRF},ml_kem512=createKyber({...opts,...PARAMS[512]}),ml_kem768=createKyber({...opts,...PARAMS[768]}),ml_kem1024=createKyber({...opts,...PARAMS[1024]});/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */function ecKeygen(curve,allowZeroKey=!1){let{lengths,keygen}=curve;if(allowZeroKey){let Fn=curve.Point.Fn;if(!Fn)throw Error("No Point.Fn");keygen=(seed=randomBytes4(lengths.seed))=>{abytes4(seed,lengths.seed,"seed");let seedScalar=Fn.isLE?bytesToNumberLE(seed):bytesToNumberBE(seed),secretKey=Fn.toBytes(Fn.create(seedScalar));return{secretKey,publicKey:curve.getPublicKey(secretKey)}}}return{lengths:{secretKey:lengths.secretKey,publicKey:lengths.publicKey,seed:lengths.seed},keygen,getPublicKey:(secretKey)=>curve.getPublicKey(secretKey)}}function ecdhKem(curve,allowZeroKey=!1){let kg=ecKeygen(curve,allowZeroKey);if(!curve.getSharedSecret)throw Error("wrong curve");return{lengths:{...kg.lengths,msg:kg.lengths.seed,cipherText:kg.lengths.publicKey},keygen:kg.keygen,getPublicKey:kg.getPublicKey,encapsulate(publicKey,rand=randomBytes4(curve.lengths.seed)){let ek=this.keygen(rand).secretKey,sharedSecret=this.decapsulate(publicKey,ek),cipherText=curve.getPublicKey(ek);return cleanBytes(ek),{sharedSecret,cipherText}},decapsulate(cipherText,secretKey){let res=curve.getSharedSecret(secretKey,cipherText);return curve.lengths.publicKeyHasPrefix?res.subarray(1):res}}}function splitLengths(lst,name){return splitCoder(name,...lst.map((i)=>{if(typeof i.lengths[name]!=="number")throw Error("wrong length: "+name);return i.lengths[name]}))}function expandSeedXof(xof){return(seed,seedLen)=>xof(seed,{dkLen:seedLen})}function combineKeys(realSeedLen,expandSeed,...ck){let seedCoder=splitLengths(ck,"seed"),pkCoder=splitLengths(ck,"publicKey");if(realSeedLen===void 0)realSeedLen=seedCoder.bytesLen;anumber4(realSeedLen);function expandDecapsulationKey(seed){abytes4(seed,realSeedLen);let expanded=seedCoder.decode(expandSeed(seed,seedCoder.bytesLen)),keys=ck.map((i,j)=>i.keygen(expanded[j])),secretKey=keys.map((i)=>i.secretKey),publicKey=keys.map((i)=>i.publicKey);return{secretKey,publicKey}}return{info:{lengths:{seed:realSeedLen,publicKey:pkCoder.bytesLen,secretKey:realSeedLen}},getPublicKey(secretKey){return this.keygen(secretKey).publicKey},keygen(seed=randomBytes4(realSeedLen)){let{publicKey:pk,secretKey}=expandDecapsulationKey(seed),publicKey=pkCoder.encode(pk);return cleanBytes(pk),cleanBytes(secretKey),{secretKey:seed,publicKey}},expandDecapsulationKey,realSeedLen}}function combineKEMS(realSeedLen,realMsgLen,expandSeed,combiner,...kems){let keys=combineKeys(realSeedLen,expandSeed,...kems),ctCoder=splitLengths(kems,"cipherText"),pkCoder=splitLengths(kems,"publicKey"),msgCoder=splitLengths(kems,"msg");if(realMsgLen===void 0)realMsgLen=msgCoder.bytesLen;return anumber4(realMsgLen),{lengths:{...keys.info.lengths,msg:realMsgLen,msgRand:msgCoder.bytesLen,cipherText:ctCoder.bytesLen},getPublicKey:keys.getPublicKey,keygen:keys.keygen,encapsulate(pk,randomness=randomBytes4(msgCoder.bytesLen)){let pks=pkCoder.decode(pk),rand=msgCoder.decode(randomness),enc=kems.map((i,j)=>i.encapsulate(pks[j],rand[j])),sharedSecret=enc.map((i)=>i.sharedSecret),cipherText=enc.map((i)=>i.cipherText),res={sharedSecret:combiner(pks,cipherText,sharedSecret),cipherText:ctCoder.encode(cipherText)};return cleanBytes(sharedSecret,cipherText),res},decapsulate(ct,seed){let cts=ctCoder.decode(ct),{publicKey,secretKey}=keys.expandDecapsulationKey(seed),sharedSecret=kems.map((i,j)=>i.decapsulate(cts[j],secretKey[j]));return combiner(publicKey,cts,sharedSecret)}}}function QSF(label,pqc,curveKEM,xof,kdf){return ahash2(xof),ahash2(kdf),combineKEMS(32,32,expandSeedXof(xof),(pk,ct,ss)=>kdf(concatBytes2(ss[0],ss[1],ct[1],pk[1],asciiToBytes(label))),pqc,curveKEM)}var QSF_ml_kem768_p256=QSF("QSF-KEM(ML-KEM-768,P-256)-XOF(SHAKE256)-KDF(SHA3-256)",ml_kem768,ecdhKem(p256,!0),shake256,sha3_256),QSF_ml_kem1024_p384=QSF("QSF-KEM(ML-KEM-1024,P-384)-XOF(SHAKE256)-KDF(SHA3-256)",ml_kem1024,ecdhKem(p384,!0),shake256,sha3_256);function createKitchenSink(label,pqc,curveKEM,xof,hash){return ahash2(xof),ahash2(hash),combineKEMS(32,32,expandSeedXof(xof),(pk,ct,ss)=>{let preimage=concatBytes2(ss[0],ss[1],ct[0],pk[0],ct[1],pk[1],asciiToBytes(label)),len=32,ikm=concatBytes2(asciiToBytes("hybrid_prk"),preimage),prk=extract2(hash,ikm),info=concatBytes2(numberToBytesBE(32,2),asciiToBytes("shared_secret"),asciiToBytes("")),res=expand2(hash,prk,info,32);return cleanBytes(prk,info,ikm,preimage),res},pqc,curveKEM)}var x25519kem=ecdhKem(x25519),KitchenSink_ml_kem768_x25519=createKitchenSink("KitchenSink-KEM(ML-KEM-768,X25519)-XOF(SHAKE256)-KDF(HKDF-SHA-256)",ml_kem768,x25519kem,shake256,sha2562),ml_kem768_x25519=(()=>combineKEMS(32,32,expandSeedXof(shake256),(pk,ct,ss)=>sha3_256(concatBytes2(ss[0],ss[1],ct[1],pk[1],asciiToBytes("\\.//^\\"))),ml_kem768,x25519kem))();function nistCurveKem(curve,scalarLen,elemLen,nseed){let Fn=curve.Point.Fn;if(!Fn)throw Error("no Point.Fn");function rejectionSampling(seed){let sk;for(let start=0,end=scalarLen;;start=end,end+=scalarLen){if(end>seed.length)throw Error("rejection sampling failed");if(sk=Fn.fromBytes(seed.subarray(start,end),!0),Fn.isValidNot0(sk))break}let secretKey=Fn.toBytes(Fn.create(sk)),publicKey=curve.getPublicKey(secretKey,!1);return{secretKey,publicKey}}return{lengths:{secretKey:scalarLen,publicKey:elemLen,seed:nseed,msg:nseed,cipherText:elemLen},keygen(seed=randomBytes4(nseed)){return abytes4(seed,nseed,"seed"),rejectionSampling(seed)},getPublicKey(secretKey){return curve.getPublicKey(secretKey,!1)},encapsulate(publicKey,rand=randomBytes4(nseed)){abytes4(rand,nseed,"rand");let{secretKey:ek}=rejectionSampling(rand),sharedSecret=this.decapsulate(publicKey,ek),cipherText=curve.getPublicKey(ek,!1);return cleanBytes(ek),{sharedSecret,cipherText}},decapsulate(cipherText,secretKey){return curve.getSharedSecret(secretKey,cipherText).subarray(1)}}}function concreteHybridKem(label,mlkem,curve,nseed){let{secretKey:scalarLen,publicKeyUncompressed:elemLen}=curve.lengths;if(!scalarLen||!elemLen)throw Error("wrong curve");let curveKem=nistCurveKem(curve,scalarLen,elemLen,nseed),mlkemSeedLen=64,totalSeedLen=mlkemSeedLen+nseed;return combineKEMS(32,32,(seed)=>{abytes4(seed,32);let expanded=shake256(seed,{dkLen:totalSeedLen}),mlkemSeed=expanded.subarray(0,mlkemSeedLen),curveSeed=expanded.subarray(mlkemSeedLen,totalSeedLen);return concatBytes2(mlkemSeed,curveSeed)},(pk,ct,ss)=>sha3_256(concatBytes2(ss[0],ss[1],ct[1],pk[1],asciiToBytes(label))),mlkem,curveKem)}var ml_kem768_p256=(()=>concreteHybridKem("MLKEM768-P256",ml_kem768,p256,128))();var MLKEM768X25519=ml_kem768_x25519,MLKEM768P256=ml_kem768_p256;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function aarray(item,title,inner=()=>{}){if(!Array.isArray(item))throw TypeError(`"${title}" expected array, got type=${typeof item}`);for(let i=0;i<item.length;i++)inner(item[i],`${title}[${i}]`);return item}var abytes5=(value,length,title)=>abytes(value,length,title),anumber5=anumber;function astring(value,title=""){if(typeof value!=="string"){let prefix=title&&`"${title}" `;throw TypeError(prefix+"expected string, got type="+typeof value)}return value}function aobject3(value,title="object"){if(value===null||typeof value!=="object"||Array.isArray(value))throw TypeError(title==="object"?"expected valid options object":`"${title}" expected object, got type=${typeof value}`);return value}function afunction(value,title){if(typeof value!=="function")throw TypeError(`"${title}" is invalid: expected function, got ${typeof value}`);return value}var bytesToHex3=bytesToHex,concatBytes3=(...arrays)=>concatBytes(...arrays),hexToBytes3=(hex)=>hexToBytes(hex),isBytes5=isBytes,randomBytes5=(bytesLength)=>randomBytes(bytesLength),_0n7=BigInt(0),_1n8=BigInt(1),atitle3=(title)=>title?`"${title}" `:"";function abool3(value,title=""){if(typeof value!=="boolean")throw TypeError(atitle3(title)+"expected boolean, got type="+typeof value);return value}function abignumber2(n){if(typeof n==="bigint"){if(!isPosBig2(n))throw RangeError("positive bigint expected, got "+n)}else anumber5(n);return n}function asafenumber(value,title=""){if(typeof value!=="number"){let prefix=title&&`"${title}" `;throw TypeError(prefix+"expected number, got type="+typeof value)}if(!Number.isSafeInteger(value)){let prefix=title&&`"${title}" `;throw RangeError(prefix+"expected safe integer, got "+value)}}function numberToHexUnpadded2(num){let hex=abignumber2(num).toString(16);return hex.length&1?"0"+hex:hex}function hexToNumber2(hex){if(typeof hex!=="string")throw TypeError("hex string expected, got "+typeof hex);return hex===""?_0n7:BigInt("0x"+hex)}function bytesToNumberBE2(bytes){return hexToNumber2(bytesToHex(bytes))}function bytesToNumberLE2(bytes){return hexToNumber2(bytesToHex(copyBytes4(abytes(bytes)).reverse()))}function numberToBytesBE2(n,len){if(anumber(len),len===0)throw Error("zero output length is invalid");n=abignumber2(n);let expectedLen=len*2,hex=n.toString(16);if(hex.length>expectedLen)throw RangeError("number is too large");return hexToBytes(hex.padStart(expectedLen,"0"))}function numberToBytesLE2(n,len){return numberToBytesBE2(n,len).reverse()}function copyBytes4(bytes){return Uint8Array.from(abytes5(bytes))}function isPosBig2(n){return typeof n==="bigint"&&_0n7<=n}function inRange2(n,min,max){return isPosBig2(n)&&isPosBig2(min)&&isPosBig2(max)&&min<=n&&n<max}function aInRange2(title,n,min,max){if(!inRange2(n,min,max))throw RangeError("expected valid "+title+": "+min+" <= n < "+max+", got "+n)}function bitLen2(n){if(n<_0n7)throw Error("expected non-negative bigint, got "+n);return n===_0n7?0:n.toString(2).length}var bitMask2=(n)=>{return asafenumber(n,"n"),(_1n8<<BigInt(n))-_1n8};function createHmacDrbg2(hashLen,qByteLen,hmacFn){if(anumber(hashLen,"hashLen"),anumber(qByteLen,"qByteLen"),typeof hmacFn!=="function")throw TypeError("hmacFn must be a function");let u8n=(len)=>new Uint8Array(len),NULL=Uint8Array.of(),byte0=Uint8Array.of(0),byte1=Uint8Array.of(1),_maxDrbgIters=1000,v=u8n(hashLen),k=u8n(hashLen),i=0,reset=()=>{v.fill(1),k.fill(0),i=0},h=(...msgs)=>hmacFn(k,concatBytes3(v,...msgs)),reseed=(seed=NULL)=>{if(k=h(byte0,seed),v=h(),seed.length===0)return;k=h(byte1,seed),v=h()},gen=()=>{if(i++>=_maxDrbgIters)throw Error("drbg: tried max amount of iterations");let len=0,out=[];while(len<qByteLen){v=h();let sl=v.slice();out.push(sl),len+=v.length}return concatBytes3(...out)};return(seed,pred)=>{reset(),reseed(seed);let res=void 0;while((res=pred(gen()))===void 0)reseed();return reset(),res}}function validateObject2(object,fields={},optFields={},title="object"){aobject3(object,title),aobject3(fields,"fields"),aobject3(optFields,"optFields");function checkField(fieldName,expectedType,isOpt){let label=title==="object"?`param "${String(fieldName)}"`:`"${title}.${String(fieldName)}"`,val=object[fieldName];if(!Object.hasOwn(object,fieldName)&&(isOpt?val!==void 0:expectedType!=="function"))throw TypeError(`${label} is invalid: expected own property`);if(isOpt&&val===void 0)return;let current=typeof val;if(current!==expectedType||val===null)throw TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`)}let iter=(f,isOpt)=>Object.entries(f).forEach(([k,v])=>checkField(k,v,isOpt));iter(fields,!1),iter(optFields,!0)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var _0n8=BigInt(0),_1n9=BigInt(1),_2n6=BigInt(2),_3n4=BigInt(3),_4n3=BigInt(4),_5n3=BigInt(5),_7n3=BigInt(7),_8n3=BigInt(8),_9n2=BigInt(9),_15n=BigInt(15),_16n2=BigInt(16),POW_WINDOWED_MIN=BigInt("0x10000000000000000");function mod3(a,b){if(b<=_0n8)throw Error("mod: expected positive modulus, got "+b);let result=a%b;return result>=_0n8?result:b+result}function pow(num,power,modulo){if(modulo<=_1n9)throw Error("pow: expected modulus > 1, got "+modulo);if(typeof power!=="bigint")throw TypeError("invalid exponent: expected bigint, got "+typeof power);if(power<_0n8)throw Error("invalid exponent, negatives unsupported");if(power===_0n8)return _1n9;if(power===_1n9)return num;let d=num%modulo;if(d<_0n8)d+=modulo;if(power<POW_WINDOWED_MIN){let p2=_1n9;while(power>_0n8){if(power&_1n9)p2=p2*d%modulo;d=d*d%modulo,power>>=_1n9}return p2}let digits=[];while(power>_0n8)digits.push(Number(power&_15n)),power>>=_4n3;let table=Array(16);table[0]=_1n9,table[1]=d;for(let i=2;i<16;i++)table[i]=table[i-1]*d%modulo;let p=table[digits[digits.length-1]];for(let w=digits.length-2;w>=0;w--){p=p*p%modulo,p=p*p%modulo,p=p*p%modulo,p=p*p%modulo;let digit=digits[w];if(digit!==0)p=p*table[digit]%modulo}return p}function pow22(x,power,modulo){if(modulo<=_1n9)throw Error("pow2: expected modulus > 1, got "+modulo);if(power<_0n8)throw Error("pow2: expected non-negative exponent, got "+power);let res=x;while(power-- >_0n8)res*=res,res%=modulo;return res}function invert2(number,modulo){if(number===_0n8)throw Error("invert: expected non-zero number");if(modulo<=_1n9)throw Error("invert: expected modulus > 1, got "+modulo);let a=mod3(number,modulo),b=modulo,x=_0n8,u=_1n9;while(a!==_0n8){let q=b/a,r=b-a*q,m=x-u*q;b=a,a=r,x=u,u=m}if(b!==_1n9)throw Error("invert: does not exist");return mod3(x,modulo)}function invertCt(a,prime){if(prime<=_1n9)throw Error("invertCt: expected prime modulus > 1, got "+prime);let an=mod3(a,prime);if(an===_0n8)throw Error("invertCt: expected non-zero number");let inverse=pow(an,prime-_2n6,prime);if(mod3(an*inverse,prime)!==_1n9)throw Error("invertCt: does not exist");return inverse}function assertIsSquare2(Fp,root,n){let F2=Fp;if(!F2.eql(F2.sqr(root),n))throw Error("Cannot find square root")}function aoddModulus(order,fnName){if((order&_1n9)===_0n8)throw Error(fnName+": expected odd modulus, got "+order)}function sqrt3mod42(Fp,n){let F2=Fp,p1div4=(F2.ORDER+_1n9)/_4n3,root=F2.pow(n,p1div4);return assertIsSquare2(F2,root,n),root}function sqrt5mod82(Fp,n){let F2=Fp,p5div8=(F2.ORDER-_5n3)/_8n3,n2=F2.mul(n,_2n6),v=F2.pow(n2,p5div8),nv=F2.mul(n,v),i=F2.mul(F2.mul(nv,_2n6),v),root=F2.mul(nv,F2.sub(i,F2.ONE));return assertIsSquare2(F2,root,n),root}function sqrt9mod162(P){let Fp_=Field2(P),tn=tonelliShanks2(P),c1=tn(Fp_,Fp_.neg(Fp_.ONE)),c2=tn(Fp_,c1),c3=tn(Fp_,Fp_.neg(c1)),c4=(P+_7n3)/_16n2;return(Fp,n)=>{let F2=Fp,tv1=F2.pow(n,c4),tv2=F2.mul(tv1,c1),tv3=F2.mul(tv1,c2),tv4=F2.mul(tv1,c3),e1=F2.eql(F2.sqr(tv2),n),e2=F2.eql(F2.sqr(tv3),n);tv1=F2.cmov(tv1,tv2,e1),tv2=F2.cmov(tv4,tv3,e2);let e3=F2.eql(F2.sqr(tv2),n),root=F2.cmov(tv1,tv2,e3);return assertIsSquare2(F2,root,n),root}}function tonelliShanks2(P){if(P<_3n4)throw Error("sqrt is not defined for small field");aoddModulus(P,"tonelliShanks");let Q2=P-_1n9,S=0;while(Q2%_2n6===_0n8)Q2/=_2n6,S++;let Z=_2n6,_Fp=Field2(P);while(FpLegendre2(_Fp,Z)===1)if(Z++>1000)throw Error("Cannot find square root: probably non-prime P");if(S===1)return sqrt3mod42;let cc=_Fp.pow(Z,Q2),Q1div2=(Q2+_1n9)/_2n6;return function(Fp,n){let F2=Fp;if(F2.is0(n))return n;if(FpLegendre2(F2,n)!==1)throw Error("Cannot find square root");let M=S,c=F2.mul(F2.ONE,cc),t=F2.pow(n,Q2),R=F2.pow(n,Q1div2);while(!F2.eql(t,F2.ONE)){if(F2.is0(t))throw Error("Cannot find square root: probably non-prime P");let i=1,t_tmp=F2.sqr(t);while(!F2.eql(t_tmp,F2.ONE))if(i++,t_tmp=F2.sqr(t_tmp),i===M)throw Error("Cannot find square root");let exponent=_1n9<<BigInt(M-i-1),b=F2.pow(c,exponent);M=i,c=F2.sqr(b),t=F2.mul(t,c),R=F2.mul(R,b)}return R}}function FpSqrt2(P){if(aoddModulus(P,"Fp.sqrt"),P%_4n3===_3n4)return sqrt3mod42;if(P%_8n3===_5n3)return sqrt5mod82;if(P%_16n2===_9n2)return sqrt9mod162(P);return tonelliShanks2(P)}var isNegativeLE2=(num,modulo)=>(mod3(num,modulo)&_1n9)===_1n9,FIELD_FIELDS2=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function validateField2(field){if(aobject3(field,"field"),typeof field.ORDER!=="bigint")throw TypeError('param "ORDER" is invalid: expected bigint, got '+typeof field.ORDER);asafenumber(field.BYTES,"BYTES"),asafenumber(field.BITS,"BITS");for(let name of FIELD_FIELDS2)afunction(field[name],"field."+name);if(field.BYTES<1||field.BITS<1)throw Error("invalid field: expected BYTES/BITS > 0");if(field.ORDER<=_1n9)throw Error("invalid field: expected ORDER > 1, got "+field.ORDER);return field}function FpInvertBatch2(Fp,nums,passZero=!1){validateField2(Fp),aarray(nums,"nums"),abool3(passZero,"passZero");let F2=Fp,inverted=Array(nums.length).fill(passZero?F2.ZERO:void 0),multipliedAcc=nums.reduce((acc,num,i)=>{if(F2.is0(num))return acc;return inverted[i]=acc,F2.mul(acc,num)},F2.ONE),invertedAcc=F2.inv(multipliedAcc);return nums.reduceRight((acc,num,i)=>{if(F2.is0(num))return acc;return inverted[i]=F2.mul(acc,inverted[i]),F2.mul(acc,num)},invertedAcc),inverted}function FpLegendre2(Fp,n){validateField2(Fp);let F2=Fp;aoddModulus(F2.ORDER,"FpLegendre");let p1mod2=(F2.ORDER-_1n9)/_2n6,powered=F2.pow(n,p1mod2),yes=F2.eql(powered,F2.ONE),zero=F2.eql(powered,F2.ZERO),no=F2.eql(powered,F2.neg(F2.ONE));if(!yes&&!zero&&!no)throw Error("invalid Legendre symbol result");return yes?1:zero?0:-1}function nLength2(n,nBitLength){if(nBitLength!==void 0)anumber5(nBitLength);if(n<=_0n8)throw Error("invalid n length: expected positive n, got "+n);if(nBitLength!==void 0&&nBitLength<1)throw Error("invalid n length: expected positive bit length, got "+nBitLength);let bits=bitLen2(n);if(nBitLength!==void 0&&nBitLength<bits)throw Error(`invalid n length: expected nBitLength (${nBitLength}) >= bitLen(n) (${bits})`);let _nBitLength=nBitLength!==void 0?nBitLength:bits,nByteLength=Math.ceil(_nBitLength/8);return{nBitLength:_nBitLength,nByteLength}}var FIELD_SQRT=new WeakMap;class _Field2{ORDER;BITS;BYTES;isLE;ZERO=_0n8;ONE=_1n9;_lengths;_mod;constructor(ORDER,opts2={}){if(ORDER<=_1n9)throw Error("invalid field: expected ORDER > 1, got "+ORDER);let _nbitLength=void 0;if(this.isLE=!1,opts2!=null&&typeof opts2==="object"){if(typeof opts2.BITS==="number")_nbitLength=opts2.BITS;if(typeof opts2.sqrt==="function")Object.defineProperty(this,"sqrt",{value:opts2.sqrt,enumerable:!0});if(typeof opts2.isLE==="boolean")this.isLE=opts2.isLE;if(opts2.allowedLengths)this._lengths=Object.freeze(opts2.allowedLengths.slice());if(typeof opts2.modFromBytes==="boolean")this._mod=opts2.modFromBytes}let{nBitLength,nByteLength}=nLength2(ORDER,_nbitLength);if(nByteLength>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=ORDER,this.BITS=nBitLength,this.BYTES=nByteLength,Object.freeze(this)}create(num){return mod3(num,this.ORDER)}isValid(num){if(typeof num!=="bigint")throw TypeError("invalid field element: expected bigint, got "+typeof num);return _0n8<=num&&num<this.ORDER}is0(num){return num===_0n8}isValidNot0(num){return!this.is0(num)&&this.isValid(num)}isOdd(num){return(num&_1n9)===_1n9}neg(num){return mod3(-num,this.ORDER)}eql(lhs,rhs){return lhs===rhs}sqr(num){return mod3(num*num,this.ORDER)}add(lhs,rhs){return mod3(lhs+rhs,this.ORDER)}sub(lhs,rhs){return mod3(lhs-rhs,this.ORDER)}mul(lhs,rhs){return mod3(lhs*rhs,this.ORDER)}pow(num,power){return pow(num,power,this.ORDER)}div(lhs,rhs){return mod3(lhs*invert2(rhs,this.ORDER),this.ORDER)}sqrN(num){return num*num}addN(lhs,rhs){return lhs+rhs}subN(lhs,rhs){return lhs-rhs}mulN(lhs,rhs){return lhs*rhs}inv(num){return invert2(num,this.ORDER)}sqrt(num){let sqrt=FIELD_SQRT.get(this);if(!sqrt)FIELD_SQRT.set(this,sqrt=FpSqrt2(this.ORDER));return sqrt(this,num)}toBytes(num){return this.isLE?numberToBytesLE2(num,this.BYTES):numberToBytesBE2(num,this.BYTES)}fromBytes(bytes,skipValidation=!1){abytes5(bytes);let{_lengths:allowedLengths,BYTES,isLE:isLE4,ORDER,_mod:modFromBytes}=this;if(allowedLengths){if(bytes.length<1||!allowedLengths.includes(bytes.length)||bytes.length>BYTES)throw Error("Field.fromBytes: expected "+allowedLengths+" bytes, got "+bytes.length);let padded=new Uint8Array(BYTES);padded.set(bytes,isLE4?0:padded.length-bytes.length),bytes=padded}if(bytes.length!==BYTES)throw Error("Field.fromBytes: expected "+BYTES+" bytes, got "+bytes.length);let scalar=isLE4?bytesToNumberLE2(bytes):bytesToNumberBE2(bytes);if(modFromBytes)scalar=mod3(scalar,ORDER);if(!skipValidation){if(!this.isValid(scalar))throw Error("invalid field element: outside of range 0..ORDER")}return scalar}invertBatch(lst){return FpInvertBatch2(this,lst,!0)}cmov(a,b,condition){return abool3(condition,"condition"),condition?b:a}}function Field2(ORDER,opts2={}){return Object.freeze(_Field2.prototype),new _Field2(ORDER,opts2)}function getFieldBytesLength2(fieldOrder){if(typeof fieldOrder!=="bigint")throw Error("field order must be bigint");if(fieldOrder<=_1n9)throw Error("field order must be greater than 1");let bitLength=bitLen2(fieldOrder-_1n9);return Math.ceil(bitLength/8)}function getMinHashLength2(fieldOrder){let length=getFieldBytesLength2(fieldOrder);return length+Math.ceil(length/2)}function mapHashToField2(key,fieldOrder,isLE4=!1){abytes5(key);let len=key.length,fieldLen=getFieldBytesLength2(fieldOrder),minLen=Math.max(getMinHashLength2(fieldOrder),16);if(len<minLen||len>1024)throw Error("expected "+minLen+"-1024 bytes of input, got "+len);let num=isLE4?bytesToNumberLE2(key):bytesToNumberBE2(key),reduced=mod3(num,fieldOrder-_1n9)+_1n9;return isLE4?numberToBytesLE2(reduced,fieldLen):numberToBytesBE2(reduced,fieldLen)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var _0n9=BigInt(0),_1n10=BigInt(1),_4n4=BigInt(4),BLIND_BYTES=16,BLIND_BITS=128,FW_WINDOW=5,TABLE_BYTES_MAX=(()=>2147483648)();function validatePointCons(Point){let pc=Point;if(typeof pc!=="function")throw TypeError('"Point" expected constructor, got type='+typeof Point);afunction(pc.fromAffine,"Point.fromAffine"),afunction(pc.fromBytes,"Point.fromBytes"),afunction(pc.fromHex,"Point.fromHex"),aobject3(pc.BASE,"Point.BASE"),aobject3(pc.ZERO,"Point.ZERO"),validateField2(pc.Fp),validateField2(pc.Fn)}function normalizeZ2(c,points){validatePointCons(c),validateMSMPoints(points,c);let invertedZs=FpInvertBatch2(c.Fp,points.map((p)=>p.Z));return points.map((p,i)=>c.fromAffine(p.toAffine(invertedZs[i])))}function validateW2(W,bits,min=1){if(!Number.isSafeInteger(W)||W<min||W>bits)throw Error("invalid window size, expected ["+min+".."+bits+"], got W="+W)}function validateTableBytes(numPoints,fpBytes){let bytes=numPoints*(4*fpBytes+128);if(bytes>TABLE_BYTES_MAX)throw Error("invalid window size: table would need ~"+Math.ceil(bytes/1048576)+" MiB, max "+TABLE_BYTES_MAX/1048576+" MiB")}function probeRandomBytes(randomBytes6,length){if(randomBytes6===void 0)return;afunction(randomBytes6,"randomBytes");try{let probe=randomBytes6(length);if(!isBytes5(probe)||probe.length!==length)return}catch{return}return randomBytes6}function validateMSMPoints(points,c){aarray(points,"points"),points.forEach((p,i)=>{if(!(p instanceof c))throw Error("invalid point at index "+i)})}function validateMSMScalars(scalars,field,maxScalar){if(!Array.isArray(scalars))throw Error("array of scalars expected");scalars.forEach((s,i)=>{if(!(maxScalar===void 0?field.isValid(s):isPosBig2(s)&&s<maxScalar))throw Error("invalid scalar at index "+i)})}var pointWindowSizes2=new WeakMap;function getWindowSize(P){return pointWindowSizes2.get(P)||1}function oddMultiples(p,size){let dbl=p.double(),t=[p];for(let j=1;j<size;j++)t.push(t[j-1].add(dbl));return t}function wnafDigits(n,W){let size=2**W,half=size/2,mask=BigInt(size-1),d=[];while(n>_0n9){let w=0;if(n&_1n10){if(w=Number(n&mask),w>=half)w-=size;n-=BigInt(w)}d.push(w),n>>=_1n10}return d}function signedWindowDigits(n,W,windows){let size=2**W,half=size/2,mask=BigInt(size-1),shiftBy=BigInt(W),d=[];for(let w=0;w<windows;w++){let v=Number(n&mask);if(n>>=shiftBy,v>half)v-=size,n+=_1n10;d.push(v)}if(n!==_0n9)throw Error("invalid wnaf");return d}function wnafWalk(zero,tables,digits){let max=0;for(let d of digits)max=Math.max(max,d.length);let acc=zero;for(let bit=max-1;bit>=0;bit--){if(bit!==max-1)acc=acc.double();for(let i=0;i<digits.length;i++){let w=digits[i][bit];if(w){let item=tables[i][Math.abs(w)-1>>1];acc=acc.add(w<0?item.negate():item)}}}return acc}class ScalarMultiplier{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(Point,randomBytes6){validatePointCons(Point),this.randomBytes=probeRandomBytes(randomBytes6,BLIND_BYTES),this.Point=Point,this.BASE=Point.BASE,this.ZERO=Point.ZERO,this.bits=Point.Fn.BITS}buildWnafTable(point,W,bits){let windows=Math.ceil(bits/W)+1,half=2**(W-1),comp=[],base=point;for(let w=0;w<windows;w++){let acc=base;for(let i=0;i<half;i++)comp.push(acc),acc=acc.add(base);base=comp[comp.length-1].double()}return{W,bits,windows,comp}}wnafCachedCT(precomputes,n){let{W,windows,comp}=precomputes,half=2**(W-1),digits=signedWindowDigits(n,W,windows),p=this.ZERO,f=this.BASE;for(let w=0;w<windows;w++){let digit=digits[w],start=w*half,idx=Math.abs(digit)-1,sel=comp[start];for(let i=1;i<half;i++)sel=i===idx?comp[start+i]:sel;let neg=sel.negate();if(digit===0)f=f.add(comp[start]);else p=p.add(digit<0?neg:sel)}return{p,f}}getWnafPrecomputes(W,point,bits,transform){let entries=this.wnafPrecomputes.get(point),comp=entries?.find((entry)=>entry.W===W&&entry.bits===bits);if(!comp){if(comp=this.buildWnafTable(point,W,bits),typeof transform==="function")comp={...comp,comp:transform(comp.comp)};if(!entries)entries=[],this.wnafPrecomputes.set(point,entries);entries.push(comp)}return comp}assertPoint(point){if(!(point instanceof this.Point))throw TypeError('"point" expected Point instance, got type='+typeof point)}validateMulInput(point,scalar){if(this.assertPoint(point),!inRange2(scalar,_1n10,this.Point.Fn.ORDER))throw Error("invalid scalar")}runCT(point,n,bits,transform){let W=getWindowSize(point);if(W===1)return this.fixedWindowCT(point,n,bits);return this.wnafCachedCT(this.getWnafPrecomputes(W,point,bits,transform),n)}mulCT(point,scalar,transform){return this.validateMulInput(point,scalar),this.runCT(point,scalar,this.bits,transform)}mulCTBlinded(point,scalar,transform){if(this.validateMulInput(point,scalar),this.randomBytes===void 0)throw Error("randomBytes is required for scalar blinding");let bits=this.Point.Fn.BITS+BLIND_BITS,blind=this.randomBytes(BLIND_BYTES);if(!isBytes5(blind)||blind.length!==BLIND_BYTES)throw Error("randomBytes returned invalid byte array");blind[0]=blind[0]&63|128;let n=scalar+bytesToNumberBE2(blind)*this.Point.Fn.ORDER;return this.runCT(point,n,bits,transform)}fixedWindowCT(point,n,bits){let W=FW_WINDOW,size=1<<W,mask=bitMask2(W),table=Array(size);table[0]=this.ZERO;for(let i=1;i<size;i++)table[i]=table[i-1].add(point);let windows=Math.ceil(bits/W),acc=this.ZERO;for(let window2=windows-1;window2>=0;window2--){if(window2!==windows-1)for(let d=0;d<W;d++)acc=acc.double();let digit=Number(n>>BigInt(window2*W)&mask),sel=table[0];for(let i=1;i<size;i++)sel=i===digit?table[i]:sel;acc=acc.add(sel)}return{p:acc,f:acc}}shouldBlind(point,cofactor){if(this.randomBytes===void 0)return!1;if(cofactor===_1n10)return!0;if(point!==this.BASE)return!1;if(this.baseCanBeBlinded===void 0)this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0();return this.baseCanBeBlinded}mulSecret(point,scalar,cofactor,transform){return this.shouldBlind(point,cofactor)?this.mulCTBlinded(point,scalar,transform):this.mulCT(point,scalar,transform)}mulUnsafe(point,scalar,transform){if(this.assertPoint(point),!isPosBig2(scalar))throw Error("invalid scalar");let W=getWindowSize(point);if(W===1||scalar>=this.Point.Fn.ORDER)return mulAddUnsafe(this.Point,[point],[scalar],!0);let precomputes=this.getWnafPrecomputes(W,point,this.bits,transform);return this.wnafCachedCT(precomputes,scalar).p}setWindowSize(point,W){this.assertPoint(point),validateW2(W,this.bits);let windows=Math.ceil((this.bits+BLIND_BITS)/W)+1;validateTableBytes(windows*2**(W-1),this.Point.Fp.BYTES),pointWindowSizes2.set(point,W),this.wnafPrecomputes.delete(point)}hasWindowSize(point){return getWindowSize(point)!==1}}function mulAddUnsafe(c,points,scalars,allowOversized=!1){if(validatePointCons(c),validateMSMPoints(points,c),abool3(allowOversized,"allowOversized"),validateMSMScalars(scalars,c.Fn,allowOversized?c.Fn.ORDER**_4n4:void 0),points.length!==scalars.length)throw Error("arrays of points and scalars must have equal length");let tables=points.map((p)=>oddMultiples(p,4)),digits=scalars.map((n)=>wnafDigits(n,4));return wnafWalk(c.ZERO,tables,digits)}function createField2(order,field,isLE4){if(field){if(field.ORDER!==order)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return validateField2(field),field}else return Field2(order,{isLE:isLE4})}function createCurveFields2(type,CURVE,curveOpts={},FpFnLE){if(type!=="weierstrass"&&type!=="edwards")throw Error('expected curve type "weierstrass" or "edwards"');if(FpFnLE===void 0)FpFnLE=type==="edwards";if(!CURVE||typeof CURVE!=="object")throw Error(`expected valid ${type} CURVE object`);validateObject2(curveOpts);for(let p of["p","n","h"]){let val=CURVE[p];if(!(isPosBig2(val)&&val!==_0n9))throw Error(`CURVE.${p} must be positive bigint`)}let Fp=createField2(CURVE.p,curveOpts.Fp,FpFnLE),Fn=createField2(CURVE.n,curveOpts.Fn,FpFnLE),params=["Gx","Gy","a",type==="weierstrass"?"b":"d"];for(let p of params)if(!Fp.isValid(CURVE[p]))throw Error(`CURVE.${p} must be valid field element of CURVE.Fp`);return CURVE=Object.freeze(Object.assign({},CURVE)),{CURVE,Fp,Fn}}function createKeygen2(randomSecretKey,getPublicKey){return function(seed){let secretKey=randomSecretKey(seed);return{secretKey,publicKey:getPublicKey(secretKey)}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var _0n10=BigInt(0);class DERErr2 extends Error{constructor(m=""){super(m)}}var _DER={Err:DERErr2,_tlv:{encode:(tag,data)=>{let{Err:E}=_DER;if(asafenumber(tag,"tag"),tag<0||tag>255)throw new E("tlv.encode: wrong tag");if(astring(data,"data"),data.length&1)throw new E("tlv.encode: unpadded data");let dataLen=data.length/2,len=numberToHexUnpadded2(dataLen);if(len.length/2&128)throw new E("tlv.encode: long form length too big");let lenLen=dataLen>127?numberToHexUnpadded2(len.length/2|128):"";return numberToHexUnpadded2(tag)+lenLen+len+data},decode(tag,data){let{Err:E}=_DER;data=abytes5(data,void 0,"DER data");let pos=0;if(tag<0||tag>255)throw new E("tlv.decode: wrong tag");if(data.length<2||data[pos++]!==tag)throw new E("tlv.decode: wrong tlv");let first=data[pos++],isLong=!!(first&128),length=0;if(!isLong)length=first;else{let lenLen=first&127;if(!lenLen)throw new E("tlv.decode(long): indefinite length not supported");if(lenLen>4)throw new E("tlv.decode(long): byte length is too big");let lengthBytes=data.subarray(pos,pos+lenLen);if(lengthBytes.length!==lenLen)throw new E("tlv.decode: length bytes not complete");if(lengthBytes[0]===0)throw new E("tlv.decode(long): zero leftmost byte");for(let b of lengthBytes)length=length<<8|b;if(pos+=lenLen,length<128)throw new E("tlv.decode(long): not minimal encoding")}let v=data.subarray(pos,pos+length);if(v.length!==length)throw new E("tlv.decode: wrong value length");return{v,l:data.subarray(pos+length)}}},_int:{encode(num){let{Err:E}=_DER;if(abignumber2(num),num<_0n10)throw new E("integer: negative integers are not allowed");let hex=numberToHexUnpadded2(num);if(Number.parseInt(hex[0],16)&8)hex="00"+hex;if(hex.length&1)throw new E("unexpected DER parsing assertion: unpadded hex");return hex},decode(data){let{Err:E}=_DER;if(data.length<1)throw new E("invalid signature integer: empty");if(data[0]&128)throw new E("invalid signature integer: negative");if(data.length>1&&data[0]===0&&!(data[1]&128))throw new E("invalid signature integer: unnecessary leading zero");return bytesToNumberBE2(data)}},toSig(bytes,maxScalarBytes){let{Err:E,_int:int,_tlv:tlv}=_DER;if(maxScalarBytes!==void 0){if(asafenumber(maxScalarBytes,"maxScalarBytes"),maxScalarBytes<1)throw new E("invalid signature: maxScalarBytes must be positive")}let data=abytes5(bytes,void 0,"signature"),{v:seqBytes,l:seqLeftBytes}=tlv.decode(48,data);if(seqLeftBytes.length)throw new E("invalid signature: left bytes after parsing");let{v:rBytes,l:rLeftBytes}=tlv.decode(2,seqBytes),{v:sBytes,l:sLeftBytes}=tlv.decode(2,rLeftBytes);if(sLeftBytes.length)throw new E("invalid signature: left bytes after parsing");if(maxScalarBytes!==void 0&&(rBytes.length>maxScalarBytes||sBytes.length>maxScalarBytes))throw new E("invalid signature: integer too large");return{r:int.decode(rBytes),s:int.decode(sBytes)}},hexFromSig(sig){let{_tlv:tlv,_int:int}=_DER;validateObject2(sig,{r:"bigint",s:"bigint"},{},"sig");let rs=tlv.encode(2,int.encode(sig.r)),ss=tlv.encode(2,int.encode(sig.s)),seq=rs+ss;return tlv.encode(48,seq)}},DER2=(()=>{return Object.freeze(_DER._tlv),Object.freeze(_DER._int),Object.freeze(_DER)})();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var divNearest2=(num,den)=>(num+(num>=0?den:-den)/_2n7)/den;function _splitEndoScalar2(k,basis,n){aInRange2("scalar",k,_0n11,n);let[[a1,b1],[a2,b2]]=basis,c1=divNearest2(b2*k,n),c2=divNearest2(-b1*k,n),k1=k-c1*a1-c2*a2,k2=-c1*b1-c2*b2,k1neg=k1<_0n11,k2neg=k2<_0n11;if(k1neg)k1=-k1;if(k2neg)k2=-k2;let MAX_NUM=bitMask2(Math.ceil(bitLen2(n)/2))+_1n11;if(k1<_0n11||k1>=MAX_NUM||k2<_0n11||k2>=MAX_NUM)throw Error("splitScalar (endomorphism): failed for k");return{k1neg,k1,k2neg,k2}}function validateSigFormat2(format){if(!["compact","recovered","der"].includes(format))throw Error('Signature format must be "compact", "recovered", or "der"');return format}function validateSigOpts2(opts2,def){validateObject2(opts2);let optsn={};for(let optName of Object.keys(def))optsn[optName]=opts2[optName]===void 0?def[optName]:opts2[optName];if(abool3(optsn.lowS,"lowS"),abool3(optsn.prehash,"prehash"),optsn.format!==void 0)validateSigFormat2(optsn.format);return optsn}var _0n11=BigInt(0),_1n11=BigInt(1),_2n7=BigInt(2),_3n5=BigInt(3),_4n5=BigInt(4);function weierstrass2(params,extraOpts={}){let validated=createCurveFields2("weierstrass",params,extraOpts),Fp=validated.Fp,Fn=validated.Fn,CURVE=validated.CURVE,{h:cofactor,n:CURVE_ORDER}=CURVE;validateObject2(extraOpts,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:endoOpts,allowInfinityPoint,clearCofactor,isTorsionFree,fromBytes,toBytes}=extraOpts,randomBytes6=extraOpts.randomBytes===void 0?randomBytes5:extraOpts.randomBytes;if(endoOpts){if(!Fp.is0(CURVE.a)||typeof endoOpts.beta!=="bigint"||!Array.isArray(endoOpts.basises))throw Error('invalid endo: expected "beta": bigint and "basises": array')}let endo=endoOpts?{beta:endoOpts.beta,basises:endoOpts.basises.map((basis)=>[...basis])}:void 0,lengths=getWLengths2(Fp,Fn);function assertCompressionIsSupported(){if(!Fp.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}function pointToBytes(_c,point,isCompressed){if(point.is0()){if(!allowInfinityPoint)throw Error("bad point: ZERO");return Uint8Array.of(0)}let{x,y}=point.toAffine(),bx=Fp.toBytes(x);if(abool3(isCompressed,"isCompressed"),isCompressed){assertCompressionIsSupported();let hasEvenY=!Fp.isOdd(y);return concatBytes3(pprefix2(hasEvenY),bx)}else return concatBytes3(Uint8Array.of(4),bx,Fp.toBytes(y))}function pointFromBytes(bytes){abytes5(bytes,void 0,"Point");let{publicKey:comp,publicKeyUncompressed:uncomp}=lengths,length=bytes.length,head=bytes[0],tail=bytes.subarray(1);if(allowInfinityPoint&&length===1&&head===0)return{x:Fp.ZERO,y:Fp.ZERO};if(length===comp&&(head===2||head===3)){let x=Fp.fromBytes(tail);if(!Fp.isValid(x))throw Error("bad point: is not on curve, wrong x");let y2=weierstrassEquation(x),y;try{y=Fp.sqrt(y2)}catch(sqrtError){let err=sqrtError instanceof Error?": "+sqrtError.message:"";throw Error("bad point: is not on curve, sqrt error"+err)}assertCompressionIsSupported();let evenY=Fp.isOdd(y);if((head&1)===1!==evenY)y=Fp.neg(y);return{x,y}}else if(length===uncomp&&head===4){let L=Fp.BYTES,x=Fp.fromBytes(tail.subarray(0,L)),y=Fp.fromBytes(tail.subarray(L,L*2));if(!isValidXY(x,y))throw Error("bad point: is not on curve");return{x,y}}else throw Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`)}let encodePoint=toBytes===void 0?pointToBytes:toBytes,decodePoint=fromBytes===void 0?pointFromBytes:fromBytes,b3=Fp.mul(CURVE.b,_3n5),mulA=Fp.is0(CURVE.a)?(_)=>Fp.ZERO:(x)=>Fp.mul(CURVE.a,x);function weierstrassEquation(x){let x2=Fp.sqr(x),x3=Fp.mul(x2,x);return Fp.add(Fp.add(x3,Fp.mul(x,CURVE.a)),CURVE.b)}function isValidXY(x,y){let left=Fp.sqr(y),right=weierstrassEquation(x);return Fp.eql(left,right)}if(!isValidXY(CURVE.Gx,CURVE.Gy))throw Error("bad curve params: generator point");let _4a3=Fp.mul(Fp.pow(CURVE.a,_3n5),_4n5),_27b2=Fp.mul(Fp.sqr(CURVE.b),BigInt(27));if(Fp.is0(Fp.add(_4a3,_27b2)))throw Error("bad curve params: a or b");function acoord(title,n,banZero=!1){if(!Fp.isValid(n)||banZero&&Fp.is0(n))throw Error(`bad point coordinate ${title}`);return typeof n==="object"&&n!==null?Fp.create(n):n}function aprjpoint(other){if(!(other instanceof Point))throw Error("Weierstrass Point expected")}function splitEndoScalarN(k){if(!endo||!endo.basises)throw Error("no endo");return _splitEndoScalar2(k,endo.basises,Fn.ORDER)}function pushWnafPair(points,scalars,p,k){if(!Fn.isValid(k))throw RangeError("invalid scalar: out of range");if(endo){let{k1neg,k1,k2neg,k2}=splitEndoScalarN(k),psi=new Point(Fp.mul(p.X,endo.beta),p.Y,p.Z);points.push(k1neg?p.negate():p,k2neg?psi.negate():psi),scalars.push(k1,k2)}else points.push(p),scalars.push(k)}let validityCache=new WeakSet;class Point{static BASE=new Point(CURVE.Gx,CURVE.Gy,Fp.ONE);static ZERO=new Point(Fp.ZERO,Fp.ONE,Fp.ZERO);static Fp=Fp;static Fn=Fn;X;Y;Z;constructor(X,Y,Z){this.X=acoord("x",X),this.Y=acoord("y",Y,!0),this.Z=acoord("z",Z),Object.freeze(this)}static CURVE(){return CURVE}static fromAffine(p){let{x,y}=p||{};if(!p||!Fp.isValid(x)||!Fp.isValid(y))throw Error("invalid affine point");if(p instanceof Point)throw Error("projective point not allowed");if(Fp.is0(x)&&Fp.is0(y))return Point.ZERO;return new Point(x,y,Fp.ONE)}static fromBytes(bytes){let P=Point.fromAffine(decodePoint(abytes5(bytes,void 0,"point")));return P.assertValidity(),P}static fromHex(hex){return Point.fromBytes(hexToBytes3(hex))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(windowSize=6,isLazy=!0){if(wnaf.setWindowSize(this,windowSize),!isLazy)this.multiply(_3n5);return this}assertValidity(){let p=this;if(p.is0()){if(allowInfinityPoint&&Fp.is0(p.X)&&Fp.eql(p.Y,Fp.ONE)&&Fp.is0(p.Z))return;throw Error("bad point: ZERO")}if(validityCache.has(p))return;let{x,y}=p.toAffine();if(!Fp.isValid(x)||!Fp.isValid(y))throw Error("bad point: x or y not field elements");if(!isValidXY(x,y))throw Error("bad point: equation left != right");if(!p.isTorsionFree())throw Error("bad point: not in prime-order subgroup");validityCache.add(p)}hasEvenY(){let{y}=this.toAffine();if(!Fp.isOdd)throw Error("Field doesn't support isOdd");return!Fp.isOdd(y)}equals(other){aprjpoint(other);let{X:X1,Y:Y1,Z:Z1}=this,{X:X2,Y:Y2,Z:Z2}=other,U1=Fp.eql(Fp.mul(X1,Z2),Fp.mul(X2,Z1)),U2=Fp.eql(Fp.mul(Y1,Z2),Fp.mul(Y2,Z1));return U1&&U2}negate(){return new Point(this.X,Fp.neg(this.Y),this.Z)}double(){let{X:X1,Y:Y1,Z:Z1}=this,X3=Fp.ZERO,Y3=Fp.ZERO,Z3=Fp.ZERO,t0=Fp.mul(X1,X1),t1=Fp.mul(Y1,Y1),t2=Fp.mul(Z1,Z1),t3=Fp.mul(X1,Y1);return t3=Fp.add(t3,t3),Z3=Fp.mul(X1,Z1),Z3=Fp.add(Z3,Z3),X3=mulA(Z3),Y3=Fp.mul(b3,t2),Y3=Fp.add(X3,Y3),X3=Fp.sub(t1,Y3),Y3=Fp.add(t1,Y3),Y3=Fp.mul(X3,Y3),X3=Fp.mul(t3,X3),Z3=Fp.mul(b3,Z3),t2=mulA(t2),t3=Fp.sub(t0,t2),t3=mulA(t3),t3=Fp.add(t3,Z3),Z3=Fp.add(t0,t0),t0=Fp.add(Z3,t0),t0=Fp.add(t0,t2),t0=Fp.mul(t0,t3),Y3=Fp.add(Y3,t0),t2=Fp.mul(Y1,Z1),t2=Fp.add(t2,t2),t0=Fp.mul(t2,t3),X3=Fp.sub(X3,t0),Z3=Fp.mul(t2,t1),Z3=Fp.add(Z3,Z3),Z3=Fp.add(Z3,Z3),new Point(X3,Y3,Z3)}add(other){aprjpoint(other);let{X:X1,Y:Y1,Z:Z1}=this,{X:X2,Y:Y2,Z:Z2}=other,X3=Fp.ZERO,Y3=Fp.ZERO,Z3=Fp.ZERO,t0=Fp.mul(X1,X2),t1=Fp.mul(Y1,Y2),t2=Fp.mul(Z1,Z2),t3=Fp.add(X1,Y1),t4=Fp.add(X2,Y2);t3=Fp.mul(t3,t4),t4=Fp.add(t0,t1),t3=Fp.sub(t3,t4),t4=Fp.add(X1,Z1);let t5=Fp.add(X2,Z2);return t4=Fp.mul(t4,t5),t5=Fp.add(t0,t2),t4=Fp.sub(t4,t5),t5=Fp.add(Y1,Z1),X3=Fp.add(Y2,Z2),t5=Fp.mul(t5,X3),X3=Fp.add(t1,t2),t5=Fp.sub(t5,X3),Z3=mulA(t4),X3=Fp.mul(b3,t2),Z3=Fp.add(X3,Z3),X3=Fp.sub(t1,Z3),Z3=Fp.add(t1,Z3),Y3=Fp.mul(X3,Z3),t1=Fp.add(t0,t0),t1=Fp.add(t1,t0),t2=mulA(t2),t4=Fp.mul(b3,t4),t1=Fp.add(t1,t2),t2=Fp.sub(t0,t2),t2=mulA(t2),t4=Fp.add(t4,t2),t0=Fp.mul(t1,t4),Y3=Fp.add(Y3,t0),t0=Fp.mul(t5,t4),X3=Fp.mul(t3,X3),X3=Fp.sub(X3,t0),t0=Fp.mul(t3,t1),Z3=Fp.mul(t5,Z3),Z3=Fp.add(Z3,t0),new Point(X3,Y3,Z3)}subtract(other){return aprjpoint(other),this.add(other.negate())}is0(){return this.equals(Point.ZERO)}multiply(scalar){if(!Fn.isValidNot0(scalar))throw RangeError("invalid scalar: out of range");let{p,f}=wnaf.mulSecret(this,scalar,cofactor,normalize);return normalize([p,f])[0]}multiplyUnsafe(scalar){let p=this,sc=scalar;if(!Fn.isValid(sc))throw RangeError("invalid scalar: out of range");if(sc===_0n11||p.is0())return Point.ZERO;if(sc===_1n11)return p;if(wnaf.hasWindowSize(this))return wnaf.mulUnsafe(p,sc,normalize);let points=[],scalars=[];return pushWnafPair(points,scalars,p,sc),mulAddUnsafe(Point,points,scalars)}mulAddUnsafe(a,other,b){aprjpoint(other);let points=[],scalars=[];return pushWnafPair(points,scalars,this,a),pushWnafPair(points,scalars,other,b),mulAddUnsafe(Point,points,scalars)}toAffine(invertedZ){let p=this,iz=invertedZ;if(iz!=null&&!Fp.isValid(iz))throw RangeError('"invertedZ" expected valid field element');let{X,Y,Z}=p;if(Fp.eql(Z,Fp.ONE))return{x:X,y:Y};let is0=p.is0();if(iz==null)iz=is0?Fp.ONE:Fp.inv(Z);let x=Fp.mul(X,iz),y=Fp.mul(Y,iz),zz=Fp.mul(Z,iz);if(is0)return{x:Fp.ZERO,y:Fp.ZERO};if(!Fp.eql(zz,Fp.ONE))throw Error("invZ was invalid");return{x,y}}isTorsionFree(){if(cofactor===_1n11)return!0;if(isTorsionFree)return isTorsionFree(Point,this);return wnaf.mulUnsafe(this,CURVE_ORDER).is0()}clearCofactor(){if(cofactor===_1n11)return this;if(clearCofactor)return clearCofactor(Point,this);return this.multiplyUnsafe(cofactor)}isSmallOrder(){if(cofactor===_1n11)return this.is0();return this.clearCofactor().is0()}toBytes(isCompressed=!0){return abool3(isCompressed,"isCompressed"),this.assertValidity(),encodePoint(Point,this,isCompressed)}toHex(isCompressed=!0){return bytesToHex3(this.toBytes(isCompressed))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let normalize=(points)=>normalizeZ2(Point,points),wnaf=new ScalarMultiplier(Point,randomBytes6);if(wnaf.bits>=6)Point.BASE.precompute(6);return Object.freeze(Point.prototype),Object.freeze(Point),Point}function pprefix2(hasEvenY){return Uint8Array.of(hasEvenY?2:3)}function getWLengths2(Fp,Fn){return{secretKey:Fn.BYTES,publicKey:1+Fp.BYTES,publicKeyUncompressed:1+2*Fp.BYTES,publicKeyHasPrefix:!0,signature:2*Fn.BYTES}}function ecdh2(Point,ecdhOpts={}){validatePointCons(Point);let{Fn}=Point,randomBytes_=ecdhOpts.randomBytes===void 0?randomBytes5:ecdhOpts.randomBytes,lengths=Object.assign(getWLengths2(Point.Fp,Fn),{seed:Math.max(getMinHashLength2(Fn.ORDER),16)});function isValidSecretKey(secretKey){try{let num=Fn.fromBytes(secretKey);return Fn.isValidNot0(num)}catch(error){return!1}}function isValidPublicKey(publicKey,isCompressed){let{publicKey:comp,publicKeyUncompressed}=lengths;try{let l=publicKey.length;if(isCompressed===!0&&l!==comp)return!1;if(isCompressed===!1&&l!==publicKeyUncompressed)return!1;return!Point.fromBytes(publicKey).is0()}catch(error){return!1}}function randomSecretKey(seed){return seed=seed===void 0?randomBytes_(lengths.seed):seed,mapHashToField2(abytes5(seed,lengths.seed,"seed"),Fn.ORDER)}function getPublicKey(secretKey,isCompressed=!0){return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed)}function isProbPub(item){let{secretKey,publicKey,publicKeyUncompressed}=lengths,allowedLengths=Fn._lengths;if(!isBytes5(item))return;let l=abytes5(item,void 0,"key").length,isPub=l===publicKey||l===publicKeyUncompressed,isSec=l===secretKey||!!allowedLengths?.includes(l);if(isPub&&isSec)return;return isPub}function getSharedSecret(secretKeyA,publicKeyB,isCompressed=!0){if(isProbPub(secretKeyA)===!0)throw Error("first arg must be private key");if(isProbPub(publicKeyB)===!1)throw Error("second arg must be public key");let s=Fn.fromBytes(secretKeyA),b=Point.fromBytes(publicKeyB);if(b.is0())throw Error("invalid public key: point at infinity");return b.multiply(s).toBytes(isCompressed)}let utils={isValidSecretKey,isValidPublicKey,randomSecretKey},keygen=createKeygen2(randomSecretKey,getPublicKey);return Object.freeze(utils),Object.freeze(lengths),Object.freeze({getPublicKey,getSharedSecret,keygen,Point,utils,lengths})}function ecdsa2(Point,hash,ecdsaOpts={}){validatePointCons(Point);let hash_=hash;ahash(hash_),validateObject2(ecdsaOpts,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let opts2=Object.assign({},ecdsaOpts),randomBytes6=opts2.randomBytes===void 0?randomBytes5:opts2.randomBytes,hmac3=opts2.hmac===void 0?(key,msg)=>hmac(hash_,key,msg):opts2.hmac,{Fp,Fn}=Point,{ORDER:CURVE_ORDER,BITS:fnBits}=Fn,blindLength=getMinHashLength2(CURVE_ORDER),csprng=probeRandomBytes(randomBytes6,blindLength),{keygen,getPublicKey,getSharedSecret,utils,lengths}=ecdh2(Point,opts2),defaultSigOpts={prehash:!0,lowS:typeof opts2.lowS==="boolean"?opts2.lowS:!0,format:"compact",extraEntropy:!1},hasLargeRecoveryLifts=CURVE_ORDER*_2n7+_1n11<Fp.ORDER;function isBiggerThanHalfOrder(number){let HALF=CURVE_ORDER>>_1n11;return number>HALF}function validateRS(title,num){if(!Fn.isValidNot0(num))throw Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);return num}function assertFieldSignIsSupported(){if(!Fp.isOdd)throw Error("Field doesn't support isOdd")}function getRecoveryBit(x,y,r){return assertFieldSignIsSupported(),(x===r?0:2)|Number(Fp.isOdd(y))}function assertRecoverableCurve(){if(hasLargeRecoveryLifts)throw Error('"recovered" sig type is not supported for cofactor >2 curves')}function validateSigLength(bytes,format){validateSigFormat2(format);let size=lengths.signature,sizer=format==="compact"?size:format==="recovered"?size+1:void 0;return abytes5(bytes,sizer)}class Signature{r;s;recovery;constructor(r,s,recovery){if(this.r=validateRS("r",r),this.s=validateRS("s",s),recovery!=null){if(assertRecoverableCurve(),![0,1,2,3].includes(recovery))throw Error("invalid recovery id");this.recovery=recovery}Object.freeze(this)}static fromBytes(bytes,format=defaultSigOpts.format){validateSigLength(bytes,format);let recid;if(format==="der"){if(bytes.length>2*Fn.BYTES+16)throw new DER2.Err("invalid signature: DER signature too long");let{r:r2,s:s2}=DER2.toSig(abytes5(bytes),Fn.BYTES+1);return new Signature(r2,s2)}if(format==="recovered")recid=bytes[0],format="compact",bytes=bytes.subarray(1);let L=lengths.signature/2,r=bytes.subarray(0,L),s=bytes.subarray(L,L*2);return new Signature(Fn.fromBytes(r),Fn.fromBytes(s),recid)}static fromHex(hex,format){return this.fromBytes(hexToBytes3(hex),format)}assertRecovery(){let{recovery}=this;if(recovery==null)throw Error("invalid recovery id: must be present");return recovery}addRecoveryBit(recovery){return new Signature(this.r,this.s,recovery)}recoverPublicKey(messageHash){let{r,s}=this,recovery=this.assertRecovery(),radj=recovery===2||recovery===3?r+CURVE_ORDER:r;if(!Fp.isValid(radj))throw Error("invalid recovery id: sig.r+curve.n != R.x");let x=Fp.toBytes(radj),R=Point.fromBytes(concatBytes3(pprefix2((recovery&1)===0),x)),ir=Fn.inv(radj),h=bits2int_modN(abytes5(messageHash,void 0,"msgHash")),u1=Fn.create(-h*ir),u2=Fn.create(s*ir),Q2=Point.BASE.mulAddUnsafe(u1,R,u2);if(Q2.is0())throw Error("invalid recovery: point at infinify");return Q2.assertValidity(),Q2}hasHighS(){return isBiggerThanHalfOrder(this.s)}toBytes(format=defaultSigOpts.format){if(validateSigFormat2(format),format==="der")return hexToBytes3(DER2.hexFromSig(this));let{r,s}=this,rb=Fn.toBytes(r),sb=Fn.toBytes(s);if(format==="recovered")return assertRecoverableCurve(),concatBytes3(Uint8Array.of(this.assertRecovery()),rb,sb);return concatBytes3(rb,sb)}toHex(format){return bytesToHex3(this.toBytes(format))}}Object.freeze(Signature.prototype),Object.freeze(Signature);let bits2int=opts2.bits2int===void 0?function(bytes){if(bytes.length>8192)throw Error("input is too large");let num=bytesToNumberBE2(bytes),delta=bytes.length*8-fnBits;return delta>0?num>>BigInt(delta):num}:opts2.bits2int,bits2int_modN=opts2.bits2int_modN===void 0?function(bytes){return Fn.create(bits2int(bytes))}:opts2.bits2int_modN,ORDER_MASK=bitMask2(fnBits);function int2octets(num){return aInRange2("num < 2^"+fnBits,num,_0n11,ORDER_MASK),Fn.toBytes(num)}function validateMsgAndHash(message,prehash){return abytes5(message,void 0,"message"),prehash?abytes5(hash_(message),void 0,"prehashed message"):message}function prepSig(message,secretKey,opts3){let{lowS,prehash,extraEntropy}=validateSigOpts2(opts3,defaultSigOpts);message=validateMsgAndHash(message,prehash);let h1int=bits2int_modN(message),d=Fn.fromBytes(secretKey);if(!Fn.isValidNot0(d))throw Error("invalid private key");let seedArgs=[int2octets(d),int2octets(h1int)];if(extraEntropy!=null&&extraEntropy!==!1){let e=extraEntropy===!0?randomBytes6(lengths.secretKey):extraEntropy;seedArgs.push(abytes5(e,void 0,"extraEntropy"))}let seed=concatBytes3(...seedArgs),m=h1int;function k2sig(kBytes){let k=bits2int(kBytes);if(!Fn.isValidNot0(k))return;let q=Point.BASE.multiply(k).toAffine(),r=Fn.create(q.x);if(r===_0n11)return;let s;if(csprng!==void 0){let b=bytesToNumberBE2(mapHashToField2(csprng(blindLength),CURVE_ORDER)),ibk=Fn.inv(Fn.mul(b,k)),bm=Fn.mul(b,m),bd=Fn.mul(b,d);s=Fn.create(ibk*Fn.create(bm+bd*r))}else{let ik=invertCt(k,CURVE_ORDER);s=Fn.create(ik*Fn.create(m+r*d))}if(s===_0n11)return;let recovery=getRecoveryBit(q.x,q.y,r),normS=s;if(lowS&&isBiggerThanHalfOrder(s))normS=Fn.neg(s),recovery^=1;return new Signature(r,normS,hasLargeRecoveryLifts?void 0:recovery)}return{seed,k2sig}}function sign(message,secretKey,opts3={}){let{seed,k2sig}=prepSig(message,secretKey,opts3);return createHmacDrbg2(hash_.outputLen,Fn.BYTES,hmac3)(seed,k2sig).toBytes(opts3.format)}function verify(signature,message,publicKey,opts3={}){let{lowS,prehash,format}=validateSigOpts2(opts3,defaultSigOpts);if(publicKey=abytes5(publicKey,void 0,"publicKey"),message=validateMsgAndHash(message,prehash),!isBytes5(signature)){let end=signature instanceof Signature?", use sig.toBytes()":"";throw Error("verify expects Uint8Array signature"+end)}validateSigLength(signature,format);try{let sig=Signature.fromBytes(signature,format),P=Point.fromBytes(publicKey);if(P.is0())return!1;if(lowS&&sig.hasHighS())return!1;let{r,s}=sig,h=bits2int_modN(message),is=Fn.inv(s),u1=Fn.create(h*is),u2=Fn.create(r*is),R=Point.BASE.mulAddUnsafe(u1,P,u2);if(R.is0())return!1;let q=R.toAffine();if(Fn.create(q.x)!==r)return!1;if(format==="recovered"&&sig.recovery!==getRecoveryBit(q.x,q.y,r))return!1;return!0}catch(e){return!1}}function recoverPublicKey(signature,message,opts3={}){let{prehash}=validateSigOpts2(opts3,defaultSigOpts);return message=validateMsgAndHash(message,prehash),Signature.fromBytes(signature,"recovered").recoverPublicKey(message).toBytes()}return Object.freeze({keygen,getPublicKey,getSharedSecret,utils,lengths,Point,sign,verify,recoverPublicKey,Signature,hash:hash_})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var p256_CURVE2=(()=>({p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")}))();var p256_Point2=weierstrass2(p256_CURVE2),p2562=ecdsa2(p256_Point2,sha256);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var _0n12=BigInt(0),_1n12=BigInt(1),_2n8=BigInt(2),_4n6=BigInt(4),_8n4=BigInt(8);function isEdValidXY(Fp,CURVE,x,y){let x2=Fp.sqr(x),y2=Fp.sqr(y),left=Fp.add(Fp.mul(CURVE.a,x2),y2),right=Fp.add(Fp.ONE,Fp.mul(CURVE.d,Fp.mul(x2,y2)));return Fp.eql(left,right)}function edwards(params,extraOpts={}){validateObject2(extraOpts,{},{},"extraOpts");let opts2=extraOpts,validated=createCurveFields2("edwards",params,opts2,opts2.FpFnLE),{Fp,Fn}=validated,CURVE=validated.CURVE,{h:cofactor}=CURVE;if(FpLegendre2(Fp,CURVE.a)!==1)throw Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(FpLegendre2(Fp,CURVE.d)!==-1)throw Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");validateObject2(opts2,{},{uvRatio:"function",randomBytes:"function"});let randomBytes6=opts2.randomBytes===void 0?randomBytes5:opts2.randomBytes,MASK=_2n8<<BigInt(Fp.BYTES*8)-_1n12;function isOdd(n){if(!Fp.isOdd)throw Error("Field does not have .isOdd()");return Fp.isOdd(n)}let uvRatio=opts2.uvRatio===void 0?(u,v)=>{try{return{isValid:!0,value:Fp.sqrt(Fp.div(u,v))}}catch(e){return{isValid:!1,value:_0n12}}}:opts2.uvRatio;if(!isEdValidXY(Fp,CURVE,CURVE.Gx,CURVE.Gy))throw Error("bad curve params: generator point");let mulA=Fp.eql(CURVE.a,Fp.neg(Fp.ONE))?(x)=>Fp.neg(x):Fp.eql(CURVE.a,Fp.ONE)?(x)=>x:(x)=>Fp.mul(CURVE.a,x);function acoord(title,n,banZero=!1){let min=banZero?_1n12:_0n12;return aInRange2("coordinate "+title,n,min,MASK),n}function aedpoint(other){if(!(other instanceof Point))throw Error("EdwardsPoint expected")}class Point{static BASE=new Point(CURVE.Gx,CURVE.Gy,Fp.ONE,Fp.mul(CURVE.Gx,CURVE.Gy));static ZERO=new Point(Fp.ZERO,Fp.ONE,Fp.ONE,Fp.ZERO);static Fp=Fp;static Fn=Fn;X;Y;Z;T;constructor(X,Y,Z,T){this.X=acoord("x",X),this.Y=acoord("y",Y),this.Z=acoord("z",Z,!0),this.T=acoord("t",T),Object.freeze(this)}static CURVE(){return CURVE}static fromAffine(p){if(p instanceof Point)throw Error("extended point not allowed");let{x,y}=p||{};return acoord("x",x),acoord("y",y),new Point(x,y,Fp.ONE,Fp.mul(x,y))}static fromBytes(bytes,zip215=!1){let len=Fp.BYTES,{a,d}=CURVE;bytes=copyBytes4(abytes5(bytes,len,"point")),abool3(zip215,"zip215");let normed=copyBytes4(bytes),lastByte=bytes[len-1];normed[len-1]=lastByte&-129;let y=bytesToNumberLE2(normed),max=zip215?MASK:Fp.ORDER;aInRange2("point.y",y,_0n12,max);let y2=Fp.sqr(y),u=Fp.sub(y2,Fp.ONE),v=Fp.sub(Fp.mulN(d,y2),a),{isValid,value:x}=uvRatio(u,v);if(!isValid)throw Error("bad point: invalid y coordinate");let isXOdd=isOdd(x),isLastByteOdd=(lastByte&128)!==0;if(!zip215&&Fp.is0(x)&&isLastByteOdd)throw Error("bad point: x=0 and x_0=1");if(isLastByteOdd!==isXOdd)x=Fp.neg(x);return Point.fromAffine({x,y})}static fromHex(hex,zip215=!1){return Point.fromBytes(hexToBytes3(hex),zip215)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(windowSize=6,isLazy=!0){if(wnaf.setWindowSize(this,windowSize),!isLazy)this.multiply(_2n8);return this}assertValidity(){let p=this,{a,d}=CURVE;if(p.is0())throw Error("bad point: ZERO");let{X,Y,Z,T}=p,X2=Fp.sqr(X),Y2=Fp.sqr(Y),Z2=Fp.sqr(Z),Z4=Fp.sqr(Z2),aX2=Fp.mul(X2,a),left=Fp.mul(Fp.add(aX2,Y2),Z2),right=Fp.add(Z4,Fp.mul(d,Fp.mul(X2,Y2)));if(!Fp.eql(left,right))throw Error("bad point: equation left != right (1)");let XY=Fp.mul(X,Y),ZT=Fp.mul(Z,T);if(!Fp.eql(XY,ZT))throw Error("bad point: equation left != right (2)")}equals(other){aedpoint(other);let{X:X1,Y:Y1,Z:Z1}=this,{X:X2,Y:Y2,Z:Z2}=other,X1Z2=Fp.mul(X1,Z2),X2Z1=Fp.mul(X2,Z1),Y1Z2=Fp.mul(Y1,Z2),Y2Z1=Fp.mul(Y2,Z1);return Fp.eql(X1Z2,X2Z1)&&Fp.eql(Y1Z2,Y2Z1)}is0(){return this.equals(Point.ZERO)}negate(){return new Point(Fp.neg(this.X),this.Y,this.Z,Fp.neg(this.T))}double(){let{X:X1,Y:Y1,Z:Z1}=this,A=Fp.sqr(X1),B=Fp.sqr(Y1),C=Fp.mul(Fp.sqr(Z1),_2n8),D=mulA(A),x1y1=Fp.addN(X1,Y1),E=Fp.sub(Fp.subN(Fp.sqr(x1y1),A),B),G=Fp.addN(D,B),F2=Fp.subN(G,C),H=Fp.subN(D,B),X3=Fp.mul(E,F2),Y3=Fp.mul(G,H),T3=Fp.mul(E,H),Z3=Fp.mul(F2,G);return new Point(X3,Y3,Z3,T3)}add(other){aedpoint(other);let{d}=CURVE,{X:X1,Y:Y1,Z:Z1,T:T1}=this,{X:X2,Y:Y2,Z:Z2,T:T2}=other,A=Fp.mul(X1,X2),B=Fp.mul(Y1,Y2),C=Fp.mul(Fp.mulN(T1,d),T2),D=Fp.mul(Z1,Z2),E=Fp.sub(Fp.subN(Fp.mulN(Fp.addN(X1,Y1),Fp.addN(X2,Y2)),A),B),F2=Fp.subN(D,C),G=Fp.addN(D,C),H=Fp.sub(B,mulA(A)),X3=Fp.mul(E,F2),Y3=Fp.mul(G,H),T3=Fp.mul(E,H),Z3=Fp.mul(F2,G);return new Point(X3,Y3,Z3,T3)}subtract(other){return aedpoint(other),this.add(other.negate())}multiply(scalar){if(!Fn.isValidNot0(scalar))throw RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p,f}=wnaf.mulSecret(this,scalar,cofactor,normalize);return normalize([p,f])[0]}multiplyUnsafe(scalar){if(!Fn.isValid(scalar))throw RangeError("invalid scalar: expected 0 <= sc < curve.n");if(scalar===_0n12)return Point.ZERO;if(this.is0()||scalar===_1n12)return this;return wnaf.mulUnsafe(this,scalar,normalize)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return wnaf.mulUnsafe(this,CURVE.n).is0()}toAffine(invertedZ){let p=this,iz=invertedZ;if(iz!=null&&typeof iz!=="bigint")throw TypeError('"invertedZ" expected bigint, got type='+typeof iz);let{X,Y,Z}=p,is0=p.is0();if(iz==null)iz=is0?Fp.create(_8n4):Fp.inv(Z);let x=Fp.mul(X,iz),y=Fp.mul(Y,iz),zz=Fp.mul(Z,iz);if(is0)return{x:Fp.ZERO,y:Fp.ONE};if(!Fp.eql(zz,Fp.ONE))throw Error("invZ was invalid");return{x,y}}clearCofactor(){if(cofactor===_1n12)return this;if(cofactor===_2n8)return this.double();if(cofactor===_4n6)return this.double().double();if(cofactor===_8n4)return this.double().double().double();return this.multiplyUnsafe(cofactor)}toBytes(){let{x,y}=this.toAffine(),bytes=Fp.toBytes(y);return bytes[bytes.length-1]|=isOdd(x)?128:0,bytes}toHex(){return bytesToHex3(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let normalize=(points)=>normalizeZ2(Point,points),wnaf=new ScalarMultiplier(Point,randomBytes6);if(wnaf.bits>=6)Point.BASE.precompute(6);return Object.freeze(Point.prototype),Object.freeze(Point),Point}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var _0n13=BigInt(0),_1n13=BigInt(1),_2n9=BigInt(2);function cmask(P,swap){return P+swap-(swap>>_1n13<<_1n13)}function cswap(P){let offset=BigInt(6)*P;return(mask,x_2,x_3)=>{let sum=x_2+x_3,a=((offset+x_3-x_2)*mask+x_2)%P;return{x_2:a,x_3:sum-a}}}function validateOpts2(curve){return validateObject2(curve,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...curve})}function montgomery2(curveDef){let CURVE=validateOpts2(curveDef),{P,type,adjustScalarBytes:adjustScalarBytes2,powPminus2,randomBytes:rand}=CURVE,mulBaseHook=CURVE.scalarMultBase,is25519=type==="x25519";if(!is25519&&type!=="x448")throw Error("invalid type");let randomBytes_=rand===void 0?randomBytes5:rand,montgomeryBits=is25519?255:448,swap=cswap(P),fieldLen=is25519?32:56,Gu=is25519?BigInt(9):BigInt(5),a24=is25519?BigInt(121665):BigInt(39081),minScalar=is25519?_2n9**BigInt(254):_2n9**BigInt(447),maxAdded=is25519?BigInt(8)*(_2n9**BigInt(251)-_1n13):BigInt(4)*(_2n9**BigInt(445)-_1n13),maxScalar=minScalar+maxAdded+_1n13,modP=(n)=>mod3(n,P),GuBytes=encodeU(Gu);function encodeU(u){return numberToBytesLE2(modP(u),fieldLen)}function decodeU(u){let _u=copyBytes4(abytes5(u,fieldLen,"uCoordinate"));if(is25519)_u[31]&=127;return modP(bytesToNumberLE2(_u))}function decodeScalar(scalar){return bytesToNumberLE2(adjustScalarBytes2(copyBytes4(abytes5(scalar,fieldLen,"scalar"))))}let lowOrderU=new Set(is25519?[_0n13,_1n13,P-_1n13,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[_0n13,_1n13,P-_1n13]);function scalarMult(scalar,u){let pointU=decodeU(u);if(lowOrderU.has(pointU))throw Error("invalid private or public key received");let pu=montgomeryLadder(pointU,decodeScalar(scalar));if(pu===_0n13)throw Error("invalid private or public key received");return encodeU(pu)}function scalarMultBase(scalar){if(mulBaseHook===void 0)return scalarMult(scalar,GuBytes);let k=decodeScalar(scalar);aInRange2("scalar",k,minScalar,maxScalar);let pu=modP(mulBaseHook(k));if(pu===_0n13)throw Error("invalid private or public key received");return encodeU(pu)}let getPublicKey=scalarMultBase,getSharedSecret=scalarMult;function montgomeryLadder(u,scalar){aInRange2("u",u,_0n13,P),aInRange2("scalar",scalar,minScalar,maxScalar);let k=scalar,x_1=u,x_2=_1n13,z_2=_0n13,x_3=u,z_3=_1n13,kx=k^k>>_1n13;for(let t=BigInt(montgomeryBits-1);t>=_0n13;t--){let mask2=cmask(P,kx>>t);({x_2,x_3}=swap(mask2,x_2,x_3)),{x_2:z_2,x_3:z_3}=swap(mask2,z_2,z_3);let A=x_2+z_2,AA=modP(A*A),B=x_2-z_2,BB=modP(B*B),E=AA-BB,C=x_3+z_3,D=x_3-z_3,DA=modP(D*A),CB=modP(C*B),dacb=DA+CB,da_cb=DA-CB;x_3=modP(dacb*dacb),z_3=modP(x_1*modP(da_cb*da_cb)),x_2=modP(AA*BB),z_2=modP(E*(AA+modP(a24*E)))}let mask=cmask(P,k);({x_2,x_3}=swap(mask,x_2,x_3)),{x_2:z_2,x_3:z_3}=swap(mask,z_2,z_3);let z2=powPminus2(z_2);return modP(x_2*z2)}let lengths={secretKey:fieldLen,publicKey:fieldLen,seed:fieldLen},randomSecretKey=(seed)=>{return seed=seed===void 0?randomBytes_(fieldLen):seed,abytes5(seed,lengths.seed,"seed"),seed},utils={randomSecretKey};return Object.freeze(lengths),Object.freeze(utils),Object.freeze({keygen:createKeygen2(randomSecretKey,getPublicKey),getSharedSecret,getPublicKey,scalarMult,scalarMultBase,utils,GuBytes:GuBytes.slice(),lengths})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var _0n14=BigInt(0),_1n14=BigInt(1),_2n10=BigInt(2),_3n6=BigInt(3),_5n4=BigInt(5),_8n5=BigInt(8),ed25519_CURVE_p2=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),ed25519_CURVE=(()=>({p:ed25519_CURVE_p2,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:_8n5,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function ed25519_pow_2_252_32(x){let _10n=BigInt(10),_20n=BigInt(20),_40n=BigInt(40),_80n=BigInt(80),P=ed25519_CURVE_p2,b2=x*x%P*x%P,b4=pow22(b2,_2n10,P)*b2%P,b5=pow22(b4,_1n14,P)*x%P,b10=pow22(b5,_5n4,P)*b5%P,b20=pow22(b10,_10n,P)*b10%P,b40=pow22(b20,_20n,P)*b20%P,b80=pow22(b40,_40n,P)*b40%P,b160=pow22(b80,_80n,P)*b80%P,b240=pow22(b160,_80n,P)*b80%P,b250=pow22(b240,_10n,P)*b10%P;return{pow_p_5_8:pow22(b250,_2n10,P)*x%P,b2}}function adjustScalarBytes2(bytes){return bytes[0]&=248,bytes[31]&=127,bytes[31]|=64,bytes}var ED25519_SQRT_M1=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function uvRatio(u,v){let P=ed25519_CURVE_p2,v3=mod3(v*v*v,P),v7=mod3(v3*v3*v,P),pow3=ed25519_pow_2_252_32(u*v7).pow_p_5_8,x=mod3(u*v3*pow3,P),vx2=mod3(v*x*x,P),root1=x,root2=mod3(x*ED25519_SQRT_M1,P),useRoot1=vx2===u,useRoot2=vx2===mod3(-u,P),noRoot=vx2===mod3(-u*ED25519_SQRT_M1,P);if(useRoot1)x=root1;if(useRoot2||noRoot)x=root2;if(isNegativeLE2(x,P))x=mod3(-x,P);return{isValid:useRoot1||useRoot2,value:x}}var ed25519_Point=edwards(ed25519_CURVE,{uvRatio});var x255192=(()=>{let P=ed25519_CURVE_p2,powPminus2=(x)=>{let{pow_p_5_8,b2}=ed25519_pow_2_252_32(x);return mod3(pow22(pow_p_5_8,_3n6,P)*b2,P)};return montgomery2({P,type:"x25519",powPminus2,adjustScalarBytes:adjustScalarBytes2,scalarMultBase:(k)=>{let kn=mod3(k,ed25519_Point.Fn.ORDER);if(kn===_0n14)return _0n14;let p=ed25519_Point.BASE.multiply(kn);return mod3((p.Z+p.Y)*powPminus2(mod3(p.Z-p.Y,P)),P)}})})();var exportable=!1,webCryptoOff=!1;async function webCryptoFallback(func,fallback){if(webCryptoOff)return await fallback();try{return await func()}catch(error){if(error instanceof ReferenceError||error instanceof DOMException&&error.name==="NotSupportedError")return await fallback();else throw error}}async function scalarMult(scalar,u){return await webCryptoFallback(async()=>{let key=isCryptoKey(scalar)?scalar:await importX25519Key(scalar),peer=await crypto.subtle.importKey("raw",domBuffer(u),{name:"X25519"},exportable,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:peer},key,256))},()=>{if(isCryptoKey(scalar))throw Error("CryptoKey provided but X25519 WebCrypto is not supported");return x255192.scalarMult(scalar,u)})}async function scalarMultBase(scalar){return await webCryptoFallback(async()=>{return scalarMult(scalar,x255192.GuBytes)},()=>{if(isCryptoKey(scalar))throw Error("CryptoKey provided but X25519 WebCrypto is not supported");return x255192.scalarMultBase(scalar)})}var pkcs8Prefix=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]);async function importX25519Key(key){if(key.length!==32)throw Error("X25519 private key must be 32 bytes");let pkcs8=new Uint8Array([...pkcs8Prefix,...key]);return crypto.subtle.importKey("pkcs8",pkcs8,{name:"X25519"},exportable,["deriveBits"])}function isCryptoKey(key){return typeof CryptoKey<"u"&&key instanceof CryptoKey}function domBuffer(arr){return arr}class LineReader{s;transcript=[];buf=new Uint8Array(0);constructor(stream){this.s=stream.getReader()}async readLine(){let line=[];while(!0){let i=this.buf.indexOf(10);if(i>=0)return line.push(this.buf.subarray(0,i)),this.transcript.push(this.buf.subarray(0,i+1)),this.buf=this.buf.subarray(i+1),asciiString(flatten(line));if(this.buf.length>0)line.push(this.buf),this.transcript.push(this.buf);let next=await this.s.read();if(next.done)return this.buf=flatten(line),null;this.buf=next.value}}close(){return this.s.releaseLock(),{rest:this.buf,transcript:flatten(this.transcript)}}}function asciiString(bytes){return bytes.forEach((b)=>{if(b<32||b>126)throw Error("invalid non-ASCII byte in header")}),new TextDecoder().decode(bytes)}function flatten(arr){let len=arr.reduce((sum,line)=>sum+line.length,0),out=new Uint8Array(len),n=0;for(let a of arr)out.set(a,n),n+=a.length;return out}function prepend(s,...prefixes){return s.pipeThrough(new TransformStream({start(controller){for(let p of prefixes)controller.enqueue(p)}}))}function stream(a){return new ReadableStream({start(controller){controller.enqueue(a),controller.close()}})}async function readAll(stream2){if(!(stream2 instanceof ReadableStream))throw Error("readAll expects a ReadableStream<Uint8Array>");return new Uint8Array(await new Response(stream2).arrayBuffer())}async function readAllString(stream2){if(!(stream2 instanceof ReadableStream))throw Error("readAllString expects a ReadableStream<Uint8Array>");return await new Response(stream2).text()}async function read(stream2,n){let reader=stream2.getReader(),chunks=[],readBytes=0;while(readBytes<n){let{done,value}=await reader.read();if(done)throw Error("stream ended before reading "+n.toString()+" bytes");chunks.push(value),readBytes+=value.length}reader.releaseLock();let buf=flatten(chunks),data=buf.subarray(0,n),rest=prepend(stream2,buf.subarray(n));return{data,rest}}class Stanza{args;body;constructor(args,body){this.args=args,this.body=body}}async function parseNextStanza(hdr){let argsLine=await hdr.readLine();if(argsLine===null)throw Error("invalid stanza");let args=argsLine.split(" ");if(args.length<2||args.shift()!=="->")return{next:argsLine};for(let arg of args)if(arg.length===0)throw Error("invalid stanza");let bodyLines=[];for(;;){let nextLine=await hdr.readLine();if(nextLine===null)throw Error("invalid stanza");let line=base64nopad.decode(nextLine);if(line.length>48)throw Error("invalid stanza");if(bodyLines.push(line),line.length<48)break}let body=flatten(bodyLines);return{s:new Stanza(args,body)}}async function parseHeader(header){let hdr=new LineReader(header),versionLine=await hdr.readLine();if(versionLine!=="age-encryption.org/v1")throw Error("invalid version "+(versionLine??"line"));let stanzas=[];for(;;){let{s,next:macLine}=await parseNextStanza(hdr);if(s!==void 0){stanzas.push(s);continue}if(!macLine.startsWith("--- "))throw Error("invalid header");let MAC=base64nopad.decode(macLine.slice(4)),{rest,transcript}=hdr.close(),headerNoMAC=transcript.slice(0,transcript.length-1-macLine.length+3);return{stanzas,headerNoMAC,MAC,headerSize:transcript.length,rest:prepend(header,rest)}}}function encodeHeaderNoMAC(recipients){let lines=[];lines.push(`age-encryption.org/v1
3
+ `);for(let s of recipients){lines.push("-> "+s.args.join(" ")+`
4
+ `);for(let i=0;i<s.body.length;i+=48){let end=i+48;if(end>s.body.length)end=s.body.length;lines.push(base64nopad.encode(s.body.subarray(i,end))+`
5
+ `)}if(s.body.length%48===0)lines.push(`
6
+ `)}return lines.push("---"),new TextEncoder().encode(lines.join(""))}function encodeHeader(recipients,MAC){return flatten([encodeHeaderNoMAC(recipients),new TextEncoder().encode(" "+base64nopad.encode(MAC)+`
7
+ `)])}function generateX25519Identity(){let scalar=randomBytes(32),identity=bech32.encodeFromBytes("AGE-SECRET-KEY-",scalar).toUpperCase();return Promise.resolve(identity)}async function identityToRecipient(identity){let scalar;if(isCryptoKey2(identity))scalar=identity;else if(identity.startsWith("AGE-SECRET-KEY-PQ-1")){let res=bech32.decodeToBytes(identity);if(res.prefix.toUpperCase()!=="AGE-SECRET-KEY-PQ-"||res.bytes.length!==32)throw Error("invalid identity");let recipient2=MLKEM768X25519.getPublicKey(res.bytes);return bech32.encode("age1pq",bech32.toWords(recipient2),!1)}else{let res=bech32.decodeToBytes(identity);if(!identity.startsWith("AGE-SECRET-KEY-1")||res.prefix.toUpperCase()!=="AGE-SECRET-KEY-"||res.bytes.length!==32)throw Error("invalid identity");scalar=res.bytes}let recipient=await scalarMultBase(scalar);return bech32.encodeFromBytes("age",recipient)}class HybridRecipient{recipient;constructor(s){let{prefix,words}=bech32.decode(s,!1),bytes=bech32.fromWords(words);if(!s.startsWith("age1pq1")||prefix.toLowerCase()!=="age1pq"||bytes.length!==1216)throw Error("invalid recipient");this.recipient=bytes}wrapFileKey(fileKey){let{cipherText:encapsulatedKey,sharedSecret}=MLKEM768X25519.encapsulate(this.recipient),label=new TextEncoder().encode("age-encryption.org/mlkem768x25519"),{key,nonce}=hpkeContext(hpkeMLKEM768X25519,sharedSecret,label),ciphertext=chacha20poly1305(key,nonce).encrypt(fileKey);return[new Stanza(["mlkem768x25519",base64nopad.encode(encapsulatedKey)],ciphertext)]}}class HybridIdentity{identity;constructor(s){let res=bech32.decodeToBytes(s);if(!s.startsWith("AGE-SECRET-KEY-PQ-1")||res.prefix.toUpperCase()!=="AGE-SECRET-KEY-PQ-"||res.bytes.length!==32)throw Error("invalid identity");this.identity=res.bytes}unwrapFileKey(stanzas){for(let s of stanzas){if(s.args.length<1||s.args[0]!=="mlkem768x25519")continue;if(s.args.length!==2)throw Error("invalid mlkem768x25519 stanza");let share=base64nopad.decode(s.args[1]);if(share.length!==1120)throw Error("invalid mlkem768x25519 stanza");if(s.body.length!==32)throw Error("invalid mlkem768x25519 stanza");let sharedSecret=MLKEM768X25519.decapsulate(share,this.identity),label=new TextEncoder().encode("age-encryption.org/mlkem768x25519"),{key,nonce}=hpkeContext(hpkeMLKEM768X25519,sharedSecret,label);try{return chacha20poly1305(key,nonce).decrypt(s.body)}catch{continue}}return null}}var hpkeMLKEM768X25519=25722,hpkeMLKEM768P256=80,hpkeDHKEMP256=16;function hpkeContext(kemID,sharedSecret,info){let suiteID=hpkeSuiteID(kemID),pskIDHash=hpkeLabeledExtract(suiteID,void 0,"psk_id_hash",new Uint8Array(0)),infoHash=hpkeLabeledExtract(suiteID,void 0,"info_hash",info),ksContext=new Uint8Array(1+pskIDHash.length+infoHash.length);ksContext[0]=0,ksContext.set(pskIDHash,1),ksContext.set(infoHash,1+pskIDHash.length);let secret=hpkeLabeledExtract(suiteID,sharedSecret,"secret",new Uint8Array(0)),key=hpkeLabeledExpand(suiteID,secret,"key",ksContext,32),nonce=hpkeLabeledExpand(suiteID,secret,"base_nonce",ksContext,12);return{key,nonce}}function hpkeSuiteID(kemID){let suiteID=new Uint8Array(10);return suiteID.set(new TextEncoder().encode("HPKE"),0),suiteID[4]=kemID>>8&255,suiteID[5]=kemID&255,suiteID[6]=0,suiteID[7]=1,suiteID[8]=0,suiteID[9]=3,suiteID}function hpkeLabeledExtract(suiteID,salt,label,ikm){let labeledIKM=new Uint8Array(7+suiteID.length+label.length+ikm.length),offset=0;return labeledIKM.set(new TextEncoder().encode("HPKE-v1"),offset),offset+=7,labeledIKM.set(suiteID,offset),offset+=suiteID.length,labeledIKM.set(new TextEncoder().encode(label),offset),offset+=label.length,labeledIKM.set(ikm,offset),extract(sha256,labeledIKM,salt)}function hpkeLabeledExpand(suiteID,prk,label,info,length){let labeledInfo=new Uint8Array(9+suiteID.length+label.length+info.length),offset=0;return labeledInfo[offset]=length>>8&255,labeledInfo[offset+1]=length&255,offset+=2,labeledInfo.set(new TextEncoder().encode("HPKE-v1"),offset),offset+=7,labeledInfo.set(suiteID,offset),offset+=suiteID.length,labeledInfo.set(new TextEncoder().encode(label),offset),offset+=label.length,labeledInfo.set(info,offset),expand(sha256,prk,labeledInfo,length)}function hpkeDHKEMP256Encapsulate(recipient){if(recipient.length!==p2562.lengths.publicKeyUncompressed)recipient=p2562.Point.fromBytes(recipient).toBytes(!1);let ephemeral=p2562.utils.randomSecretKey(),encapsulatedKey=p2562.getPublicKey(ephemeral,!1),ss=p2562.getSharedSecret(ephemeral,recipient,!0).subarray(1),kemContext=new Uint8Array(encapsulatedKey.length+recipient.length);kemContext.set(encapsulatedKey,0),kemContext.set(recipient,encapsulatedKey.length);let suiteID=new Uint8Array(5);suiteID.set(new TextEncoder().encode("KEM"),0),suiteID[3]=hpkeDHKEMP256>>8,suiteID[4]=hpkeDHKEMP256&255;let eaePRK=hpkeLabeledExtract(suiteID,void 0,"eae_prk",ss),sharedSecret=hpkeLabeledExpand(suiteID,eaePRK,"shared_secret",kemContext,32);return{encapsulatedKey,sharedSecret}}class TagRecipient{recipient;constructor(s){let res=bech32.decodeToBytes(s);if(!s.startsWith("age1tag1")||res.prefix.toLowerCase()!=="age1tag"||res.bytes.length!==33)throw Error("invalid recipient");this.recipient=res.bytes}wrapFileKey(fileKey){let{encapsulatedKey,sharedSecret}=hpkeDHKEMP256Encapsulate(this.recipient),label=new TextEncoder().encode("age-encryption.org/p256tag"),tag=(()=>{let recipientHash=sha256(this.recipient).subarray(0,4),ikm=new Uint8Array(encapsulatedKey.length+recipientHash.length);return ikm.set(encapsulatedKey,0),ikm.set(recipientHash,encapsulatedKey.length),extract(sha256,ikm,label).subarray(0,4)})(),{key,nonce}=hpkeContext(hpkeDHKEMP256,sharedSecret,label),ciphertext=chacha20poly1305(key,nonce).encrypt(fileKey);return[new Stanza(["p256tag",base64nopad.encode(tag),base64nopad.encode(encapsulatedKey)],ciphertext)]}}class HybridTagRecipient{recipient;constructor(s){let{prefix,words}=bech32.decode(s,!1),bytes=bech32.fromWords(words);if(!s.startsWith("age1tagpq1")||prefix.toLowerCase()!=="age1tagpq"||bytes.length!==1249)throw Error("invalid recipient");this.recipient=bytes}wrapFileKey(fileKey){let{cipherText:encapsulatedKey,sharedSecret}=MLKEM768P256.encapsulate(this.recipient),label=new TextEncoder().encode("age-encryption.org/mlkem768p256tag"),tag=(()=>{let recipientHash=sha256(this.recipient.subarray(1184)).subarray(0,4),ikm=new Uint8Array(encapsulatedKey.length+recipientHash.length);return ikm.set(encapsulatedKey,0),ikm.set(recipientHash,encapsulatedKey.length),extract(sha256,ikm,label).subarray(0,4)})(),{key,nonce}=hpkeContext(hpkeMLKEM768P256,sharedSecret,label),ciphertext=chacha20poly1305(key,nonce).encrypt(fileKey);return[new Stanza(["mlkem768p256tag",base64nopad.encode(tag),base64nopad.encode(encapsulatedKey)],ciphertext)]}}class X25519Recipient{recipient;constructor(s){let res=bech32.decodeToBytes(s);if(!s.startsWith("age1")||res.prefix.toLowerCase()!=="age"||res.bytes.length!==32)throw Error("invalid recipient");this.recipient=res.bytes}async wrapFileKey(fileKey){let ephemeral=randomBytes(32),share=await scalarMultBase(ephemeral),secret=await scalarMult(ephemeral,this.recipient),salt=new Uint8Array(share.length+this.recipient.length);salt.set(share),salt.set(this.recipient,share.length);let label=new TextEncoder().encode("age-encryption.org/v1/X25519"),key=hkdf(sha256,secret,salt,label,32);return[new Stanza(["X25519",base64nopad.encode(share)],encryptFileKey(fileKey,key))]}}class X25519Identity{identity;recipient;constructor(s){if(isCryptoKey2(s)){this.identity=s,this.recipient=scalarMultBase(s);return}let res=bech32.decodeToBytes(s);if(!s.startsWith("AGE-SECRET-KEY-1")||res.prefix.toUpperCase()!=="AGE-SECRET-KEY-"||res.bytes.length!==32)throw Error("invalid identity");this.identity=res.bytes,this.recipient=scalarMultBase(res.bytes)}async unwrapFileKey(stanzas){for(let s of stanzas){if(s.args.length<1||s.args[0]!=="X25519")continue;if(s.args.length!==2)throw Error("invalid X25519 stanza");let share=base64nopad.decode(s.args[1]);if(share.length!==32)throw Error("invalid X25519 stanza");let secret=await scalarMult(this.identity,share),recipient=await this.recipient,salt=new Uint8Array(share.length+recipient.length);salt.set(share),salt.set(recipient,share.length);let label=new TextEncoder().encode("age-encryption.org/v1/X25519"),key=hkdf(sha256,secret,salt,label,32),fileKey=decryptFileKey(s.body,key);if(fileKey!==null)return fileKey}return null}}class ScryptRecipient{passphrase;logN;constructor(passphrase,logN){this.passphrase=passphrase,this.logN=logN}wrapFileKey(fileKey){let salt=randomBytes(16),label="age-encryption.org/v1/scrypt",labelAndSalt=new Uint8Array(44);labelAndSalt.set(new TextEncoder().encode("age-encryption.org/v1/scrypt")),labelAndSalt.set(salt,28);let key=scrypt(this.passphrase,labelAndSalt,{N:2**this.logN,r:8,p:1,dkLen:32});return[new Stanza(["scrypt",base64nopad.encode(salt),this.logN.toString()],encryptFileKey(fileKey,key))]}}class ScryptIdentity{passphrase;constructor(passphrase){this.passphrase=passphrase}unwrapFileKey(stanzas){for(let s of stanzas){if(s.args.length<1||s.args[0]!=="scrypt")continue;if(stanzas.length!==1)throw Error("scrypt recipient is not the only one in the header");if(s.args.length!==3)throw Error("invalid scrypt stanza");if(!/^[1-9][0-9]*$/.test(s.args[2]))throw Error("invalid scrypt stanza");let salt=base64nopad.decode(s.args[1]);if(salt.length!==16)throw Error("invalid scrypt stanza");let logN=Number(s.args[2]);if(logN>20)throw Error("scrypt work factor is too high");let label="age-encryption.org/v1/scrypt",labelAndSalt=new Uint8Array(label.length+16);labelAndSalt.set(new TextEncoder().encode(label)),labelAndSalt.set(salt,label.length);let key=scrypt(this.passphrase,labelAndSalt,{N:2**logN,r:8,p:1,dkLen:32}),fileKey=decryptFileKey(s.body,key);if(fileKey!==null)return fileKey}return null}}function encryptFileKey(fileKey,key){let nonce=new Uint8Array(12);return chacha20poly1305(key,nonce).encrypt(fileKey)}function decryptFileKey(body,key){if(body.length!==32)throw Error("invalid stanza");let nonce=new Uint8Array(12);try{return chacha20poly1305(key,nonce).decrypt(body)}catch{return null}}function isCryptoKey2(key){return typeof CryptoKey<"u"&&key instanceof CryptoKey}var chacha20poly1305Overhead=16,chunkSize=(()=>65536)(),chunkSizeWithOverhead=(()=>chunkSize+chacha20poly1305Overhead)();function decryptSTREAM(key){let streamNonce=new Uint8Array(12),incNonce=()=>{for(let i=streamNonce.length-2;i>=0;i--)if(streamNonce[i]++,streamNonce[i]!==0)break},firstChunk=!0,ciphertextBuffer=new Uint8Array(chunkSizeWithOverhead),ciphertextBufferUsed=0;return new TransformStream({transform(chunk,controller){while(chunk.length>0){if(ciphertextBufferUsed===ciphertextBuffer.length){let decryptedChunk=chacha20poly1305(key,streamNonce).decrypt(ciphertextBuffer);controller.enqueue(decryptedChunk),incNonce(),ciphertextBufferUsed=0,firstChunk=!1}let n=Math.min(ciphertextBuffer.length-ciphertextBufferUsed,chunk.length);ciphertextBuffer.set(chunk.subarray(0,n),ciphertextBufferUsed),ciphertextBufferUsed+=n,chunk=chunk.subarray(n)}},flush(controller){streamNonce[11]=1;let decryptedChunk=chacha20poly1305(key,streamNonce).decrypt(ciphertextBuffer.subarray(0,ciphertextBufferUsed));if(!firstChunk&&decryptedChunk.length===0)throw Error("final chunk is empty");controller.enqueue(decryptedChunk)}})}function plaintextSize(ciphertextSize){if(ciphertextSize<chacha20poly1305Overhead)throw Error("ciphertext is too small");if(ciphertextSize===chacha20poly1305Overhead)return 0;let fullChunks=Math.floor(ciphertextSize/chunkSizeWithOverhead),lastChunk=ciphertextSize%chunkSizeWithOverhead;if(0<lastChunk&&lastChunk<=chacha20poly1305Overhead)throw Error("ciphertext size is invalid");let size=ciphertextSize;return size-=fullChunks*chacha20poly1305Overhead,size-=lastChunk>0?chacha20poly1305Overhead:0,size}function encryptSTREAM(key){let streamNonce=new Uint8Array(12),incNonce=()=>{for(let i=streamNonce.length-2;i>=0;i--)if(streamNonce[i]++,streamNonce[i]!==0)break},plaintextBuffer=new Uint8Array(chunkSize),plaintextBufferUsed=0;return new TransformStream({transform(chunk,controller){while(chunk.length>0){if(plaintextBufferUsed===plaintextBuffer.length){let encryptedChunk=chacha20poly1305(key,streamNonce).encrypt(plaintextBuffer);controller.enqueue(encryptedChunk),incNonce(),plaintextBufferUsed=0}let n=Math.min(plaintextBuffer.length-plaintextBufferUsed,chunk.length);plaintextBuffer.set(chunk.subarray(0,n),plaintextBufferUsed),plaintextBufferUsed+=n,chunk=chunk.subarray(n)}},flush(controller){streamNonce[11]=1;let encryptedChunk=chacha20poly1305(key,streamNonce).encrypt(plaintextBuffer.subarray(0,plaintextBufferUsed));controller.enqueue(encryptedChunk)}})}function ciphertextSize(plaintextSize2){let chunks=Math.max(1,Math.ceil(plaintextSize2/chunkSize));return plaintextSize2+chacha20poly1305Overhead*chunks}var exports_armor={};__export(exports_armor,{encode:()=>encode,decode:()=>decode});function encode(file){let lines=[];lines.push(`-----BEGIN AGE ENCRYPTED FILE-----
8
+ `);for(let i=0;i<file.length;i+=48){let end=i+48;if(end>file.length)end=file.length;lines.push(base64.encode(file.subarray(i,end))+`
9
+ `)}return lines.push(`-----END AGE ENCRYPTED FILE-----
10
+ `),lines.join("")}function decode(file){let lines=file.trim().replaceAll(`\r
11
+ `,`
12
+ `).split(`
13
+ `);if(lines.shift()!=="-----BEGIN AGE ENCRYPTED FILE-----")throw Error("invalid header");if(lines.pop()!=="-----END AGE ENCRYPTED FILE-----")throw Error("invalid footer");function isLineLengthValid(i,l){if(i===lines.length-1)return l.length>0&&l.length<=64&&l.length%4===0;return l.length===64}if(!lines.every((l,i)=>isLineLengthValid(i,l)))throw Error("invalid line length");if(!lines.every((l)=>/^[A-Za-z0-9+/=]+$/.test(l)))throw Error("invalid base64");return base64.decode(lines.join(""))}class Encrypter{passphrase=null;scryptWorkFactor=18;recipients=[];setPassphrase(s){if(this.passphrase!==null)throw Error("can encrypt to at most one passphrase");if(this.recipients.length!==0)throw Error("can't encrypt to both recipients and passphrases");this.passphrase=s}setScryptWorkFactor(logN){this.scryptWorkFactor=logN}addRecipient(s){if(this.passphrase!==null)throw Error("can't encrypt to both recipients and passphrases");if(typeof s==="string")if(s.startsWith("age1pq1"))this.recipients.push(new HybridRecipient(s));else if(s.startsWith("age1tag1"))this.recipients.push(new TagRecipient(s));else if(s.startsWith("age1tagpq1"))this.recipients.push(new HybridTagRecipient(s));else if(s.startsWith("age1"))this.recipients.push(new X25519Recipient(s));else throw Error("unrecognized recipient type");else this.recipients.push(s)}async encrypt(file){let fileKey=randomBytes(16),stanzas=[],recipients=this.recipients;if(this.passphrase!==null)recipients=[new ScryptRecipient(this.passphrase,this.scryptWorkFactor)];for(let recipient of recipients)stanzas.push(...await recipient.wrapFileKey(fileKey));let labelHeader=new TextEncoder().encode("header"),hmacKey=hkdf(sha256,fileKey,void 0,labelHeader,32),mac=hmac(sha256,hmacKey,encodeHeaderNoMAC(stanzas)),header=encodeHeader(stanzas,mac),nonce=randomBytes(16),labelPayload=new TextEncoder().encode("payload"),streamKey=hkdf(sha256,fileKey,nonce,labelPayload,32),encrypter=encryptSTREAM(streamKey);if(!(file instanceof ReadableStream)){if(typeof file==="string")file=new TextEncoder().encode(file);return await readAll(prepend(stream(file).pipeThrough(encrypter),header,nonce))}return Object.assign(prepend(file.pipeThrough(encrypter),header,nonce),{size:(size)=>ciphertextSize(size)+header.length+nonce.length})}}class Decrypter{identities=[];addPassphrase(s){this.identities.push(new ScryptIdentity(s))}addIdentity(s){if(isCryptoKey3(s))this.identities.push(new X25519Identity(s));else if(typeof s==="string")if(s.startsWith("AGE-SECRET-KEY-1"))this.identities.push(new X25519Identity(s));else if(s.startsWith("AGE-SECRET-KEY-PQ-1"))this.identities.push(new HybridIdentity(s));else throw Error("unrecognized identity type");else this.identities.push(s)}async decrypt(file,outputFormat){let s=file instanceof ReadableStream?file:stream(file),{fileKey,headerSize,rest}=await this.decryptHeaderInternal(s),{data:nonce,rest:payload}=await read(rest,16),label=new TextEncoder().encode("payload"),streamKey=hkdf(sha256,fileKey,nonce,label,32),decrypter=decryptSTREAM(streamKey),out=payload.pipeThrough(decrypter),outWithSize=Object.assign(out,{size:(size)=>plaintextSize(size-headerSize-nonce.length)});if(file instanceof ReadableStream)return outWithSize;if(outputFormat==="text")return await readAllString(out);return await readAll(out)}async decryptHeader(header){return(await this.decryptHeaderInternal(stream(header))).fileKey}async decryptHeaderInternal(file){let h=await parseHeader(file),fileKey=await this.unwrapFileKey(h.stanzas);if(fileKey===null)throw Error("no identity matched any of the file's recipients");let label=new TextEncoder().encode("header"),hmacKey=hkdf(sha256,fileKey,void 0,label,32),mac=hmac(sha256,hmacKey,h.headerNoMAC);if(!compareBytes(h.MAC,mac))throw Error("invalid header HMAC");return{fileKey,headerSize:h.headerSize,rest:h.rest}}async unwrapFileKey(stanzas){for(let identity of this.identities){let fileKey=await identity.unwrapFileKey(stanzas);if(fileKey!==null)return fileKey}return null}}function compareBytes(a,b){if(a.length!==b.length)return!1;let acc=0;for(let i=0;i<a.length;i++)acc|=a[i]^b[i];return acc===0}function isCryptoKey3(key){return typeof CryptoKey<"u"&&key instanceof CryptoKey}var DEFAULT_INBOX_SERVER="https://relay.sma1lboy.me",INBOX_TEXT_MAX_CHARS=48000,MAX_SKEW_MS=300000,RECENT_KEPT=20;function defaultInboxPath(homeDir=readRoveHomeDirEnv()??homedir()){return join(homeDir,ROVE_STATE_DIR_BASENAME,"bridge","inbox.json")}function defaultInboxMessagesPath(homeDir=readRoveHomeDirEnv()??homedir()){return join(homeDir,ROVE_STATE_DIR_BASENAME,"bridge","inbox-messages.json")}function defaultInboxDir(homeDir=readRoveHomeDirEnv()??homedir()){return join(homeDir,ROVE_STATE_DIR_BASENAME,"inbox")}function inboxIdOf(agentKey){return createHash("sha256").update(agentKey).digest().subarray(0,16).toString("base64url")}function tokenHash(token){return createHash("sha256").update(token).digest("hex")}function parseRate(text){let m=/^(\d+(?:\.\d+)?)\/(s|m|h)$/.exec(text.trim());if(!m)return null;let n=Number(m[1])/{s:1,m:60,h:3600}[m[2]];return n>0?n:null}function parseDuration(text){let m=/^(\d+)(d|h)$/.exec(text.trim());return m?Number(m[1])*(m[2]==="d"?86400000:3600000):null}async function newInboxAddress(server){let identity=await generateX25519Identity(),agentKey=randomBytes6(32).toString("base64url");return{server,id:inboxIdOf(agentKey),agentKey,identity,recipient:await identityToRecipient(identity)}}function inboxUrl(address){return`${address.server.replace(/\/+$/,"")}/in/${address.id}`}function encryptEnvelope(recipient,envelope){let e=new Encrypter;return e.addRecipient(recipient),e.encrypt(JSON.stringify(envelope))}async function decryptEnvelope(identity,body){let binary=new TextDecoder().decode(body.subarray(0,40)).startsWith("-----BEGIN AGE ENCRYPTED FILE-----")?exports_armor.decode(new TextDecoder().decode(body)):body,d=new Decrypter;return d.addIdentity(identity),JSON.parse(await d.decrypt(binary,"text"))}var hourOf=(ms)=>String(Math.floor(ms/3600000));function record(token,now,accepted,reason){let hour=hourOf(now),counts=token.hours[hour]??[0,0];counts[accepted?0:1]+=1,token.hours[hour]=counts;let oldest=Number(hour)-24;for(let h of Object.keys(token.hours))if(Number(h)<=oldest)delete token.hours[h];token.recent=[{at:new Date(now).toISOString(),accepted,reason},...token.recent].slice(0,RECENT_KEPT),token.lastUsedAt=new Date(now).toISOString()}function last24h(token,now){let oldest=Number(hourOf(now))-24,accepted=0,rejected=0;for(let[h,[ok,no]]of Object.entries(token.hours)){if(Number(h)<=oldest)continue;accepted+=ok,rejected+=no}return{accepted,rejected}}function readEnvelope(value){if(!value||typeof value!=="object")return null;let v=value;if(typeof v.token!=="string"||typeof v.nonce!=="string"||typeof v.text!=="string")return null;if(typeof v.ts!=="number"||!Number.isFinite(v.ts))return null;if(v.nonce.length<8||v.nonce.length>128)return null;let kind=v.kind==="notify"||v.kind==="agent"?{kind:v.kind}:{};return{token:v.token,ts:v.ts,nonce:v.nonce,text:v.text,...kind}}function withId(t){return t.id?t:{...t,id:t.name}}class RelayInboxStore{path;#file={version:1,address:null,tokens:[]};#loaded=!1;#nonces=new Map;constructor(path){this.path=path}async#load(){if(this.#loaded)return this.#file;try{let raw=JSON.parse(await readFile(this.path,"utf8"));this.#file={version:1,address:raw.address??null,tokens:Array.isArray(raw.tokens)?raw.tokens.map(withId):[]}}catch{}return this.#loaded=!0,this.#file}#save(){return writeJsonAtomic(this.path,this.#file,{mode:384})}async read(){return await this.#load()}ensureAddress(server=DEFAULT_INBOX_SERVER){return serialized(this.path,async()=>{let file=await this.#load();if(!file.address)file.address=await newInboxAddress(server),await this.#save();return file.address})}rotate(server){return serialized(this.path,async()=>{let file=await this.#load();return file.address=await newInboxAddress(server??file.address?.server??DEFAULT_INBOX_SERVER),await this.#save(),file.address})}addToken(input){return serialized(this.path,async()=>{let file=await this.#load();if(file.tokens.some((t)=>t.id===input.id))return{error:"ID_TAKEN"};let token=`rvi_${randomBytes6(24).toString("base64url")}`,now=Date.now(),rec={...input,hash:tokenHash(token),createdAt:new Date(now).toISOString(),bucket:{tokens:input.burst,at:now},day:{date:"",count:0},hours:{},recent:[]};return file.tokens.push(rec),await this.#save(),{token,record:rec}})}revokeToken(id){return serialized(this.path,async()=>{let file=await this.#load(),before=file.tokens.length;if(file.tokens=file.tokens.filter((t)=>t.id!==id),file.tokens.length===before)return!1;return await this.#save(),!0})}deliver(body,routineReady,now=Date.now()){return serialized(this.path,async()=>{let file=await this.#load();if(!file.address)return{ok:!1,status:401,reason:"no_inbox"};let envelope;try{envelope=readEnvelope(await decryptEnvelope(file.address.identity,body))}catch{envelope=null}if(!envelope)return{ok:!1,status:401,reason:"undecryptable"};let hash=tokenHash(envelope.token),token=file.tokens.find((t)=>t.hash===hash);if(!token)return{ok:!1,status:401,reason:"unknown_token"};let agent=(envelope.kind??(token.routineId?"agent":"notify"))==="agent"&&(token.agent===!0||token.routineId!==void 0),verdict=agent&&token.routineId&&!routineReady(token.routineId)?{ok:!1,status:409,reason:"routine_unavailable",token}:this.#check(token,envelope,agent,now);return record(token,now,verdict.ok,verdict.ok?"accepted":verdict.reason),await this.#save(),verdict})}#check(token,env,agent,now){let refuse=(status,reason)=>({ok:!1,status,reason,token});if(token.expiresAt&&Date.parse(token.expiresAt)<=now)return refuse(401,"expired");if(Math.abs(now-env.ts*1000)>MAX_SKEW_MS)return refuse(401,"stale_ts");for(let[n,until]of this.#nonces)if(until<=now)this.#nonces.delete(n);let nonceKey=`${token.hash}:${env.nonce}`;if(this.#nonces.has(nonceKey))return refuse(401,"replayed_nonce");if(env.text.length>INBOX_TEXT_MAX_CHARS)return refuse(413,"too_large");let refill=(now-token.bucket.at)/1000*token.rate,tokens=Math.min(token.burst,token.bucket.tokens+refill);if(tokens<1)return token.bucket={tokens,at:now},refuse(429,"rate_limited");let date=new Date(now).toISOString().slice(0,10),count=token.day.date===date?token.day.count:0;if(token.daily!==void 0&&count>=token.daily)return refuse(429,"daily_limit");return token.bucket={tokens:tokens-1,at:now},token.day={date,count:count+1},this.#nonces.set(nonceKey,now+2*MAX_SKEW_MS),{ok:!0,token,text:env.text,agent}}}function agentPrompt(input){let perMinute=Math.round(input.rate*60*100)/100;return`You can send messages to my Rove (a coding-agent manager on my computer) through an end-to-end encrypted inbox.
14
+
15
+ ${input.agent?`Each message has a kind, and you choose it per message:
16
+ - "notify" (the default): I read it myself, nothing runs. Use it for a summary of work you finished, a status, anything that is only for me to know.
17
+ - "agent": one of my coding agents starts on your message and acts on it. Use it only when the message asks for work an agent can do on its own, and write it as a complete brief: the agent sees nothing but your text.
18
+ When unsure, send "notify".`:'Every message is a notice ("kind": "notify"): I read it myself and no agent runs on it. This token cannot start an agent; asking for one still only shows me the message.'}
19
+
20
+ Inbox URL: ${input.url}
21
+ Public key: ${input.recipient}
22
+ Token: ${input.token}
23
+
24
+ Keep the token secret: it is the credential. The relay in the middle cannot read your messages or see the token.
25
+
26
+ How to send one message:
27
+ 1. You need the \`age\` CLI (https://age-encryption.org): \`apt-get install age\`, \`brew install age\`, or a release binary from https://github.com/FiloSottile/age/releases.
28
+ 2. Build a JSON envelope with exactly these fields:
29
+ - "token": the token above
30
+ - "ts": the current Unix time in SECONDS (\`date +%s\`); it must be within 5 minutes of real time
31
+ - "nonce": a fresh random string for every message, 8-128 characters (\`openssl rand -hex 16\`); never reuse one
32
+ - "text": your message, plain text or markdown, at most ${INBOX_TEXT_MAX_CHARS} characters
33
+ - "kind": "notify"${input.agent?' or "agent"':""}
34
+ 3. Encrypt it to the public key and POST the ciphertext:
35
+
36
+ \`\`\`sh
37
+ ENVELOPE=$(jq -cn --arg token "$TOKEN" --arg text "$TEXT" --arg kind notify --arg nonce "$(openssl rand -hex 16)" --argjson ts "$(date +%s)" '{token:$token,ts:$ts,nonce:$nonce,text:$text,kind:$kind}')
38
+ printf '%s' "$ENVELOPE" | age -r ${input.recipient} | curl -sS -o /dev/null -w '%{http_code}\\n' --data-binary @- ${input.url}
39
+ \`\`\`
40
+
41
+ Status codes:
42
+ - 202: delivered.
43
+ - 404 or 503: my inbox is offline (or the URL is wrong). Nothing was queued. Retry with backoff (30s, 1m, 2m, 5m, then every 10m), for at most a few hours.
44
+ - 429: too fast. The limit is ${perMinute} messages per minute with bursts of ${input.burst}; there may also be a daily cap. Wait at least 60 seconds, then retry. Repeated failed requests from one IP also get 429 for a while: stop and back off.
45
+ - 401: the token, timestamp, nonce or encryption was refused. Do not retry the same envelope: check your clock, use a fresh nonce, and the exact token and key above.
46
+ - 413: the message is too long; shorten it.
47
+ - 504: no answer in time; it may or may not have arrived. Retry once after a minute with a new envelope.${input.agent?`
48
+ - 409: my side is misconfigured (what an agent message starts is off or gone). Stop and tell me.`:""}
49
+
50
+ Send one message per finished piece of work (for example a summary when you finish a task), not a stream of updates. Build a new envelope (new ts and nonce) for every attempt, retries included.`}
51
+ export{defaultInboxPath,defaultInboxMessagesPath,defaultInboxDir,parseRate,parseDuration,inboxUrl,encryptEnvelope,last24h,RelayInboxStore,agentPrompt};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{shQuote}from"./chunk-wrqv141p.js";import{WINDOWS_LOCATE_ROVE,WINDOWS_ROVE_MISSING,WINDOWS_SCRIPTS_DISABLED,WINDOWS_SSHD_BANNER,WINDOWS_SSHD_STEPS,isWindowsMachine,isWindowsPath,windowsNoRoveMessage,windowsRoveCommand}from"./chunk-r478tzjz.js";import{machineSocketDir,machineSshArgs,sshTargetOf}from"./chunk-0b9dhq9b.js";import{PRE_RENAME_VERSION_KEY}from"./chunk-g6wb8p4p.js";import{spawn}from"child_process";import{mkdirSync}from"fs";import{posix}from"path";var PATTERNS=[["host-key-changed",/REMOTE HOST IDENTIFICATION HAS CHANGED|Host key for .* has changed/i],["host-key-unverified",/Host key verification failed|No .*host key is known for/i],["auth-denied",/Permission denied \(|Too many authentication failures|no matching host key type/i],["unresolved",/Could not resolve hostname|Name or service not known|nodename nor servname/i],["refused",/Connection refused/i],["timeout",/timed out|Operation timed out|No route to host|Network is unreachable/i]];function classifySshFailure(stderr){for(let[kind,pattern]of PATTERNS)if(pattern.test(stderr))return kind;return"unknown"}function sshFailureRemedy(kind,target,windows=!1){if(windows&&(kind==="refused"||kind==="timeout"))return[`${target} (Windows) ${kind==="refused"?"refused the connection: its OpenSSH Server is not running":"did not answer on the ssh port: its OpenSSH Server is off, or the firewall drops it"}.`,"In an elevated PowerShell there:",...WINDOWS_SSHD_STEPS.map((step)=>` ${step}`)].join(`
2
+ import{shQuote}from"./chunk-wrqv141p.js";import{WINDOWS_LOCATE_ROVE,WINDOWS_ROVE_MISSING,WINDOWS_SCRIPTS_DISABLED,WINDOWS_SSHD_BANNER,WINDOWS_SSHD_STEPS,isWindowsMachine,isWindowsPath,windowsNoRoveMessage,windowsRoveCommand}from"./chunk-r478tzjz.js";import{machineSocketDir,machineSshArgs,sshTargetOf}from"./chunk-navavqt2.js";import{PRE_RENAME_VERSION_KEY}from"./chunk-g6wb8p4p.js";import{spawn}from"child_process";import{mkdirSync}from"fs";import{posix}from"path";var PATTERNS=[["host-key-changed",/REMOTE HOST IDENTIFICATION HAS CHANGED|Host key for .* has changed/i],["host-key-unverified",/Host key verification failed|No .*host key is known for/i],["auth-denied",/Permission denied \(|Too many authentication failures|no matching host key type/i],["unresolved",/Could not resolve hostname|Name or service not known|nodename nor servname/i],["refused",/Connection refused/i],["timeout",/timed out|Operation timed out|No route to host|Network is unreachable/i]];function classifySshFailure(stderr){for(let[kind,pattern]of PATTERNS)if(pattern.test(stderr))return kind;return"unknown"}function sshFailureRemedy(kind,target,windows=!1){if(windows&&(kind==="refused"||kind==="timeout"))return[`${target} (Windows) ${kind==="refused"?"refused the connection: its OpenSSH Server is not running":"did not answer on the ssh port: its OpenSSH Server is off, or the firewall drops it"}.`,"In an elevated PowerShell there:",...WINDOWS_SSHD_STEPS.map((step)=>` ${step}`)].join(`
3
3
  `);if(windows&&kind==="auth-denied")return`${target} (Windows) rejected every key ssh offered. For an Administrators account, OpenSSH for Windows reads only %ProgramData%\\ssh\\administrators_authorized_keys; ~\\.ssh\\authorized_keys is ignored.`;switch(kind){case"unresolved":return`${target} does not resolve to an address. Check the name, or the Host block in ~/.ssh/config; on a tailnet, check \`tailscale status\`.`;case"refused":return`${target} refused the connection: nothing listens for ssh there. Enable Remote Login / start sshd on it (Windows: \`Start-Service sshd\`, elevated), or pass the right --port.`;case"timeout":return`${target} did not answer. Is it awake and on this network (or VPN / tailnet)?`;case"host-key-changed":return`${target}'s host key CHANGED since you last connected. That is either a reinstall or someone in the middle. If you reinstalled it, remove the old key with \`ssh-keygen -R <host>\` and retry; otherwise stop here.`;case"host-key-unverified":return`${target}'s host key is not trusted yet. Run \`rove machine add\` in a terminal to confirm its fingerprint, or connect once with \`ssh ${target}\`.`;case"auth-denied":return`${target} rejected every key ssh offered. Load your key into ssh-agent, pass --identity <key>, or install a key there with \`ssh-copy-id ${target}\`.`;case"unknown":return`ssh to ${target} failed. Run \`ssh ${target} true\` to see why.`}}async function runOnMachine(alias,config,command,opts={}){try{mkdirSync(machineSocketDir(alias,opts.home),{recursive:!0,mode:448})}catch{}let base=machineSshArgs(alias,config,{home:opts.home,mux:opts.sshFlags===void 0}),argv=[base[0]??"ssh",...opts.sshFlags??[],...base.slice(1),command];return await new Promise((resolve)=>{let stdout="",stderr="",settled=!1,done=(exitCode)=>{if(settled)return;settled=!0,clearTimeout(timer),resolve({stdout,stderr,exitCode})},child=spawn(argv[0]??"ssh",argv.slice(1),{stdio:["ignore","pipe","pipe"]}),timer=setTimeout(()=>{child.kill("SIGKILL"),stderr+=`
4
4
  timed out`,done(-1)},opts.timeoutMs??30000);child.stdout?.on("data",(c)=>{stdout+=c.toString()}),child.stderr?.on("data",(c)=>{stderr+=c.toString()}),child.on("error",()=>done(-1)),child.on("close",(code)=>done(code??-1))})}function unansweringDaemonPid(stdout){let match=/\(stale pidfile pid=(\d+)\)/.exec(stdout);return match?Number(match[1]):null}async function discoverMachine(alias,config,opts={}){let found=await probe(alias,config,config.roveBin,opts);if(found.ok||found.code!=="NO_ROVE")return found;let locate=found.windows?WINDOWS_LOCATE_ROVE:LOCATE_ROVE_SCRIPT,located=parseLocatedRove((await runOnMachine(alias,config,locate,opts)).stdout);if(!located||located===config.roveBin)return found;let retry=await probe(alias,config,located,opts);return retry.ok?{...retry,roveBin:located}:retry}function learnedFrom(found){return{sockets:{daemon:found.status.socketPath,pty:found.status.ptySocketPath},...found.roveBin?{roveBin:found.roveBin}:{},...found.status.relayPreamble?{relayPreamble:!0}:{}}}function remoteRove(roveBin,args){if(roveBin&&isWindowsPath(roveBin))return windowsRoveCommand(roveBin,args);return[roveCommand(roveBin),...args].join(" ")}function roveCommand(roveBin){if(!roveBin)return"rove";return`PATH=${shQuote(posix.dirname(roveBin))}:"$PATH" ${shQuote(roveBin)}`}var LOCATE_ROVE_SCRIPT=[`p=$("\${SHELL:-sh}" -lc 'command -v rove' 2>/dev/null)`,'if [ -n "$p" ] && [ -x "$p" ]; then echo "ROVE_BIN=$p"; exit 0; fi','for p in "$HOME/.bun/bin/rove" "$HOME/.npm-global/bin/rove" "$HOME/.local/bin/rove" /opt/homebrew/bin/rove /usr/local/bin/rove "$HOME"/.nvm/versions/node/*/bin/rove; do',' if [ -x "$p" ]; then echo "ROVE_BIN=$p"; exit 0; fi',"done","exit 1"].join(`
5
5
  `);function parseLocatedRove(stdout){return/^ROVE_BIN=((?:\/|[A-Za-z]:\\)\S.*)$/m.exec(stdout)?.[1]?.trim()??null}var ROVE_MISSING=/(?:^|\W)rove:? (?:command not found|not found)|command not found:? rove|\/rove:? No such file or directory|no such file or directory: \S*\/rove\b/i;async function probe(alias,config,roveBin,opts){let status=remoteRove(roveBin,["daemon","status","--json"]),first=await runOnMachine(alias,config,status,opts),parsed=parseStatusJson(first.stdout);if(parsed)return withNoise(windowsReady(alias,parsed),first.stdout);let combined=`${first.stdout}