nostr-double-ratchet 0.0.29 → 0.0.30

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.
@@ -1 +1 @@
1
- {"version":3,"file":"Session.d.ts","sourceRoot":"","sources":["../src/Session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAyD,aAAa,EAAE,aAAa,EAA+B,MAAM,aAAa,CAAC;AAE/I,OAAO,EACL,YAAY,EAEZ,WAAW,EACX,cAAc,EACd,aAAa,EAEb,KAAK,EAEN,MAAM,SAAS,CAAC;AAQjB;;;;;GAKG;AACH,qBAAa,OAAO;IASN,OAAO,CAAC,cAAc;IAAyB,KAAK,EAAE,YAAY;IAR9E,OAAO,CAAC,mBAAmB,CAAC,CAAc;IAC1C,OAAO,CAAC,gBAAgB,CAAC,CAAc;IACvC,OAAO,CAAC,oBAAoB,CAAC,CAAc;IAC3C,OAAO,CAAC,qBAAqB,CAAoC;IACjE,OAAO,CAAC,6BAA6B,CAAK;IACnC,IAAI,EAAE,MAAM,CAAC;gBAGA,cAAc,EAAE,cAAc,EAAS,KAAK,EAAE,YAAY;IAI9E;;;;;;;;;OASG;IACH,MAAM,CAAC,IAAI,CACT,cAAc,EAAE,cAAc,EAC9B,4BAA4B,EAAE,MAAM,EACpC,2BAA2B,EAAE,UAAU,EACvC,WAAW,EAAE,OAAO,EACpB,YAAY,EAAE,UAAU,EACxB,IAAI,CAAC,EAAE,MAAM,GACZ,OAAO;IA8CV;;;;;;OAMG;IACH,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG;QAAC,KAAK,EAAE,aAAa,CAAC;QAAC,UAAU,EAAE,KAAK,CAAA;KAAC;IAO7D;;;;;;OAMG;IACH,SAAS,CAAC,KAAK,EAAE,OAAO,CAAC,aAAa,CAAC,GAAG;QAAC,KAAK,EAAE,aAAa,CAAC;QAAC,UAAU,EAAE,KAAK,CAAA;KAAC;IAyCnF;;;;OAIG;IACH,OAAO,CAAC,QAAQ,EAAE,aAAa,GAAG,WAAW;IAO7C;;OAEG;IACH,KAAK;IAQL,OAAO,CAAC,cAAc;IAWtB,OAAO,CAAC,cAAc;IAatB,OAAO,CAAC,WAAW;IAwBnB,OAAO,CAAC,eAAe;IAkCvB,OAAO,CAAC,qBAAqB;IAkB7B,OAAO,CAAC,aAAa;IAmCrB,OAAO,CAAC,gBAAgB;IAuCxB,OAAO,CAAC,sBAAsB;CAsB/B"}
1
+ {"version":3,"file":"Session.d.ts","sourceRoot":"","sources":["../src/Session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAyD,aAAa,EAAE,aAAa,EAA+B,MAAM,aAAa,CAAC;AAE/I,OAAO,EACL,YAAY,EAEZ,WAAW,EACX,cAAc,EACd,aAAa,EAEb,KAAK,EAEN,MAAM,SAAS,CAAC;AAQjB;;;;;GAKG;AACH,qBAAa,OAAO;IASN,OAAO,CAAC,cAAc;IAAyB,KAAK,EAAE,YAAY;IAR9E,OAAO,CAAC,mBAAmB,CAAC,CAAc;IAC1C,OAAO,CAAC,gBAAgB,CAAC,CAAc;IACvC,OAAO,CAAC,oBAAoB,CAAC,CAAc;IAC3C,OAAO,CAAC,qBAAqB,CAAoC;IACjE,OAAO,CAAC,6BAA6B,CAAK;IACnC,IAAI,EAAE,MAAM,CAAC;gBAGA,cAAc,EAAE,cAAc,EAAS,KAAK,EAAE,YAAY;IAI9E;;;;;;;;;OASG;IACH,MAAM,CAAC,IAAI,CACT,cAAc,EAAE,cAAc,EAC9B,4BAA4B,EAAE,MAAM,EACpC,2BAA2B,EAAE,UAAU,EACvC,WAAW,EAAE,OAAO,EACpB,YAAY,EAAE,UAAU,EACxB,IAAI,CAAC,EAAE,MAAM,GACZ,OAAO;IA8CV;;;;;;OAMG;IACH,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG;QAAC,KAAK,EAAE,aAAa,CAAC;QAAC,UAAU,EAAE,KAAK,CAAA;KAAC;IAO7D;;;;;;OAMG;IACH,SAAS,CAAC,KAAK,EAAE,OAAO,CAAC,aAAa,CAAC,GAAG;QAAC,KAAK,EAAE,aAAa,CAAC;QAAC,UAAU,EAAE,KAAK,CAAA;KAAC;IAyCnF;;;;OAIG;IACH,OAAO,CAAC,QAAQ,EAAE,aAAa,GAAG,WAAW;IAO7C;;OAEG;IACH,KAAK;IAQL,OAAO,CAAC,cAAc;IAWtB,OAAO,CAAC,cAAc;IAatB,OAAO,CAAC,WAAW;IAwBnB,OAAO,CAAC,eAAe;IAkCvB,OAAO,CAAC,qBAAqB;IAkB7B,OAAO,CAAC,aAAa;IAmCrB,OAAO,CAAC,gBAAgB;IA8CxB,OAAO,CAAC,sBAAsB;CAsB/B"}
@@ -10,6 +10,7 @@ export default class SessionManager {
10
10
  private deviceId;
11
11
  private invite?;
12
12
  private storage;
13
+ private messageQueue;
13
14
  constructor(ourIdentityKey: Uint8Array, deviceId: string, nostrSubscribe: NostrSubscribe, nostrPublish: NostrPublish, storage?: StorageAdapter);
14
15
  private _initialised;
15
16
  /**
@@ -22,8 +23,8 @@ export default class SessionManager {
22
23
  private saveSession;
23
24
  getDeviceId(): string;
24
25
  getInvite(): Invite;
25
- sendText(recipientIdentityKey: string, text: string): Promise<import("nostr-tools").VerifiedEvent[]>;
26
- sendEvent(recipientIdentityKey: string, event: Partial<Rumor>): Promise<import("nostr-tools").VerifiedEvent[]>;
26
+ sendText(recipientIdentityKey: string, text: string): Promise<any[]>;
27
+ sendEvent(recipientIdentityKey: string, event: Partial<Rumor>): Promise<any[]>;
27
28
  listenToUser(userPubkey: string): void;
28
29
  stopListeningToUser(userPubkey: string): void;
29
30
  private internalSubscriptions;
@@ -1 +1 @@
1
- {"version":3,"file":"SessionManager.d.ts","sourceRoot":"","sources":["../src/SessionManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,YAAY,EAAE,cAAc,EAAE,KAAK,EAAe,MAAM,SAAS,CAAA;AAE7F,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAA;AAEjC,OAAO,EAAE,cAAc,EAA0B,MAAM,kBAAkB,CAAA;AAIzE,MAAM,CAAC,OAAO,OAAO,cAAc;IAC/B,OAAO,CAAC,WAAW,CAAqC;IACxD,OAAO,CAAC,cAAc,CAAgB;IACtC,OAAO,CAAC,YAAY,CAAc;IAClC,OAAO,CAAC,cAAc,CAAY;IAClC,OAAO,CAAC,kBAAkB,CAAsC;IAChE,OAAO,CAAC,QAAQ,CAAQ;IACxB,OAAO,CAAC,MAAM,CAAC,CAAQ;IACvB,OAAO,CAAC,OAAO,CAAgB;gBAG3B,cAAc,EAAE,UAAU,EAC1B,QAAQ,EAAE,MAAM,EAChB,cAAc,EAAE,cAAc,EAC9B,YAAY,EAAE,YAAY,EAC1B,OAAO,GAAE,cAA6C;IAc1D,OAAO,CAAC,YAAY,CAAQ;IAE5B;;;;OAIG;IACU,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;YA2FpB,YAAY;YAiCZ,WAAW;IAOzB,WAAW,IAAI,MAAM;IAIrB,SAAS,IAAI,MAAM;IAOb,QAAQ,CAAC,oBAAoB,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM;IAQnD,SAAS,CAAC,oBAAoB,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,CAAC;IA+BnE,YAAY,CAAC,UAAU,EAAE,MAAM;IAoC/B,mBAAmB,CAAC,UAAU,EAAE,MAAM;IAStC,OAAO,CAAC,qBAAqB,CAAyC;IAEtE,OAAO,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI;IAkBxC,KAAK;IAiBL;;;OAGG;IACU,eAAe,CAAC,MAAM,EAAE,MAAM;CAgB9C"}
1
+ {"version":3,"file":"SessionManager.d.ts","sourceRoot":"","sources":["../src/SessionManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,YAAY,EAAE,cAAc,EAAE,KAAK,EAAe,MAAM,SAAS,CAAA;AAE7F,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAA;AAEjC,OAAO,EAAE,cAAc,EAA0B,MAAM,kBAAkB,CAAA;AAIzE,MAAM,CAAC,OAAO,OAAO,cAAc;IAC/B,OAAO,CAAC,WAAW,CAAqC;IACxD,OAAO,CAAC,cAAc,CAAgB;IACtC,OAAO,CAAC,YAAY,CAAc;IAClC,OAAO,CAAC,cAAc,CAAY;IAClC,OAAO,CAAC,kBAAkB,CAAsC;IAChE,OAAO,CAAC,QAAQ,CAAQ;IACxB,OAAO,CAAC,MAAM,CAAC,CAAQ;IACvB,OAAO,CAAC,OAAO,CAAgB;IAC/B,OAAO,CAAC,YAAY,CAA4F;gBAG5G,cAAc,EAAE,UAAU,EAC1B,QAAQ,EAAE,MAAM,EAChB,cAAc,EAAE,cAAc,EAC9B,YAAY,EAAE,YAAY,EAC1B,OAAO,GAAE,cAA6C;IAc1D,OAAO,CAAC,YAAY,CAAQ;IAE5B;;;;OAIG;IACU,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;YAgGpB,YAAY;YAiCZ,WAAW;IAOzB,WAAW,IAAI,MAAM;IAIrB,SAAS,IAAI,MAAM;IAOb,QAAQ,CAAC,oBAAoB,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM;IAQnD,SAAS,CAAC,oBAAoB,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,CAAC;IA4DnE,YAAY,CAAC,UAAU,EAAE,MAAM;IA8D/B,mBAAmB,CAAC,UAAU,EAAE,MAAM;IAStC,OAAO,CAAC,qBAAqB,CAAyC;IAEtE,OAAO,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI;IAkBxC,KAAK;IAiBL;;;OAGG;IACU,eAAe,CAAC,MAAM,EAAE,MAAM;CAgB9C"}
@@ -51,6 +51,7 @@ export declare class UserRecord {
51
51
  * Return all sessions that are currently considered *active*.
52
52
  * For now this means any session in a non-stale device record as well as
53
53
  * all sessions added through `addSession`.
54
+ * Prioritizes initiator sessions (can send first message) over responder sessions.
54
55
  */
55
56
  getActiveSessions(): Session[];
56
57
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"UserRecord.d.ts","sourceRoot":"","sources":["../src/UserRecord.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAUzC;;;GAGG;AACH,qBAAa,UAAU;IAMZ,OAAO,EAAE,MAAM;IACtB,OAAO,CAAC,eAAe;IANzB,OAAO,CAAC,aAAa,CAAwC;IAC7D,OAAO,CAAC,OAAO,CAAkB;IACjC,OAAO,CAAC,cAAc,CAAC,CAAS;gBAGvB,OAAO,EAAE,MAAM,EACd,eAAe,EAAE,cAAc;IAIzC;;OAEG;IACI,iBAAiB,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,IAAI;IAanE;;OAEG;IACI,aAAa,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI;IAI9D;;OAEG;IACI,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI;IAuBhE;;OAEG;IACI,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI;IAQ9C;;OAEG;IACI,aAAa,IAAI,IAAI;IAK5B;;OAEG;IACI,gBAAgB,IAAI,KAAK,CAAC,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAQnD;;OAEG;IACI,aAAa,CAClB,QAAQ,EAAE,MAAM,EAChB,YAAY,EAAE,UAAU,EACxB,oBAAoB,EAAE,UAAU,EAChC,WAAW,EAAE,OAAO,EACpB,IAAI,CAAC,EAAE,MAAM,GACZ,OAAO;IAmBV;;OAEG;IACI,iBAAiB,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI;IAyBlD;;OAEG;IACI,KAAK,IAAI,IAAI;IAYpB;;;;OAIG;IACI,iBAAiB,IAAI,OAAO,EAAE;IAYrC;;;;OAIG;IACI,cAAc,IAAI,OAAO,EAAE;IAalC;;;;OAIG;IACI,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,EAAE,OAAO,EAAE,OAAO;CAsBpE"}
1
+ {"version":3,"file":"UserRecord.d.ts","sourceRoot":"","sources":["../src/UserRecord.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAUzC;;;GAGG;AACH,qBAAa,UAAU;IAMZ,OAAO,EAAE,MAAM;IACtB,OAAO,CAAC,eAAe;IANzB,OAAO,CAAC,aAAa,CAAwC;IAC7D,OAAO,CAAC,OAAO,CAAkB;IACjC,OAAO,CAAC,cAAc,CAAC,CAAS;gBAGvB,OAAO,EAAE,MAAM,EACd,eAAe,EAAE,cAAc;IAIzC;;OAEG;IACI,iBAAiB,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,IAAI;IAanE;;OAEG;IACI,aAAa,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI;IAI9D;;OAEG;IACI,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI;IAuBhE;;OAEG;IACI,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI;IAQ9C;;OAEG;IACI,aAAa,IAAI,IAAI;IAK5B;;OAEG;IACI,gBAAgB,IAAI,KAAK,CAAC,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAQnD;;OAEG;IACI,aAAa,CAClB,QAAQ,EAAE,MAAM,EAChB,YAAY,EAAE,UAAU,EACxB,oBAAoB,EAAE,UAAU,EAChC,WAAW,EAAE,OAAO,EACpB,IAAI,CAAC,EAAE,MAAM,GACZ,OAAO;IAmBV;;OAEG;IACI,iBAAiB,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI;IAyBlD;;OAEG;IACI,KAAK,IAAI,IAAI;IAYpB;;;;;OAKG;IACI,iBAAiB,IAAI,OAAO,EAAE;IAqBrC;;;;OAIG;IACI,cAAc,IAAI,OAAO,EAAE;IAalC;;;;OAIG;IACI,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,EAAE,OAAO,EAAE,OAAO;CAsBpE"}
@@ -4039,17 +4039,25 @@ class ot {
4039
4039
  throw new Error("Failed to decrypt header with current and skipped header keys");
4040
4040
  }
4041
4041
  handleNostrEvent(t) {
4042
- var c, a;
4043
- const [n, r, i] = this.decryptHeader(t);
4044
- if (!i)
4045
- this.state.theirNextNostrPublicKey !== n.nextPublicKey && (this.state.theirCurrentNostrPublicKey = this.state.theirNextNostrPublicKey, this.state.theirNextNostrPublicKey = n.nextPublicKey, (c = this.nostrUnsubscribe) == null || c.call(this), this.nostrUnsubscribe = this.nostrNextUnsubscribe, this.nostrNextUnsubscribe = this.nostrSubscribe(
4046
- { authors: [this.state.theirNextNostrPublicKey], kinds: [Oe] },
4047
- (l) => this.handleNostrEvent(l)
4048
- )), r && (this.skipMessageKeys(n.previousChainLength, t.pubkey), this.ratchetStep());
4049
- else if (!((a = this.state.skippedKeys[t.pubkey]) != null && a.messageKeys[n.number]))
4050
- return;
4051
- const s = this.ratchetDecrypt(n, t.content, t.pubkey), o = JSON.parse(s);
4052
- pt(o) && o.id === qe(o) && this.internalSubscriptions.forEach((l) => l(o, t));
4042
+ var n, r;
4043
+ try {
4044
+ const [i, s, o] = this.decryptHeader(t);
4045
+ if (!o)
4046
+ this.state.theirNextNostrPublicKey !== i.nextPublicKey && (this.state.theirCurrentNostrPublicKey = this.state.theirNextNostrPublicKey, this.state.theirNextNostrPublicKey = i.nextPublicKey, (n = this.nostrUnsubscribe) == null || n.call(this), this.nostrUnsubscribe = this.nostrNextUnsubscribe, this.nostrNextUnsubscribe = this.nostrSubscribe(
4047
+ { authors: [this.state.theirNextNostrPublicKey], kinds: [Oe] },
4048
+ (l) => this.handleNostrEvent(l)
4049
+ )), s && (this.skipMessageKeys(i.previousChainLength, t.pubkey), this.ratchetStep());
4050
+ else if (!((r = this.state.skippedKeys[t.pubkey]) != null && r.messageKeys[i.number]))
4051
+ return;
4052
+ const c = this.ratchetDecrypt(i, t.content, t.pubkey), a = JSON.parse(c);
4053
+ if (!pt(a) || a.id !== qe(a))
4054
+ return;
4055
+ this.internalSubscriptions.forEach((l) => l(a, t));
4056
+ } catch (i) {
4057
+ if (i instanceof Error && i.message.includes("Failed to decrypt header"))
4058
+ return;
4059
+ throw i;
4060
+ }
4053
4061
  }
4054
4062
  subscribeToNostrEvents() {
4055
4063
  if (this.nostrNextUnsubscribe) return;
@@ -1 +1 @@
1
- (function(P,J){typeof exports=="object"&&typeof module<"u"?J(exports):typeof define=="function"&&define.amd?define(["exports"],J):(P=typeof globalThis<"u"?globalThis:P||self,J(P["nostr-double-ratchet"]={}))})(this,function(P){"use strict";var hu=Object.defineProperty;var du=(P,J,Ie)=>J in P?hu(P,J,{enumerable:!0,configurable:!0,writable:!0,value:Ie}):P[J]=Ie;var te=(P,J,Ie)=>du(P,typeof J!="symbol"?J+"":J,Ie);function J(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function Ie(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function Si(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");J(e.outputLen),J(e.blockLen)}function nt(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Ai(e,t){Ie(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}const Kt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const kn=e=>e instanceof Uint8Array,St=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),se=(e,t)=>e<<32-t|e>>>t;if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");function Ci(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function At(e){if(typeof e=="string"&&(e=Ci(e)),!kn(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}function Ii(...e){const t=new Uint8Array(e.reduce((r,i)=>r+i.length,0));let n=0;return e.forEach(r=>{if(!kn(r))throw new Error("Uint8Array expected");t.set(r,n),n+=r.length}),t}let _n=class{clone(){return this._cloneInto()}};function Bi(e){const t=r=>e().update(At(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Un(e=32){if(Kt&&typeof Kt.getRandomValues=="function")return Kt.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}function ki(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),c=Number(n&s),a=r?4:0,f=r?0:4;e.setUint32(t+a,o,r),e.setUint32(t+f,c,r)}let _i=class extends _n{constructor(t,n,r,i){super(),this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=St(this.buffer)}update(t){nt(this);const{view:n,buffer:r,blockLen:i}=this;t=At(t);const s=t.length;for(let o=0;o<s;){const c=Math.min(i-this.pos,s-o);if(c===i){const a=St(t);for(;i<=s-o;o+=i)this.process(a,o);continue}r.set(t.subarray(o,o+c),this.pos),this.pos+=c,o+=c,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){nt(this),Ai(t,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(r,0),o=0);for(let u=o;u<i;u++)n[u]=0;ki(r,i-8,BigInt(this.length*8),s),this.process(r,0);const c=St(t),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const f=a/4,l=this.get();if(f>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<f;u++)c.setUint32(4*u,l[u],s)}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:c}=this;return t.length=i,t.pos=c,t.finished=s,t.destroyed=o,i%n&&t.buffer.set(r),t}};const Ui=(e,t,n)=>e&t^~e&n,Li=(e,t,n)=>e&t^e&n^t&n,$i=new Uint32Array([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]),be=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ve=new Uint32Array(64);let Ti=class extends _i{constructor(){super(64,32,8,!1),this.A=be[0]|0,this.B=be[1]|0,this.C=be[2]|0,this.D=be[3]|0,this.E=be[4]|0,this.F=be[5]|0,this.G=be[6]|0,this.H=be[7]|0}get(){const{A:t,B:n,C:r,D:i,E:s,F:o,G:c,H:a}=this;return[t,n,r,i,s,o,c,a]}set(t,n,r,i,s,o,c,a){this.A=t|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=c|0,this.H=a|0}process(t,n){for(let u=0;u<16;u++,n+=4)ve[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const p=ve[u-15],w=ve[u-2],g=se(p,7)^se(p,18)^p>>>3,h=se(w,17)^se(w,19)^w>>>10;ve[u]=h+ve[u-7]+g+ve[u-16]|0}let{A:r,B:i,C:s,D:o,E:c,F:a,G:f,H:l}=this;for(let u=0;u<64;u++){const p=se(c,6)^se(c,11)^se(c,25),w=l+p+Ui(c,a,f)+$i[u]+ve[u]|0,h=(se(r,2)^se(r,13)^se(r,22))+Li(r,i,s)|0;l=f,f=a,a=c,c=o+w|0,o=s,s=i,i=r,r=w+h|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,c=c+this.E|0,a=a+this.F|0,f=f+this.G|0,l=l+this.H|0,this.set(r,i,s,o,c,a,f,l)}roundClean(){ve.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const Ct=Bi(()=>new Ti);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ln=BigInt(0),rt=BigInt(1),Ri=BigInt(2),it=e=>e instanceof Uint8Array,Oi=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Me(e){if(!it(e))throw new Error("Uint8Array expected");let t="";for(let n=0;n<e.length;n++)t+=Oi[e[n]];return t}function $n(e){const t=e.toString(16);return t.length&1?`0${t}`:t}function It(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return BigInt(e===""?"0":`0x${e}`)}function Pe(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);const t=e.length;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(t/2);for(let r=0;r<n.length;r++){const i=r*2,s=e.slice(i,i+2),o=Number.parseInt(s,16);if(Number.isNaN(o)||o<0)throw new Error("Invalid byte sequence");n[r]=o}return n}function Y(e){return It(Me(e))}function Bt(e){if(!it(e))throw new Error("Uint8Array expected");return It(Me(Uint8Array.from(e).reverse()))}function me(e,t){return Pe(e.toString(16).padStart(t*2,"0"))}function kt(e,t){return me(e,t).reverse()}function Mi(e){return Pe($n(e))}function G(e,t,n){let r;if(typeof t=="string")try{r=Pe(t)}catch(s){throw new Error(`${e} must be valid hex string, got "${t}". Cause: ${s}`)}else if(it(t))r=Uint8Array.from(t);else throw new Error(`${e} must be hex string or Uint8Array`);const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(`${e} expected ${n} bytes, got ${i}`);return r}function Be(...e){const t=new Uint8Array(e.reduce((r,i)=>r+i.length,0));let n=0;return e.forEach(r=>{if(!it(r))throw new Error("Uint8Array expected");t.set(r,n),n+=r.length}),t}function Pi(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Hi(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function Di(e){let t;for(t=0;e>Ln;e>>=rt,t+=1);return t}function qi(e,t){return e>>BigInt(t)&rt}const ji=(e,t,n)=>e|(n?rt:Ln)<<BigInt(t),_t=e=>(Ri<<BigInt(e-1))-rt,Ut=e=>new Uint8Array(e),Tn=e=>Uint8Array.from(e);function Rn(e,t,n){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");let r=Ut(e),i=Ut(e),s=0;const o=()=>{r.fill(1),i.fill(0),s=0},c=(...u)=>n(i,r,...u),a=(u=Ut())=>{i=c(Tn([0]),u),r=c(),u.length!==0&&(i=c(Tn([1]),u),r=c())},f=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let u=0;const p=[];for(;u<t;){r=c();const w=r.slice();p.push(w),u+=r.length}return Be(...p)};return(u,p)=>{o(),a(u);let w;for(;!(w=p(f()));)a();return o(),w}}const zi={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||e instanceof Uint8Array,isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};function Fe(e,t,n={}){const r=(i,s,o)=>{const c=zi[s];if(typeof c!="function")throw new Error(`Invalid validator "${s}", expected function`);const a=e[i];if(!(o&&a===void 0)&&!c(a,e))throw new Error(`Invalid param ${String(i)}=${a} (${typeof a}), expected ${s}`)};for(const[i,s]of Object.entries(t))r(i,s,!1);for(const[i,s]of Object.entries(n))r(i,s,!0);return e}const Vi=Object.freeze(Object.defineProperty({__proto__:null,bitGet:qi,bitLen:Di,bitMask:_t,bitSet:ji,bytesToHex:Me,bytesToNumberBE:Y,bytesToNumberLE:Bt,concatBytes:Be,createHmacDrbg:Rn,ensureBytes:G,equalBytes:Pi,hexToBytes:Pe,hexToNumber:It,numberToBytesBE:me,numberToBytesLE:kt,numberToHexUnpadded:$n,numberToVarBytesBE:Mi,utf8ToBytes:Hi,validateObject:Fe},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const W=BigInt(0),z=BigInt(1),ke=BigInt(2),Wi=BigInt(3),Lt=BigInt(4),On=BigInt(5),Mn=BigInt(8);BigInt(9),BigInt(16);function Z(e,t){const n=e%t;return n>=W?n:t+n}function Zi(e,t,n){if(n<=W||t<W)throw new Error("Expected power/modulo > 0");if(n===z)return W;let r=z;for(;t>W;)t&z&&(r=r*e%n),e=e*e%n,t>>=z;return r}function X(e,t,n){let r=e;for(;t-- >W;)r*=r,r%=n;return r}function $t(e,t){if(e===W||t<=W)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let n=Z(e,t),r=t,i=W,s=z;for(;n!==W;){const c=r/n,a=r%n,f=i-s*c;r=n,n=a,i=s,s=f}if(r!==z)throw new Error("invert: does not exist");return Z(i,t)}function Gi(e){const t=(e-z)/ke;let n,r,i;for(n=e-z,r=0;n%ke===W;n/=ke,r++);for(i=ke;i<e&&Zi(i,t,e)!==e-z;i++);if(r===1){const o=(e+z)/Lt;return function(a,f){const l=a.pow(f,o);if(!a.eql(a.sqr(l),f))throw new Error("Cannot find square root");return l}}const s=(n+z)/ke;return function(c,a){if(c.pow(a,t)===c.neg(c.ONE))throw new Error("Cannot find square root");let f=r,l=c.pow(c.mul(c.ONE,i),n),u=c.pow(a,s),p=c.pow(a,n);for(;!c.eql(p,c.ONE);){if(c.eql(p,c.ZERO))return c.ZERO;let w=1;for(let h=c.sqr(p);w<f&&!c.eql(h,c.ONE);w++)h=c.sqr(h);const g=c.pow(l,z<<BigInt(f-w-1));l=c.sqr(g),u=c.mul(u,g),p=c.mul(p,l),f=w}return u}}function Fi(e){if(e%Lt===Wi){const t=(e+z)/Lt;return function(r,i){const s=r.pow(i,t);if(!r.eql(r.sqr(s),i))throw new Error("Cannot find square root");return s}}if(e%Mn===On){const t=(e-On)/Mn;return function(r,i){const s=r.mul(i,ke),o=r.pow(s,t),c=r.mul(i,o),a=r.mul(r.mul(c,ke),o),f=r.mul(c,r.sub(a,r.ONE));if(!r.eql(r.sqr(f),i))throw new Error("Cannot find square root");return f}}return Gi(e)}const Ji=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Yi(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=Ji.reduce((r,i)=>(r[i]="function",r),t);return Fe(e,n)}function Xi(e,t,n){if(n<W)throw new Error("Expected power > 0");if(n===W)return e.ONE;if(n===z)return t;let r=e.ONE,i=t;for(;n>W;)n&z&&(r=e.mul(r,i)),i=e.sqr(i),n>>=z;return r}function Qi(e,t){const n=new Array(t.length),r=t.reduce((s,o,c)=>e.is0(o)?s:(n[c]=s,e.mul(s,o)),e.ONE),i=e.inv(r);return t.reduceRight((s,o,c)=>e.is0(o)?s:(n[c]=e.mul(s,n[c]),e.mul(s,o)),i),n}function Pn(e,t){const n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function es(e,t,n=!1,r={}){if(e<=W)throw new Error(`Expected Field ORDER > 0, got ${e}`);const{nBitLength:i,nByteLength:s}=Pn(e,t);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");const o=Fi(e),c=Object.freeze({ORDER:e,BITS:i,BYTES:s,MASK:_t(i),ZERO:W,ONE:z,create:a=>Z(a,e),isValid:a=>{if(typeof a!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof a}`);return W<=a&&a<e},is0:a=>a===W,isOdd:a=>(a&z)===z,neg:a=>Z(-a,e),eql:(a,f)=>a===f,sqr:a=>Z(a*a,e),add:(a,f)=>Z(a+f,e),sub:(a,f)=>Z(a-f,e),mul:(a,f)=>Z(a*f,e),pow:(a,f)=>Xi(c,a,f),div:(a,f)=>Z(a*$t(f,e),e),sqrN:a=>a*a,addN:(a,f)=>a+f,subN:(a,f)=>a-f,mulN:(a,f)=>a*f,inv:a=>$t(a,e),sqrt:r.sqrt||(a=>o(c,a)),invertBatch:a=>Qi(c,a),cmov:(a,f,l)=>l?f:a,toBytes:a=>n?kt(a,s):me(a,s),fromBytes:a=>{if(a.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${a.length}`);return n?Bt(a):Y(a)}});return Object.freeze(c)}function Hn(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Dn(e){const t=Hn(e);return t+Math.ceil(t/2)}function ts(e,t,n=!1){const r=e.length,i=Hn(t),s=Dn(t);if(r<16||r<s||r>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${r}`);const o=n?Y(e):Bt(e),c=Z(o,t-z)+z;return n?kt(c,i):me(c,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ns=BigInt(0),Tt=BigInt(1);function rs(e,t){const n=(i,s)=>{const o=s.negate();return i?o:s},r=i=>{const s=Math.ceil(t/i)+1,o=2**(i-1);return{windows:s,windowSize:o}};return{constTimeNegate:n,unsafeLadder(i,s){let o=e.ZERO,c=i;for(;s>ns;)s&Tt&&(o=o.add(c)),c=c.double(),s>>=Tt;return o},precomputeWindow(i,s){const{windows:o,windowSize:c}=r(s),a=[];let f=i,l=f;for(let u=0;u<o;u++){l=f,a.push(l);for(let p=1;p<c;p++)l=l.add(f),a.push(l);f=l.double()}return a},wNAF(i,s,o){const{windows:c,windowSize:a}=r(i);let f=e.ZERO,l=e.BASE;const u=BigInt(2**i-1),p=2**i,w=BigInt(i);for(let g=0;g<c;g++){const h=g*a;let d=Number(o&u);o>>=w,d>a&&(d-=p,o+=Tt);const y=h,E=h+Math.abs(d)-1,S=g%2!==0,_=d<0;d===0?l=l.add(n(S,s[y])):f=f.add(n(_,s[E]))}return{p:f,f:l}},wNAFCached(i,s,o,c){const a=i._WINDOW_SIZE||1;let f=s.get(i);return f||(f=this.precomputeWindow(i,a),a!==1&&s.set(i,c(f))),this.wNAF(a,f,o)}}}function qn(e){return Yi(e.Fp),Fe(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Pn(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function is(e){const t=qn(e);Fe(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:n,Fp:r,a:i}=t;if(n){if(!r.eql(i,r.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof n!="object"||typeof n.beta!="bigint"||typeof n.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}const{bytesToNumberBE:ss,hexToBytes:os}=Vi,_e={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(e){const{Err:t}=_e;if(e.length<2||e[0]!==2)throw new t("Invalid signature integer tag");const n=e[1],r=e.subarray(2,n+2);if(!n||r.length!==n)throw new t("Invalid signature integer: wrong length");if(r[0]&128)throw new t("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return{d:ss(r),l:e.subarray(n+2)}},toSig(e){const{Err:t}=_e,n=typeof e=="string"?os(e):e;if(!(n instanceof Uint8Array))throw new Error("ui8a expected");let r=n.length;if(r<2||n[0]!=48)throw new t("Invalid signature tag");if(n[1]!==r-2)throw new t("Invalid signature: incorrect length");const{d:i,l:s}=_e._parseInt(n.subarray(2)),{d:o,l:c}=_e._parseInt(s);if(c.length)throw new t("Invalid signature: left bytes after parsing");return{r:i,s:o}},hexFromSig(e){const t=f=>Number.parseInt(f[0],16)&8?"00"+f:f,n=f=>{const l=f.toString(16);return l.length&1?`0${l}`:l},r=t(n(e.s)),i=t(n(e.r)),s=r.length/2,o=i.length/2,c=n(s),a=n(o);return`30${n(o+s+4)}02${a}${i}02${c}${r}`}},fe=BigInt(0),Q=BigInt(1);BigInt(2);const jn=BigInt(3);BigInt(4);function as(e){const t=is(e),{Fp:n}=t,r=t.toBytes||((g,h,d)=>{const y=h.toAffine();return Be(Uint8Array.from([4]),n.toBytes(y.x),n.toBytes(y.y))}),i=t.fromBytes||(g=>{const h=g.subarray(1),d=n.fromBytes(h.subarray(0,n.BYTES)),y=n.fromBytes(h.subarray(n.BYTES,2*n.BYTES));return{x:d,y}});function s(g){const{a:h,b:d}=t,y=n.sqr(g),E=n.mul(y,g);return n.add(n.add(E,n.mul(g,h)),d)}if(!n.eql(n.sqr(t.Gy),s(t.Gx)))throw new Error("bad generator point: equation left != right");function o(g){return typeof g=="bigint"&&fe<g&&g<t.n}function c(g){if(!o(g))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function a(g){const{allowedPrivateKeyLengths:h,nByteLength:d,wrapPrivateKey:y,n:E}=t;if(h&&typeof g!="bigint"){if(g instanceof Uint8Array&&(g=Me(g)),typeof g!="string"||!h.includes(g.length))throw new Error("Invalid key");g=g.padStart(d*2,"0")}let S;try{S=typeof g=="bigint"?g:Y(G("private key",g,d))}catch{throw new Error(`private key must be ${d} bytes, hex or bigint, not ${typeof g}`)}return y&&(S=Z(S,E)),c(S),S}const f=new Map;function l(g){if(!(g instanceof u))throw new Error("ProjectivePoint expected")}class u{constructor(h,d,y){if(this.px=h,this.py=d,this.pz=y,h==null||!n.isValid(h))throw new Error("x required");if(d==null||!n.isValid(d))throw new Error("y required");if(y==null||!n.isValid(y))throw new Error("z required")}static fromAffine(h){const{x:d,y}=h||{};if(!h||!n.isValid(d)||!n.isValid(y))throw new Error("invalid affine point");if(h instanceof u)throw new Error("projective point not allowed");const E=S=>n.eql(S,n.ZERO);return E(d)&&E(y)?u.ZERO:new u(d,y,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){const d=n.invertBatch(h.map(y=>y.pz));return h.map((y,E)=>y.toAffine(d[E])).map(u.fromAffine)}static fromHex(h){const d=u.fromAffine(i(G("pointHex",h)));return d.assertValidity(),d}static fromPrivateKey(h){return u.BASE.multiply(a(h))}_setWindowSize(h){this._WINDOW_SIZE=h,f.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!n.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:h,y:d}=this.toAffine();if(!n.isValid(h)||!n.isValid(d))throw new Error("bad point: x or y not FE");const y=n.sqr(d),E=s(h);if(!n.eql(y,E))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:h}=this.toAffine();if(n.isOdd)return!n.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){l(h);const{px:d,py:y,pz:E}=this,{px:S,py:_,pz:I}=h,m=n.eql(n.mul(d,I),n.mul(S,E)),x=n.eql(n.mul(y,I),n.mul(_,E));return m&&x}negate(){return new u(this.px,n.neg(this.py),this.pz)}double(){const{a:h,b:d}=t,y=n.mul(d,jn),{px:E,py:S,pz:_}=this;let I=n.ZERO,m=n.ZERO,x=n.ZERO,N=n.mul(E,E),M=n.mul(S,S),k=n.mul(_,_),A=n.mul(E,S);return A=n.add(A,A),x=n.mul(E,_),x=n.add(x,x),I=n.mul(h,x),m=n.mul(y,k),m=n.add(I,m),I=n.sub(M,m),m=n.add(M,m),m=n.mul(I,m),I=n.mul(A,I),x=n.mul(y,x),k=n.mul(h,k),A=n.sub(N,k),A=n.mul(h,A),A=n.add(A,x),x=n.add(N,N),N=n.add(x,N),N=n.add(N,k),N=n.mul(N,A),m=n.add(m,N),k=n.mul(S,_),k=n.add(k,k),N=n.mul(k,A),I=n.sub(I,N),x=n.mul(k,M),x=n.add(x,x),x=n.add(x,x),new u(I,m,x)}add(h){l(h);const{px:d,py:y,pz:E}=this,{px:S,py:_,pz:I}=h;let m=n.ZERO,x=n.ZERO,N=n.ZERO;const M=t.a,k=n.mul(t.b,jn);let A=n.mul(d,S),T=n.mul(y,_),R=n.mul(E,I),j=n.add(d,y),b=n.add(S,_);j=n.mul(j,b),b=n.add(A,T),j=n.sub(j,b),b=n.add(d,E);let v=n.add(S,I);return b=n.mul(b,v),v=n.add(A,R),b=n.sub(b,v),v=n.add(y,E),m=n.add(_,I),v=n.mul(v,m),m=n.add(T,R),v=n.sub(v,m),N=n.mul(M,b),m=n.mul(k,R),N=n.add(m,N),m=n.sub(T,N),N=n.add(T,N),x=n.mul(m,N),T=n.add(A,A),T=n.add(T,A),R=n.mul(M,R),b=n.mul(k,b),T=n.add(T,R),R=n.sub(A,R),R=n.mul(M,R),b=n.add(b,R),A=n.mul(T,b),x=n.add(x,A),A=n.mul(v,b),m=n.mul(j,m),m=n.sub(m,A),A=n.mul(j,T),N=n.mul(v,N),N=n.add(N,A),new u(m,x,N)}subtract(h){return this.add(h.negate())}is0(){return this.equals(u.ZERO)}wNAF(h){return w.wNAFCached(this,f,h,d=>{const y=n.invertBatch(d.map(E=>E.pz));return d.map((E,S)=>E.toAffine(y[S])).map(u.fromAffine)})}multiplyUnsafe(h){const d=u.ZERO;if(h===fe)return d;if(c(h),h===Q)return this;const{endo:y}=t;if(!y)return w.unsafeLadder(this,h);let{k1neg:E,k1:S,k2neg:_,k2:I}=y.splitScalar(h),m=d,x=d,N=this;for(;S>fe||I>fe;)S&Q&&(m=m.add(N)),I&Q&&(x=x.add(N)),N=N.double(),S>>=Q,I>>=Q;return E&&(m=m.negate()),_&&(x=x.negate()),x=new u(n.mul(x.px,y.beta),x.py,x.pz),m.add(x)}multiply(h){c(h);let d=h,y,E;const{endo:S}=t;if(S){const{k1neg:_,k1:I,k2neg:m,k2:x}=S.splitScalar(d);let{p:N,f:M}=this.wNAF(I),{p:k,f:A}=this.wNAF(x);N=w.constTimeNegate(_,N),k=w.constTimeNegate(m,k),k=new u(n.mul(k.px,S.beta),k.py,k.pz),y=N.add(k),E=M.add(A)}else{const{p:_,f:I}=this.wNAF(d);y=_,E=I}return u.normalizeZ([y,E])[0]}multiplyAndAddUnsafe(h,d,y){const E=u.BASE,S=(I,m)=>m===fe||m===Q||!I.equals(E)?I.multiplyUnsafe(m):I.multiply(m),_=S(this,d).add(S(h,y));return _.is0()?void 0:_}toAffine(h){const{px:d,py:y,pz:E}=this,S=this.is0();h==null&&(h=S?n.ONE:n.inv(E));const _=n.mul(d,h),I=n.mul(y,h),m=n.mul(E,h);if(S)return{x:n.ZERO,y:n.ZERO};if(!n.eql(m,n.ONE))throw new Error("invZ was invalid");return{x:_,y:I}}isTorsionFree(){const{h,isTorsionFree:d}=t;if(h===Q)return!0;if(d)return d(u,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h,clearCofactor:d}=t;return h===Q?this:d?d(u,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return this.assertValidity(),r(u,this,h)}toHex(h=!0){return Me(this.toRawBytes(h))}}u.BASE=new u(t.Gx,t.Gy,n.ONE),u.ZERO=new u(n.ZERO,n.ONE,n.ZERO);const p=t.nBitLength,w=rs(u,t.endo?Math.ceil(p/2):p);return{CURVE:t,ProjectivePoint:u,normPrivateKeyToScalar:a,weierstrassEquation:s,isWithinCurveOrder:o}}function cs(e){const t=qn(e);return Fe(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function us(e){const t=cs(e),{Fp:n,n:r}=t,i=n.BYTES+1,s=2*n.BYTES+1;function o(b){return fe<b&&b<n.ORDER}function c(b){return Z(b,r)}function a(b){return $t(b,r)}const{ProjectivePoint:f,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:p}=as({...t,toBytes(b,v,K){const B=v.toAffine(),C=n.toBytes(B.x),L=Be;return K?L(Uint8Array.from([v.hasEvenY()?2:3]),C):L(Uint8Array.from([4]),C,n.toBytes(B.y))},fromBytes(b){const v=b.length,K=b[0],B=b.subarray(1);if(v===i&&(K===2||K===3)){const C=Y(B);if(!o(C))throw new Error("Point is not on curve");const L=u(C);let O=n.sqrt(L);const $=(O&Q)===Q;return(K&1)===1!==$&&(O=n.neg(O)),{x:C,y:O}}else if(v===s&&K===4){const C=n.fromBytes(B.subarray(0,n.BYTES)),L=n.fromBytes(B.subarray(n.BYTES,2*n.BYTES));return{x:C,y:L}}else throw new Error(`Point of length ${v} was invalid. Expected ${i} compressed bytes or ${s} uncompressed bytes`)}}),w=b=>Me(me(b,t.nByteLength));function g(b){const v=r>>Q;return b>v}function h(b){return g(b)?c(-b):b}const d=(b,v,K)=>Y(b.slice(v,K));class y{constructor(v,K,B){this.r=v,this.s=K,this.recovery=B,this.assertValidity()}static fromCompact(v){const K=t.nByteLength;return v=G("compactSignature",v,K*2),new y(d(v,0,K),d(v,K,2*K))}static fromDER(v){const{r:K,s:B}=_e.toSig(G("DER",v));return new y(K,B)}assertValidity(){if(!p(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!p(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(v){return new y(this.r,this.s,v)}recoverPublicKey(v){const{r:K,s:B,recovery:C}=this,L=x(G("msgHash",v));if(C==null||![0,1,2,3].includes(C))throw new Error("recovery id invalid");const O=C===2||C===3?K+t.n:K;if(O>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const $=(C&1)===0?"02":"03",re=f.fromHex($+w(O)),Ae=a(O),Ve=c(-L*Ae),tt=c(B*Ae),Ce=f.BASE.multiplyAndAddUnsafe(re,Ve,tt);if(!Ce)throw new Error("point at infinify");return Ce.assertValidity(),Ce}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return Pe(this.toDERHex())}toDERHex(){return _e.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Pe(this.toCompactHex())}toCompactHex(){return w(this.r)+w(this.s)}}const E={isValidPrivateKey(b){try{return l(b),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const b=Dn(t.n);return ts(t.randomBytes(b),t.n)},precompute(b=8,v=f.BASE){return v._setWindowSize(b),v.multiply(BigInt(3)),v}};function S(b,v=!0){return f.fromPrivateKey(b).toRawBytes(v)}function _(b){const v=b instanceof Uint8Array,K=typeof b=="string",B=(v||K)&&b.length;return v?B===i||B===s:K?B===2*i||B===2*s:b instanceof f}function I(b,v,K=!0){if(_(b))throw new Error("first arg must be private key");if(!_(v))throw new Error("second arg must be public key");return f.fromHex(v).multiply(l(b)).toRawBytes(K)}const m=t.bits2int||function(b){const v=Y(b),K=b.length*8-t.nBitLength;return K>0?v>>BigInt(K):v},x=t.bits2int_modN||function(b){return c(m(b))},N=_t(t.nBitLength);function M(b){if(typeof b!="bigint")throw new Error("bigint expected");if(!(fe<=b&&b<N))throw new Error(`bigint expected < 2^${t.nBitLength}`);return me(b,t.nByteLength)}function k(b,v,K=A){if(["recovered","canonical"].some(Oe=>Oe in K))throw new Error("sign() legacy options not supported");const{hash:B,randomBytes:C}=t;let{lowS:L,prehash:O,extraEntropy:$}=K;L==null&&(L=!0),b=G("msgHash",b),O&&(b=G("prehashed msgHash",B(b)));const re=x(b),Ae=l(v),Ve=[M(Ae),M(re)];if($!=null){const Oe=$===!0?C(n.BYTES):$;Ve.push(G("extraEntropy",Oe))}const tt=Be(...Ve),Ce=re;function Bn(Oe){const We=m(Oe);if(!p(We))return;const xi=a(We),Ze=f.BASE.multiply(We).toAffine(),ie=c(Ze.x);if(ie===fe)return;const Ge=c(xi*c(Ce+ie*Ae));if(Ge===fe)return;let Ni=(Ze.x===ie?0:2)|Number(Ze.y&Q),Ki=Ge;return L&&g(Ge)&&(Ki=h(Ge),Ni^=1),new y(ie,Ki,Ni)}return{seed:tt,k2sig:Bn}}const A={lowS:t.lowS,prehash:!1},T={lowS:t.lowS,prehash:!1};function R(b,v,K=A){const{seed:B,k2sig:C}=k(b,v,K),L=t;return Rn(L.hash.outputLen,L.nByteLength,L.hmac)(B,C)}f.BASE._setWindowSize(8);function j(b,v,K,B=T){var Ze;const C=b;if(v=G("msgHash",v),K=G("publicKey",K),"strict"in B)throw new Error("options.strict was renamed to lowS");const{lowS:L,prehash:O}=B;let $,re;try{if(typeof C=="string"||C instanceof Uint8Array)try{$=y.fromDER(C)}catch(ie){if(!(ie instanceof _e.Err))throw ie;$=y.fromCompact(C)}else if(typeof C=="object"&&typeof C.r=="bigint"&&typeof C.s=="bigint"){const{r:ie,s:Ge}=C;$=new y(ie,Ge)}else throw new Error("PARSE");re=f.fromHex(K)}catch(ie){if(ie.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(L&&$.hasHighS())return!1;O&&(v=t.hash(v));const{r:Ae,s:Ve}=$,tt=x(v),Ce=a(Ve),Bn=c(tt*Ce),Oe=c(Ae*Ce),We=(Ze=f.BASE.multiplyAndAddUnsafe(re,Bn,Oe))==null?void 0:Ze.toAffine();return We?c(We.x)===Ae:!1}return{CURVE:t,getPublicKey:S,getSharedSecret:I,sign:R,verify:j,ProjectivePoint:f,Signature:y,utils:E}}let zn=class extends _n{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,Si(t);const r=At(n);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?t.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=t.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),s.fill(0)}update(t){return nt(this),this.iHash.update(t),this}digestInto(t){nt(this),Ie(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:c}=this;return t=t,t.finished=i,t.destroyed=s,t.blockLen=o,t.outputLen=c,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Vn=(e,t,n)=>new zn(e,t).update(n).digest();Vn.create=(e,t)=>new zn(e,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function fs(e){return{hash:e,hmac:(t,...n)=>Vn(e,t,Ii(...n)),randomBytes:Un}}function ls(e,t){const n=r=>us({...e,...fs(r)});return Object.freeze({...n(t),create:n})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const st=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),ot=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Wn=BigInt(1),at=BigInt(2),Zn=(e,t)=>(e+t/at)/t;function Gn(e){const t=st,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),c=BigInt(44),a=BigInt(88),f=e*e*e%t,l=f*f*e%t,u=X(l,n,t)*l%t,p=X(u,n,t)*l%t,w=X(p,at,t)*f%t,g=X(w,i,t)*w%t,h=X(g,s,t)*g%t,d=X(h,c,t)*h%t,y=X(d,a,t)*d%t,E=X(y,c,t)*h%t,S=X(E,n,t)*l%t,_=X(S,o,t)*g%t,I=X(_,r,t)*f%t,m=X(I,at,t);if(!Rt.eql(Rt.sqr(m),e))throw new Error("Cannot find square root");return m}const Rt=es(st,void 0,void 0,{sqrt:Gn}),Ue=ls({a:BigInt(0),b:BigInt(7),Fp:Rt,n:ot,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=ot,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-Wn*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=n,o=BigInt("0x100000000000000000000000000000000"),c=Zn(s*e,t),a=Zn(-r*e,t);let f=Z(e-c*n-a*i,t),l=Z(-c*r-a*s,t);const u=f>o,p=l>o;if(u&&(f=t-f),p&&(l=t-l),f>o||l>o)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:u,k1:f,k2neg:p,k2:l}}}},Ct),ct=BigInt(0),Fn=e=>typeof e=="bigint"&&ct<e&&e<st,hs=e=>typeof e=="bigint"&&ct<e&&e<ot,Jn={};function ut(e,...t){let n=Jn[e];if(n===void 0){const r=Ct(Uint8Array.from(e,i=>i.charCodeAt(0)));n=Be(r,r),Jn[e]=n}return Ct(Be(n,...t))}const Ot=e=>e.toRawBytes(!0).slice(1),Mt=e=>me(e,32),Pt=e=>Z(e,st),Je=e=>Z(e,ot),Ht=Ue.ProjectivePoint,ds=(e,t,n)=>Ht.BASE.multiplyAndAddUnsafe(e,t,n);function Dt(e){let t=Ue.utils.normPrivateKeyToScalar(e),n=Ht.fromPrivateKey(t);return{scalar:n.hasEvenY()?t:Je(-t),bytes:Ot(n)}}function Yn(e){if(!Fn(e))throw new Error("bad x: need 0 < x < p");const t=Pt(e*e),n=Pt(t*e+BigInt(7));let r=Gn(n);r%at!==ct&&(r=Pt(-r));const i=new Ht(e,r,Wn);return i.assertValidity(),i}function Xn(...e){return Je(Y(ut("BIP0340/challenge",...e)))}function ps(e){return Dt(e).bytes}function ys(e,t,n=Un(32)){const r=G("message",e),{bytes:i,scalar:s}=Dt(t),o=G("auxRand",n,32),c=Mt(s^Y(ut("BIP0340/aux",o))),a=ut("BIP0340/nonce",c,i,r),f=Je(Y(a));if(f===ct)throw new Error("sign failed: k is zero");const{bytes:l,scalar:u}=Dt(f),p=Xn(l,i,r),w=new Uint8Array(64);if(w.set(l,0),w.set(Mt(Je(u+p*s)),32),!Qn(w,r,i))throw new Error("sign: Invalid signature produced");return w}function Qn(e,t,n){const r=G("signature",e,64),i=G("message",t),s=G("publicKey",n,32);try{const o=Yn(Y(s)),c=Y(r.subarray(0,32));if(!Fn(c))return!1;const a=Y(r.subarray(32,64));if(!hs(a))return!1;const f=Xn(Mt(c),Ot(o),i),l=ds(o,a,Je(-f));return!(!l||!l.hasEvenY()||l.toAffine().x!==c)}catch{return!1}}const Ye={getPublicKey:ps,sign:ys,verify:Qn,utils:{randomPrivateKey:Ue.utils.randomPrivateKey,lift_x:Yn,pointToBytes:Ot,numberToBytesBE:me,bytesToNumberBE:Y,taggedHash:ut,mod:Z}},qt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const jt=e=>e instanceof Uint8Array,zt=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),oe=(e,t)=>e<<32-t|e>>>t;if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");const gs=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function H(e){if(!jt(e))throw new Error("Uint8Array expected");let t="";for(let n=0;n<e.length;n++)t+=gs[e[n]];return t}function V(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);const t=e.length;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(t/2);for(let r=0;r<n.length;r++){const i=r*2,s=e.slice(i,i+2),o=Number.parseInt(s,16);if(Number.isNaN(o)||o<0)throw new Error("Invalid byte sequence");n[r]=o}return n}function ws(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function Xe(e){if(typeof e=="string"&&(e=ws(e)),!jt(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}function ft(...e){const t=new Uint8Array(e.reduce((r,i)=>r+i.length,0));let n=0;return e.forEach(r=>{if(!jt(r))throw new Error("Uint8Array expected");t.set(r,n),n+=r.length}),t}class er{clone(){return this._cloneInto()}}function tr(e){const t=r=>e().update(Xe(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function nr(e=32){if(qt&&typeof qt.getRandomValues=="function")return qt.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}function Vt(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function bs(e){if(typeof e!="boolean")throw new Error(`Expected boolean, not ${e}`)}function rr(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function vs(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Vt(e.outputLen),Vt(e.blockLen)}function ms(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Es(e,t){rr(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}const ae={number:Vt,bool:bs,bytes:rr,hash:vs,exists:ms,output:Es};function xs(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),c=Number(n&s),a=r?4:0,f=r?0:4;e.setUint32(t+a,o,r),e.setUint32(t+f,c,r)}class Ns extends er{constructor(t,n,r,i){super(),this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=zt(this.buffer)}update(t){ae.exists(this);const{view:n,buffer:r,blockLen:i}=this;t=Xe(t);const s=t.length;for(let o=0;o<s;){const c=Math.min(i-this.pos,s-o);if(c===i){const a=zt(t);for(;i<=s-o;o+=i)this.process(a,o);continue}r.set(t.subarray(o,o+c),this.pos),this.pos+=c,o+=c,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){ae.exists(this),ae.output(t,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(r,0),o=0);for(let u=o;u<i;u++)n[u]=0;xs(r,i-8,BigInt(this.length*8),s),this.process(r,0);const c=zt(t),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const f=a/4,l=this.get();if(f>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<f;u++)c.setUint32(4*u,l[u],s)}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:c}=this;return t.length=i,t.pos=c,t.finished=s,t.destroyed=o,i%n&&t.buffer.set(r),t}}const Ks=(e,t,n)=>e&t^~e&n,Ss=(e,t,n)=>e&t^e&n^t&n,As=new Uint32Array([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]),Ee=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),xe=new Uint32Array(64);class ir extends Ns{constructor(){super(64,32,8,!1),this.A=Ee[0]|0,this.B=Ee[1]|0,this.C=Ee[2]|0,this.D=Ee[3]|0,this.E=Ee[4]|0,this.F=Ee[5]|0,this.G=Ee[6]|0,this.H=Ee[7]|0}get(){const{A:t,B:n,C:r,D:i,E:s,F:o,G:c,H:a}=this;return[t,n,r,i,s,o,c,a]}set(t,n,r,i,s,o,c,a){this.A=t|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=c|0,this.H=a|0}process(t,n){for(let u=0;u<16;u++,n+=4)xe[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const p=xe[u-15],w=xe[u-2],g=oe(p,7)^oe(p,18)^p>>>3,h=oe(w,17)^oe(w,19)^w>>>10;xe[u]=h+xe[u-7]+g+xe[u-16]|0}let{A:r,B:i,C:s,D:o,E:c,F:a,G:f,H:l}=this;for(let u=0;u<64;u++){const p=oe(c,6)^oe(c,11)^oe(c,25),w=l+p+Ks(c,a,f)+As[u]+xe[u]|0,h=(oe(r,2)^oe(r,13)^oe(r,22))+Ss(r,i,s)|0;l=f,f=a,a=c,c=o+w|0,o=s,s=i,i=r,r=w+h|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,c=c+this.E|0,a=a+this.F|0,f=f+this.G|0,l=l+this.H|0,this.set(r,i,s,o,c,a,f,l)}roundClean(){xe.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}class Cs extends ir{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}}const le=tr(()=>new ir);tr(()=>new Cs);/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function He(e){if(!Number.isSafeInteger(e))throw new Error(`Wrong integer: ${e}`)}function he(...e){const t=(i,s)=>o=>i(s(o)),n=Array.from(e).reverse().reduce((i,s)=>i?t(i,s.encode):s.encode,void 0),r=e.reduce((i,s)=>i?t(i,s.decode):s.decode,void 0);return{encode:n,decode:r}}function de(e){return{encode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return t.map(n=>{if(He(n),n<0||n>=e.length)throw new Error(`Digit index outside alphabet: ${n} (alphabet: ${e.length})`);return e[n]})},decode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="string")throw new Error("alphabet.decode input should be array of strings");return t.map(n=>{if(typeof n!="string")throw new Error(`alphabet.decode: not string element=${n}`);const r=e.indexOf(n);if(r===-1)throw new Error(`Unknown letter: "${n}". Allowed: ${e}`);return r})}}}function pe(e=""){if(typeof e!="string")throw new Error("join separator should be string");return{encode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="string")throw new Error("join.encode input should be array of strings");for(let n of t)if(typeof n!="string")throw new Error(`join.encode: non-string input=${n}`);return t.join(e)},decode:t=>{if(typeof t!="string")throw new Error("join.decode input should be string");return t.split(e)}}}function lt(e,t="="){if(He(e),typeof t!="string")throw new Error("padding chr should be string");return{encode(n){if(!Array.isArray(n)||n.length&&typeof n[0]!="string")throw new Error("padding.encode input should be array of strings");for(let r of n)if(typeof r!="string")throw new Error(`padding.encode: non-string input=${r}`);for(;n.length*e%8;)n.push(t);return n},decode(n){if(!Array.isArray(n)||n.length&&typeof n[0]!="string")throw new Error("padding.encode input should be array of strings");for(let i of n)if(typeof i!="string")throw new Error(`padding.decode: non-string input=${i}`);let r=n.length;if(r*e%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;r>0&&n[r-1]===t;r--)if(!((r-1)*e%8))throw new Error("Invalid padding: string has too much padding");return n.slice(0,r)}}}function sr(e){if(typeof e!="function")throw new Error("normalize fn should be function");return{encode:t=>t,decode:t=>e(t)}}function or(e,t,n){if(t<2)throw new Error(`convertRadix: wrong from=${t}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: wrong to=${n}, base cannot be less than 2`);if(!Array.isArray(e))throw new Error("convertRadix: data should be array");if(!e.length)return[];let r=0;const i=[],s=Array.from(e);for(s.forEach(o=>{if(He(o),o<0||o>=t)throw new Error(`Wrong integer: ${o}`)});;){let o=0,c=!0;for(let a=r;a<s.length;a++){const f=s[a],l=t*o+f;if(!Number.isSafeInteger(l)||t*o/t!==o||l-f!==t*o)throw new Error("convertRadix: carry overflow");if(o=l%n,s[a]=Math.floor(l/n),!Number.isSafeInteger(s[a])||s[a]*n+o!==l)throw new Error("convertRadix: carry overflow");if(c)s[a]?c=!1:r=a;else continue}if(i.push(o),c)break}for(let o=0;o<e.length-1&&e[o]===0;o++)i.push(0);return i.reverse()}const ar=(e,t)=>t?ar(t,e%t):e,ht=(e,t)=>e+(t-ar(e,t));function Wt(e,t,n,r){if(!Array.isArray(e))throw new Error("convertRadix2: data should be array");if(t<=0||t>32)throw new Error(`convertRadix2: wrong from=${t}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(ht(t,n)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${ht(t,n)}`);let i=0,s=0;const o=2**n-1,c=[];for(const a of e){if(He(a),a>=2**t)throw new Error(`convertRadix2: invalid data word=${a} from=${t}`);if(i=i<<t|a,s+t>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${t}`);for(s+=t;s>=n;s-=n)c.push((i>>s-n&o)>>>0);i&=2**s-1}if(i=i<<n-s&o,!r&&s>=t)throw new Error("Excess padding");if(!r&&i)throw new Error(`Non-zero padding: ${i}`);return r&&s>0&&c.push(i>>>0),c}function Is(e){return He(e),{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return or(Array.from(t),2**8,e)},decode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="number")throw new Error("radix.decode input should be array of strings");return Uint8Array.from(or(t,e,2**8))}}}function Ne(e,t=!1){if(He(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(ht(8,e)>32||ht(e,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!(n instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return Wt(Array.from(n),8,e,!t)},decode:n=>{if(!Array.isArray(n)||n.length&&typeof n[0]!="number")throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(Wt(n,e,8,t))}}}function cr(e){if(typeof e!="function")throw new Error("unsafeWrapper fn should be function");return function(...t){try{return e.apply(null,t)}catch{}}}const Bs=he(Ne(4),de("0123456789ABCDEF"),pe("")),ks=he(Ne(5),de("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),lt(5),pe(""));he(Ne(5),de("0123456789ABCDEFGHIJKLMNOPQRSTUV"),lt(5),pe("")),he(Ne(5),de("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),pe(""),sr(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")));const ye=he(Ne(6),de("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),lt(6),pe("")),_s=he(Ne(6),de("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),lt(6),pe("")),Zt=e=>he(Is(58),de(e),pe("")),Gt=Zt("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");Zt("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),Zt("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const ur=[0,2,3,5,6,7,9,10,11],Us={encode(e){let t="";for(let n=0;n<e.length;n+=8){const r=e.subarray(n,n+8);t+=Gt.encode(r).padStart(ur[r.length],"1")}return t},decode(e){let t=[];for(let n=0;n<e.length;n+=11){const r=e.slice(n,n+11),i=ur.indexOf(r.length),s=Gt.decode(r);for(let o=0;o<s.length-i;o++)if(s[o]!==0)throw new Error("base58xmr: wrong padding");t=t.concat(Array.from(s.slice(s.length-i)))}return Uint8Array.from(t)}},Ft=he(de("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),pe("")),fr=[996825010,642813549,513874426,1027748829,705979059];function Qe(e){const t=e>>25;let n=(e&33554431)<<5;for(let r=0;r<fr.length;r++)(t>>r&1)===1&&(n^=fr[r]);return n}function lr(e,t,n=1){const r=e.length;let i=1;for(let s=0;s<r;s++){const o=e.charCodeAt(s);if(o<33||o>126)throw new Error(`Invalid prefix (${e})`);i=Qe(i)^o>>5}i=Qe(i);for(let s=0;s<r;s++)i=Qe(i)^e.charCodeAt(s)&31;for(let s of t)i=Qe(i)^s;for(let s=0;s<6;s++)i=Qe(i);return i^=n,Ft.encode(Wt([i%2**30],30,5,!1))}function hr(e){const t=e==="bech32"?1:734539939,n=Ne(5),r=n.decode,i=n.encode,s=cr(r);function o(l,u,p=90){if(typeof l!="string")throw new Error(`bech32.encode prefix should be string, not ${typeof l}`);if(!Array.isArray(u)||u.length&&typeof u[0]!="number")throw new Error(`bech32.encode words should be array of numbers, not ${typeof u}`);const w=l.length+7+u.length;if(p!==!1&&w>p)throw new TypeError(`Length ${w} exceeds limit ${p}`);return l=l.toLowerCase(),`${l}1${Ft.encode(u)}${lr(l,u,t)}`}function c(l,u=90){if(typeof l!="string")throw new Error(`bech32.decode input should be string, not ${typeof l}`);if(l.length<8||u!==!1&&l.length>u)throw new TypeError(`Wrong string length: ${l.length} (${l}). Expected (8..${u})`);const p=l.toLowerCase();if(l!==p&&l!==l.toUpperCase())throw new Error("String must be lowercase or uppercase");l=p;const w=l.lastIndexOf("1");if(w===0||w===-1)throw new Error('Letter "1" must be present between prefix and data only');const g=l.slice(0,w),h=l.slice(w+1);if(h.length<6)throw new Error("Data must be at least 6 characters long");const d=Ft.decode(h).slice(0,-6),y=lr(g,d,t);if(!h.endsWith(y))throw new Error(`Invalid checksum in ${l}: expected "${y}"`);return{prefix:g,words:d}}const a=cr(c);function f(l){const{prefix:u,words:p}=c(l,!1);return{prefix:u,words:p,bytes:r(p)}}return{encode:o,decode:c,decodeToBytes:f,decodeUnsafe:a,fromWords:r,fromWordsUnsafe:s,toWords:i}}const De=hr("bech32");hr("bech32m");const Ls={encode:e=>new TextDecoder().decode(e),decode:e=>new TextEncoder().encode(e)},$s=he(Ne(4),de("0123456789abcdef"),pe(""),sr(e=>{if(typeof e!="string"||e.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()}));`${Object.keys({utf8:Ls,hex:$s,base16:Bs,base32:ks,base64:ye,base64url:_s,base58:Gt,base58xmr:Us}).join(", ")}`;function Jt(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function dr(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}function Ts(e){return e instanceof Uint8Array||e!=null&&typeof e=="object"&&e.constructor.name==="Uint8Array"}function ge(e,...t){if(!Ts(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */const F=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");function Rs(e,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(e,t)}function Os(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}const Ms=(e,t)=>(Object.assign(t,e),t),Ke=16,Ps=283;function Yt(e){return e<<1^Ps&-(e>>7)}function qe(e,t){let n=0;for(;t>0;t>>=1)n^=e&-(t&1),e=Yt(e);return n}const Xt=(()=>{let e=new Uint8Array(256);for(let n=0,r=1;n<256;n++,r^=Yt(r))e[n]=r;const t=new Uint8Array(256);t[0]=99;for(let n=0;n<255;n++){let r=e[255-n];r|=r<<8,t[e[n]]=(r^r>>4^r>>5^r>>6^r>>7^99)&255}return t})(),Hs=Xt.map((e,t)=>Xt.indexOf(t)),Ds=e=>e<<24|e>>>8,Qt=e=>e<<8|e>>>24;function pr(e,t){if(e.length!==256)throw new Error("Wrong sbox length");const n=new Uint32Array(256).map((f,l)=>t(e[l])),r=n.map(Qt),i=r.map(Qt),s=i.map(Qt),o=new Uint32Array(256*256),c=new Uint32Array(256*256),a=new Uint16Array(256*256);for(let f=0;f<256;f++)for(let l=0;l<256;l++){const u=f*256+l;o[u]=n[f]^r[l],c[u]=i[f]^s[l],a[u]=e[f]<<8|e[l]}return{sbox:e,sbox2:a,T0:n,T1:r,T2:i,T3:s,T01:o,T23:c}}const en=pr(Xt,e=>qe(e,3)<<24|e<<16|e<<8|qe(e,2)),yr=pr(Hs,e=>qe(e,11)<<24|qe(e,13)<<16|qe(e,9)<<8|qe(e,14)),qs=(()=>{const e=new Uint8Array(16);for(let t=0,n=1;t<16;t++,n=Yt(n))e[t]=n;return e})();function gr(e){ge(e);const t=e.length;if(![16,24,32].includes(t))throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${t}`);const{sbox2:n}=en,r=F(e),i=r.length,s=c=>ce(n,c,c,c,c),o=new Uint32Array(t+28);o.set(r);for(let c=i;c<o.length;c++){let a=o[c-1];c%i===0?a=s(Ds(a))^qs[c/i-1]:i>6&&c%i===4&&(a=s(a)),o[c]=o[c-i]^a}return o}function js(e){const t=gr(e),n=t.slice(),r=t.length,{sbox2:i}=en,{T0:s,T1:o,T2:c,T3:a}=yr;for(let f=0;f<r;f+=4)for(let l=0;l<4;l++)n[f+l]=t[r-f-4+l];t.fill(0);for(let f=4;f<r-4;f++){const l=n[f],u=ce(i,l,l,l,l);n[f]=s[u&255]^o[u>>>8&255]^c[u>>>16&255]^a[u>>>24]}return n}function Se(e,t,n,r,i,s){return e[n<<8&65280|r>>>8&255]^t[i>>>8&65280|s>>>24&255]}function ce(e,t,n,r,i){return e[t&255|n&65280]|e[r>>>16&255|i>>>16&65280]<<16}function wr(e,t,n,r,i){const{sbox2:s,T01:o,T23:c}=en;let a=0;t^=e[a++],n^=e[a++],r^=e[a++],i^=e[a++];const f=e.length/4-2;for(let g=0;g<f;g++){const h=e[a++]^Se(o,c,t,n,r,i),d=e[a++]^Se(o,c,n,r,i,t),y=e[a++]^Se(o,c,r,i,t,n),E=e[a++]^Se(o,c,i,t,n,r);t=h,n=d,r=y,i=E}const l=e[a++]^ce(s,t,n,r,i),u=e[a++]^ce(s,n,r,i,t),p=e[a++]^ce(s,r,i,t,n),w=e[a++]^ce(s,i,t,n,r);return{s0:l,s1:u,s2:p,s3:w}}function zs(e,t,n,r,i){const{sbox2:s,T01:o,T23:c}=yr;let a=0;t^=e[a++],n^=e[a++],r^=e[a++],i^=e[a++];const f=e.length/4-2;for(let g=0;g<f;g++){const h=e[a++]^Se(o,c,t,i,r,n),d=e[a++]^Se(o,c,n,t,i,r),y=e[a++]^Se(o,c,r,n,t,i),E=e[a++]^Se(o,c,i,r,n,t);t=h,n=d,r=y,i=E}const l=e[a++]^ce(s,t,i,r,n),u=e[a++]^ce(s,n,t,i,r),p=e[a++]^ce(s,r,n,t,i),w=e[a++]^ce(s,i,r,n,t);return{s0:l,s1:u,s2:p,s3:w}}function br(e,t){if(!t)return new Uint8Array(e);if(ge(t),t.length<e)throw new Error(`aes: wrong destination length, expected at least ${e}, got: ${t.length}`);return t}function Vs(e){if(ge(e),e.length%Ke!==0)throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${Ke}`)}function Ws(e,t,n){let r=e.length;const i=r%Ke;if(!t&&i!==0)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");const s=F(e);if(t){let a=Ke-i;a||(a=Ke),r=r+a}const o=br(r,n),c=F(o);return{b:s,o:c,out:o}}function Zs(e,t){if(!t)return e;const n=e.length;if(!n)throw new Error("aes/pcks5: empty ciphertext not allowed");const r=e[n-1];if(r<=0||r>16)throw new Error(`aes/pcks5: wrong padding byte: ${r}`);const i=e.subarray(0,-r);for(let s=0;s<r;s++)if(e[n-s-1]!==r)throw new Error("aes/pcks5: wrong padding");return i}function Gs(e){const t=new Uint8Array(16),n=F(t);t.set(e);const r=Ke-e.length;for(let i=Ke-r;i<Ke;i++)t[i]=r;return n}const vr=Ms({blockSize:16,nonceLength:16},function(t,n,r={}){ge(t),ge(n,16);const i=!r.disablePadding;return{encrypt:(s,o)=>{const c=gr(t),{b:a,o:f,out:l}=Ws(s,i,o),u=F(n);let p=u[0],w=u[1],g=u[2],h=u[3],d=0;for(;d+4<=a.length;)p^=a[d+0],w^=a[d+1],g^=a[d+2],h^=a[d+3],{s0:p,s1:w,s2:g,s3:h}=wr(c,p,w,g,h),f[d++]=p,f[d++]=w,f[d++]=g,f[d++]=h;if(i){const y=Gs(s.subarray(d*4));p^=y[0],w^=y[1],g^=y[2],h^=y[3],{s0:p,s1:w,s2:g,s3:h}=wr(c,p,w,g,h),f[d++]=p,f[d++]=w,f[d++]=g,f[d++]=h}return c.fill(0),l},decrypt:(s,o)=>{Vs(s);const c=js(t),a=F(n),f=br(s.length,o),l=F(s),u=F(f);let p=a[0],w=a[1],g=a[2],h=a[3];for(let d=0;d+4<=l.length;){const y=p,E=w,S=g,_=h;p=l[d+0],w=l[d+1],g=l[d+2],h=l[d+3];const{s0:I,s1:m,s2:x,s3:N}=zs(c,p,w,g,h);u[d++]=I^y,u[d++]=m^E,u[d++]=x^S,u[d++]=N^_}return c.fill(0),Zs(f,i)}}}),mr=e=>Uint8Array.from(e.split("").map(t=>t.charCodeAt(0))),Fs=mr("expand 16-byte k"),Js=mr("expand 32-byte k"),Ys=F(Fs),Er=F(Js);Er.slice();function U(e,t){return e<<t|e>>>32-t}function tn(e){return e.byteOffset%4===0}const dt=64,Xs=16,xr=2**32-1,Nr=new Uint32Array;function Qs(e,t,n,r,i,s,o,c){const a=i.length,f=new Uint8Array(dt),l=F(f),u=tn(i)&&tn(s),p=u?F(i):Nr,w=u?F(s):Nr;for(let g=0;g<a;o++){if(e(t,n,r,l,o,c),o>=xr)throw new Error("arx: counter overflow");const h=Math.min(dt,a-g);if(u&&h===dt){const d=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let y=0,E;y<Xs;y++)E=d+y,w[E]=p[E]^l[y];g+=dt;continue}for(let d=0,y;d<h;d++)y=g+d,s[y]=i[y]^f[d];g+=h}}function eo(e,t){const{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:s,rounds:o}=Rs({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!="function")throw new Error("core must be a function");return Jt(i),Jt(o),dr(s),dr(n),(c,a,f,l,u=0)=>{ge(c),ge(a),ge(f);const p=f.length;if(l||(l=new Uint8Array(p)),ge(l),Jt(u),u<0||u>=xr)throw new Error("arx: counter overflow");if(l.length<p)throw new Error(`arx: output (${l.length}) is shorter than data (${p})`);const w=[];let g=c.length,h,d;if(g===32)h=c.slice(),w.push(h),d=Er;else if(g===16&&n)h=new Uint8Array(32),h.set(c),h.set(c,16),d=Ys,w.push(h);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);tn(a)||(a=a.slice(),w.push(a));const y=F(h);if(r){if(a.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(d,y,F(a.subarray(0,16)),y),a=a.subarray(16)}const E=16-i;if(E!==a.length)throw new Error(`arx: nonce must be ${E} or 16 bytes`);if(E!==12){const _=new Uint8Array(12);_.set(a,s?0:12-a.length),a=_,w.push(a)}const S=F(a);for(Qs(e,d,y,S,f,l,u,o);w.length>0;)w.pop().fill(0);return l}}function to(e,t,n,r,i,s=20){let o=e[0],c=e[1],a=e[2],f=e[3],l=t[0],u=t[1],p=t[2],w=t[3],g=t[4],h=t[5],d=t[6],y=t[7],E=i,S=n[0],_=n[1],I=n[2],m=o,x=c,N=a,M=f,k=l,A=u,T=p,R=w,j=g,b=h,v=d,K=y,B=E,C=S,L=_,O=I;for(let re=0;re<s;re+=2)m=m+k|0,B=U(B^m,16),j=j+B|0,k=U(k^j,12),m=m+k|0,B=U(B^m,8),j=j+B|0,k=U(k^j,7),x=x+A|0,C=U(C^x,16),b=b+C|0,A=U(A^b,12),x=x+A|0,C=U(C^x,8),b=b+C|0,A=U(A^b,7),N=N+T|0,L=U(L^N,16),v=v+L|0,T=U(T^v,12),N=N+T|0,L=U(L^N,8),v=v+L|0,T=U(T^v,7),M=M+R|0,O=U(O^M,16),K=K+O|0,R=U(R^K,12),M=M+R|0,O=U(O^M,8),K=K+O|0,R=U(R^K,7),m=m+A|0,O=U(O^m,16),v=v+O|0,A=U(A^v,12),m=m+A|0,O=U(O^m,8),v=v+O|0,A=U(A^v,7),x=x+T|0,B=U(B^x,16),K=K+B|0,T=U(T^K,12),x=x+T|0,B=U(B^x,8),K=K+B|0,T=U(T^K,7),N=N+R|0,C=U(C^N,16),j=j+C|0,R=U(R^j,12),N=N+R|0,C=U(C^N,8),j=j+C|0,R=U(R^j,7),M=M+k|0,L=U(L^M,16),b=b+L|0,k=U(k^b,12),M=M+k|0,L=U(L^M,8),b=b+L|0,k=U(k^b,7);let $=0;r[$++]=o+m|0,r[$++]=c+x|0,r[$++]=a+N|0,r[$++]=f+M|0,r[$++]=l+k|0,r[$++]=u+A|0,r[$++]=p+T|0,r[$++]=w+R|0,r[$++]=g+j|0,r[$++]=h+b|0,r[$++]=d+v|0,r[$++]=y+K|0,r[$++]=E+B|0,r[$++]=S+C|0,r[$++]=_+L|0,r[$++]=I+O|0}const Kr=eo(to,{counterRight:!1,counterLength:4,allowShortKeys:!1});class Sr extends er{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,ae.hash(t);const r=Xe(n);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?t.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=t.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),s.fill(0)}update(t){return ae.exists(this),this.iHash.update(t),this}digestInto(t){ae.exists(this),ae.bytes(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:c}=this;return t=t,t.finished=i,t.destroyed=s,t.blockLen=o,t.outputLen=c,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const pt=(e,t,n)=>new Sr(e,t).update(n).digest();pt.create=(e,t)=>new Sr(e,t);function nn(e,t,n){return ae.hash(e),n===void 0&&(n=new Uint8Array(e.outputLen)),pt(e,Xe(n),Xe(t))}const rn=new Uint8Array([0]),Ar=new Uint8Array;function Cr(e,t,n,r=32){if(ae.hash(e),ae.number(r),r>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(r/e.outputLen);n===void 0&&(n=Ar);const s=new Uint8Array(i*e.outputLen),o=pt.create(e,t),c=o._cloneInto(),a=new Uint8Array(o.outputLen);for(let f=0;f<i;f++)rn[0]=f+1,c.update(f===0?Ar:a).update(n).update(rn).digestInto(a),s.set(a,e.outputLen*f),o._cloneInto(c);return o.destroy(),c.destroy(),a.fill(0),rn.fill(0),s.slice(0,r)}var no=Object.defineProperty,D=(e,t)=>{for(var n in t)no(e,n,{get:t[n],enumerable:!0})},je=Symbol("verified"),ro=e=>e instanceof Object;function yt(e){if(!ro(e)||typeof e.kind!="number"||typeof e.content!="string"||typeof e.created_at!="number"||typeof e.pubkey!="string"||!e.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(e.tags))return!1;for(let t=0;t<e.tags.length;t++){let n=e.tags[t];if(!Array.isArray(n))return!1;for(let r=0;r<n.length;r++)if(typeof n[r]!="string")return!1}return!0}var io={};D(io,{Queue:()=>co,QueueNode:()=>Ir,binarySearch:()=>sn,bytesToHex:()=>H,hexToBytes:()=>V,insertEventIntoAscendingList:()=>ao,insertEventIntoDescendingList:()=>oo,normalizeURL:()=>so,utf8Decoder:()=>we,utf8Encoder:()=>ne});var we=new TextDecoder("utf-8"),ne=new TextEncoder;function so(e){try{e.indexOf("://")===-1&&(e="wss://"+e);let t=new URL(e);return t.pathname=t.pathname.replace(/\/+/g,"/"),t.pathname.endsWith("/")&&(t.pathname=t.pathname.slice(0,-1)),(t.port==="80"&&t.protocol==="ws:"||t.port==="443"&&t.protocol==="wss:")&&(t.port=""),t.searchParams.sort(),t.hash="",t.toString()}catch{throw new Error(`Invalid URL: ${e}`)}}function oo(e,t){const[n,r]=sn(e,i=>t.id===i.id?0:t.created_at===i.created_at?-1:i.created_at-t.created_at);return r||e.splice(n,0,t),e}function ao(e,t){const[n,r]=sn(e,i=>t.id===i.id?0:t.created_at===i.created_at?-1:t.created_at-i.created_at);return r||e.splice(n,0,t),e}function sn(e,t){let n=0,r=e.length-1;for(;n<=r;){const i=Math.floor((n+r)/2),s=t(e[i]);if(s===0)return[i,!0];s<0?r=i-1:n=i+1}return[n,!1]}var Ir=class{constructor(e){te(this,"value");te(this,"next",null);te(this,"prev",null);this.value=e}},co=class{constructor(){te(this,"first");te(this,"last");this.first=null,this.last=null}enqueue(e){const t=new Ir(e);return this.last?this.last===this.first?(this.last=t,this.last.prev=this.first,this.first.next=t):(t.prev=this.last,this.last.next=t,this.last=t):(this.first=t,this.last=t),!0}dequeue(){if(!this.first)return null;if(this.first===this.last){const t=this.first;return this.first=null,this.last=null,t.value}const e=this.first;return this.first=e.next,this.first&&(this.first.prev=null),e.value}},uo=class{generateSecretKey(){return Ye.utils.randomPrivateKey()}getPublicKey(e){return H(Ye.getPublicKey(e))}finalizeEvent(e,t){const n=e;return n.pubkey=H(Ye.getPublicKey(t)),n.id=ze(n),n.sig=H(Ye.sign(ze(n),t)),n[je]=!0,n}verifyEvent(e){if(typeof e[je]=="boolean")return e[je];const t=ze(e);if(t!==e.id)return e[je]=!1,!1;try{const n=Ye.verify(e.sig,t,e.pubkey);return e[je]=n,n}catch{return e[je]=!1,!1}}};function fo(e){if(!yt(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function ze(e){let t=le(ne.encode(fo(e)));return H(t)}var gt=new uo,Le=gt.generateSecretKey,ue=gt.getPublicKey,ee=gt.finalizeEvent,wt=gt.verifyEvent,lo={};D(lo,{Application:()=>la,BadgeAward:()=>mo,BadgeDefinition:()=>ia,BlockedRelaysList:()=>qo,BookmarkList:()=>Po,Bookmarksets:()=>ta,Calendar:()=>ba,CalendarEventRSVP:()=>va,ChannelCreation:()=>$r,ChannelHideMessage:()=>Or,ChannelMessage:()=>Rr,ChannelMetadata:()=>Tr,ChannelMuteUser:()=>Mr,ClassifiedListing:()=>pa,ClientAuth:()=>Hr,CommunitiesList:()=>Ho,CommunityDefinition:()=>xa,CommunityPostApproval:()=>Io,Contacts:()=>wo,CreateOrUpdateProduct:()=>aa,CreateOrUpdateStall:()=>oa,Curationsets:()=>na,Date:()=>ga,DirectMessageRelaysList:()=>Wo,DraftClassifiedListing:()=>ya,DraftLong:()=>ua,Emojisets:()=>fa,EncryptedDirectMessage:()=>bo,EventDeletion:()=>vo,FileMetadata:()=>xo,FileServerPreference:()=>Zo,Followsets:()=>Xo,GenericRepost:()=>fn,Genericlists:()=>Qo,GiftWrap:()=>Pr,HTTPAuth:()=>ln,Handlerinformation:()=>Ea,Handlerrecommendation:()=>ma,Highlights:()=>To,InterestsList:()=>zo,Interestsets:()=>sa,JobFeedback:()=>_o,JobRequest:()=>Bo,JobResult:()=>ko,Label:()=>Co,LightningPubRPC:()=>Fo,LiveChatMessage:()=>No,LiveEvent:()=>ha,LongFormArticle:()=>ca,Metadata:()=>yo,Mutelist:()=>Ro,NWCWalletInfo:()=>Go,NWCWalletRequest:()=>Dr,NWCWalletResponse:()=>Jo,NostrConnect:()=>Yo,OpenTimestamps:()=>Eo,Pinlist:()=>Oo,PrivateDirectMessage:()=>Lr,ProblemTracker:()=>Ko,ProfileBadges:()=>ra,PublicChatsList:()=>Do,Reaction:()=>un,RecommendRelay:()=>go,RelayList:()=>Mo,Relaysets:()=>ea,Report:()=>So,Reporting:()=>Ao,Repost:()=>cn,Seal:()=>Ur,SearchRelaysList:()=>jo,ShortTextNote:()=>_r,Time:()=>wa,UserEmojiList:()=>Vo,UserStatuses:()=>da,Zap:()=>$o,ZapGoal:()=>Uo,ZapRequest:()=>Lo,classifyKind:()=>ho,isAddressableKind:()=>an,isEphemeralKind:()=>kr,isKind:()=>po,isRegularKind:()=>Br,isReplaceableKind:()=>on});function Br(e){return 1e3<=e&&e<1e4||[1,2,4,5,6,7,8,16,40,41,42,43,44].includes(e)}function on(e){return[0,3].includes(e)||1e4<=e&&e<2e4}function kr(e){return 2e4<=e&&e<3e4}function an(e){return 3e4<=e&&e<4e4}function ho(e){return Br(e)?"regular":on(e)?"replaceable":kr(e)?"ephemeral":an(e)?"parameterized":"unknown"}function po(e,t){const n=t instanceof Array?t:[t];return yt(e)&&n.includes(e.kind)||!1}var yo=0,_r=1,go=2,wo=3,bo=4,vo=5,cn=6,un=7,mo=8,Ur=13,Lr=14,fn=16,$r=40,Tr=41,Rr=42,Or=43,Mr=44,Eo=1040,Pr=1059,xo=1063,No=1311,Ko=1971,So=1984,Ao=1984,Co=1985,Io=4550,Bo=5999,ko=6999,_o=7e3,Uo=9041,Lo=9734,$o=9735,To=9802,Ro=1e4,Oo=10001,Mo=10002,Po=10003,Ho=10004,Do=10005,qo=10006,jo=10007,zo=10015,Vo=10030,Wo=10050,Zo=10096,Go=13194,Fo=21e3,Hr=22242,Dr=23194,Jo=23195,Yo=24133,ln=27235,Xo=3e4,Qo=30001,ea=30002,ta=30003,na=30004,ra=30008,ia=30009,sa=30015,oa=30017,aa=30018,ca=30023,ua=30024,fa=30030,la=30078,ha=30311,da=30315,pa=30402,ya=30403,ga=31922,wa=31923,ba=31924,va=31925,ma=31989,Ea=31990,xa=34550,Na={};D(Na,{getHex64:()=>hn,getInt:()=>qr,getSubscriptionId:()=>Ka,matchEventId:()=>Sa,matchEventKind:()=>Ca,matchEventPubkey:()=>Aa});function hn(e,t){let n=t.length+3,r=e.indexOf(`"${t}":`)+n,i=e.slice(r).indexOf('"')+r+1;return e.slice(i,i+64)}function qr(e,t){let n=t.length,r=e.indexOf(`"${t}":`)+n+3,i=e.slice(r),s=Math.min(i.indexOf(","),i.indexOf("}"));return parseInt(i.slice(0,s),10)}function Ka(e){let t=e.slice(0,22).indexOf('"EVENT"');if(t===-1)return null;let n=e.slice(t+7+1).indexOf('"');if(n===-1)return null;let r=t+7+1+n,i=e.slice(r+1,80).indexOf('"');if(i===-1)return null;let s=r+1+i;return e.slice(r+1,s)}function Sa(e,t){return t===hn(e,"id")}function Aa(e,t){return t===hn(e,"pubkey")}function Ca(e,t){return t===qr(e,"kind")}var Ia={};D(Ia,{makeAuthEvent:()=>Ba});function Ba(e,t){return{kind:Hr,created_at:Math.floor(Date.now()/1e3),tags:[["relay",e],["challenge",t]],content:""}}var ka;try{ka=WebSocket}catch{}var _a;try{_a=WebSocket}catch{}var Ua={};D(Ua,{BECH32_REGEX:()=>jr,Bech32MaxSize:()=>dn,NostrTypeGuard:()=>La,decode:()=>bt,decodeNostrURI:()=>Ta,encodeBytes:()=>mt,naddrEncode:()=>Da,neventEncode:()=>Ha,noteEncode:()=>Ma,nprofileEncode:()=>Pa,npubEncode:()=>Oa,nsecEncode:()=>Ra});var La={isNProfile:e=>/^nprofile1[a-z\d]+$/.test(e||""),isNEvent:e=>/^nevent1[a-z\d]+$/.test(e||""),isNAddr:e=>/^naddr1[a-z\d]+$/.test(e||""),isNSec:e=>/^nsec1[a-z\d]{58}$/.test(e||""),isNPub:e=>/^npub1[a-z\d]{58}$/.test(e||""),isNote:e=>/^note1[a-z\d]+$/.test(e||""),isNcryptsec:e=>/^ncryptsec1[a-z\d]+$/.test(e||"")},dn=5e3,jr=/[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;function $a(e){const t=new Uint8Array(4);return t[0]=e>>24&255,t[1]=e>>16&255,t[2]=e>>8&255,t[3]=e&255,t}function Ta(e){try{return e.startsWith("nostr:")&&(e=e.substring(6)),bt(e)}catch{return{type:"invalid",data:null}}}function bt(e){var i,s,o,c,a,f,l;let{prefix:t,words:n}=De.decode(e,dn),r=new Uint8Array(De.fromWords(n));switch(t){case"nprofile":{let u=pn(r);if(!((i=u[0])!=null&&i[0]))throw new Error("missing TLV 0 for nprofile");if(u[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:H(u[0][0]),relays:u[1]?u[1].map(p=>we.decode(p)):[]}}}case"nevent":{let u=pn(r);if(!((s=u[0])!=null&&s[0]))throw new Error("missing TLV 0 for nevent");if(u[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");if(u[2]&&u[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(u[3]&&u[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:H(u[0][0]),relays:u[1]?u[1].map(p=>we.decode(p)):[],author:(o=u[2])!=null&&o[0]?H(u[2][0]):void 0,kind:(c=u[3])!=null&&c[0]?parseInt(H(u[3][0]),16):void 0}}}case"naddr":{let u=pn(r);if(!((a=u[0])!=null&&a[0]))throw new Error("missing TLV 0 for naddr");if(!((f=u[2])!=null&&f[0]))throw new Error("missing TLV 2 for naddr");if(u[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(!((l=u[3])!=null&&l[0]))throw new Error("missing TLV 3 for naddr");if(u[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:we.decode(u[0][0]),pubkey:H(u[2][0]),kind:parseInt(H(u[3][0]),16),relays:u[1]?u[1].map(p=>we.decode(p)):[]}}}case"nsec":return{type:t,data:r};case"npub":case"note":return{type:t,data:H(r)};default:throw new Error(`unknown prefix ${t}`)}}function pn(e){let t={},n=e;for(;n.length>0;){let r=n[0],i=n[1],s=n.slice(2,2+i);if(n=n.slice(2+i),s.length<i)throw new Error(`not enough data to read on TLV ${r}`);t[r]=t[r]||[],t[r].push(s)}return t}function Ra(e){return mt("nsec",e)}function Oa(e){return mt("npub",V(e))}function Ma(e){return mt("note",V(e))}function vt(e,t){let n=De.toWords(t);return De.encode(e,n,dn)}function mt(e,t){return vt(e,t)}function Pa(e){let t=yn({0:[V(e.pubkey)],1:(e.relays||[]).map(n=>ne.encode(n))});return vt("nprofile",t)}function Ha(e){let t;e.kind!==void 0&&(t=$a(e.kind));let n=yn({0:[V(e.id)],1:(e.relays||[]).map(r=>ne.encode(r)),2:e.author?[V(e.author)]:[],3:t?[new Uint8Array(t)]:[]});return vt("nevent",n)}function Da(e){let t=new ArrayBuffer(4);new DataView(t).setUint32(0,e.kind,!1);let n=yn({0:[ne.encode(e.identifier)],1:(e.relays||[]).map(r=>ne.encode(r)),2:[V(e.pubkey)],3:[new Uint8Array(t)]});return vt("naddr",n)}function yn(e){let t=[];return Object.entries(e).reverse().forEach(([n,r])=>{r.forEach(i=>{let s=new Uint8Array(i.length+2);s.set([parseInt(n)],0),s.set([i.length],1),s.set(i,2),t.push(s)})}),ft(...t)}var qa={};D(qa,{decrypt:()=>ja,encrypt:()=>zr});function zr(e,t,n){const r=e instanceof Uint8Array?H(e):e,i=Ue.getSharedSecret(r,"02"+t),s=Vr(i);let o=Uint8Array.from(nr(16)),c=ne.encode(n),a=vr(s,o).encrypt(c),f=ye.encode(new Uint8Array(a)),l=ye.encode(new Uint8Array(o.buffer));return`${f}?iv=${l}`}function ja(e,t,n){const r=e instanceof Uint8Array?H(e):e;let[i,s]=n.split("?iv="),o=Ue.getSharedSecret(r,"02"+t),c=Vr(o),a=ye.decode(s),f=ye.decode(i),l=vr(c,a).decrypt(f);return we.decode(l)}function Vr(e){return e.slice(1,33)}var za={};D(za,{NIP05_REGEX:()=>gn,isNip05:()=>Va,isValid:()=>Ga,queryProfile:()=>Wr,searchDomain:()=>Za,useFetchImplementation:()=>Wa});var gn=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,Va=e=>gn.test(e||""),Et;try{Et=fetch}catch{}function Wa(e){Et=e}async function Za(e,t=""){try{const n=`https://${e}/.well-known/nostr.json?name=${t}`,r=await Et(n,{redirect:"manual"});if(r.status!==200)throw Error("Wrong response code");return(await r.json()).names}catch{return{}}}async function Wr(e){var i;const t=e.match(gn);if(!t)return null;const[,n="_",r]=t;try{const s=`https://${r}/.well-known/nostr.json?name=${n}`,o=await Et(s,{redirect:"manual"});if(o.status!==200)throw Error("Wrong response code");const c=await o.json(),a=c.names[n];return a?{pubkey:a,relays:(i=c.relays)==null?void 0:i[a]}:null}catch{return null}}async function Ga(e,t){const n=await Wr(t);return n?n.pubkey===e:!1}var Fa={};D(Fa,{parse:()=>Ja});function Ja(e){const t={reply:void 0,root:void 0,mentions:[],profiles:[],quotes:[]};let n,r;for(let i=e.tags.length-1;i>=0;i--){const s=e.tags[i];if(s[0]==="e"&&s[1]){const[o,c,a,f,l]=s,u={id:c,relays:a?[a]:[],author:l};if(f==="root"){t.root=u;continue}if(f==="reply"){t.reply=u;continue}if(f==="mention"){t.mentions.push(u);continue}n?r=u:n=u,t.mentions.push(u);continue}if(s[0]==="q"&&s[1]){const[o,c,a]=s;t.quotes.push({id:c,relays:a?[a]:[]})}if(s[0]==="p"&&s[1]){t.profiles.push({pubkey:s[1],relays:s[2]?[s[2]]:[]});continue}}return t.root||(t.root=r||n||t.reply),t.reply||(t.reply=n||t.root),[t.reply,t.root].forEach(i=>{if(!i)return;let s=t.mentions.indexOf(i);if(s!==-1&&t.mentions.splice(s,1),i.author){let o=t.profiles.find(c=>c.pubkey===i.author);o&&o.relays&&(i.relays||(i.relays=[]),o.relays.forEach(c=>{var a;((a=i.relays)==null?void 0:a.indexOf(c))===-1&&i.relays.push(c)}),o.relays=i.relays)}}),t.mentions.forEach(i=>{if(i.author){let s=t.profiles.find(o=>o.pubkey===i.author);s&&s.relays&&(i.relays||(i.relays=[]),s.relays.forEach(o=>{i.relays.indexOf(o)===-1&&i.relays.push(o)}),s.relays=i.relays)}}),t}var Ya={};D(Ya,{fetchRelayInformation:()=>Qa,useFetchImplementation:()=>Xa});var Zr;try{Zr=fetch}catch{}function Xa(e){Zr=e}async function Qa(e){return await(await fetch(e.replace("ws://","http://").replace("wss://","https://"),{headers:{Accept:"application/nostr+json"}})).json()}var ec={};D(ec,{fastEventHash:()=>Fr,getPow:()=>Gr,minePow:()=>tc});function Gr(e){let t=0;for(let n=0;n<64;n+=8){const r=parseInt(e.substring(n,n+8),16);if(r===0)t+=32;else{t+=Math.clz32(r);break}}return t}function tc(e,t){let n=0;const r=e,i=["nonce",n.toString(),t.toString()];for(r.tags.push(i);;){const s=Math.floor(new Date().getTime()/1e3);if(s!==r.created_at&&(n=0,r.created_at=s),i[1]=(++n).toString(),r.id=Fr(r),Gr(r.id)>=t)break}return r}function Fr(e){return H(le(ne.encode(JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content]))))}var nc={};D(nc,{unwrapEvent:()=>dc,unwrapManyEvents:()=>pc,wrapEvent:()=>ui,wrapManyEvents:()=>hc});var rc={};D(rc,{createRumor:()=>si,createSeal:()=>oi,createWrap:()=>ai,unwrapEvent:()=>En,unwrapManyEvents:()=>ci,wrapEvent:()=>xt,wrapManyEvents:()=>fc});var q={};D(q,{decrypt:()=>mn,encrypt:()=>vn,getConversationKey:()=>wn,v2:()=>cc});var Jr=1,Yr=65535;function wn(e,t){const n=Ue.getSharedSecret(e,"02"+t).subarray(1,33);return nn(le,n,"nip44-v2")}function Xr(e,t){const n=Cr(le,e,t,76);return{chacha_key:n.subarray(0,32),chacha_nonce:n.subarray(32,44),hmac_key:n.subarray(44,76)}}function bn(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("expected positive integer");if(e<=32)return 32;const t=1<<Math.floor(Math.log2(e-1))+1,n=t<=256?32:t/8;return n*(Math.floor((e-1)/n)+1)}function ic(e){if(!Number.isSafeInteger(e)||e<Jr||e>Yr)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");const t=new Uint8Array(2);return new DataView(t.buffer).setUint16(0,e,!1),t}function sc(e){const t=ne.encode(e),n=t.length,r=ic(n),i=new Uint8Array(bn(n)-n);return ft(r,t,i)}function oc(e){const t=new DataView(e.buffer).getUint16(0),n=e.subarray(2,2+t);if(t<Jr||t>Yr||n.length!==t||e.length!==2+bn(t))throw new Error("invalid padding");return we.decode(n)}function Qr(e,t,n){if(n.length!==32)throw new Error("AAD associated data must be 32 bytes");const r=ft(n,t);return pt(le,e,r)}function ac(e){if(typeof e!="string")throw new Error("payload must be a valid string");const t=e.length;if(t<132||t>87472)throw new Error("invalid payload length: "+t);if(e[0]==="#")throw new Error("unknown encryption version");let n;try{n=ye.decode(e)}catch(s){throw new Error("invalid base64: "+s.message)}const r=n.length;if(r<99||r>65603)throw new Error("invalid data length: "+r);const i=n[0];if(i!==2)throw new Error("unknown encryption version "+i);return{nonce:n.subarray(1,33),ciphertext:n.subarray(33,-32),mac:n.subarray(-32)}}function vn(e,t,n=nr(32)){const{chacha_key:r,chacha_nonce:i,hmac_key:s}=Xr(t,n),o=sc(e),c=Kr(r,i,o),a=Qr(s,c,n);return ye.encode(ft(new Uint8Array([2]),n,c,a))}function mn(e,t){const{nonce:n,ciphertext:r,mac:i}=ac(e),{chacha_key:s,chacha_nonce:o,hmac_key:c}=Xr(t,n),a=Qr(c,r,n);if(!Os(a,i))throw new Error("invalid MAC");const f=Kr(s,o,r);return oc(f)}var cc={utils:{getConversationKey:wn,calcPaddedLen:bn},encrypt:vn,decrypt:mn},uc=2*24*60*60,ei=()=>Math.round(Date.now()/1e3),ti=()=>Math.round(ei()-Math.random()*uc),ni=(e,t)=>wn(e,t),ri=(e,t,n)=>vn(JSON.stringify(e),ni(t,n)),ii=(e,t)=>JSON.parse(mn(e.content,ni(t,e.pubkey)));function si(e,t){const n={created_at:ei(),content:"",tags:[],...e,pubkey:ue(t)};return n.id=ze(n),n}function oi(e,t,n){return ee({kind:Ur,content:ri(e,t,n),created_at:ti(),tags:[]},t)}function ai(e,t){const n=Le();return ee({kind:Pr,content:ri(e,n,t),created_at:ti(),tags:[["p",t]]},n)}function xt(e,t,n){const r=si(e,t),i=oi(r,t,n);return ai(i,n)}function fc(e,t,n){if(!n||n.length===0)throw new Error("At least one recipient is required.");const r=ue(t),i=[xt(e,t,r)];return n.forEach(s=>{i.push(xt(e,t,s))}),i}function En(e,t){const n=ii(e,t);return ii(n,t)}function ci(e,t){let n=[];return e.forEach(r=>{n.push(En(r,t))}),n.sort((r,i)=>r.created_at-i.created_at),n}function lc(e,t,n,r){const i={created_at:Math.ceil(Date.now()/1e3),kind:Lr,tags:[],content:t};return(Array.isArray(e)?e:[e]).forEach(({publicKey:o,relayUrl:c})=>{i.tags.push(c?["p",o,c]:["p",o])}),r&&i.tags.push(["e",r.eventId,r.relayUrl||"","reply"]),n&&i.tags.push(["subject",n]),i}function ui(e,t,n,r,i){const s=lc(t,n,r,i);return xt(s,e,t.publicKey)}function hc(e,t,n,r,i){if(!t||t.length===0)throw new Error("At least one recipient is required.");return[{publicKey:ue(e)},...t].map(o=>ui(e,o,n,r,i))}var dc=En,pc=ci,yc={};D(yc,{finishRepostEvent:()=>gc,getRepostedEvent:()=>wc,getRepostedEventPointer:()=>fi});function gc(e,t,n,r){var o;let i;const s=[...e.tags??[],["e",t.id,n],["p",t.pubkey]];return t.kind===_r?i=cn:(i=fn,s.push(["k",String(t.kind)])),ee({kind:i,tags:s,content:e.content===""||(o=t.tags)!=null&&o.find(c=>c[0]==="-")?"":JSON.stringify(t),created_at:e.created_at},r)}function fi(e){if(![cn,fn].includes(e.kind))return;let t,n;for(let r=e.tags.length-1;r>=0&&(t===void 0||n===void 0);r--){const i=e.tags[r];i.length>=2&&(i[0]==="e"&&t===void 0?t=i:i[0]==="p"&&n===void 0&&(n=i))}if(t!==void 0)return{id:t[1],relays:[t[2],n==null?void 0:n[2]].filter(r=>typeof r=="string"),author:n==null?void 0:n[1]}}function wc(e,{skipVerification:t}={}){const n=fi(e);if(n===void 0||e.content==="")return;let r;try{r=JSON.parse(e.content)}catch{return}if(r.id===n.id&&!(!t&&!wt(r)))return r}var bc={};D(bc,{NOSTR_URI_REGEX:()=>xn,parse:()=>mc,test:()=>vc});var xn=new RegExp(`nostr:(${jr.source})`);function vc(e){return typeof e=="string"&&new RegExp(`^${xn.source}$`).test(e)}function mc(e){const t=e.match(new RegExp(`^${xn.source}$`));if(!t)throw new Error(`Invalid Nostr URI: ${e}`);return{uri:t[0],value:t[1],decoded:bt(t[1])}}var Ec={};D(Ec,{finishReactionEvent:()=>xc,getReactedEventPointer:()=>Nc});function xc(e,t,n){const r=t.tags.filter(i=>i.length>=2&&(i[0]==="e"||i[0]==="p"));return ee({...e,kind:un,tags:[...e.tags??[],...r,["e",t.id],["p",t.pubkey]],content:e.content??"+"},n)}function Nc(e){if(e.kind!==un)return;let t,n;for(let r=e.tags.length-1;r>=0&&(t===void 0||n===void 0);r--){const i=e.tags[r];i.length>=2&&(i[0]==="e"&&t===void 0?t=i:i[0]==="p"&&n===void 0&&(n=i))}if(!(t===void 0||n===void 0))return{id:t[1],relays:[t[2],n[2]].filter(r=>r!==void 0),author:n[1]}}var Kc={};D(Kc,{parse:()=>Ac});var Sc=/\W/m,li=/\W |\W$|$|,| /m;function*Ac(e){const t=e.length;let n=0,r=0;for(;r<t;){let i=e.indexOf(":",r);if(i===-1)break;if(e.substring(i-5,i)==="nostr"){const s=e.substring(i+60).match(Sc),o=s?i+60+s.index:t;try{let c,{data:a,type:f}=bt(e.substring(i+1,o));switch(f){case"npub":c={pubkey:a};break;case"nsec":case"note":r=o+1;continue;default:c=a}n!==i-5&&(yield{type:"text",text:e.substring(n,i-5)}),yield{type:"reference",pointer:c},r=o,n=r;continue}catch{r=i+1;continue}}else if(e.substring(i-5,i)==="https"||e.substring(i-4,i)==="http"){const s=e.substring(i+4).match(li),o=s?i+4+s.index:t,c=e[i-1]==="s"?5:4;try{let a=new URL(e.substring(i-c,o));if(a.hostname.indexOf(".")===-1)throw new Error("invalid url");if(n!==i-c&&(yield{type:"text",text:e.substring(n,i-c)}),a.pathname.endsWith(".png")||a.pathname.endsWith(".jpg")||a.pathname.endsWith(".jpeg")||a.pathname.endsWith(".gif")||a.pathname.endsWith(".webp")){yield{type:"image",url:a.toString()},r=o,n=r;continue}if(a.pathname.endsWith(".mp4")||a.pathname.endsWith(".avi")||a.pathname.endsWith(".webm")||a.pathname.endsWith(".mkv")){yield{type:"video",url:a.toString()},r=o,n=r;continue}if(a.pathname.endsWith(".mp3")||a.pathname.endsWith(".aac")||a.pathname.endsWith(".ogg")||a.pathname.endsWith(".opus")){yield{type:"audio",url:a.toString()},r=o,n=r;continue}yield{type:"url",url:a.toString()},r=o,n=r;continue}catch{r=o+1;continue}}else if(e.substring(i-3,i)==="wss"||e.substring(i-2,i)==="ws"){const s=e.substring(i+4).match(li),o=s?i+4+s.index:t,c=e[i-1]==="s"?3:2;try{let a=new URL(e.substring(i-c,o));if(a.hostname.indexOf(".")===-1)throw new Error("invalid ws url");n!==i-c&&(yield{type:"text",text:e.substring(n,i-c)}),yield{type:"relay",url:a.toString()},r=o,n=r;continue}catch{r=o+1;continue}}else{r=i+1;continue}}n!==t&&(yield{type:"text",text:e.substring(n)})}var Cc={};D(Cc,{channelCreateEvent:()=>Ic,channelHideMessageEvent:()=>_c,channelMessageEvent:()=>kc,channelMetadataEvent:()=>Bc,channelMuteUserEvent:()=>Uc});var Ic=(e,t)=>{let n;if(typeof e.content=="object")n=JSON.stringify(e.content);else if(typeof e.content=="string")n=e.content;else return;return ee({kind:$r,tags:[...e.tags??[]],content:n,created_at:e.created_at},t)},Bc=(e,t)=>{let n;if(typeof e.content=="object")n=JSON.stringify(e.content);else if(typeof e.content=="string")n=e.content;else return;return ee({kind:Tr,tags:[["e",e.channel_create_event_id],...e.tags??[]],content:n,created_at:e.created_at},t)},kc=(e,t)=>{const n=[["e",e.channel_create_event_id,e.relay_url,"root"]];return e.reply_to_channel_message_event_id&&n.push(["e",e.reply_to_channel_message_event_id,e.relay_url,"reply"]),ee({kind:Rr,tags:[...n,...e.tags??[]],content:e.content,created_at:e.created_at},t)},_c=(e,t)=>{let n;if(typeof e.content=="object")n=JSON.stringify(e.content);else if(typeof e.content=="string")n=e.content;else return;return ee({kind:Or,tags:[["e",e.channel_message_event_id],...e.tags??[]],content:n,created_at:e.created_at},t)},Uc=(e,t)=>{let n;if(typeof e.content=="object")n=JSON.stringify(e.content);else if(typeof e.content=="string")n=e.content;else return;return ee({kind:Mr,tags:[["p",e.pubkey_to_mute],...e.tags??[]],content:n,created_at:e.created_at},t)},Lc={};D(Lc,{EMOJI_SHORTCODE_REGEX:()=>hi,matchAll:()=>$c,regex:()=>Nn,replaceAll:()=>Tc});var hi=/:(\w+):/,Nn=()=>new RegExp(`\\B${hi.source}\\B`,"g");function*$c(e){const t=e.matchAll(Nn());for(const n of t)try{const[r,i]=n;yield{shortcode:r,name:i,start:n.index,end:n.index+r.length}}catch{}}function Tc(e,t){return e.replaceAll(Nn(),(n,r)=>t({shortcode:n,name:r}))}var Rc={};D(Rc,{useFetchImplementation:()=>Oc,validateGithub:()=>Mc});var Kn;try{Kn=fetch}catch{}function Oc(e){Kn=e}async function Mc(e,t,n){try{return await(await Kn(`https://gist.github.com/${t}/${n}/raw`)).text()===`Verifying that I control the following Nostr public key: ${e}`}catch{return!1}}var Pc={};D(Pc,{makeNwcRequestEvent:()=>Dc,parseConnectionString:()=>Hc});function Hc(e){const{pathname:t,searchParams:n}=new URL(e),r=t,i=n.get("relay"),s=n.get("secret");if(!r||!i||!s)throw new Error("invalid connection string");return{pubkey:r,relay:i,secret:s}}async function Dc(e,t,n){const i=zr(t,e,JSON.stringify({method:"pay_invoice",params:{invoice:n}})),s={kind:Dr,created_at:Math.round(Date.now()/1e3),content:i,tags:[["p",e]]};return ee(s,t)}var qc={};D(qc,{normalizeIdentifier:()=>jc});function jc(e){return e=e.trim().toLowerCase(),e=e.normalize("NFKC"),Array.from(e).map(t=>new RegExp("\\p{Letter}","u").test(t)||new RegExp("\\p{Number}","u").test(t)?t:"-").join("")}var zc={};D(zc,{getSatoshisAmountFromBolt11:()=>Jc,getZapEndpoint:()=>Wc,makeZapReceipt:()=>Fc,makeZapRequest:()=>Zc,useFetchImplementation:()=>Vc,validateZapRequest:()=>Gc});var Sn;try{Sn=fetch}catch{}function Vc(e){Sn=e}async function Wc(e){try{let t="",{lud06:n,lud16:r}=JSON.parse(e.content);if(n){let{words:o}=De.decode(n,1e3),c=De.fromWords(o);t=we.decode(c)}else if(r){let[o,c]=r.split("@");t=new URL(`/.well-known/lnurlp/${o}`,`https://${c}`).toString()}else return null;let s=await(await Sn(t)).json();if(s.allowsNostr&&s.nostrPubkey)return s.callback}catch{}return null}function Zc({profile:e,event:t,amount:n,relays:r,comment:i=""}){if(!n)throw new Error("amount not given");if(!e)throw new Error("profile not given");let s={kind:9734,created_at:Math.round(Date.now()/1e3),content:i,tags:[["p",e],["amount",n.toString()],["relays",...r]]};if(t&&typeof t=="string"&&s.tags.push(["e",t]),t&&typeof t=="object"){if(on(t.kind)){const o=["a",`${t.kind}:${t.pubkey}:`];s.tags.push(o)}else if(an(t.kind)){let o=t.tags.find(([a,f])=>a==="d"&&f);if(!o)throw new Error("d tag not found or is empty");const c=["a",`${t.kind}:${t.pubkey}:${o[1]}`];s.tags.push(c)}}return s}function Gc(e){let t;try{t=JSON.parse(e)}catch{return"Invalid zap request JSON."}if(!yt(t))return"Zap request is not a valid Nostr event.";if(!wt(t))return"Invalid signature on zap request.";let n=t.tags.find(([s,o])=>s==="p"&&o);if(!n)return"Zap request doesn't have a 'p' tag.";if(!n[1].match(/^[a-f0-9]{64}$/))return"Zap request 'p' tag is not valid hex.";let r=t.tags.find(([s,o])=>s==="e"&&o);return r&&!r[1].match(/^[a-f0-9]{64}$/)?"Zap request 'e' tag is not valid hex.":t.tags.find(([s,o])=>s==="relays"&&o)?null:"Zap request doesn't have a 'relays' tag."}function Fc({zapRequest:e,preimage:t,bolt11:n,paidAt:r}){let i=JSON.parse(e),s=i.tags.filter(([c])=>c==="e"||c==="p"||c==="a"),o={kind:9735,created_at:Math.round(r.getTime()/1e3),content:"",tags:[...s,["P",i.pubkey],["bolt11",n],["description",e]]};return t&&o.tags.push(["preimage",t]),o}function Jc(e){if(e.length<50)return 0;e=e.substring(0,50);const t=e.lastIndexOf("1");if(t===-1)return 0;const n=e.substring(0,t);if(!n.startsWith("lnbc"))return 0;const r=n.substring(4);if(r.length<1)return 0;const i=r[r.length-1],s=i.charCodeAt(0)-48,o=s>=0&&s<=9;let c=r.length-1;if(o&&c++,c<1)return 0;const a=parseInt(r.substring(0,c));switch(i){case"m":return a*1e5;case"u":return a*100;case"n":return a/10;case"p":return a/1e4;default:return a*1e8}}var Yc={};D(Yc,{getToken:()=>Xc,hashPayload:()=>An,unpackEventFromToken:()=>pi,validateEvent:()=>mi,validateEventKind:()=>gi,validateEventMethodTag:()=>bi,validateEventPayloadTag:()=>vi,validateEventTimestamp:()=>yi,validateEventUrlTag:()=>wi,validateToken:()=>Qc});var di="Nostr ";async function Xc(e,t,n,r=!1,i){const s={kind:ln,tags:[["u",e],["method",t]],created_at:Math.round(new Date().getTime()/1e3),content:""};i&&s.tags.push(["payload",An(i)]);const o=await n(s);return(r?di:"")+ye.encode(ne.encode(JSON.stringify(o)))}async function Qc(e,t,n){const r=await pi(e).catch(s=>{throw s});return await mi(r,t,n).catch(s=>{throw s})}async function pi(e){if(!e)throw new Error("Missing token");e=e.replace(di,"");const t=we.decode(ye.decode(e));if(!t||t.length===0||!t.startsWith("{"))throw new Error("Invalid token");return JSON.parse(t)}function yi(e){return e.created_at?Math.round(new Date().getTime()/1e3)-e.created_at<60:!1}function gi(e){return e.kind===ln}function wi(e,t){const n=e.tags.find(r=>r[0]==="u");return n?n.length>0&&n[1]===t:!1}function bi(e,t){const n=e.tags.find(r=>r[0]==="method");return n?n.length>0&&n[1].toLowerCase()===t.toLowerCase():!1}function An(e){const t=le(ne.encode(JSON.stringify(e)));return H(t)}function vi(e,t){const n=e.tags.find(i=>i[0]==="payload");if(!n)return!1;const r=An(t);return n.length>0&&n[1]===r}async function mi(e,t,n,r){if(!wt(e))throw new Error("Invalid nostr event, signature invalid");if(!gi(e))throw new Error("Invalid nostr event, kind invalid");if(!yi(e))throw new Error("Invalid nostr event, created_at timestamp invalid");if(!wi(e,t))throw new Error("Invalid nostr event, url tag invalid");if(!bi(e,n))throw new Error("Invalid nostr event, method tag invalid");if(r&&typeof r=="object"&&Object.keys(r).length>0&&!vi(e,r))throw new Error("Invalid nostr event, payload tag does not match request body hash");return!0}const $e=1060,Cn=30078,In=1059,Ei=14,eu=100,tu=1;function nu(e){return JSON.stringify({version:tu,rootKey:H(e.rootKey),theirCurrentNostrPublicKey:e.theirCurrentNostrPublicKey,theirNextNostrPublicKey:e.theirNextNostrPublicKey,ourCurrentNostrKey:e.ourCurrentNostrKey?{publicKey:e.ourCurrentNostrKey.publicKey,privateKey:H(e.ourCurrentNostrKey.privateKey)}:void 0,ourNextNostrKey:{publicKey:e.ourNextNostrKey.publicKey,privateKey:H(e.ourNextNostrKey.privateKey)},receivingChainKey:e.receivingChainKey?H(e.receivingChainKey):void 0,sendingChainKey:e.sendingChainKey?H(e.sendingChainKey):void 0,sendingChainMessageNumber:e.sendingChainMessageNumber,receivingChainMessageNumber:e.receivingChainMessageNumber,previousSendingChainMessageCount:e.previousSendingChainMessageCount,skippedKeys:Object.fromEntries(Object.entries(e.skippedKeys).map(([t,n])=>[t,{headerKeys:n.headerKeys.map(r=>H(r)),messageKeys:Object.fromEntries(Object.entries(n.messageKeys).map(([r,i])=>[r,H(i)]))}]))})}function ru(e){const t=JSON.parse(e);if(!t.version){const n={};return t.skippedMessageKeys&&Object.entries(t.skippedMessageKeys).forEach(([r,i])=>{var s;n[r]={headerKeys:((s=t.skippedHeaderKeys)==null?void 0:s[r])||[],messageKeys:i}}),{rootKey:V(t.rootKey),theirCurrentNostrPublicKey:t.theirCurrentNostrPublicKey,theirNextNostrPublicKey:t.theirNextNostrPublicKey,ourCurrentNostrKey:t.ourCurrentNostrKey?{publicKey:t.ourCurrentNostrKey.publicKey,privateKey:V(t.ourCurrentNostrKey.privateKey)}:void 0,ourNextNostrKey:{publicKey:t.ourNextNostrKey.publicKey,privateKey:V(t.ourNextNostrKey.privateKey)},receivingChainKey:t.receivingChainKey?V(t.receivingChainKey):void 0,sendingChainKey:t.sendingChainKey?V(t.sendingChainKey):void 0,sendingChainMessageNumber:t.sendingChainMessageNumber,receivingChainMessageNumber:t.receivingChainMessageNumber,previousSendingChainMessageCount:t.previousSendingChainMessageCount,skippedKeys:n}}return{rootKey:V(t.rootKey),theirCurrentNostrPublicKey:t.theirCurrentNostrPublicKey,theirNextNostrPublicKey:t.theirNextNostrPublicKey,ourCurrentNostrKey:t.ourCurrentNostrKey?{publicKey:t.ourCurrentNostrKey.publicKey,privateKey:V(t.ourCurrentNostrKey.privateKey)}:void 0,ourNextNostrKey:{publicKey:t.ourNextNostrKey.publicKey,privateKey:V(t.ourNextNostrKey.privateKey)},receivingChainKey:t.receivingChainKey?V(t.receivingChainKey):void 0,sendingChainKey:t.sendingChainKey?V(t.sendingChainKey):void 0,sendingChainMessageNumber:t.sendingChainMessageNumber,receivingChainMessageNumber:t.receivingChainMessageNumber,previousSendingChainMessageCount:t.previousSendingChainMessageCount,skippedKeys:Object.fromEntries(Object.entries(t.skippedKeys||{}).map(([n,r])=>[n,{headerKeys:r.headerKeys.map(i=>V(i)),messageKeys:Object.fromEntries(Object.entries(r.messageKeys).map(([i,s])=>[i,V(s)]))}]))}}async function*iu(e){const t=[];let n=null;const r=e.onEvent(i=>{n?(n(i),n=null):t.push(i)});try{for(;;)t.length>0?yield t.shift():yield new Promise(i=>{n=i})}finally{r()}}function Te(e,t=new Uint8Array(32),n=1){const r=nn(le,e,t),i=[];for(let s=1;s<=n;s++)i.push(Cr(le,r,new Uint8Array([s]),32));return i}function su(e,t){return`${e}:${t}`}function ou(e){var n;const t=(n=e.tags)==null?void 0:n.find(r=>r[0]==="ms");return t?parseInt(t[1]):e.created_at*1e3}const au=1e3,cu="0000000000000000000000000000000000000000000000000000000000000000";class et{constructor(t,n){te(this,"skippedSubscription");te(this,"nostrUnsubscribe");te(this,"nostrNextUnsubscribe");te(this,"internalSubscriptions",new Map);te(this,"currentInternalSubscriptionId",0);te(this,"name");this.nostrSubscribe=t,this.state=n,this.name=Math.random().toString(36).substring(2,6)}static init(t,n,r,i,s,o){const c=Le();let a,f,l,u;i?([a,f]=Te(s,q.getConversationKey(c,n),2),l={publicKey:ue(r),privateKey:r},u={publicKey:ue(c),privateKey:c}):(a=s,f=void 0,l=void 0,u={publicKey:ue(r),privateKey:r});const p={rootKey:a,theirNextNostrPublicKey:n,ourCurrentNostrKey:l,ourNextNostrKey:u,receivingChainKey:void 0,sendingChainKey:f,sendingChainMessageNumber:0,receivingChainMessageNumber:0,previousSendingChainMessageCount:0,skippedKeys:{}},w=new et(t,p);return o&&(w.name=o),w}send(t){return this.sendEvent({content:t,kind:Ei})}sendEvent(t){if(!this.state.theirNextNostrPublicKey||!this.state.ourCurrentNostrKey)throw new Error("we are not the initiator, so we can't send the first message");if("sig"in t)throw new Error("Event must be unsigned "+JSON.stringify(t));const n=Date.now(),r={...t,content:t.content||"",kind:t.kind||$e,created_at:t.created_at||Math.floor(n/1e3),tags:t.tags||[],pubkey:t.pubkey||cu};r.tags.some(([f])=>f==="ms")||r.tags.push(["ms",String(n)]),r.id=ze(r);const[i,s]=this.ratchetEncrypt(JSON.stringify(r)),o=q.getConversationKey(this.state.ourCurrentNostrKey.privateKey,this.state.theirNextNostrPublicKey),c=q.encrypt(JSON.stringify(i),o);return{event:ee({content:s,kind:$e,tags:[["header",c]],created_at:Math.floor(n/1e3)},this.state.ourCurrentNostrKey.privateKey),innerEvent:r}}onEvent(t){const n=this.currentInternalSubscriptionId++;return this.internalSubscriptions.set(n,t),this.subscribeToNostrEvents(),()=>this.internalSubscriptions.delete(n)}close(){var t,n,r;(t=this.nostrUnsubscribe)==null||t.call(this),(n=this.nostrNextUnsubscribe)==null||n.call(this),(r=this.skippedSubscription)==null||r.call(this),this.internalSubscriptions.clear()}ratchetEncrypt(t){const[n,r]=Te(this.state.sendingChainKey,new Uint8Array([1]),2);return this.state.sendingChainKey=n,[{number:this.state.sendingChainMessageNumber++,nextPublicKey:this.state.ourNextNostrKey.publicKey,previousChainLength:this.state.previousSendingChainMessageCount},q.encrypt(t,r)]}ratchetDecrypt(t,n,r){const i=this.trySkippedMessageKeys(t,n,r);if(i)return i;this.skipMessageKeys(t.number,r);const[s,o]=Te(this.state.receivingChainKey,new Uint8Array([1]),2);return this.state.receivingChainKey=s,this.state.receivingChainMessageNumber++,q.decrypt(n,o)}ratchetStep(){this.state.previousSendingChainMessageCount=this.state.sendingChainMessageNumber,this.state.sendingChainMessageNumber=0,this.state.receivingChainMessageNumber=0;const t=q.getConversationKey(this.state.ourNextNostrKey.privateKey,this.state.theirNextNostrPublicKey),[n,r]=Te(this.state.rootKey,t,2);this.state.receivingChainKey=r,this.state.ourCurrentNostrKey=this.state.ourNextNostrKey;const i=Le();this.state.ourNextNostrKey={publicKey:ue(i),privateKey:i};const s=q.getConversationKey(this.state.ourNextNostrKey.privateKey,this.state.theirNextNostrPublicKey),[o,c]=Te(n,s,2);this.state.rootKey=o,this.state.sendingChainKey=c}skipMessageKeys(t,n){if(!(t<=this.state.receivingChainMessageNumber)){if(t>this.state.receivingChainMessageNumber+au)throw new Error("Too many skipped messages");if(!this.state.skippedKeys[n]){if(this.state.skippedKeys[n]={headerKeys:[],messageKeys:{}},this.state.ourCurrentNostrKey){const i=q.getConversationKey(this.state.ourCurrentNostrKey.privateKey,n);this.state.skippedKeys[n].headerKeys.includes(i)||this.state.skippedKeys[n].headerKeys.push(i)}const r=q.getConversationKey(this.state.ourNextNostrKey.privateKey,n);this.state.skippedKeys[n].headerKeys.includes(r)||this.state.skippedKeys[n].headerKeys.push(r)}for(;this.state.receivingChainMessageNumber<t;){const[r,i]=Te(this.state.receivingChainKey,new Uint8Array([1]),2);this.state.receivingChainKey=r,this.state.skippedKeys[n].messageKeys[this.state.receivingChainMessageNumber]=i,this.state.receivingChainMessageNumber++}}}trySkippedMessageKeys(t,n,r){const i=this.state.skippedKeys[r];if(!i)return null;const s=i.messageKeys[t.number];return s?(delete i.messageKeys[t.number],Object.keys(i.messageKeys).length===0&&delete this.state.skippedKeys[r],q.decrypt(n,s)):null}decryptHeader(t){const n=t.tags[0][1];if(this.state.ourCurrentNostrKey){const s=q.getConversationKey(this.state.ourCurrentNostrKey.privateKey,t.pubkey);try{return[JSON.parse(q.decrypt(n,s)),!1,!1]}catch{}}const r=q.getConversationKey(this.state.ourNextNostrKey.privateKey,t.pubkey);try{return[JSON.parse(q.decrypt(n,r)),!0,!1]}catch{}const i=this.state.skippedKeys[t.pubkey];if(i!=null&&i.headerKeys)for(const s of i.headerKeys)try{return[JSON.parse(q.decrypt(n,s)),!1,!0]}catch{}throw new Error("Failed to decrypt header with current and skipped header keys")}handleNostrEvent(t){var c,a;const[n,r,i]=this.decryptHeader(t);if(!i)this.state.theirNextNostrPublicKey!==n.nextPublicKey&&(this.state.theirCurrentNostrPublicKey=this.state.theirNextNostrPublicKey,this.state.theirNextNostrPublicKey=n.nextPublicKey,(c=this.nostrUnsubscribe)==null||c.call(this),this.nostrUnsubscribe=this.nostrNextUnsubscribe,this.nostrNextUnsubscribe=this.nostrSubscribe({authors:[this.state.theirNextNostrPublicKey],kinds:[$e]},f=>this.handleNostrEvent(f))),r&&(this.skipMessageKeys(n.previousChainLength,t.pubkey),this.ratchetStep());else if(!((a=this.state.skippedKeys[t.pubkey])!=null&&a.messageKeys[n.number]))return;const s=this.ratchetDecrypt(n,t.content,t.pubkey),o=JSON.parse(s);yt(o)&&o.id===ze(o)&&this.internalSubscriptions.forEach(f=>f(o,t))}subscribeToNostrEvents(){if(this.nostrNextUnsubscribe)return;this.nostrNextUnsubscribe=this.nostrSubscribe({authors:[this.state.theirNextNostrPublicKey],kinds:[$e]},n=>this.handleNostrEvent(n)),this.state.theirCurrentNostrPublicKey&&(this.nostrUnsubscribe=this.nostrSubscribe({authors:[this.state.theirCurrentNostrPublicKey],kinds:[$e]},n=>this.handleNostrEvent(n)));const t=Object.keys(this.state.skippedKeys);t.length&&(this.skippedSubscription=this.nostrSubscribe({authors:t,kinds:[$e]},n=>this.handleNostrEvent(n)))}}new TextDecoder("utf-8"),new TextEncoder;function Nt(e,t){const n=Ue.getSharedSecret(e,"02"+t).subarray(1,33);return nn(le,n,"nip44-v2")}const uu=2*24*60*60,fu=()=>Math.round(Date.now()/1e3),lu=()=>Math.round(fu()-Math.random()*uu);class Re{constructor(t,n,r,i,s,o,c=[]){this.inviterEphemeralPublicKey=t,this.sharedSecret=n,this.inviter=r,this.inviterEphemeralPrivateKey=i,this.deviceId=s,this.maxUses=o,this.usedBy=c}static createNew(t,n,r){if(!t)throw new Error("Inviter public key is required");const i=Le(),s=ue(i),o=H(Le());return new Re(s,o,t,i,n,r)}static fromUrl(t){const r=new URL(t).hash.slice(1);if(!r)throw new Error("No invite data found in the URL hash.");const i=decodeURIComponent(r);let s;try{s=JSON.parse(i)}catch(f){throw new Error("Invite data in URL hash is not valid JSON: "+f)}const{inviter:o,ephemeralKey:c,sharedSecret:a}=s;if(!o||!c||!a)throw new Error("Missing required fields (inviter, ephemeralKey, sharedSecret) in invite data.");return new Re(c,a,o)}static deserialize(t){const n=JSON.parse(t);return new Re(n.inviterEphemeralPublicKey,n.sharedSecret,n.inviter,n.inviterEphemeralPrivateKey?new Uint8Array(n.inviterEphemeralPrivateKey):void 0,n.deviceId,n.maxUses,n.usedBy)}static fromEvent(t){var a,f,l,u;if(!t.sig)throw new Error("Event is not signed");if(!wt(t))throw new Error("Event signature is invalid");const{tags:n}=t;if(!n)throw new Error("Invalid invite event: missing tags");const r=(a=n.find(([p])=>p==="ephemeralKey"))==null?void 0:a[1],i=(f=n.find(([p])=>p==="sharedSecret"))==null?void 0:f[1],s=t.pubkey,o=(l=n.find(([p])=>p==="d"))==null?void 0:l[1],c=(u=o==null?void 0:o.split("/"))==null?void 0:u[2];if(!r||!i)throw new Error("Invalid invite event: missing session key or sharedSecret");return new Re(r,i,s,void 0,c)}static fromUser(t,n,r){const i={kinds:[Cn],authors:[t],"#l":["double-ratchet/invites"]},s=new Set;return n(i,c=>{if(!s.has(c.id)){s.add(c.id);try{const a=Re.fromEvent(c);r(a)}catch{}}})}serialize(){return JSON.stringify({inviterEphemeralPublicKey:this.inviterEphemeralPublicKey,sharedSecret:this.sharedSecret,inviter:this.inviter,inviterEphemeralPrivateKey:this.inviterEphemeralPrivateKey?Array.from(this.inviterEphemeralPrivateKey):void 0,deviceId:this.deviceId,maxUses:this.maxUses,usedBy:this.usedBy})}getUrl(t="https://iris.to"){const n={inviter:this.inviter,ephemeralKey:this.inviterEphemeralPublicKey,sharedSecret:this.sharedSecret},r=new URL(t);return r.hash=encodeURIComponent(JSON.stringify(n)),r.toString()}getEvent(){if(!this.deviceId)throw new Error("Device ID is required");return{kind:Cn,pubkey:this.inviter,content:"",created_at:Math.floor(Date.now()/1e3),tags:[["ephemeralKey",this.inviterEphemeralPublicKey],["sharedSecret",this.sharedSecret],["d","double-ratchet/invites/"+this.deviceId],["l","double-ratchet/invites"]]}}async accept(t,n,r){const i=Le(),s=ue(i),o=this.inviter||this.inviterEphemeralPublicKey,c=V(this.sharedSecret),a=et.init(t,this.inviterEphemeralPublicKey,i,!0,c,void 0),l=await(typeof r=="function"?r:(d,y)=>Promise.resolve(q.encrypt(d,Nt(r,y))))(s,o),u={pubkey:n,content:await q.encrypt(l,c),created_at:Math.floor(Date.now()/1e3)},p=JSON.stringify(u),w=Le(),g=ue(w),h={kind:In,pubkey:g,content:q.encrypt(p,Nt(w,this.inviterEphemeralPublicKey)),created_at:lu(),tags:[["p",this.inviterEphemeralPublicKey]]};return{session:a,event:ee(h,w)}}listen(t,n,r){if(!this.inviterEphemeralPrivateKey)throw new Error("Inviter session key is not available");const i={kinds:[In],"#p":[this.inviterEphemeralPublicKey]};return n(i,async s=>{try{if(this.maxUses&&this.usedBy.length>=this.maxUses)return;const o=await q.decrypt(s.content,Nt(this.inviterEphemeralPrivateKey,s.pubkey)),c=JSON.parse(o),a=V(this.sharedSecret),f=c.pubkey;this.usedBy.push(f);const l=await q.decrypt(c.content,a),p=await(typeof t=="function"?t:(h,d)=>Promise.resolve(q.decrypt(h,Nt(t,d))))(l,f),w=s.id,g=et.init(n,p,this.inviterEphemeralPrivateKey,!1,a,w);r(g,f)}catch{}})}}P.CHAT_MESSAGE_KIND=Ei,P.INVITE_EVENT_KIND=Cn,P.INVITE_RESPONSE_KIND=In,P.Invite=Re,P.MAX_SKIP=eu,P.MESSAGE_EVENT_KIND=$e,P.Session=et,P.createEventStream=iu,P.deserializeSessionState=ru,P.getMillisecondTimestamp=ou,P.kdf=Te,P.serializeSessionState=nu,P.skippedMessageIndexKey=su,Object.defineProperty(P,Symbol.toStringTag,{value:"Module"})});
1
+ (function(P,J){typeof exports=="object"&&typeof module<"u"?J(exports):typeof define=="function"&&define.amd?define(["exports"],J):(P=typeof globalThis<"u"?globalThis:P||self,J(P["nostr-double-ratchet"]={}))})(this,function(P){"use strict";var hu=Object.defineProperty;var du=(P,J,Ie)=>J in P?hu(P,J,{enumerable:!0,configurable:!0,writable:!0,value:Ie}):P[J]=Ie;var te=(P,J,Ie)=>du(P,typeof J!="symbol"?J+"":J,Ie);function J(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function Ie(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function Si(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");J(e.outputLen),J(e.blockLen)}function nt(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Ai(e,t){Ie(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}const Kt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const kn=e=>e instanceof Uint8Array,St=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),se=(e,t)=>e<<32-t|e>>>t;if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");function Ci(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function At(e){if(typeof e=="string"&&(e=Ci(e)),!kn(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}function Ii(...e){const t=new Uint8Array(e.reduce((r,i)=>r+i.length,0));let n=0;return e.forEach(r=>{if(!kn(r))throw new Error("Uint8Array expected");t.set(r,n),n+=r.length}),t}let _n=class{clone(){return this._cloneInto()}};function Bi(e){const t=r=>e().update(At(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Un(e=32){if(Kt&&typeof Kt.getRandomValues=="function")return Kt.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}function ki(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),c=Number(n&s),a=r?4:0,f=r?0:4;e.setUint32(t+a,o,r),e.setUint32(t+f,c,r)}let _i=class extends _n{constructor(t,n,r,i){super(),this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=St(this.buffer)}update(t){nt(this);const{view:n,buffer:r,blockLen:i}=this;t=At(t);const s=t.length;for(let o=0;o<s;){const c=Math.min(i-this.pos,s-o);if(c===i){const a=St(t);for(;i<=s-o;o+=i)this.process(a,o);continue}r.set(t.subarray(o,o+c),this.pos),this.pos+=c,o+=c,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){nt(this),Ai(t,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(r,0),o=0);for(let u=o;u<i;u++)n[u]=0;ki(r,i-8,BigInt(this.length*8),s),this.process(r,0);const c=St(t),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const f=a/4,l=this.get();if(f>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<f;u++)c.setUint32(4*u,l[u],s)}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:c}=this;return t.length=i,t.pos=c,t.finished=s,t.destroyed=o,i%n&&t.buffer.set(r),t}};const Ui=(e,t,n)=>e&t^~e&n,Li=(e,t,n)=>e&t^e&n^t&n,$i=new Uint32Array([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]),be=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ve=new Uint32Array(64);let Ti=class extends _i{constructor(){super(64,32,8,!1),this.A=be[0]|0,this.B=be[1]|0,this.C=be[2]|0,this.D=be[3]|0,this.E=be[4]|0,this.F=be[5]|0,this.G=be[6]|0,this.H=be[7]|0}get(){const{A:t,B:n,C:r,D:i,E:s,F:o,G:c,H:a}=this;return[t,n,r,i,s,o,c,a]}set(t,n,r,i,s,o,c,a){this.A=t|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=c|0,this.H=a|0}process(t,n){for(let u=0;u<16;u++,n+=4)ve[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const p=ve[u-15],w=ve[u-2],g=se(p,7)^se(p,18)^p>>>3,h=se(w,17)^se(w,19)^w>>>10;ve[u]=h+ve[u-7]+g+ve[u-16]|0}let{A:r,B:i,C:s,D:o,E:c,F:a,G:f,H:l}=this;for(let u=0;u<64;u++){const p=se(c,6)^se(c,11)^se(c,25),w=l+p+Ui(c,a,f)+$i[u]+ve[u]|0,h=(se(r,2)^se(r,13)^se(r,22))+Li(r,i,s)|0;l=f,f=a,a=c,c=o+w|0,o=s,s=i,i=r,r=w+h|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,c=c+this.E|0,a=a+this.F|0,f=f+this.G|0,l=l+this.H|0,this.set(r,i,s,o,c,a,f,l)}roundClean(){ve.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const Ct=Bi(()=>new Ti);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ln=BigInt(0),rt=BigInt(1),Ri=BigInt(2),it=e=>e instanceof Uint8Array,Oi=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Me(e){if(!it(e))throw new Error("Uint8Array expected");let t="";for(let n=0;n<e.length;n++)t+=Oi[e[n]];return t}function $n(e){const t=e.toString(16);return t.length&1?`0${t}`:t}function It(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return BigInt(e===""?"0":`0x${e}`)}function Pe(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);const t=e.length;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(t/2);for(let r=0;r<n.length;r++){const i=r*2,s=e.slice(i,i+2),o=Number.parseInt(s,16);if(Number.isNaN(o)||o<0)throw new Error("Invalid byte sequence");n[r]=o}return n}function Y(e){return It(Me(e))}function Bt(e){if(!it(e))throw new Error("Uint8Array expected");return It(Me(Uint8Array.from(e).reverse()))}function me(e,t){return Pe(e.toString(16).padStart(t*2,"0"))}function kt(e,t){return me(e,t).reverse()}function Mi(e){return Pe($n(e))}function G(e,t,n){let r;if(typeof t=="string")try{r=Pe(t)}catch(s){throw new Error(`${e} must be valid hex string, got "${t}". Cause: ${s}`)}else if(it(t))r=Uint8Array.from(t);else throw new Error(`${e} must be hex string or Uint8Array`);const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(`${e} expected ${n} bytes, got ${i}`);return r}function Be(...e){const t=new Uint8Array(e.reduce((r,i)=>r+i.length,0));let n=0;return e.forEach(r=>{if(!it(r))throw new Error("Uint8Array expected");t.set(r,n),n+=r.length}),t}function Pi(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Hi(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function Di(e){let t;for(t=0;e>Ln;e>>=rt,t+=1);return t}function qi(e,t){return e>>BigInt(t)&rt}const ji=(e,t,n)=>e|(n?rt:Ln)<<BigInt(t),_t=e=>(Ri<<BigInt(e-1))-rt,Ut=e=>new Uint8Array(e),Tn=e=>Uint8Array.from(e);function Rn(e,t,n){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");let r=Ut(e),i=Ut(e),s=0;const o=()=>{r.fill(1),i.fill(0),s=0},c=(...u)=>n(i,r,...u),a=(u=Ut())=>{i=c(Tn([0]),u),r=c(),u.length!==0&&(i=c(Tn([1]),u),r=c())},f=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let u=0;const p=[];for(;u<t;){r=c();const w=r.slice();p.push(w),u+=r.length}return Be(...p)};return(u,p)=>{o(),a(u);let w;for(;!(w=p(f()));)a();return o(),w}}const zi={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||e instanceof Uint8Array,isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};function Fe(e,t,n={}){const r=(i,s,o)=>{const c=zi[s];if(typeof c!="function")throw new Error(`Invalid validator "${s}", expected function`);const a=e[i];if(!(o&&a===void 0)&&!c(a,e))throw new Error(`Invalid param ${String(i)}=${a} (${typeof a}), expected ${s}`)};for(const[i,s]of Object.entries(t))r(i,s,!1);for(const[i,s]of Object.entries(n))r(i,s,!0);return e}const Vi=Object.freeze(Object.defineProperty({__proto__:null,bitGet:qi,bitLen:Di,bitMask:_t,bitSet:ji,bytesToHex:Me,bytesToNumberBE:Y,bytesToNumberLE:Bt,concatBytes:Be,createHmacDrbg:Rn,ensureBytes:G,equalBytes:Pi,hexToBytes:Pe,hexToNumber:It,numberToBytesBE:me,numberToBytesLE:kt,numberToHexUnpadded:$n,numberToVarBytesBE:Mi,utf8ToBytes:Hi,validateObject:Fe},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const W=BigInt(0),z=BigInt(1),ke=BigInt(2),Wi=BigInt(3),Lt=BigInt(4),On=BigInt(5),Mn=BigInt(8);BigInt(9),BigInt(16);function Z(e,t){const n=e%t;return n>=W?n:t+n}function Zi(e,t,n){if(n<=W||t<W)throw new Error("Expected power/modulo > 0");if(n===z)return W;let r=z;for(;t>W;)t&z&&(r=r*e%n),e=e*e%n,t>>=z;return r}function X(e,t,n){let r=e;for(;t-- >W;)r*=r,r%=n;return r}function $t(e,t){if(e===W||t<=W)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let n=Z(e,t),r=t,i=W,s=z;for(;n!==W;){const c=r/n,a=r%n,f=i-s*c;r=n,n=a,i=s,s=f}if(r!==z)throw new Error("invert: does not exist");return Z(i,t)}function Gi(e){const t=(e-z)/ke;let n,r,i;for(n=e-z,r=0;n%ke===W;n/=ke,r++);for(i=ke;i<e&&Zi(i,t,e)!==e-z;i++);if(r===1){const o=(e+z)/Lt;return function(a,f){const l=a.pow(f,o);if(!a.eql(a.sqr(l),f))throw new Error("Cannot find square root");return l}}const s=(n+z)/ke;return function(c,a){if(c.pow(a,t)===c.neg(c.ONE))throw new Error("Cannot find square root");let f=r,l=c.pow(c.mul(c.ONE,i),n),u=c.pow(a,s),p=c.pow(a,n);for(;!c.eql(p,c.ONE);){if(c.eql(p,c.ZERO))return c.ZERO;let w=1;for(let h=c.sqr(p);w<f&&!c.eql(h,c.ONE);w++)h=c.sqr(h);const g=c.pow(l,z<<BigInt(f-w-1));l=c.sqr(g),u=c.mul(u,g),p=c.mul(p,l),f=w}return u}}function Fi(e){if(e%Lt===Wi){const t=(e+z)/Lt;return function(r,i){const s=r.pow(i,t);if(!r.eql(r.sqr(s),i))throw new Error("Cannot find square root");return s}}if(e%Mn===On){const t=(e-On)/Mn;return function(r,i){const s=r.mul(i,ke),o=r.pow(s,t),c=r.mul(i,o),a=r.mul(r.mul(c,ke),o),f=r.mul(c,r.sub(a,r.ONE));if(!r.eql(r.sqr(f),i))throw new Error("Cannot find square root");return f}}return Gi(e)}const Ji=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Yi(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=Ji.reduce((r,i)=>(r[i]="function",r),t);return Fe(e,n)}function Xi(e,t,n){if(n<W)throw new Error("Expected power > 0");if(n===W)return e.ONE;if(n===z)return t;let r=e.ONE,i=t;for(;n>W;)n&z&&(r=e.mul(r,i)),i=e.sqr(i),n>>=z;return r}function Qi(e,t){const n=new Array(t.length),r=t.reduce((s,o,c)=>e.is0(o)?s:(n[c]=s,e.mul(s,o)),e.ONE),i=e.inv(r);return t.reduceRight((s,o,c)=>e.is0(o)?s:(n[c]=e.mul(s,n[c]),e.mul(s,o)),i),n}function Pn(e,t){const n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function es(e,t,n=!1,r={}){if(e<=W)throw new Error(`Expected Field ORDER > 0, got ${e}`);const{nBitLength:i,nByteLength:s}=Pn(e,t);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");const o=Fi(e),c=Object.freeze({ORDER:e,BITS:i,BYTES:s,MASK:_t(i),ZERO:W,ONE:z,create:a=>Z(a,e),isValid:a=>{if(typeof a!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof a}`);return W<=a&&a<e},is0:a=>a===W,isOdd:a=>(a&z)===z,neg:a=>Z(-a,e),eql:(a,f)=>a===f,sqr:a=>Z(a*a,e),add:(a,f)=>Z(a+f,e),sub:(a,f)=>Z(a-f,e),mul:(a,f)=>Z(a*f,e),pow:(a,f)=>Xi(c,a,f),div:(a,f)=>Z(a*$t(f,e),e),sqrN:a=>a*a,addN:(a,f)=>a+f,subN:(a,f)=>a-f,mulN:(a,f)=>a*f,inv:a=>$t(a,e),sqrt:r.sqrt||(a=>o(c,a)),invertBatch:a=>Qi(c,a),cmov:(a,f,l)=>l?f:a,toBytes:a=>n?kt(a,s):me(a,s),fromBytes:a=>{if(a.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${a.length}`);return n?Bt(a):Y(a)}});return Object.freeze(c)}function Hn(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Dn(e){const t=Hn(e);return t+Math.ceil(t/2)}function ts(e,t,n=!1){const r=e.length,i=Hn(t),s=Dn(t);if(r<16||r<s||r>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${r}`);const o=n?Y(e):Bt(e),c=Z(o,t-z)+z;return n?kt(c,i):me(c,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ns=BigInt(0),Tt=BigInt(1);function rs(e,t){const n=(i,s)=>{const o=s.negate();return i?o:s},r=i=>{const s=Math.ceil(t/i)+1,o=2**(i-1);return{windows:s,windowSize:o}};return{constTimeNegate:n,unsafeLadder(i,s){let o=e.ZERO,c=i;for(;s>ns;)s&Tt&&(o=o.add(c)),c=c.double(),s>>=Tt;return o},precomputeWindow(i,s){const{windows:o,windowSize:c}=r(s),a=[];let f=i,l=f;for(let u=0;u<o;u++){l=f,a.push(l);for(let p=1;p<c;p++)l=l.add(f),a.push(l);f=l.double()}return a},wNAF(i,s,o){const{windows:c,windowSize:a}=r(i);let f=e.ZERO,l=e.BASE;const u=BigInt(2**i-1),p=2**i,w=BigInt(i);for(let g=0;g<c;g++){const h=g*a;let d=Number(o&u);o>>=w,d>a&&(d-=p,o+=Tt);const y=h,E=h+Math.abs(d)-1,S=g%2!==0,_=d<0;d===0?l=l.add(n(S,s[y])):f=f.add(n(_,s[E]))}return{p:f,f:l}},wNAFCached(i,s,o,c){const a=i._WINDOW_SIZE||1;let f=s.get(i);return f||(f=this.precomputeWindow(i,a),a!==1&&s.set(i,c(f))),this.wNAF(a,f,o)}}}function qn(e){return Yi(e.Fp),Fe(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Pn(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function is(e){const t=qn(e);Fe(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:n,Fp:r,a:i}=t;if(n){if(!r.eql(i,r.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof n!="object"||typeof n.beta!="bigint"||typeof n.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}const{bytesToNumberBE:ss,hexToBytes:os}=Vi,_e={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(e){const{Err:t}=_e;if(e.length<2||e[0]!==2)throw new t("Invalid signature integer tag");const n=e[1],r=e.subarray(2,n+2);if(!n||r.length!==n)throw new t("Invalid signature integer: wrong length");if(r[0]&128)throw new t("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return{d:ss(r),l:e.subarray(n+2)}},toSig(e){const{Err:t}=_e,n=typeof e=="string"?os(e):e;if(!(n instanceof Uint8Array))throw new Error("ui8a expected");let r=n.length;if(r<2||n[0]!=48)throw new t("Invalid signature tag");if(n[1]!==r-2)throw new t("Invalid signature: incorrect length");const{d:i,l:s}=_e._parseInt(n.subarray(2)),{d:o,l:c}=_e._parseInt(s);if(c.length)throw new t("Invalid signature: left bytes after parsing");return{r:i,s:o}},hexFromSig(e){const t=f=>Number.parseInt(f[0],16)&8?"00"+f:f,n=f=>{const l=f.toString(16);return l.length&1?`0${l}`:l},r=t(n(e.s)),i=t(n(e.r)),s=r.length/2,o=i.length/2,c=n(s),a=n(o);return`30${n(o+s+4)}02${a}${i}02${c}${r}`}},fe=BigInt(0),Q=BigInt(1);BigInt(2);const jn=BigInt(3);BigInt(4);function as(e){const t=is(e),{Fp:n}=t,r=t.toBytes||((g,h,d)=>{const y=h.toAffine();return Be(Uint8Array.from([4]),n.toBytes(y.x),n.toBytes(y.y))}),i=t.fromBytes||(g=>{const h=g.subarray(1),d=n.fromBytes(h.subarray(0,n.BYTES)),y=n.fromBytes(h.subarray(n.BYTES,2*n.BYTES));return{x:d,y}});function s(g){const{a:h,b:d}=t,y=n.sqr(g),E=n.mul(y,g);return n.add(n.add(E,n.mul(g,h)),d)}if(!n.eql(n.sqr(t.Gy),s(t.Gx)))throw new Error("bad generator point: equation left != right");function o(g){return typeof g=="bigint"&&fe<g&&g<t.n}function c(g){if(!o(g))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function a(g){const{allowedPrivateKeyLengths:h,nByteLength:d,wrapPrivateKey:y,n:E}=t;if(h&&typeof g!="bigint"){if(g instanceof Uint8Array&&(g=Me(g)),typeof g!="string"||!h.includes(g.length))throw new Error("Invalid key");g=g.padStart(d*2,"0")}let S;try{S=typeof g=="bigint"?g:Y(G("private key",g,d))}catch{throw new Error(`private key must be ${d} bytes, hex or bigint, not ${typeof g}`)}return y&&(S=Z(S,E)),c(S),S}const f=new Map;function l(g){if(!(g instanceof u))throw new Error("ProjectivePoint expected")}class u{constructor(h,d,y){if(this.px=h,this.py=d,this.pz=y,h==null||!n.isValid(h))throw new Error("x required");if(d==null||!n.isValid(d))throw new Error("y required");if(y==null||!n.isValid(y))throw new Error("z required")}static fromAffine(h){const{x:d,y}=h||{};if(!h||!n.isValid(d)||!n.isValid(y))throw new Error("invalid affine point");if(h instanceof u)throw new Error("projective point not allowed");const E=S=>n.eql(S,n.ZERO);return E(d)&&E(y)?u.ZERO:new u(d,y,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){const d=n.invertBatch(h.map(y=>y.pz));return h.map((y,E)=>y.toAffine(d[E])).map(u.fromAffine)}static fromHex(h){const d=u.fromAffine(i(G("pointHex",h)));return d.assertValidity(),d}static fromPrivateKey(h){return u.BASE.multiply(a(h))}_setWindowSize(h){this._WINDOW_SIZE=h,f.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!n.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:h,y:d}=this.toAffine();if(!n.isValid(h)||!n.isValid(d))throw new Error("bad point: x or y not FE");const y=n.sqr(d),E=s(h);if(!n.eql(y,E))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:h}=this.toAffine();if(n.isOdd)return!n.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){l(h);const{px:d,py:y,pz:E}=this,{px:S,py:_,pz:I}=h,m=n.eql(n.mul(d,I),n.mul(S,E)),x=n.eql(n.mul(y,I),n.mul(_,E));return m&&x}negate(){return new u(this.px,n.neg(this.py),this.pz)}double(){const{a:h,b:d}=t,y=n.mul(d,jn),{px:E,py:S,pz:_}=this;let I=n.ZERO,m=n.ZERO,x=n.ZERO,N=n.mul(E,E),M=n.mul(S,S),k=n.mul(_,_),A=n.mul(E,S);return A=n.add(A,A),x=n.mul(E,_),x=n.add(x,x),I=n.mul(h,x),m=n.mul(y,k),m=n.add(I,m),I=n.sub(M,m),m=n.add(M,m),m=n.mul(I,m),I=n.mul(A,I),x=n.mul(y,x),k=n.mul(h,k),A=n.sub(N,k),A=n.mul(h,A),A=n.add(A,x),x=n.add(N,N),N=n.add(x,N),N=n.add(N,k),N=n.mul(N,A),m=n.add(m,N),k=n.mul(S,_),k=n.add(k,k),N=n.mul(k,A),I=n.sub(I,N),x=n.mul(k,M),x=n.add(x,x),x=n.add(x,x),new u(I,m,x)}add(h){l(h);const{px:d,py:y,pz:E}=this,{px:S,py:_,pz:I}=h;let m=n.ZERO,x=n.ZERO,N=n.ZERO;const M=t.a,k=n.mul(t.b,jn);let A=n.mul(d,S),T=n.mul(y,_),R=n.mul(E,I),j=n.add(d,y),b=n.add(S,_);j=n.mul(j,b),b=n.add(A,T),j=n.sub(j,b),b=n.add(d,E);let v=n.add(S,I);return b=n.mul(b,v),v=n.add(A,R),b=n.sub(b,v),v=n.add(y,E),m=n.add(_,I),v=n.mul(v,m),m=n.add(T,R),v=n.sub(v,m),N=n.mul(M,b),m=n.mul(k,R),N=n.add(m,N),m=n.sub(T,N),N=n.add(T,N),x=n.mul(m,N),T=n.add(A,A),T=n.add(T,A),R=n.mul(M,R),b=n.mul(k,b),T=n.add(T,R),R=n.sub(A,R),R=n.mul(M,R),b=n.add(b,R),A=n.mul(T,b),x=n.add(x,A),A=n.mul(v,b),m=n.mul(j,m),m=n.sub(m,A),A=n.mul(j,T),N=n.mul(v,N),N=n.add(N,A),new u(m,x,N)}subtract(h){return this.add(h.negate())}is0(){return this.equals(u.ZERO)}wNAF(h){return w.wNAFCached(this,f,h,d=>{const y=n.invertBatch(d.map(E=>E.pz));return d.map((E,S)=>E.toAffine(y[S])).map(u.fromAffine)})}multiplyUnsafe(h){const d=u.ZERO;if(h===fe)return d;if(c(h),h===Q)return this;const{endo:y}=t;if(!y)return w.unsafeLadder(this,h);let{k1neg:E,k1:S,k2neg:_,k2:I}=y.splitScalar(h),m=d,x=d,N=this;for(;S>fe||I>fe;)S&Q&&(m=m.add(N)),I&Q&&(x=x.add(N)),N=N.double(),S>>=Q,I>>=Q;return E&&(m=m.negate()),_&&(x=x.negate()),x=new u(n.mul(x.px,y.beta),x.py,x.pz),m.add(x)}multiply(h){c(h);let d=h,y,E;const{endo:S}=t;if(S){const{k1neg:_,k1:I,k2neg:m,k2:x}=S.splitScalar(d);let{p:N,f:M}=this.wNAF(I),{p:k,f:A}=this.wNAF(x);N=w.constTimeNegate(_,N),k=w.constTimeNegate(m,k),k=new u(n.mul(k.px,S.beta),k.py,k.pz),y=N.add(k),E=M.add(A)}else{const{p:_,f:I}=this.wNAF(d);y=_,E=I}return u.normalizeZ([y,E])[0]}multiplyAndAddUnsafe(h,d,y){const E=u.BASE,S=(I,m)=>m===fe||m===Q||!I.equals(E)?I.multiplyUnsafe(m):I.multiply(m),_=S(this,d).add(S(h,y));return _.is0()?void 0:_}toAffine(h){const{px:d,py:y,pz:E}=this,S=this.is0();h==null&&(h=S?n.ONE:n.inv(E));const _=n.mul(d,h),I=n.mul(y,h),m=n.mul(E,h);if(S)return{x:n.ZERO,y:n.ZERO};if(!n.eql(m,n.ONE))throw new Error("invZ was invalid");return{x:_,y:I}}isTorsionFree(){const{h,isTorsionFree:d}=t;if(h===Q)return!0;if(d)return d(u,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h,clearCofactor:d}=t;return h===Q?this:d?d(u,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return this.assertValidity(),r(u,this,h)}toHex(h=!0){return Me(this.toRawBytes(h))}}u.BASE=new u(t.Gx,t.Gy,n.ONE),u.ZERO=new u(n.ZERO,n.ONE,n.ZERO);const p=t.nBitLength,w=rs(u,t.endo?Math.ceil(p/2):p);return{CURVE:t,ProjectivePoint:u,normPrivateKeyToScalar:a,weierstrassEquation:s,isWithinCurveOrder:o}}function cs(e){const t=qn(e);return Fe(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function us(e){const t=cs(e),{Fp:n,n:r}=t,i=n.BYTES+1,s=2*n.BYTES+1;function o(b){return fe<b&&b<n.ORDER}function c(b){return Z(b,r)}function a(b){return $t(b,r)}const{ProjectivePoint:f,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:p}=as({...t,toBytes(b,v,K){const B=v.toAffine(),C=n.toBytes(B.x),L=Be;return K?L(Uint8Array.from([v.hasEvenY()?2:3]),C):L(Uint8Array.from([4]),C,n.toBytes(B.y))},fromBytes(b){const v=b.length,K=b[0],B=b.subarray(1);if(v===i&&(K===2||K===3)){const C=Y(B);if(!o(C))throw new Error("Point is not on curve");const L=u(C);let O=n.sqrt(L);const $=(O&Q)===Q;return(K&1)===1!==$&&(O=n.neg(O)),{x:C,y:O}}else if(v===s&&K===4){const C=n.fromBytes(B.subarray(0,n.BYTES)),L=n.fromBytes(B.subarray(n.BYTES,2*n.BYTES));return{x:C,y:L}}else throw new Error(`Point of length ${v} was invalid. Expected ${i} compressed bytes or ${s} uncompressed bytes`)}}),w=b=>Me(me(b,t.nByteLength));function g(b){const v=r>>Q;return b>v}function h(b){return g(b)?c(-b):b}const d=(b,v,K)=>Y(b.slice(v,K));class y{constructor(v,K,B){this.r=v,this.s=K,this.recovery=B,this.assertValidity()}static fromCompact(v){const K=t.nByteLength;return v=G("compactSignature",v,K*2),new y(d(v,0,K),d(v,K,2*K))}static fromDER(v){const{r:K,s:B}=_e.toSig(G("DER",v));return new y(K,B)}assertValidity(){if(!p(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!p(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(v){return new y(this.r,this.s,v)}recoverPublicKey(v){const{r:K,s:B,recovery:C}=this,L=x(G("msgHash",v));if(C==null||![0,1,2,3].includes(C))throw new Error("recovery id invalid");const O=C===2||C===3?K+t.n:K;if(O>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const $=(C&1)===0?"02":"03",re=f.fromHex($+w(O)),Ae=a(O),Ve=c(-L*Ae),tt=c(B*Ae),Ce=f.BASE.multiplyAndAddUnsafe(re,Ve,tt);if(!Ce)throw new Error("point at infinify");return Ce.assertValidity(),Ce}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return Pe(this.toDERHex())}toDERHex(){return _e.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Pe(this.toCompactHex())}toCompactHex(){return w(this.r)+w(this.s)}}const E={isValidPrivateKey(b){try{return l(b),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const b=Dn(t.n);return ts(t.randomBytes(b),t.n)},precompute(b=8,v=f.BASE){return v._setWindowSize(b),v.multiply(BigInt(3)),v}};function S(b,v=!0){return f.fromPrivateKey(b).toRawBytes(v)}function _(b){const v=b instanceof Uint8Array,K=typeof b=="string",B=(v||K)&&b.length;return v?B===i||B===s:K?B===2*i||B===2*s:b instanceof f}function I(b,v,K=!0){if(_(b))throw new Error("first arg must be private key");if(!_(v))throw new Error("second arg must be public key");return f.fromHex(v).multiply(l(b)).toRawBytes(K)}const m=t.bits2int||function(b){const v=Y(b),K=b.length*8-t.nBitLength;return K>0?v>>BigInt(K):v},x=t.bits2int_modN||function(b){return c(m(b))},N=_t(t.nBitLength);function M(b){if(typeof b!="bigint")throw new Error("bigint expected");if(!(fe<=b&&b<N))throw new Error(`bigint expected < 2^${t.nBitLength}`);return me(b,t.nByteLength)}function k(b,v,K=A){if(["recovered","canonical"].some(Oe=>Oe in K))throw new Error("sign() legacy options not supported");const{hash:B,randomBytes:C}=t;let{lowS:L,prehash:O,extraEntropy:$}=K;L==null&&(L=!0),b=G("msgHash",b),O&&(b=G("prehashed msgHash",B(b)));const re=x(b),Ae=l(v),Ve=[M(Ae),M(re)];if($!=null){const Oe=$===!0?C(n.BYTES):$;Ve.push(G("extraEntropy",Oe))}const tt=Be(...Ve),Ce=re;function Bn(Oe){const We=m(Oe);if(!p(We))return;const xi=a(We),Ze=f.BASE.multiply(We).toAffine(),ie=c(Ze.x);if(ie===fe)return;const Ge=c(xi*c(Ce+ie*Ae));if(Ge===fe)return;let Ni=(Ze.x===ie?0:2)|Number(Ze.y&Q),Ki=Ge;return L&&g(Ge)&&(Ki=h(Ge),Ni^=1),new y(ie,Ki,Ni)}return{seed:tt,k2sig:Bn}}const A={lowS:t.lowS,prehash:!1},T={lowS:t.lowS,prehash:!1};function R(b,v,K=A){const{seed:B,k2sig:C}=k(b,v,K),L=t;return Rn(L.hash.outputLen,L.nByteLength,L.hmac)(B,C)}f.BASE._setWindowSize(8);function j(b,v,K,B=T){var Ze;const C=b;if(v=G("msgHash",v),K=G("publicKey",K),"strict"in B)throw new Error("options.strict was renamed to lowS");const{lowS:L,prehash:O}=B;let $,re;try{if(typeof C=="string"||C instanceof Uint8Array)try{$=y.fromDER(C)}catch(ie){if(!(ie instanceof _e.Err))throw ie;$=y.fromCompact(C)}else if(typeof C=="object"&&typeof C.r=="bigint"&&typeof C.s=="bigint"){const{r:ie,s:Ge}=C;$=new y(ie,Ge)}else throw new Error("PARSE");re=f.fromHex(K)}catch(ie){if(ie.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(L&&$.hasHighS())return!1;O&&(v=t.hash(v));const{r:Ae,s:Ve}=$,tt=x(v),Ce=a(Ve),Bn=c(tt*Ce),Oe=c(Ae*Ce),We=(Ze=f.BASE.multiplyAndAddUnsafe(re,Bn,Oe))==null?void 0:Ze.toAffine();return We?c(We.x)===Ae:!1}return{CURVE:t,getPublicKey:S,getSharedSecret:I,sign:R,verify:j,ProjectivePoint:f,Signature:y,utils:E}}let zn=class extends _n{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,Si(t);const r=At(n);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?t.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=t.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),s.fill(0)}update(t){return nt(this),this.iHash.update(t),this}digestInto(t){nt(this),Ie(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:c}=this;return t=t,t.finished=i,t.destroyed=s,t.blockLen=o,t.outputLen=c,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Vn=(e,t,n)=>new zn(e,t).update(n).digest();Vn.create=(e,t)=>new zn(e,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function fs(e){return{hash:e,hmac:(t,...n)=>Vn(e,t,Ii(...n)),randomBytes:Un}}function ls(e,t){const n=r=>us({...e,...fs(r)});return Object.freeze({...n(t),create:n})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const st=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),ot=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Wn=BigInt(1),at=BigInt(2),Zn=(e,t)=>(e+t/at)/t;function Gn(e){const t=st,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),c=BigInt(44),a=BigInt(88),f=e*e*e%t,l=f*f*e%t,u=X(l,n,t)*l%t,p=X(u,n,t)*l%t,w=X(p,at,t)*f%t,g=X(w,i,t)*w%t,h=X(g,s,t)*g%t,d=X(h,c,t)*h%t,y=X(d,a,t)*d%t,E=X(y,c,t)*h%t,S=X(E,n,t)*l%t,_=X(S,o,t)*g%t,I=X(_,r,t)*f%t,m=X(I,at,t);if(!Rt.eql(Rt.sqr(m),e))throw new Error("Cannot find square root");return m}const Rt=es(st,void 0,void 0,{sqrt:Gn}),Ue=ls({a:BigInt(0),b:BigInt(7),Fp:Rt,n:ot,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=ot,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-Wn*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=n,o=BigInt("0x100000000000000000000000000000000"),c=Zn(s*e,t),a=Zn(-r*e,t);let f=Z(e-c*n-a*i,t),l=Z(-c*r-a*s,t);const u=f>o,p=l>o;if(u&&(f=t-f),p&&(l=t-l),f>o||l>o)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:u,k1:f,k2neg:p,k2:l}}}},Ct),ct=BigInt(0),Fn=e=>typeof e=="bigint"&&ct<e&&e<st,hs=e=>typeof e=="bigint"&&ct<e&&e<ot,Jn={};function ut(e,...t){let n=Jn[e];if(n===void 0){const r=Ct(Uint8Array.from(e,i=>i.charCodeAt(0)));n=Be(r,r),Jn[e]=n}return Ct(Be(n,...t))}const Ot=e=>e.toRawBytes(!0).slice(1),Mt=e=>me(e,32),Pt=e=>Z(e,st),Je=e=>Z(e,ot),Ht=Ue.ProjectivePoint,ds=(e,t,n)=>Ht.BASE.multiplyAndAddUnsafe(e,t,n);function Dt(e){let t=Ue.utils.normPrivateKeyToScalar(e),n=Ht.fromPrivateKey(t);return{scalar:n.hasEvenY()?t:Je(-t),bytes:Ot(n)}}function Yn(e){if(!Fn(e))throw new Error("bad x: need 0 < x < p");const t=Pt(e*e),n=Pt(t*e+BigInt(7));let r=Gn(n);r%at!==ct&&(r=Pt(-r));const i=new Ht(e,r,Wn);return i.assertValidity(),i}function Xn(...e){return Je(Y(ut("BIP0340/challenge",...e)))}function ps(e){return Dt(e).bytes}function ys(e,t,n=Un(32)){const r=G("message",e),{bytes:i,scalar:s}=Dt(t),o=G("auxRand",n,32),c=Mt(s^Y(ut("BIP0340/aux",o))),a=ut("BIP0340/nonce",c,i,r),f=Je(Y(a));if(f===ct)throw new Error("sign failed: k is zero");const{bytes:l,scalar:u}=Dt(f),p=Xn(l,i,r),w=new Uint8Array(64);if(w.set(l,0),w.set(Mt(Je(u+p*s)),32),!Qn(w,r,i))throw new Error("sign: Invalid signature produced");return w}function Qn(e,t,n){const r=G("signature",e,64),i=G("message",t),s=G("publicKey",n,32);try{const o=Yn(Y(s)),c=Y(r.subarray(0,32));if(!Fn(c))return!1;const a=Y(r.subarray(32,64));if(!hs(a))return!1;const f=Xn(Mt(c),Ot(o),i),l=ds(o,a,Je(-f));return!(!l||!l.hasEvenY()||l.toAffine().x!==c)}catch{return!1}}const Ye={getPublicKey:ps,sign:ys,verify:Qn,utils:{randomPrivateKey:Ue.utils.randomPrivateKey,lift_x:Yn,pointToBytes:Ot,numberToBytesBE:me,bytesToNumberBE:Y,taggedHash:ut,mod:Z}},qt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const jt=e=>e instanceof Uint8Array,zt=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),oe=(e,t)=>e<<32-t|e>>>t;if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");const gs=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function H(e){if(!jt(e))throw new Error("Uint8Array expected");let t="";for(let n=0;n<e.length;n++)t+=gs[e[n]];return t}function V(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);const t=e.length;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(t/2);for(let r=0;r<n.length;r++){const i=r*2,s=e.slice(i,i+2),o=Number.parseInt(s,16);if(Number.isNaN(o)||o<0)throw new Error("Invalid byte sequence");n[r]=o}return n}function ws(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function Xe(e){if(typeof e=="string"&&(e=ws(e)),!jt(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}function ft(...e){const t=new Uint8Array(e.reduce((r,i)=>r+i.length,0));let n=0;return e.forEach(r=>{if(!jt(r))throw new Error("Uint8Array expected");t.set(r,n),n+=r.length}),t}class er{clone(){return this._cloneInto()}}function tr(e){const t=r=>e().update(Xe(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function nr(e=32){if(qt&&typeof qt.getRandomValues=="function")return qt.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}function Vt(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function bs(e){if(typeof e!="boolean")throw new Error(`Expected boolean, not ${e}`)}function rr(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function vs(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Vt(e.outputLen),Vt(e.blockLen)}function ms(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Es(e,t){rr(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}const ae={number:Vt,bool:bs,bytes:rr,hash:vs,exists:ms,output:Es};function xs(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),c=Number(n&s),a=r?4:0,f=r?0:4;e.setUint32(t+a,o,r),e.setUint32(t+f,c,r)}class Ns extends er{constructor(t,n,r,i){super(),this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=zt(this.buffer)}update(t){ae.exists(this);const{view:n,buffer:r,blockLen:i}=this;t=Xe(t);const s=t.length;for(let o=0;o<s;){const c=Math.min(i-this.pos,s-o);if(c===i){const a=zt(t);for(;i<=s-o;o+=i)this.process(a,o);continue}r.set(t.subarray(o,o+c),this.pos),this.pos+=c,o+=c,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){ae.exists(this),ae.output(t,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(r,0),o=0);for(let u=o;u<i;u++)n[u]=0;xs(r,i-8,BigInt(this.length*8),s),this.process(r,0);const c=zt(t),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const f=a/4,l=this.get();if(f>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<f;u++)c.setUint32(4*u,l[u],s)}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:c}=this;return t.length=i,t.pos=c,t.finished=s,t.destroyed=o,i%n&&t.buffer.set(r),t}}const Ks=(e,t,n)=>e&t^~e&n,Ss=(e,t,n)=>e&t^e&n^t&n,As=new Uint32Array([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]),Ee=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),xe=new Uint32Array(64);class ir extends Ns{constructor(){super(64,32,8,!1),this.A=Ee[0]|0,this.B=Ee[1]|0,this.C=Ee[2]|0,this.D=Ee[3]|0,this.E=Ee[4]|0,this.F=Ee[5]|0,this.G=Ee[6]|0,this.H=Ee[7]|0}get(){const{A:t,B:n,C:r,D:i,E:s,F:o,G:c,H:a}=this;return[t,n,r,i,s,o,c,a]}set(t,n,r,i,s,o,c,a){this.A=t|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=c|0,this.H=a|0}process(t,n){for(let u=0;u<16;u++,n+=4)xe[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const p=xe[u-15],w=xe[u-2],g=oe(p,7)^oe(p,18)^p>>>3,h=oe(w,17)^oe(w,19)^w>>>10;xe[u]=h+xe[u-7]+g+xe[u-16]|0}let{A:r,B:i,C:s,D:o,E:c,F:a,G:f,H:l}=this;for(let u=0;u<64;u++){const p=oe(c,6)^oe(c,11)^oe(c,25),w=l+p+Ks(c,a,f)+As[u]+xe[u]|0,h=(oe(r,2)^oe(r,13)^oe(r,22))+Ss(r,i,s)|0;l=f,f=a,a=c,c=o+w|0,o=s,s=i,i=r,r=w+h|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,c=c+this.E|0,a=a+this.F|0,f=f+this.G|0,l=l+this.H|0,this.set(r,i,s,o,c,a,f,l)}roundClean(){xe.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}class Cs extends ir{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}}const le=tr(()=>new ir);tr(()=>new Cs);/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function He(e){if(!Number.isSafeInteger(e))throw new Error(`Wrong integer: ${e}`)}function he(...e){const t=(i,s)=>o=>i(s(o)),n=Array.from(e).reverse().reduce((i,s)=>i?t(i,s.encode):s.encode,void 0),r=e.reduce((i,s)=>i?t(i,s.decode):s.decode,void 0);return{encode:n,decode:r}}function de(e){return{encode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return t.map(n=>{if(He(n),n<0||n>=e.length)throw new Error(`Digit index outside alphabet: ${n} (alphabet: ${e.length})`);return e[n]})},decode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="string")throw new Error("alphabet.decode input should be array of strings");return t.map(n=>{if(typeof n!="string")throw new Error(`alphabet.decode: not string element=${n}`);const r=e.indexOf(n);if(r===-1)throw new Error(`Unknown letter: "${n}". Allowed: ${e}`);return r})}}}function pe(e=""){if(typeof e!="string")throw new Error("join separator should be string");return{encode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="string")throw new Error("join.encode input should be array of strings");for(let n of t)if(typeof n!="string")throw new Error(`join.encode: non-string input=${n}`);return t.join(e)},decode:t=>{if(typeof t!="string")throw new Error("join.decode input should be string");return t.split(e)}}}function lt(e,t="="){if(He(e),typeof t!="string")throw new Error("padding chr should be string");return{encode(n){if(!Array.isArray(n)||n.length&&typeof n[0]!="string")throw new Error("padding.encode input should be array of strings");for(let r of n)if(typeof r!="string")throw new Error(`padding.encode: non-string input=${r}`);for(;n.length*e%8;)n.push(t);return n},decode(n){if(!Array.isArray(n)||n.length&&typeof n[0]!="string")throw new Error("padding.encode input should be array of strings");for(let i of n)if(typeof i!="string")throw new Error(`padding.decode: non-string input=${i}`);let r=n.length;if(r*e%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;r>0&&n[r-1]===t;r--)if(!((r-1)*e%8))throw new Error("Invalid padding: string has too much padding");return n.slice(0,r)}}}function sr(e){if(typeof e!="function")throw new Error("normalize fn should be function");return{encode:t=>t,decode:t=>e(t)}}function or(e,t,n){if(t<2)throw new Error(`convertRadix: wrong from=${t}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: wrong to=${n}, base cannot be less than 2`);if(!Array.isArray(e))throw new Error("convertRadix: data should be array");if(!e.length)return[];let r=0;const i=[],s=Array.from(e);for(s.forEach(o=>{if(He(o),o<0||o>=t)throw new Error(`Wrong integer: ${o}`)});;){let o=0,c=!0;for(let a=r;a<s.length;a++){const f=s[a],l=t*o+f;if(!Number.isSafeInteger(l)||t*o/t!==o||l-f!==t*o)throw new Error("convertRadix: carry overflow");if(o=l%n,s[a]=Math.floor(l/n),!Number.isSafeInteger(s[a])||s[a]*n+o!==l)throw new Error("convertRadix: carry overflow");if(c)s[a]?c=!1:r=a;else continue}if(i.push(o),c)break}for(let o=0;o<e.length-1&&e[o]===0;o++)i.push(0);return i.reverse()}const ar=(e,t)=>t?ar(t,e%t):e,ht=(e,t)=>e+(t-ar(e,t));function Wt(e,t,n,r){if(!Array.isArray(e))throw new Error("convertRadix2: data should be array");if(t<=0||t>32)throw new Error(`convertRadix2: wrong from=${t}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(ht(t,n)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${ht(t,n)}`);let i=0,s=0;const o=2**n-1,c=[];for(const a of e){if(He(a),a>=2**t)throw new Error(`convertRadix2: invalid data word=${a} from=${t}`);if(i=i<<t|a,s+t>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${t}`);for(s+=t;s>=n;s-=n)c.push((i>>s-n&o)>>>0);i&=2**s-1}if(i=i<<n-s&o,!r&&s>=t)throw new Error("Excess padding");if(!r&&i)throw new Error(`Non-zero padding: ${i}`);return r&&s>0&&c.push(i>>>0),c}function Is(e){return He(e),{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return or(Array.from(t),2**8,e)},decode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="number")throw new Error("radix.decode input should be array of strings");return Uint8Array.from(or(t,e,2**8))}}}function Ne(e,t=!1){if(He(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(ht(8,e)>32||ht(e,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!(n instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return Wt(Array.from(n),8,e,!t)},decode:n=>{if(!Array.isArray(n)||n.length&&typeof n[0]!="number")throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(Wt(n,e,8,t))}}}function cr(e){if(typeof e!="function")throw new Error("unsafeWrapper fn should be function");return function(...t){try{return e.apply(null,t)}catch{}}}const Bs=he(Ne(4),de("0123456789ABCDEF"),pe("")),ks=he(Ne(5),de("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),lt(5),pe(""));he(Ne(5),de("0123456789ABCDEFGHIJKLMNOPQRSTUV"),lt(5),pe("")),he(Ne(5),de("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),pe(""),sr(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")));const ye=he(Ne(6),de("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),lt(6),pe("")),_s=he(Ne(6),de("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),lt(6),pe("")),Zt=e=>he(Is(58),de(e),pe("")),Gt=Zt("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");Zt("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),Zt("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const ur=[0,2,3,5,6,7,9,10,11],Us={encode(e){let t="";for(let n=0;n<e.length;n+=8){const r=e.subarray(n,n+8);t+=Gt.encode(r).padStart(ur[r.length],"1")}return t},decode(e){let t=[];for(let n=0;n<e.length;n+=11){const r=e.slice(n,n+11),i=ur.indexOf(r.length),s=Gt.decode(r);for(let o=0;o<s.length-i;o++)if(s[o]!==0)throw new Error("base58xmr: wrong padding");t=t.concat(Array.from(s.slice(s.length-i)))}return Uint8Array.from(t)}},Ft=he(de("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),pe("")),fr=[996825010,642813549,513874426,1027748829,705979059];function Qe(e){const t=e>>25;let n=(e&33554431)<<5;for(let r=0;r<fr.length;r++)(t>>r&1)===1&&(n^=fr[r]);return n}function lr(e,t,n=1){const r=e.length;let i=1;for(let s=0;s<r;s++){const o=e.charCodeAt(s);if(o<33||o>126)throw new Error(`Invalid prefix (${e})`);i=Qe(i)^o>>5}i=Qe(i);for(let s=0;s<r;s++)i=Qe(i)^e.charCodeAt(s)&31;for(let s of t)i=Qe(i)^s;for(let s=0;s<6;s++)i=Qe(i);return i^=n,Ft.encode(Wt([i%2**30],30,5,!1))}function hr(e){const t=e==="bech32"?1:734539939,n=Ne(5),r=n.decode,i=n.encode,s=cr(r);function o(l,u,p=90){if(typeof l!="string")throw new Error(`bech32.encode prefix should be string, not ${typeof l}`);if(!Array.isArray(u)||u.length&&typeof u[0]!="number")throw new Error(`bech32.encode words should be array of numbers, not ${typeof u}`);const w=l.length+7+u.length;if(p!==!1&&w>p)throw new TypeError(`Length ${w} exceeds limit ${p}`);return l=l.toLowerCase(),`${l}1${Ft.encode(u)}${lr(l,u,t)}`}function c(l,u=90){if(typeof l!="string")throw new Error(`bech32.decode input should be string, not ${typeof l}`);if(l.length<8||u!==!1&&l.length>u)throw new TypeError(`Wrong string length: ${l.length} (${l}). Expected (8..${u})`);const p=l.toLowerCase();if(l!==p&&l!==l.toUpperCase())throw new Error("String must be lowercase or uppercase");l=p;const w=l.lastIndexOf("1");if(w===0||w===-1)throw new Error('Letter "1" must be present between prefix and data only');const g=l.slice(0,w),h=l.slice(w+1);if(h.length<6)throw new Error("Data must be at least 6 characters long");const d=Ft.decode(h).slice(0,-6),y=lr(g,d,t);if(!h.endsWith(y))throw new Error(`Invalid checksum in ${l}: expected "${y}"`);return{prefix:g,words:d}}const a=cr(c);function f(l){const{prefix:u,words:p}=c(l,!1);return{prefix:u,words:p,bytes:r(p)}}return{encode:o,decode:c,decodeToBytes:f,decodeUnsafe:a,fromWords:r,fromWordsUnsafe:s,toWords:i}}const De=hr("bech32");hr("bech32m");const Ls={encode:e=>new TextDecoder().decode(e),decode:e=>new TextEncoder().encode(e)},$s=he(Ne(4),de("0123456789abcdef"),pe(""),sr(e=>{if(typeof e!="string"||e.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()}));`${Object.keys({utf8:Ls,hex:$s,base16:Bs,base32:ks,base64:ye,base64url:_s,base58:Gt,base58xmr:Us}).join(", ")}`;function Jt(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function dr(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}function Ts(e){return e instanceof Uint8Array||e!=null&&typeof e=="object"&&e.constructor.name==="Uint8Array"}function ge(e,...t){if(!Ts(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */const F=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");function Rs(e,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(e,t)}function Os(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}const Ms=(e,t)=>(Object.assign(t,e),t),Ke=16,Ps=283;function Yt(e){return e<<1^Ps&-(e>>7)}function qe(e,t){let n=0;for(;t>0;t>>=1)n^=e&-(t&1),e=Yt(e);return n}const Xt=(()=>{let e=new Uint8Array(256);for(let n=0,r=1;n<256;n++,r^=Yt(r))e[n]=r;const t=new Uint8Array(256);t[0]=99;for(let n=0;n<255;n++){let r=e[255-n];r|=r<<8,t[e[n]]=(r^r>>4^r>>5^r>>6^r>>7^99)&255}return t})(),Hs=Xt.map((e,t)=>Xt.indexOf(t)),Ds=e=>e<<24|e>>>8,Qt=e=>e<<8|e>>>24;function pr(e,t){if(e.length!==256)throw new Error("Wrong sbox length");const n=new Uint32Array(256).map((f,l)=>t(e[l])),r=n.map(Qt),i=r.map(Qt),s=i.map(Qt),o=new Uint32Array(256*256),c=new Uint32Array(256*256),a=new Uint16Array(256*256);for(let f=0;f<256;f++)for(let l=0;l<256;l++){const u=f*256+l;o[u]=n[f]^r[l],c[u]=i[f]^s[l],a[u]=e[f]<<8|e[l]}return{sbox:e,sbox2:a,T0:n,T1:r,T2:i,T3:s,T01:o,T23:c}}const en=pr(Xt,e=>qe(e,3)<<24|e<<16|e<<8|qe(e,2)),yr=pr(Hs,e=>qe(e,11)<<24|qe(e,13)<<16|qe(e,9)<<8|qe(e,14)),qs=(()=>{const e=new Uint8Array(16);for(let t=0,n=1;t<16;t++,n=Yt(n))e[t]=n;return e})();function gr(e){ge(e);const t=e.length;if(![16,24,32].includes(t))throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${t}`);const{sbox2:n}=en,r=F(e),i=r.length,s=c=>ce(n,c,c,c,c),o=new Uint32Array(t+28);o.set(r);for(let c=i;c<o.length;c++){let a=o[c-1];c%i===0?a=s(Ds(a))^qs[c/i-1]:i>6&&c%i===4&&(a=s(a)),o[c]=o[c-i]^a}return o}function js(e){const t=gr(e),n=t.slice(),r=t.length,{sbox2:i}=en,{T0:s,T1:o,T2:c,T3:a}=yr;for(let f=0;f<r;f+=4)for(let l=0;l<4;l++)n[f+l]=t[r-f-4+l];t.fill(0);for(let f=4;f<r-4;f++){const l=n[f],u=ce(i,l,l,l,l);n[f]=s[u&255]^o[u>>>8&255]^c[u>>>16&255]^a[u>>>24]}return n}function Se(e,t,n,r,i,s){return e[n<<8&65280|r>>>8&255]^t[i>>>8&65280|s>>>24&255]}function ce(e,t,n,r,i){return e[t&255|n&65280]|e[r>>>16&255|i>>>16&65280]<<16}function wr(e,t,n,r,i){const{sbox2:s,T01:o,T23:c}=en;let a=0;t^=e[a++],n^=e[a++],r^=e[a++],i^=e[a++];const f=e.length/4-2;for(let g=0;g<f;g++){const h=e[a++]^Se(o,c,t,n,r,i),d=e[a++]^Se(o,c,n,r,i,t),y=e[a++]^Se(o,c,r,i,t,n),E=e[a++]^Se(o,c,i,t,n,r);t=h,n=d,r=y,i=E}const l=e[a++]^ce(s,t,n,r,i),u=e[a++]^ce(s,n,r,i,t),p=e[a++]^ce(s,r,i,t,n),w=e[a++]^ce(s,i,t,n,r);return{s0:l,s1:u,s2:p,s3:w}}function zs(e,t,n,r,i){const{sbox2:s,T01:o,T23:c}=yr;let a=0;t^=e[a++],n^=e[a++],r^=e[a++],i^=e[a++];const f=e.length/4-2;for(let g=0;g<f;g++){const h=e[a++]^Se(o,c,t,i,r,n),d=e[a++]^Se(o,c,n,t,i,r),y=e[a++]^Se(o,c,r,n,t,i),E=e[a++]^Se(o,c,i,r,n,t);t=h,n=d,r=y,i=E}const l=e[a++]^ce(s,t,i,r,n),u=e[a++]^ce(s,n,t,i,r),p=e[a++]^ce(s,r,n,t,i),w=e[a++]^ce(s,i,r,n,t);return{s0:l,s1:u,s2:p,s3:w}}function br(e,t){if(!t)return new Uint8Array(e);if(ge(t),t.length<e)throw new Error(`aes: wrong destination length, expected at least ${e}, got: ${t.length}`);return t}function Vs(e){if(ge(e),e.length%Ke!==0)throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${Ke}`)}function Ws(e,t,n){let r=e.length;const i=r%Ke;if(!t&&i!==0)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");const s=F(e);if(t){let a=Ke-i;a||(a=Ke),r=r+a}const o=br(r,n),c=F(o);return{b:s,o:c,out:o}}function Zs(e,t){if(!t)return e;const n=e.length;if(!n)throw new Error("aes/pcks5: empty ciphertext not allowed");const r=e[n-1];if(r<=0||r>16)throw new Error(`aes/pcks5: wrong padding byte: ${r}`);const i=e.subarray(0,-r);for(let s=0;s<r;s++)if(e[n-s-1]!==r)throw new Error("aes/pcks5: wrong padding");return i}function Gs(e){const t=new Uint8Array(16),n=F(t);t.set(e);const r=Ke-e.length;for(let i=Ke-r;i<Ke;i++)t[i]=r;return n}const vr=Ms({blockSize:16,nonceLength:16},function(t,n,r={}){ge(t),ge(n,16);const i=!r.disablePadding;return{encrypt:(s,o)=>{const c=gr(t),{b:a,o:f,out:l}=Ws(s,i,o),u=F(n);let p=u[0],w=u[1],g=u[2],h=u[3],d=0;for(;d+4<=a.length;)p^=a[d+0],w^=a[d+1],g^=a[d+2],h^=a[d+3],{s0:p,s1:w,s2:g,s3:h}=wr(c,p,w,g,h),f[d++]=p,f[d++]=w,f[d++]=g,f[d++]=h;if(i){const y=Gs(s.subarray(d*4));p^=y[0],w^=y[1],g^=y[2],h^=y[3],{s0:p,s1:w,s2:g,s3:h}=wr(c,p,w,g,h),f[d++]=p,f[d++]=w,f[d++]=g,f[d++]=h}return c.fill(0),l},decrypt:(s,o)=>{Vs(s);const c=js(t),a=F(n),f=br(s.length,o),l=F(s),u=F(f);let p=a[0],w=a[1],g=a[2],h=a[3];for(let d=0;d+4<=l.length;){const y=p,E=w,S=g,_=h;p=l[d+0],w=l[d+1],g=l[d+2],h=l[d+3];const{s0:I,s1:m,s2:x,s3:N}=zs(c,p,w,g,h);u[d++]=I^y,u[d++]=m^E,u[d++]=x^S,u[d++]=N^_}return c.fill(0),Zs(f,i)}}}),mr=e=>Uint8Array.from(e.split("").map(t=>t.charCodeAt(0))),Fs=mr("expand 16-byte k"),Js=mr("expand 32-byte k"),Ys=F(Fs),Er=F(Js);Er.slice();function U(e,t){return e<<t|e>>>32-t}function tn(e){return e.byteOffset%4===0}const dt=64,Xs=16,xr=2**32-1,Nr=new Uint32Array;function Qs(e,t,n,r,i,s,o,c){const a=i.length,f=new Uint8Array(dt),l=F(f),u=tn(i)&&tn(s),p=u?F(i):Nr,w=u?F(s):Nr;for(let g=0;g<a;o++){if(e(t,n,r,l,o,c),o>=xr)throw new Error("arx: counter overflow");const h=Math.min(dt,a-g);if(u&&h===dt){const d=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let y=0,E;y<Xs;y++)E=d+y,w[E]=p[E]^l[y];g+=dt;continue}for(let d=0,y;d<h;d++)y=g+d,s[y]=i[y]^f[d];g+=h}}function eo(e,t){const{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:s,rounds:o}=Rs({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!="function")throw new Error("core must be a function");return Jt(i),Jt(o),dr(s),dr(n),(c,a,f,l,u=0)=>{ge(c),ge(a),ge(f);const p=f.length;if(l||(l=new Uint8Array(p)),ge(l),Jt(u),u<0||u>=xr)throw new Error("arx: counter overflow");if(l.length<p)throw new Error(`arx: output (${l.length}) is shorter than data (${p})`);const w=[];let g=c.length,h,d;if(g===32)h=c.slice(),w.push(h),d=Er;else if(g===16&&n)h=new Uint8Array(32),h.set(c),h.set(c,16),d=Ys,w.push(h);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);tn(a)||(a=a.slice(),w.push(a));const y=F(h);if(r){if(a.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(d,y,F(a.subarray(0,16)),y),a=a.subarray(16)}const E=16-i;if(E!==a.length)throw new Error(`arx: nonce must be ${E} or 16 bytes`);if(E!==12){const _=new Uint8Array(12);_.set(a,s?0:12-a.length),a=_,w.push(a)}const S=F(a);for(Qs(e,d,y,S,f,l,u,o);w.length>0;)w.pop().fill(0);return l}}function to(e,t,n,r,i,s=20){let o=e[0],c=e[1],a=e[2],f=e[3],l=t[0],u=t[1],p=t[2],w=t[3],g=t[4],h=t[5],d=t[6],y=t[7],E=i,S=n[0],_=n[1],I=n[2],m=o,x=c,N=a,M=f,k=l,A=u,T=p,R=w,j=g,b=h,v=d,K=y,B=E,C=S,L=_,O=I;for(let re=0;re<s;re+=2)m=m+k|0,B=U(B^m,16),j=j+B|0,k=U(k^j,12),m=m+k|0,B=U(B^m,8),j=j+B|0,k=U(k^j,7),x=x+A|0,C=U(C^x,16),b=b+C|0,A=U(A^b,12),x=x+A|0,C=U(C^x,8),b=b+C|0,A=U(A^b,7),N=N+T|0,L=U(L^N,16),v=v+L|0,T=U(T^v,12),N=N+T|0,L=U(L^N,8),v=v+L|0,T=U(T^v,7),M=M+R|0,O=U(O^M,16),K=K+O|0,R=U(R^K,12),M=M+R|0,O=U(O^M,8),K=K+O|0,R=U(R^K,7),m=m+A|0,O=U(O^m,16),v=v+O|0,A=U(A^v,12),m=m+A|0,O=U(O^m,8),v=v+O|0,A=U(A^v,7),x=x+T|0,B=U(B^x,16),K=K+B|0,T=U(T^K,12),x=x+T|0,B=U(B^x,8),K=K+B|0,T=U(T^K,7),N=N+R|0,C=U(C^N,16),j=j+C|0,R=U(R^j,12),N=N+R|0,C=U(C^N,8),j=j+C|0,R=U(R^j,7),M=M+k|0,L=U(L^M,16),b=b+L|0,k=U(k^b,12),M=M+k|0,L=U(L^M,8),b=b+L|0,k=U(k^b,7);let $=0;r[$++]=o+m|0,r[$++]=c+x|0,r[$++]=a+N|0,r[$++]=f+M|0,r[$++]=l+k|0,r[$++]=u+A|0,r[$++]=p+T|0,r[$++]=w+R|0,r[$++]=g+j|0,r[$++]=h+b|0,r[$++]=d+v|0,r[$++]=y+K|0,r[$++]=E+B|0,r[$++]=S+C|0,r[$++]=_+L|0,r[$++]=I+O|0}const Kr=eo(to,{counterRight:!1,counterLength:4,allowShortKeys:!1});class Sr extends er{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,ae.hash(t);const r=Xe(n);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?t.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=t.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),s.fill(0)}update(t){return ae.exists(this),this.iHash.update(t),this}digestInto(t){ae.exists(this),ae.bytes(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:c}=this;return t=t,t.finished=i,t.destroyed=s,t.blockLen=o,t.outputLen=c,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const pt=(e,t,n)=>new Sr(e,t).update(n).digest();pt.create=(e,t)=>new Sr(e,t);function nn(e,t,n){return ae.hash(e),n===void 0&&(n=new Uint8Array(e.outputLen)),pt(e,Xe(n),Xe(t))}const rn=new Uint8Array([0]),Ar=new Uint8Array;function Cr(e,t,n,r=32){if(ae.hash(e),ae.number(r),r>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(r/e.outputLen);n===void 0&&(n=Ar);const s=new Uint8Array(i*e.outputLen),o=pt.create(e,t),c=o._cloneInto(),a=new Uint8Array(o.outputLen);for(let f=0;f<i;f++)rn[0]=f+1,c.update(f===0?Ar:a).update(n).update(rn).digestInto(a),s.set(a,e.outputLen*f),o._cloneInto(c);return o.destroy(),c.destroy(),a.fill(0),rn.fill(0),s.slice(0,r)}var no=Object.defineProperty,D=(e,t)=>{for(var n in t)no(e,n,{get:t[n],enumerable:!0})},je=Symbol("verified"),ro=e=>e instanceof Object;function yt(e){if(!ro(e)||typeof e.kind!="number"||typeof e.content!="string"||typeof e.created_at!="number"||typeof e.pubkey!="string"||!e.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(e.tags))return!1;for(let t=0;t<e.tags.length;t++){let n=e.tags[t];if(!Array.isArray(n))return!1;for(let r=0;r<n.length;r++)if(typeof n[r]!="string")return!1}return!0}var io={};D(io,{Queue:()=>co,QueueNode:()=>Ir,binarySearch:()=>sn,bytesToHex:()=>H,hexToBytes:()=>V,insertEventIntoAscendingList:()=>ao,insertEventIntoDescendingList:()=>oo,normalizeURL:()=>so,utf8Decoder:()=>we,utf8Encoder:()=>ne});var we=new TextDecoder("utf-8"),ne=new TextEncoder;function so(e){try{e.indexOf("://")===-1&&(e="wss://"+e);let t=new URL(e);return t.pathname=t.pathname.replace(/\/+/g,"/"),t.pathname.endsWith("/")&&(t.pathname=t.pathname.slice(0,-1)),(t.port==="80"&&t.protocol==="ws:"||t.port==="443"&&t.protocol==="wss:")&&(t.port=""),t.searchParams.sort(),t.hash="",t.toString()}catch{throw new Error(`Invalid URL: ${e}`)}}function oo(e,t){const[n,r]=sn(e,i=>t.id===i.id?0:t.created_at===i.created_at?-1:i.created_at-t.created_at);return r||e.splice(n,0,t),e}function ao(e,t){const[n,r]=sn(e,i=>t.id===i.id?0:t.created_at===i.created_at?-1:t.created_at-i.created_at);return r||e.splice(n,0,t),e}function sn(e,t){let n=0,r=e.length-1;for(;n<=r;){const i=Math.floor((n+r)/2),s=t(e[i]);if(s===0)return[i,!0];s<0?r=i-1:n=i+1}return[n,!1]}var Ir=class{constructor(e){te(this,"value");te(this,"next",null);te(this,"prev",null);this.value=e}},co=class{constructor(){te(this,"first");te(this,"last");this.first=null,this.last=null}enqueue(e){const t=new Ir(e);return this.last?this.last===this.first?(this.last=t,this.last.prev=this.first,this.first.next=t):(t.prev=this.last,this.last.next=t,this.last=t):(this.first=t,this.last=t),!0}dequeue(){if(!this.first)return null;if(this.first===this.last){const t=this.first;return this.first=null,this.last=null,t.value}const e=this.first;return this.first=e.next,this.first&&(this.first.prev=null),e.value}},uo=class{generateSecretKey(){return Ye.utils.randomPrivateKey()}getPublicKey(e){return H(Ye.getPublicKey(e))}finalizeEvent(e,t){const n=e;return n.pubkey=H(Ye.getPublicKey(t)),n.id=ze(n),n.sig=H(Ye.sign(ze(n),t)),n[je]=!0,n}verifyEvent(e){if(typeof e[je]=="boolean")return e[je];const t=ze(e);if(t!==e.id)return e[je]=!1,!1;try{const n=Ye.verify(e.sig,t,e.pubkey);return e[je]=n,n}catch{return e[je]=!1,!1}}};function fo(e){if(!yt(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function ze(e){let t=le(ne.encode(fo(e)));return H(t)}var gt=new uo,Le=gt.generateSecretKey,ue=gt.getPublicKey,ee=gt.finalizeEvent,wt=gt.verifyEvent,lo={};D(lo,{Application:()=>la,BadgeAward:()=>mo,BadgeDefinition:()=>ia,BlockedRelaysList:()=>qo,BookmarkList:()=>Po,Bookmarksets:()=>ta,Calendar:()=>ba,CalendarEventRSVP:()=>va,ChannelCreation:()=>$r,ChannelHideMessage:()=>Or,ChannelMessage:()=>Rr,ChannelMetadata:()=>Tr,ChannelMuteUser:()=>Mr,ClassifiedListing:()=>pa,ClientAuth:()=>Hr,CommunitiesList:()=>Ho,CommunityDefinition:()=>xa,CommunityPostApproval:()=>Io,Contacts:()=>wo,CreateOrUpdateProduct:()=>aa,CreateOrUpdateStall:()=>oa,Curationsets:()=>na,Date:()=>ga,DirectMessageRelaysList:()=>Wo,DraftClassifiedListing:()=>ya,DraftLong:()=>ua,Emojisets:()=>fa,EncryptedDirectMessage:()=>bo,EventDeletion:()=>vo,FileMetadata:()=>xo,FileServerPreference:()=>Zo,Followsets:()=>Xo,GenericRepost:()=>fn,Genericlists:()=>Qo,GiftWrap:()=>Pr,HTTPAuth:()=>ln,Handlerinformation:()=>Ea,Handlerrecommendation:()=>ma,Highlights:()=>To,InterestsList:()=>zo,Interestsets:()=>sa,JobFeedback:()=>_o,JobRequest:()=>Bo,JobResult:()=>ko,Label:()=>Co,LightningPubRPC:()=>Fo,LiveChatMessage:()=>No,LiveEvent:()=>ha,LongFormArticle:()=>ca,Metadata:()=>yo,Mutelist:()=>Ro,NWCWalletInfo:()=>Go,NWCWalletRequest:()=>Dr,NWCWalletResponse:()=>Jo,NostrConnect:()=>Yo,OpenTimestamps:()=>Eo,Pinlist:()=>Oo,PrivateDirectMessage:()=>Lr,ProblemTracker:()=>Ko,ProfileBadges:()=>ra,PublicChatsList:()=>Do,Reaction:()=>un,RecommendRelay:()=>go,RelayList:()=>Mo,Relaysets:()=>ea,Report:()=>So,Reporting:()=>Ao,Repost:()=>cn,Seal:()=>Ur,SearchRelaysList:()=>jo,ShortTextNote:()=>_r,Time:()=>wa,UserEmojiList:()=>Vo,UserStatuses:()=>da,Zap:()=>$o,ZapGoal:()=>Uo,ZapRequest:()=>Lo,classifyKind:()=>ho,isAddressableKind:()=>an,isEphemeralKind:()=>kr,isKind:()=>po,isRegularKind:()=>Br,isReplaceableKind:()=>on});function Br(e){return 1e3<=e&&e<1e4||[1,2,4,5,6,7,8,16,40,41,42,43,44].includes(e)}function on(e){return[0,3].includes(e)||1e4<=e&&e<2e4}function kr(e){return 2e4<=e&&e<3e4}function an(e){return 3e4<=e&&e<4e4}function ho(e){return Br(e)?"regular":on(e)?"replaceable":kr(e)?"ephemeral":an(e)?"parameterized":"unknown"}function po(e,t){const n=t instanceof Array?t:[t];return yt(e)&&n.includes(e.kind)||!1}var yo=0,_r=1,go=2,wo=3,bo=4,vo=5,cn=6,un=7,mo=8,Ur=13,Lr=14,fn=16,$r=40,Tr=41,Rr=42,Or=43,Mr=44,Eo=1040,Pr=1059,xo=1063,No=1311,Ko=1971,So=1984,Ao=1984,Co=1985,Io=4550,Bo=5999,ko=6999,_o=7e3,Uo=9041,Lo=9734,$o=9735,To=9802,Ro=1e4,Oo=10001,Mo=10002,Po=10003,Ho=10004,Do=10005,qo=10006,jo=10007,zo=10015,Vo=10030,Wo=10050,Zo=10096,Go=13194,Fo=21e3,Hr=22242,Dr=23194,Jo=23195,Yo=24133,ln=27235,Xo=3e4,Qo=30001,ea=30002,ta=30003,na=30004,ra=30008,ia=30009,sa=30015,oa=30017,aa=30018,ca=30023,ua=30024,fa=30030,la=30078,ha=30311,da=30315,pa=30402,ya=30403,ga=31922,wa=31923,ba=31924,va=31925,ma=31989,Ea=31990,xa=34550,Na={};D(Na,{getHex64:()=>hn,getInt:()=>qr,getSubscriptionId:()=>Ka,matchEventId:()=>Sa,matchEventKind:()=>Ca,matchEventPubkey:()=>Aa});function hn(e,t){let n=t.length+3,r=e.indexOf(`"${t}":`)+n,i=e.slice(r).indexOf('"')+r+1;return e.slice(i,i+64)}function qr(e,t){let n=t.length,r=e.indexOf(`"${t}":`)+n+3,i=e.slice(r),s=Math.min(i.indexOf(","),i.indexOf("}"));return parseInt(i.slice(0,s),10)}function Ka(e){let t=e.slice(0,22).indexOf('"EVENT"');if(t===-1)return null;let n=e.slice(t+7+1).indexOf('"');if(n===-1)return null;let r=t+7+1+n,i=e.slice(r+1,80).indexOf('"');if(i===-1)return null;let s=r+1+i;return e.slice(r+1,s)}function Sa(e,t){return t===hn(e,"id")}function Aa(e,t){return t===hn(e,"pubkey")}function Ca(e,t){return t===qr(e,"kind")}var Ia={};D(Ia,{makeAuthEvent:()=>Ba});function Ba(e,t){return{kind:Hr,created_at:Math.floor(Date.now()/1e3),tags:[["relay",e],["challenge",t]],content:""}}var ka;try{ka=WebSocket}catch{}var _a;try{_a=WebSocket}catch{}var Ua={};D(Ua,{BECH32_REGEX:()=>jr,Bech32MaxSize:()=>dn,NostrTypeGuard:()=>La,decode:()=>bt,decodeNostrURI:()=>Ta,encodeBytes:()=>mt,naddrEncode:()=>Da,neventEncode:()=>Ha,noteEncode:()=>Ma,nprofileEncode:()=>Pa,npubEncode:()=>Oa,nsecEncode:()=>Ra});var La={isNProfile:e=>/^nprofile1[a-z\d]+$/.test(e||""),isNEvent:e=>/^nevent1[a-z\d]+$/.test(e||""),isNAddr:e=>/^naddr1[a-z\d]+$/.test(e||""),isNSec:e=>/^nsec1[a-z\d]{58}$/.test(e||""),isNPub:e=>/^npub1[a-z\d]{58}$/.test(e||""),isNote:e=>/^note1[a-z\d]+$/.test(e||""),isNcryptsec:e=>/^ncryptsec1[a-z\d]+$/.test(e||"")},dn=5e3,jr=/[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;function $a(e){const t=new Uint8Array(4);return t[0]=e>>24&255,t[1]=e>>16&255,t[2]=e>>8&255,t[3]=e&255,t}function Ta(e){try{return e.startsWith("nostr:")&&(e=e.substring(6)),bt(e)}catch{return{type:"invalid",data:null}}}function bt(e){var i,s,o,c,a,f,l;let{prefix:t,words:n}=De.decode(e,dn),r=new Uint8Array(De.fromWords(n));switch(t){case"nprofile":{let u=pn(r);if(!((i=u[0])!=null&&i[0]))throw new Error("missing TLV 0 for nprofile");if(u[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:H(u[0][0]),relays:u[1]?u[1].map(p=>we.decode(p)):[]}}}case"nevent":{let u=pn(r);if(!((s=u[0])!=null&&s[0]))throw new Error("missing TLV 0 for nevent");if(u[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");if(u[2]&&u[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(u[3]&&u[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:H(u[0][0]),relays:u[1]?u[1].map(p=>we.decode(p)):[],author:(o=u[2])!=null&&o[0]?H(u[2][0]):void 0,kind:(c=u[3])!=null&&c[0]?parseInt(H(u[3][0]),16):void 0}}}case"naddr":{let u=pn(r);if(!((a=u[0])!=null&&a[0]))throw new Error("missing TLV 0 for naddr");if(!((f=u[2])!=null&&f[0]))throw new Error("missing TLV 2 for naddr");if(u[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(!((l=u[3])!=null&&l[0]))throw new Error("missing TLV 3 for naddr");if(u[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:we.decode(u[0][0]),pubkey:H(u[2][0]),kind:parseInt(H(u[3][0]),16),relays:u[1]?u[1].map(p=>we.decode(p)):[]}}}case"nsec":return{type:t,data:r};case"npub":case"note":return{type:t,data:H(r)};default:throw new Error(`unknown prefix ${t}`)}}function pn(e){let t={},n=e;for(;n.length>0;){let r=n[0],i=n[1],s=n.slice(2,2+i);if(n=n.slice(2+i),s.length<i)throw new Error(`not enough data to read on TLV ${r}`);t[r]=t[r]||[],t[r].push(s)}return t}function Ra(e){return mt("nsec",e)}function Oa(e){return mt("npub",V(e))}function Ma(e){return mt("note",V(e))}function vt(e,t){let n=De.toWords(t);return De.encode(e,n,dn)}function mt(e,t){return vt(e,t)}function Pa(e){let t=yn({0:[V(e.pubkey)],1:(e.relays||[]).map(n=>ne.encode(n))});return vt("nprofile",t)}function Ha(e){let t;e.kind!==void 0&&(t=$a(e.kind));let n=yn({0:[V(e.id)],1:(e.relays||[]).map(r=>ne.encode(r)),2:e.author?[V(e.author)]:[],3:t?[new Uint8Array(t)]:[]});return vt("nevent",n)}function Da(e){let t=new ArrayBuffer(4);new DataView(t).setUint32(0,e.kind,!1);let n=yn({0:[ne.encode(e.identifier)],1:(e.relays||[]).map(r=>ne.encode(r)),2:[V(e.pubkey)],3:[new Uint8Array(t)]});return vt("naddr",n)}function yn(e){let t=[];return Object.entries(e).reverse().forEach(([n,r])=>{r.forEach(i=>{let s=new Uint8Array(i.length+2);s.set([parseInt(n)],0),s.set([i.length],1),s.set(i,2),t.push(s)})}),ft(...t)}var qa={};D(qa,{decrypt:()=>ja,encrypt:()=>zr});function zr(e,t,n){const r=e instanceof Uint8Array?H(e):e,i=Ue.getSharedSecret(r,"02"+t),s=Vr(i);let o=Uint8Array.from(nr(16)),c=ne.encode(n),a=vr(s,o).encrypt(c),f=ye.encode(new Uint8Array(a)),l=ye.encode(new Uint8Array(o.buffer));return`${f}?iv=${l}`}function ja(e,t,n){const r=e instanceof Uint8Array?H(e):e;let[i,s]=n.split("?iv="),o=Ue.getSharedSecret(r,"02"+t),c=Vr(o),a=ye.decode(s),f=ye.decode(i),l=vr(c,a).decrypt(f);return we.decode(l)}function Vr(e){return e.slice(1,33)}var za={};D(za,{NIP05_REGEX:()=>gn,isNip05:()=>Va,isValid:()=>Ga,queryProfile:()=>Wr,searchDomain:()=>Za,useFetchImplementation:()=>Wa});var gn=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,Va=e=>gn.test(e||""),Et;try{Et=fetch}catch{}function Wa(e){Et=e}async function Za(e,t=""){try{const n=`https://${e}/.well-known/nostr.json?name=${t}`,r=await Et(n,{redirect:"manual"});if(r.status!==200)throw Error("Wrong response code");return(await r.json()).names}catch{return{}}}async function Wr(e){var i;const t=e.match(gn);if(!t)return null;const[,n="_",r]=t;try{const s=`https://${r}/.well-known/nostr.json?name=${n}`,o=await Et(s,{redirect:"manual"});if(o.status!==200)throw Error("Wrong response code");const c=await o.json(),a=c.names[n];return a?{pubkey:a,relays:(i=c.relays)==null?void 0:i[a]}:null}catch{return null}}async function Ga(e,t){const n=await Wr(t);return n?n.pubkey===e:!1}var Fa={};D(Fa,{parse:()=>Ja});function Ja(e){const t={reply:void 0,root:void 0,mentions:[],profiles:[],quotes:[]};let n,r;for(let i=e.tags.length-1;i>=0;i--){const s=e.tags[i];if(s[0]==="e"&&s[1]){const[o,c,a,f,l]=s,u={id:c,relays:a?[a]:[],author:l};if(f==="root"){t.root=u;continue}if(f==="reply"){t.reply=u;continue}if(f==="mention"){t.mentions.push(u);continue}n?r=u:n=u,t.mentions.push(u);continue}if(s[0]==="q"&&s[1]){const[o,c,a]=s;t.quotes.push({id:c,relays:a?[a]:[]})}if(s[0]==="p"&&s[1]){t.profiles.push({pubkey:s[1],relays:s[2]?[s[2]]:[]});continue}}return t.root||(t.root=r||n||t.reply),t.reply||(t.reply=n||t.root),[t.reply,t.root].forEach(i=>{if(!i)return;let s=t.mentions.indexOf(i);if(s!==-1&&t.mentions.splice(s,1),i.author){let o=t.profiles.find(c=>c.pubkey===i.author);o&&o.relays&&(i.relays||(i.relays=[]),o.relays.forEach(c=>{var a;((a=i.relays)==null?void 0:a.indexOf(c))===-1&&i.relays.push(c)}),o.relays=i.relays)}}),t.mentions.forEach(i=>{if(i.author){let s=t.profiles.find(o=>o.pubkey===i.author);s&&s.relays&&(i.relays||(i.relays=[]),s.relays.forEach(o=>{i.relays.indexOf(o)===-1&&i.relays.push(o)}),s.relays=i.relays)}}),t}var Ya={};D(Ya,{fetchRelayInformation:()=>Qa,useFetchImplementation:()=>Xa});var Zr;try{Zr=fetch}catch{}function Xa(e){Zr=e}async function Qa(e){return await(await fetch(e.replace("ws://","http://").replace("wss://","https://"),{headers:{Accept:"application/nostr+json"}})).json()}var ec={};D(ec,{fastEventHash:()=>Fr,getPow:()=>Gr,minePow:()=>tc});function Gr(e){let t=0;for(let n=0;n<64;n+=8){const r=parseInt(e.substring(n,n+8),16);if(r===0)t+=32;else{t+=Math.clz32(r);break}}return t}function tc(e,t){let n=0;const r=e,i=["nonce",n.toString(),t.toString()];for(r.tags.push(i);;){const s=Math.floor(new Date().getTime()/1e3);if(s!==r.created_at&&(n=0,r.created_at=s),i[1]=(++n).toString(),r.id=Fr(r),Gr(r.id)>=t)break}return r}function Fr(e){return H(le(ne.encode(JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content]))))}var nc={};D(nc,{unwrapEvent:()=>dc,unwrapManyEvents:()=>pc,wrapEvent:()=>ui,wrapManyEvents:()=>hc});var rc={};D(rc,{createRumor:()=>si,createSeal:()=>oi,createWrap:()=>ai,unwrapEvent:()=>En,unwrapManyEvents:()=>ci,wrapEvent:()=>xt,wrapManyEvents:()=>fc});var q={};D(q,{decrypt:()=>mn,encrypt:()=>vn,getConversationKey:()=>wn,v2:()=>cc});var Jr=1,Yr=65535;function wn(e,t){const n=Ue.getSharedSecret(e,"02"+t).subarray(1,33);return nn(le,n,"nip44-v2")}function Xr(e,t){const n=Cr(le,e,t,76);return{chacha_key:n.subarray(0,32),chacha_nonce:n.subarray(32,44),hmac_key:n.subarray(44,76)}}function bn(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("expected positive integer");if(e<=32)return 32;const t=1<<Math.floor(Math.log2(e-1))+1,n=t<=256?32:t/8;return n*(Math.floor((e-1)/n)+1)}function ic(e){if(!Number.isSafeInteger(e)||e<Jr||e>Yr)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");const t=new Uint8Array(2);return new DataView(t.buffer).setUint16(0,e,!1),t}function sc(e){const t=ne.encode(e),n=t.length,r=ic(n),i=new Uint8Array(bn(n)-n);return ft(r,t,i)}function oc(e){const t=new DataView(e.buffer).getUint16(0),n=e.subarray(2,2+t);if(t<Jr||t>Yr||n.length!==t||e.length!==2+bn(t))throw new Error("invalid padding");return we.decode(n)}function Qr(e,t,n){if(n.length!==32)throw new Error("AAD associated data must be 32 bytes");const r=ft(n,t);return pt(le,e,r)}function ac(e){if(typeof e!="string")throw new Error("payload must be a valid string");const t=e.length;if(t<132||t>87472)throw new Error("invalid payload length: "+t);if(e[0]==="#")throw new Error("unknown encryption version");let n;try{n=ye.decode(e)}catch(s){throw new Error("invalid base64: "+s.message)}const r=n.length;if(r<99||r>65603)throw new Error("invalid data length: "+r);const i=n[0];if(i!==2)throw new Error("unknown encryption version "+i);return{nonce:n.subarray(1,33),ciphertext:n.subarray(33,-32),mac:n.subarray(-32)}}function vn(e,t,n=nr(32)){const{chacha_key:r,chacha_nonce:i,hmac_key:s}=Xr(t,n),o=sc(e),c=Kr(r,i,o),a=Qr(s,c,n);return ye.encode(ft(new Uint8Array([2]),n,c,a))}function mn(e,t){const{nonce:n,ciphertext:r,mac:i}=ac(e),{chacha_key:s,chacha_nonce:o,hmac_key:c}=Xr(t,n),a=Qr(c,r,n);if(!Os(a,i))throw new Error("invalid MAC");const f=Kr(s,o,r);return oc(f)}var cc={utils:{getConversationKey:wn,calcPaddedLen:bn},encrypt:vn,decrypt:mn},uc=2*24*60*60,ei=()=>Math.round(Date.now()/1e3),ti=()=>Math.round(ei()-Math.random()*uc),ni=(e,t)=>wn(e,t),ri=(e,t,n)=>vn(JSON.stringify(e),ni(t,n)),ii=(e,t)=>JSON.parse(mn(e.content,ni(t,e.pubkey)));function si(e,t){const n={created_at:ei(),content:"",tags:[],...e,pubkey:ue(t)};return n.id=ze(n),n}function oi(e,t,n){return ee({kind:Ur,content:ri(e,t,n),created_at:ti(),tags:[]},t)}function ai(e,t){const n=Le();return ee({kind:Pr,content:ri(e,n,t),created_at:ti(),tags:[["p",t]]},n)}function xt(e,t,n){const r=si(e,t),i=oi(r,t,n);return ai(i,n)}function fc(e,t,n){if(!n||n.length===0)throw new Error("At least one recipient is required.");const r=ue(t),i=[xt(e,t,r)];return n.forEach(s=>{i.push(xt(e,t,s))}),i}function En(e,t){const n=ii(e,t);return ii(n,t)}function ci(e,t){let n=[];return e.forEach(r=>{n.push(En(r,t))}),n.sort((r,i)=>r.created_at-i.created_at),n}function lc(e,t,n,r){const i={created_at:Math.ceil(Date.now()/1e3),kind:Lr,tags:[],content:t};return(Array.isArray(e)?e:[e]).forEach(({publicKey:o,relayUrl:c})=>{i.tags.push(c?["p",o,c]:["p",o])}),r&&i.tags.push(["e",r.eventId,r.relayUrl||"","reply"]),n&&i.tags.push(["subject",n]),i}function ui(e,t,n,r,i){const s=lc(t,n,r,i);return xt(s,e,t.publicKey)}function hc(e,t,n,r,i){if(!t||t.length===0)throw new Error("At least one recipient is required.");return[{publicKey:ue(e)},...t].map(o=>ui(e,o,n,r,i))}var dc=En,pc=ci,yc={};D(yc,{finishRepostEvent:()=>gc,getRepostedEvent:()=>wc,getRepostedEventPointer:()=>fi});function gc(e,t,n,r){var o;let i;const s=[...e.tags??[],["e",t.id,n],["p",t.pubkey]];return t.kind===_r?i=cn:(i=fn,s.push(["k",String(t.kind)])),ee({kind:i,tags:s,content:e.content===""||(o=t.tags)!=null&&o.find(c=>c[0]==="-")?"":JSON.stringify(t),created_at:e.created_at},r)}function fi(e){if(![cn,fn].includes(e.kind))return;let t,n;for(let r=e.tags.length-1;r>=0&&(t===void 0||n===void 0);r--){const i=e.tags[r];i.length>=2&&(i[0]==="e"&&t===void 0?t=i:i[0]==="p"&&n===void 0&&(n=i))}if(t!==void 0)return{id:t[1],relays:[t[2],n==null?void 0:n[2]].filter(r=>typeof r=="string"),author:n==null?void 0:n[1]}}function wc(e,{skipVerification:t}={}){const n=fi(e);if(n===void 0||e.content==="")return;let r;try{r=JSON.parse(e.content)}catch{return}if(r.id===n.id&&!(!t&&!wt(r)))return r}var bc={};D(bc,{NOSTR_URI_REGEX:()=>xn,parse:()=>mc,test:()=>vc});var xn=new RegExp(`nostr:(${jr.source})`);function vc(e){return typeof e=="string"&&new RegExp(`^${xn.source}$`).test(e)}function mc(e){const t=e.match(new RegExp(`^${xn.source}$`));if(!t)throw new Error(`Invalid Nostr URI: ${e}`);return{uri:t[0],value:t[1],decoded:bt(t[1])}}var Ec={};D(Ec,{finishReactionEvent:()=>xc,getReactedEventPointer:()=>Nc});function xc(e,t,n){const r=t.tags.filter(i=>i.length>=2&&(i[0]==="e"||i[0]==="p"));return ee({...e,kind:un,tags:[...e.tags??[],...r,["e",t.id],["p",t.pubkey]],content:e.content??"+"},n)}function Nc(e){if(e.kind!==un)return;let t,n;for(let r=e.tags.length-1;r>=0&&(t===void 0||n===void 0);r--){const i=e.tags[r];i.length>=2&&(i[0]==="e"&&t===void 0?t=i:i[0]==="p"&&n===void 0&&(n=i))}if(!(t===void 0||n===void 0))return{id:t[1],relays:[t[2],n[2]].filter(r=>r!==void 0),author:n[1]}}var Kc={};D(Kc,{parse:()=>Ac});var Sc=/\W/m,li=/\W |\W$|$|,| /m;function*Ac(e){const t=e.length;let n=0,r=0;for(;r<t;){let i=e.indexOf(":",r);if(i===-1)break;if(e.substring(i-5,i)==="nostr"){const s=e.substring(i+60).match(Sc),o=s?i+60+s.index:t;try{let c,{data:a,type:f}=bt(e.substring(i+1,o));switch(f){case"npub":c={pubkey:a};break;case"nsec":case"note":r=o+1;continue;default:c=a}n!==i-5&&(yield{type:"text",text:e.substring(n,i-5)}),yield{type:"reference",pointer:c},r=o,n=r;continue}catch{r=i+1;continue}}else if(e.substring(i-5,i)==="https"||e.substring(i-4,i)==="http"){const s=e.substring(i+4).match(li),o=s?i+4+s.index:t,c=e[i-1]==="s"?5:4;try{let a=new URL(e.substring(i-c,o));if(a.hostname.indexOf(".")===-1)throw new Error("invalid url");if(n!==i-c&&(yield{type:"text",text:e.substring(n,i-c)}),a.pathname.endsWith(".png")||a.pathname.endsWith(".jpg")||a.pathname.endsWith(".jpeg")||a.pathname.endsWith(".gif")||a.pathname.endsWith(".webp")){yield{type:"image",url:a.toString()},r=o,n=r;continue}if(a.pathname.endsWith(".mp4")||a.pathname.endsWith(".avi")||a.pathname.endsWith(".webm")||a.pathname.endsWith(".mkv")){yield{type:"video",url:a.toString()},r=o,n=r;continue}if(a.pathname.endsWith(".mp3")||a.pathname.endsWith(".aac")||a.pathname.endsWith(".ogg")||a.pathname.endsWith(".opus")){yield{type:"audio",url:a.toString()},r=o,n=r;continue}yield{type:"url",url:a.toString()},r=o,n=r;continue}catch{r=o+1;continue}}else if(e.substring(i-3,i)==="wss"||e.substring(i-2,i)==="ws"){const s=e.substring(i+4).match(li),o=s?i+4+s.index:t,c=e[i-1]==="s"?3:2;try{let a=new URL(e.substring(i-c,o));if(a.hostname.indexOf(".")===-1)throw new Error("invalid ws url");n!==i-c&&(yield{type:"text",text:e.substring(n,i-c)}),yield{type:"relay",url:a.toString()},r=o,n=r;continue}catch{r=o+1;continue}}else{r=i+1;continue}}n!==t&&(yield{type:"text",text:e.substring(n)})}var Cc={};D(Cc,{channelCreateEvent:()=>Ic,channelHideMessageEvent:()=>_c,channelMessageEvent:()=>kc,channelMetadataEvent:()=>Bc,channelMuteUserEvent:()=>Uc});var Ic=(e,t)=>{let n;if(typeof e.content=="object")n=JSON.stringify(e.content);else if(typeof e.content=="string")n=e.content;else return;return ee({kind:$r,tags:[...e.tags??[]],content:n,created_at:e.created_at},t)},Bc=(e,t)=>{let n;if(typeof e.content=="object")n=JSON.stringify(e.content);else if(typeof e.content=="string")n=e.content;else return;return ee({kind:Tr,tags:[["e",e.channel_create_event_id],...e.tags??[]],content:n,created_at:e.created_at},t)},kc=(e,t)=>{const n=[["e",e.channel_create_event_id,e.relay_url,"root"]];return e.reply_to_channel_message_event_id&&n.push(["e",e.reply_to_channel_message_event_id,e.relay_url,"reply"]),ee({kind:Rr,tags:[...n,...e.tags??[]],content:e.content,created_at:e.created_at},t)},_c=(e,t)=>{let n;if(typeof e.content=="object")n=JSON.stringify(e.content);else if(typeof e.content=="string")n=e.content;else return;return ee({kind:Or,tags:[["e",e.channel_message_event_id],...e.tags??[]],content:n,created_at:e.created_at},t)},Uc=(e,t)=>{let n;if(typeof e.content=="object")n=JSON.stringify(e.content);else if(typeof e.content=="string")n=e.content;else return;return ee({kind:Mr,tags:[["p",e.pubkey_to_mute],...e.tags??[]],content:n,created_at:e.created_at},t)},Lc={};D(Lc,{EMOJI_SHORTCODE_REGEX:()=>hi,matchAll:()=>$c,regex:()=>Nn,replaceAll:()=>Tc});var hi=/:(\w+):/,Nn=()=>new RegExp(`\\B${hi.source}\\B`,"g");function*$c(e){const t=e.matchAll(Nn());for(const n of t)try{const[r,i]=n;yield{shortcode:r,name:i,start:n.index,end:n.index+r.length}}catch{}}function Tc(e,t){return e.replaceAll(Nn(),(n,r)=>t({shortcode:n,name:r}))}var Rc={};D(Rc,{useFetchImplementation:()=>Oc,validateGithub:()=>Mc});var Kn;try{Kn=fetch}catch{}function Oc(e){Kn=e}async function Mc(e,t,n){try{return await(await Kn(`https://gist.github.com/${t}/${n}/raw`)).text()===`Verifying that I control the following Nostr public key: ${e}`}catch{return!1}}var Pc={};D(Pc,{makeNwcRequestEvent:()=>Dc,parseConnectionString:()=>Hc});function Hc(e){const{pathname:t,searchParams:n}=new URL(e),r=t,i=n.get("relay"),s=n.get("secret");if(!r||!i||!s)throw new Error("invalid connection string");return{pubkey:r,relay:i,secret:s}}async function Dc(e,t,n){const i=zr(t,e,JSON.stringify({method:"pay_invoice",params:{invoice:n}})),s={kind:Dr,created_at:Math.round(Date.now()/1e3),content:i,tags:[["p",e]]};return ee(s,t)}var qc={};D(qc,{normalizeIdentifier:()=>jc});function jc(e){return e=e.trim().toLowerCase(),e=e.normalize("NFKC"),Array.from(e).map(t=>new RegExp("\\p{Letter}","u").test(t)||new RegExp("\\p{Number}","u").test(t)?t:"-").join("")}var zc={};D(zc,{getSatoshisAmountFromBolt11:()=>Jc,getZapEndpoint:()=>Wc,makeZapReceipt:()=>Fc,makeZapRequest:()=>Zc,useFetchImplementation:()=>Vc,validateZapRequest:()=>Gc});var Sn;try{Sn=fetch}catch{}function Vc(e){Sn=e}async function Wc(e){try{let t="",{lud06:n,lud16:r}=JSON.parse(e.content);if(n){let{words:o}=De.decode(n,1e3),c=De.fromWords(o);t=we.decode(c)}else if(r){let[o,c]=r.split("@");t=new URL(`/.well-known/lnurlp/${o}`,`https://${c}`).toString()}else return null;let s=await(await Sn(t)).json();if(s.allowsNostr&&s.nostrPubkey)return s.callback}catch{}return null}function Zc({profile:e,event:t,amount:n,relays:r,comment:i=""}){if(!n)throw new Error("amount not given");if(!e)throw new Error("profile not given");let s={kind:9734,created_at:Math.round(Date.now()/1e3),content:i,tags:[["p",e],["amount",n.toString()],["relays",...r]]};if(t&&typeof t=="string"&&s.tags.push(["e",t]),t&&typeof t=="object"){if(on(t.kind)){const o=["a",`${t.kind}:${t.pubkey}:`];s.tags.push(o)}else if(an(t.kind)){let o=t.tags.find(([a,f])=>a==="d"&&f);if(!o)throw new Error("d tag not found or is empty");const c=["a",`${t.kind}:${t.pubkey}:${o[1]}`];s.tags.push(c)}}return s}function Gc(e){let t;try{t=JSON.parse(e)}catch{return"Invalid zap request JSON."}if(!yt(t))return"Zap request is not a valid Nostr event.";if(!wt(t))return"Invalid signature on zap request.";let n=t.tags.find(([s,o])=>s==="p"&&o);if(!n)return"Zap request doesn't have a 'p' tag.";if(!n[1].match(/^[a-f0-9]{64}$/))return"Zap request 'p' tag is not valid hex.";let r=t.tags.find(([s,o])=>s==="e"&&o);return r&&!r[1].match(/^[a-f0-9]{64}$/)?"Zap request 'e' tag is not valid hex.":t.tags.find(([s,o])=>s==="relays"&&o)?null:"Zap request doesn't have a 'relays' tag."}function Fc({zapRequest:e,preimage:t,bolt11:n,paidAt:r}){let i=JSON.parse(e),s=i.tags.filter(([c])=>c==="e"||c==="p"||c==="a"),o={kind:9735,created_at:Math.round(r.getTime()/1e3),content:"",tags:[...s,["P",i.pubkey],["bolt11",n],["description",e]]};return t&&o.tags.push(["preimage",t]),o}function Jc(e){if(e.length<50)return 0;e=e.substring(0,50);const t=e.lastIndexOf("1");if(t===-1)return 0;const n=e.substring(0,t);if(!n.startsWith("lnbc"))return 0;const r=n.substring(4);if(r.length<1)return 0;const i=r[r.length-1],s=i.charCodeAt(0)-48,o=s>=0&&s<=9;let c=r.length-1;if(o&&c++,c<1)return 0;const a=parseInt(r.substring(0,c));switch(i){case"m":return a*1e5;case"u":return a*100;case"n":return a/10;case"p":return a/1e4;default:return a*1e8}}var Yc={};D(Yc,{getToken:()=>Xc,hashPayload:()=>An,unpackEventFromToken:()=>pi,validateEvent:()=>mi,validateEventKind:()=>gi,validateEventMethodTag:()=>bi,validateEventPayloadTag:()=>vi,validateEventTimestamp:()=>yi,validateEventUrlTag:()=>wi,validateToken:()=>Qc});var di="Nostr ";async function Xc(e,t,n,r=!1,i){const s={kind:ln,tags:[["u",e],["method",t]],created_at:Math.round(new Date().getTime()/1e3),content:""};i&&s.tags.push(["payload",An(i)]);const o=await n(s);return(r?di:"")+ye.encode(ne.encode(JSON.stringify(o)))}async function Qc(e,t,n){const r=await pi(e).catch(s=>{throw s});return await mi(r,t,n).catch(s=>{throw s})}async function pi(e){if(!e)throw new Error("Missing token");e=e.replace(di,"");const t=we.decode(ye.decode(e));if(!t||t.length===0||!t.startsWith("{"))throw new Error("Invalid token");return JSON.parse(t)}function yi(e){return e.created_at?Math.round(new Date().getTime()/1e3)-e.created_at<60:!1}function gi(e){return e.kind===ln}function wi(e,t){const n=e.tags.find(r=>r[0]==="u");return n?n.length>0&&n[1]===t:!1}function bi(e,t){const n=e.tags.find(r=>r[0]==="method");return n?n.length>0&&n[1].toLowerCase()===t.toLowerCase():!1}function An(e){const t=le(ne.encode(JSON.stringify(e)));return H(t)}function vi(e,t){const n=e.tags.find(i=>i[0]==="payload");if(!n)return!1;const r=An(t);return n.length>0&&n[1]===r}async function mi(e,t,n,r){if(!wt(e))throw new Error("Invalid nostr event, signature invalid");if(!gi(e))throw new Error("Invalid nostr event, kind invalid");if(!yi(e))throw new Error("Invalid nostr event, created_at timestamp invalid");if(!wi(e,t))throw new Error("Invalid nostr event, url tag invalid");if(!bi(e,n))throw new Error("Invalid nostr event, method tag invalid");if(r&&typeof r=="object"&&Object.keys(r).length>0&&!vi(e,r))throw new Error("Invalid nostr event, payload tag does not match request body hash");return!0}const $e=1060,Cn=30078,In=1059,Ei=14,eu=100,tu=1;function nu(e){return JSON.stringify({version:tu,rootKey:H(e.rootKey),theirCurrentNostrPublicKey:e.theirCurrentNostrPublicKey,theirNextNostrPublicKey:e.theirNextNostrPublicKey,ourCurrentNostrKey:e.ourCurrentNostrKey?{publicKey:e.ourCurrentNostrKey.publicKey,privateKey:H(e.ourCurrentNostrKey.privateKey)}:void 0,ourNextNostrKey:{publicKey:e.ourNextNostrKey.publicKey,privateKey:H(e.ourNextNostrKey.privateKey)},receivingChainKey:e.receivingChainKey?H(e.receivingChainKey):void 0,sendingChainKey:e.sendingChainKey?H(e.sendingChainKey):void 0,sendingChainMessageNumber:e.sendingChainMessageNumber,receivingChainMessageNumber:e.receivingChainMessageNumber,previousSendingChainMessageCount:e.previousSendingChainMessageCount,skippedKeys:Object.fromEntries(Object.entries(e.skippedKeys).map(([t,n])=>[t,{headerKeys:n.headerKeys.map(r=>H(r)),messageKeys:Object.fromEntries(Object.entries(n.messageKeys).map(([r,i])=>[r,H(i)]))}]))})}function ru(e){const t=JSON.parse(e);if(!t.version){const n={};return t.skippedMessageKeys&&Object.entries(t.skippedMessageKeys).forEach(([r,i])=>{var s;n[r]={headerKeys:((s=t.skippedHeaderKeys)==null?void 0:s[r])||[],messageKeys:i}}),{rootKey:V(t.rootKey),theirCurrentNostrPublicKey:t.theirCurrentNostrPublicKey,theirNextNostrPublicKey:t.theirNextNostrPublicKey,ourCurrentNostrKey:t.ourCurrentNostrKey?{publicKey:t.ourCurrentNostrKey.publicKey,privateKey:V(t.ourCurrentNostrKey.privateKey)}:void 0,ourNextNostrKey:{publicKey:t.ourNextNostrKey.publicKey,privateKey:V(t.ourNextNostrKey.privateKey)},receivingChainKey:t.receivingChainKey?V(t.receivingChainKey):void 0,sendingChainKey:t.sendingChainKey?V(t.sendingChainKey):void 0,sendingChainMessageNumber:t.sendingChainMessageNumber,receivingChainMessageNumber:t.receivingChainMessageNumber,previousSendingChainMessageCount:t.previousSendingChainMessageCount,skippedKeys:n}}return{rootKey:V(t.rootKey),theirCurrentNostrPublicKey:t.theirCurrentNostrPublicKey,theirNextNostrPublicKey:t.theirNextNostrPublicKey,ourCurrentNostrKey:t.ourCurrentNostrKey?{publicKey:t.ourCurrentNostrKey.publicKey,privateKey:V(t.ourCurrentNostrKey.privateKey)}:void 0,ourNextNostrKey:{publicKey:t.ourNextNostrKey.publicKey,privateKey:V(t.ourNextNostrKey.privateKey)},receivingChainKey:t.receivingChainKey?V(t.receivingChainKey):void 0,sendingChainKey:t.sendingChainKey?V(t.sendingChainKey):void 0,sendingChainMessageNumber:t.sendingChainMessageNumber,receivingChainMessageNumber:t.receivingChainMessageNumber,previousSendingChainMessageCount:t.previousSendingChainMessageCount,skippedKeys:Object.fromEntries(Object.entries(t.skippedKeys||{}).map(([n,r])=>[n,{headerKeys:r.headerKeys.map(i=>V(i)),messageKeys:Object.fromEntries(Object.entries(r.messageKeys).map(([i,s])=>[i,V(s)]))}]))}}async function*iu(e){const t=[];let n=null;const r=e.onEvent(i=>{n?(n(i),n=null):t.push(i)});try{for(;;)t.length>0?yield t.shift():yield new Promise(i=>{n=i})}finally{r()}}function Te(e,t=new Uint8Array(32),n=1){const r=nn(le,e,t),i=[];for(let s=1;s<=n;s++)i.push(Cr(le,r,new Uint8Array([s]),32));return i}function su(e,t){return`${e}:${t}`}function ou(e){var n;const t=(n=e.tags)==null?void 0:n.find(r=>r[0]==="ms");return t?parseInt(t[1]):e.created_at*1e3}const au=1e3,cu="0000000000000000000000000000000000000000000000000000000000000000";class et{constructor(t,n){te(this,"skippedSubscription");te(this,"nostrUnsubscribe");te(this,"nostrNextUnsubscribe");te(this,"internalSubscriptions",new Map);te(this,"currentInternalSubscriptionId",0);te(this,"name");this.nostrSubscribe=t,this.state=n,this.name=Math.random().toString(36).substring(2,6)}static init(t,n,r,i,s,o){const c=Le();let a,f,l,u;i?([a,f]=Te(s,q.getConversationKey(c,n),2),l={publicKey:ue(r),privateKey:r},u={publicKey:ue(c),privateKey:c}):(a=s,f=void 0,l=void 0,u={publicKey:ue(r),privateKey:r});const p={rootKey:a,theirNextNostrPublicKey:n,ourCurrentNostrKey:l,ourNextNostrKey:u,receivingChainKey:void 0,sendingChainKey:f,sendingChainMessageNumber:0,receivingChainMessageNumber:0,previousSendingChainMessageCount:0,skippedKeys:{}},w=new et(t,p);return o&&(w.name=o),w}send(t){return this.sendEvent({content:t,kind:Ei})}sendEvent(t){if(!this.state.theirNextNostrPublicKey||!this.state.ourCurrentNostrKey)throw new Error("we are not the initiator, so we can't send the first message");if("sig"in t)throw new Error("Event must be unsigned "+JSON.stringify(t));const n=Date.now(),r={...t,content:t.content||"",kind:t.kind||$e,created_at:t.created_at||Math.floor(n/1e3),tags:t.tags||[],pubkey:t.pubkey||cu};r.tags.some(([f])=>f==="ms")||r.tags.push(["ms",String(n)]),r.id=ze(r);const[i,s]=this.ratchetEncrypt(JSON.stringify(r)),o=q.getConversationKey(this.state.ourCurrentNostrKey.privateKey,this.state.theirNextNostrPublicKey),c=q.encrypt(JSON.stringify(i),o);return{event:ee({content:s,kind:$e,tags:[["header",c]],created_at:Math.floor(n/1e3)},this.state.ourCurrentNostrKey.privateKey),innerEvent:r}}onEvent(t){const n=this.currentInternalSubscriptionId++;return this.internalSubscriptions.set(n,t),this.subscribeToNostrEvents(),()=>this.internalSubscriptions.delete(n)}close(){var t,n,r;(t=this.nostrUnsubscribe)==null||t.call(this),(n=this.nostrNextUnsubscribe)==null||n.call(this),(r=this.skippedSubscription)==null||r.call(this),this.internalSubscriptions.clear()}ratchetEncrypt(t){const[n,r]=Te(this.state.sendingChainKey,new Uint8Array([1]),2);return this.state.sendingChainKey=n,[{number:this.state.sendingChainMessageNumber++,nextPublicKey:this.state.ourNextNostrKey.publicKey,previousChainLength:this.state.previousSendingChainMessageCount},q.encrypt(t,r)]}ratchetDecrypt(t,n,r){const i=this.trySkippedMessageKeys(t,n,r);if(i)return i;this.skipMessageKeys(t.number,r);const[s,o]=Te(this.state.receivingChainKey,new Uint8Array([1]),2);return this.state.receivingChainKey=s,this.state.receivingChainMessageNumber++,q.decrypt(n,o)}ratchetStep(){this.state.previousSendingChainMessageCount=this.state.sendingChainMessageNumber,this.state.sendingChainMessageNumber=0,this.state.receivingChainMessageNumber=0;const t=q.getConversationKey(this.state.ourNextNostrKey.privateKey,this.state.theirNextNostrPublicKey),[n,r]=Te(this.state.rootKey,t,2);this.state.receivingChainKey=r,this.state.ourCurrentNostrKey=this.state.ourNextNostrKey;const i=Le();this.state.ourNextNostrKey={publicKey:ue(i),privateKey:i};const s=q.getConversationKey(this.state.ourNextNostrKey.privateKey,this.state.theirNextNostrPublicKey),[o,c]=Te(n,s,2);this.state.rootKey=o,this.state.sendingChainKey=c}skipMessageKeys(t,n){if(!(t<=this.state.receivingChainMessageNumber)){if(t>this.state.receivingChainMessageNumber+au)throw new Error("Too many skipped messages");if(!this.state.skippedKeys[n]){if(this.state.skippedKeys[n]={headerKeys:[],messageKeys:{}},this.state.ourCurrentNostrKey){const i=q.getConversationKey(this.state.ourCurrentNostrKey.privateKey,n);this.state.skippedKeys[n].headerKeys.includes(i)||this.state.skippedKeys[n].headerKeys.push(i)}const r=q.getConversationKey(this.state.ourNextNostrKey.privateKey,n);this.state.skippedKeys[n].headerKeys.includes(r)||this.state.skippedKeys[n].headerKeys.push(r)}for(;this.state.receivingChainMessageNumber<t;){const[r,i]=Te(this.state.receivingChainKey,new Uint8Array([1]),2);this.state.receivingChainKey=r,this.state.skippedKeys[n].messageKeys[this.state.receivingChainMessageNumber]=i,this.state.receivingChainMessageNumber++}}}trySkippedMessageKeys(t,n,r){const i=this.state.skippedKeys[r];if(!i)return null;const s=i.messageKeys[t.number];return s?(delete i.messageKeys[t.number],Object.keys(i.messageKeys).length===0&&delete this.state.skippedKeys[r],q.decrypt(n,s)):null}decryptHeader(t){const n=t.tags[0][1];if(this.state.ourCurrentNostrKey){const s=q.getConversationKey(this.state.ourCurrentNostrKey.privateKey,t.pubkey);try{return[JSON.parse(q.decrypt(n,s)),!1,!1]}catch{}}const r=q.getConversationKey(this.state.ourNextNostrKey.privateKey,t.pubkey);try{return[JSON.parse(q.decrypt(n,r)),!0,!1]}catch{}const i=this.state.skippedKeys[t.pubkey];if(i!=null&&i.headerKeys)for(const s of i.headerKeys)try{return[JSON.parse(q.decrypt(n,s)),!1,!0]}catch{}throw new Error("Failed to decrypt header with current and skipped header keys")}handleNostrEvent(t){var n,r;try{const[i,s,o]=this.decryptHeader(t);if(!o)this.state.theirNextNostrPublicKey!==i.nextPublicKey&&(this.state.theirCurrentNostrPublicKey=this.state.theirNextNostrPublicKey,this.state.theirNextNostrPublicKey=i.nextPublicKey,(n=this.nostrUnsubscribe)==null||n.call(this),this.nostrUnsubscribe=this.nostrNextUnsubscribe,this.nostrNextUnsubscribe=this.nostrSubscribe({authors:[this.state.theirNextNostrPublicKey],kinds:[$e]},f=>this.handleNostrEvent(f))),s&&(this.skipMessageKeys(i.previousChainLength,t.pubkey),this.ratchetStep());else if(!((r=this.state.skippedKeys[t.pubkey])!=null&&r.messageKeys[i.number]))return;const c=this.ratchetDecrypt(i,t.content,t.pubkey),a=JSON.parse(c);if(!yt(a)||a.id!==ze(a))return;this.internalSubscriptions.forEach(f=>f(a,t))}catch(i){if(i instanceof Error&&i.message.includes("Failed to decrypt header"))return;throw i}}subscribeToNostrEvents(){if(this.nostrNextUnsubscribe)return;this.nostrNextUnsubscribe=this.nostrSubscribe({authors:[this.state.theirNextNostrPublicKey],kinds:[$e]},n=>this.handleNostrEvent(n)),this.state.theirCurrentNostrPublicKey&&(this.nostrUnsubscribe=this.nostrSubscribe({authors:[this.state.theirCurrentNostrPublicKey],kinds:[$e]},n=>this.handleNostrEvent(n)));const t=Object.keys(this.state.skippedKeys);t.length&&(this.skippedSubscription=this.nostrSubscribe({authors:t,kinds:[$e]},n=>this.handleNostrEvent(n)))}}new TextDecoder("utf-8"),new TextEncoder;function Nt(e,t){const n=Ue.getSharedSecret(e,"02"+t).subarray(1,33);return nn(le,n,"nip44-v2")}const uu=2*24*60*60,fu=()=>Math.round(Date.now()/1e3),lu=()=>Math.round(fu()-Math.random()*uu);class Re{constructor(t,n,r,i,s,o,c=[]){this.inviterEphemeralPublicKey=t,this.sharedSecret=n,this.inviter=r,this.inviterEphemeralPrivateKey=i,this.deviceId=s,this.maxUses=o,this.usedBy=c}static createNew(t,n,r){if(!t)throw new Error("Inviter public key is required");const i=Le(),s=ue(i),o=H(Le());return new Re(s,o,t,i,n,r)}static fromUrl(t){const r=new URL(t).hash.slice(1);if(!r)throw new Error("No invite data found in the URL hash.");const i=decodeURIComponent(r);let s;try{s=JSON.parse(i)}catch(f){throw new Error("Invite data in URL hash is not valid JSON: "+f)}const{inviter:o,ephemeralKey:c,sharedSecret:a}=s;if(!o||!c||!a)throw new Error("Missing required fields (inviter, ephemeralKey, sharedSecret) in invite data.");return new Re(c,a,o)}static deserialize(t){const n=JSON.parse(t);return new Re(n.inviterEphemeralPublicKey,n.sharedSecret,n.inviter,n.inviterEphemeralPrivateKey?new Uint8Array(n.inviterEphemeralPrivateKey):void 0,n.deviceId,n.maxUses,n.usedBy)}static fromEvent(t){var a,f,l,u;if(!t.sig)throw new Error("Event is not signed");if(!wt(t))throw new Error("Event signature is invalid");const{tags:n}=t;if(!n)throw new Error("Invalid invite event: missing tags");const r=(a=n.find(([p])=>p==="ephemeralKey"))==null?void 0:a[1],i=(f=n.find(([p])=>p==="sharedSecret"))==null?void 0:f[1],s=t.pubkey,o=(l=n.find(([p])=>p==="d"))==null?void 0:l[1],c=(u=o==null?void 0:o.split("/"))==null?void 0:u[2];if(!r||!i)throw new Error("Invalid invite event: missing session key or sharedSecret");return new Re(r,i,s,void 0,c)}static fromUser(t,n,r){const i={kinds:[Cn],authors:[t],"#l":["double-ratchet/invites"]},s=new Set;return n(i,c=>{if(!s.has(c.id)){s.add(c.id);try{const a=Re.fromEvent(c);r(a)}catch{}}})}serialize(){return JSON.stringify({inviterEphemeralPublicKey:this.inviterEphemeralPublicKey,sharedSecret:this.sharedSecret,inviter:this.inviter,inviterEphemeralPrivateKey:this.inviterEphemeralPrivateKey?Array.from(this.inviterEphemeralPrivateKey):void 0,deviceId:this.deviceId,maxUses:this.maxUses,usedBy:this.usedBy})}getUrl(t="https://iris.to"){const n={inviter:this.inviter,ephemeralKey:this.inviterEphemeralPublicKey,sharedSecret:this.sharedSecret},r=new URL(t);return r.hash=encodeURIComponent(JSON.stringify(n)),r.toString()}getEvent(){if(!this.deviceId)throw new Error("Device ID is required");return{kind:Cn,pubkey:this.inviter,content:"",created_at:Math.floor(Date.now()/1e3),tags:[["ephemeralKey",this.inviterEphemeralPublicKey],["sharedSecret",this.sharedSecret],["d","double-ratchet/invites/"+this.deviceId],["l","double-ratchet/invites"]]}}async accept(t,n,r){const i=Le(),s=ue(i),o=this.inviter||this.inviterEphemeralPublicKey,c=V(this.sharedSecret),a=et.init(t,this.inviterEphemeralPublicKey,i,!0,c,void 0),l=await(typeof r=="function"?r:(d,y)=>Promise.resolve(q.encrypt(d,Nt(r,y))))(s,o),u={pubkey:n,content:await q.encrypt(l,c),created_at:Math.floor(Date.now()/1e3)},p=JSON.stringify(u),w=Le(),g=ue(w),h={kind:In,pubkey:g,content:q.encrypt(p,Nt(w,this.inviterEphemeralPublicKey)),created_at:lu(),tags:[["p",this.inviterEphemeralPublicKey]]};return{session:a,event:ee(h,w)}}listen(t,n,r){if(!this.inviterEphemeralPrivateKey)throw new Error("Inviter session key is not available");const i={kinds:[In],"#p":[this.inviterEphemeralPublicKey]};return n(i,async s=>{try{if(this.maxUses&&this.usedBy.length>=this.maxUses)return;const o=await q.decrypt(s.content,Nt(this.inviterEphemeralPrivateKey,s.pubkey)),c=JSON.parse(o),a=V(this.sharedSecret),f=c.pubkey;this.usedBy.push(f);const l=await q.decrypt(c.content,a),p=await(typeof t=="function"?t:(h,d)=>Promise.resolve(q.decrypt(h,Nt(t,d))))(l,f),w=s.id,g=et.init(n,p,this.inviterEphemeralPrivateKey,!1,a,w);r(g,f)}catch{}})}}P.CHAT_MESSAGE_KIND=Ei,P.INVITE_EVENT_KIND=Cn,P.INVITE_RESPONSE_KIND=In,P.Invite=Re,P.MAX_SKIP=eu,P.MESSAGE_EVENT_KIND=$e,P.Session=et,P.createEventStream=iu,P.deserializeSessionState=ru,P.getMillisecondTimestamp=ou,P.kdf=Te,P.serializeSessionState=nu,P.skippedMessageIndexKey=su,Object.defineProperty(P,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nostr-double-ratchet",
3
- "version": "0.0.29",
3
+ "version": "0.0.30",
4
4
  "type": "module",
5
5
  "packageManager": "yarn@1.22.22",
6
6
  "description": "Nostr double ratchet library",
package/src/Session.ts CHANGED
@@ -320,42 +320,49 @@ export class Session {
320
320
  }
321
321
 
322
322
  private handleNostrEvent(e: { tags: string[][]; pubkey: string; content: string }) {
323
- const [header, shouldRatchet, isSkipped] = this.decryptHeader(e);
324
-
325
- if (!isSkipped) {
326
- if (this.state.theirNextNostrPublicKey !== header.nextPublicKey) {
327
- this.state.theirCurrentNostrPublicKey = this.state.theirNextNostrPublicKey;
328
- this.state.theirNextNostrPublicKey = header.nextPublicKey;
329
- this.nostrUnsubscribe?.();
330
- this.nostrUnsubscribe = this.nostrNextUnsubscribe;
331
- this.nostrNextUnsubscribe = this.nostrSubscribe(
332
- {authors: [this.state.theirNextNostrPublicKey], kinds: [MESSAGE_EVENT_KIND]},
333
- (e) => this.handleNostrEvent(e)
334
- );
335
- }
336
-
337
- if (shouldRatchet) {
338
- this.skipMessageKeys(header.previousChainLength, e.pubkey);
339
- this.ratchetStep();
323
+ try {
324
+ const [header, shouldRatchet, isSkipped] = this.decryptHeader(e);
325
+
326
+ if (!isSkipped) {
327
+ if (this.state.theirNextNostrPublicKey !== header.nextPublicKey) {
328
+ this.state.theirCurrentNostrPublicKey = this.state.theirNextNostrPublicKey;
329
+ this.state.theirNextNostrPublicKey = header.nextPublicKey;
330
+ this.nostrUnsubscribe?.();
331
+ this.nostrUnsubscribe = this.nostrNextUnsubscribe;
332
+ this.nostrNextUnsubscribe = this.nostrSubscribe(
333
+ {authors: [this.state.theirNextNostrPublicKey], kinds: [MESSAGE_EVENT_KIND]},
334
+ (e) => this.handleNostrEvent(e)
335
+ );
336
+ }
337
+
338
+ if (shouldRatchet) {
339
+ this.skipMessageKeys(header.previousChainLength, e.pubkey);
340
+ this.ratchetStep();
341
+ }
342
+ } else {
343
+ if (!this.state.skippedKeys[e.pubkey]?.messageKeys[header.number]) {
344
+ // Maybe we already processed this message — no error
345
+ return
346
+ }
340
347
  }
341
- } else {
342
- if (!this.state.skippedKeys[e.pubkey]?.messageKeys[header.number]) {
343
- // Maybe we already processed this message — no error
344
- return
348
+
349
+ const text = this.ratchetDecrypt(header, e.content, e.pubkey);
350
+ const innerEvent = JSON.parse(text);
351
+ if (!validateEvent(innerEvent)) {
352
+ return;
345
353
  }
346
- }
347
354
 
348
- const text = this.ratchetDecrypt(header, e.content, e.pubkey);
349
- const innerEvent = JSON.parse(text);
350
- if (!validateEvent(innerEvent)) {
351
- return;
352
- }
355
+ if (innerEvent.id !== getEventHash(innerEvent)) {
356
+ return;
357
+ }
353
358
 
354
- if (innerEvent.id !== getEventHash(innerEvent)) {
355
- return;
359
+ this.internalSubscriptions.forEach(callback => callback(innerEvent, e as VerifiedEvent));
360
+ } catch (error) {
361
+ if (error instanceof Error && error.message.includes("Failed to decrypt header")) {
362
+ return;
363
+ }
364
+ throw error;
356
365
  }
357
-
358
- this.internalSubscriptions.forEach(callback => callback(innerEvent, e as VerifiedEvent));
359
366
  }
360
367
 
361
368
  private subscribeToNostrEvents() {
@@ -15,6 +15,7 @@ export default class SessionManager {
15
15
  private deviceId: string
16
16
  private invite?: Invite
17
17
  private storage: StorageAdapter
18
+ private messageQueue: Map<string, Array<{event: Partial<Rumor>, resolve: (results: any[]) => void}>> = new Map()
18
19
 
19
20
  constructor(
20
21
  ourIdentityKey: Uint8Array,
@@ -71,16 +72,19 @@ export default class SessionManager {
71
72
  this.nostrSubscribe,
72
73
  (session, inviteePubkey) => {
73
74
  if (!inviteePubkey) return
75
+
76
+ const targetUserKey = inviteePubkey
77
+
74
78
  try {
75
- let userRecord = this.userRecords.get(inviteePubkey)
79
+ let userRecord = this.userRecords.get(targetUserKey)
76
80
  if (!userRecord) {
77
- userRecord = new UserRecord(inviteePubkey, this.nostrSubscribe)
78
- this.userRecords.set(inviteePubkey, userRecord)
81
+ userRecord = new UserRecord(targetUserKey, this.nostrSubscribe)
82
+ this.userRecords.set(targetUserKey, userRecord)
79
83
  }
80
84
 
81
85
  const deviceKey = session.name || 'unknown'
82
86
  userRecord.upsertSession(deviceKey, session)
83
- this.saveSession(inviteePubkey, deviceKey, session)
87
+ this.saveSession(targetUserKey, deviceKey, session)
84
88
 
85
89
  session.onEvent((_event: Rumor) => {
86
90
  this.internalSubscriptions.forEach(cb => cb(_event))
@@ -129,6 +133,8 @@ export default class SessionManager {
129
133
  }
130
134
  })
131
135
 
136
+
137
+
132
138
  this._initialised = true
133
139
  await this.nostrPublish(this.invite.getEvent()).catch(() => {})
134
140
  }
@@ -193,33 +199,62 @@ export default class SessionManager {
193
199
  }
194
200
 
195
201
  async sendEvent(recipientIdentityKey: string, event: Partial<Rumor>) {
202
+ console.log("Sending event to", recipientIdentityKey, event)
203
+ // Immediately notify local subscribers so that UI can render sent message optimistically
204
+ this.internalSubscriptions.forEach(cb => cb(event as Rumor))
205
+
196
206
  const results = []
197
-
207
+ const publishPromises: Promise<any>[] = []
208
+
198
209
  // Send to recipient's devices
199
210
  const userRecord = this.userRecords.get(recipientIdentityKey)
200
211
  if (!userRecord) {
201
- // Listen for invites from recipient and return without throwing; caller
202
- // can await a subsequent session establishment.
203
- this.listenToUser(recipientIdentityKey)
204
- return []
212
+ return new Promise<any[]>((resolve) => {
213
+ if (!this.messageQueue.has(recipientIdentityKey)) {
214
+ this.messageQueue.set(recipientIdentityKey, [])
215
+ }
216
+ this.messageQueue.get(recipientIdentityKey)!.push({event, resolve})
217
+ this.listenToUser(recipientIdentityKey)
218
+ })
219
+ }
220
+
221
+ const activeSessions = userRecord.getActiveSessions()
222
+ const sendableSessions = activeSessions.filter(s => !!(s.state?.theirNextNostrPublicKey && s.state?.ourCurrentNostrKey))
223
+
224
+ if (sendableSessions.length === 0) {
225
+ return new Promise<any[]>((resolve) => {
226
+ if (!this.messageQueue.has(recipientIdentityKey)) {
227
+ this.messageQueue.set(recipientIdentityKey, [])
228
+ }
229
+ this.messageQueue.get(recipientIdentityKey)!.push({event, resolve})
230
+ this.listenToUser(recipientIdentityKey)
231
+ })
205
232
  }
206
233
 
207
- // Send to all active sessions with recipient
208
- for (const session of userRecord.getActiveSessions()) {
234
+ // Send to all sendable sessions with recipient
235
+ for (const session of sendableSessions) {
209
236
  const { event: encryptedEvent } = session.sendEvent(event)
210
237
  results.push(encryptedEvent)
238
+ publishPromises.push(this.nostrPublish(encryptedEvent).catch(() => {}))
211
239
  }
212
240
 
213
241
  // Send to our own devices (for multi-device sync)
214
242
  const ourPublicKey = getPublicKey(this.ourIdentityKey)
215
243
  const ownUserRecord = this.userRecords.get(ourPublicKey)
216
244
  if (ownUserRecord) {
217
- for (const session of ownUserRecord.getActiveSessions()) {
245
+ const ownSendableSessions = ownUserRecord.getActiveSessions().filter(s => !!(s.state?.theirNextNostrPublicKey && s.state?.ourCurrentNostrKey))
246
+ for (const session of ownSendableSessions) {
218
247
  const { event: encryptedEvent } = session.sendEvent(event)
219
248
  results.push(encryptedEvent)
249
+ publishPromises.push(this.nostrPublish(encryptedEvent).catch(() => {}))
220
250
  }
221
251
  }
222
252
 
253
+ // Ensure all publish operations settled before returning
254
+ if (publishPromises.length > 0) {
255
+ await Promise.all(publishPromises)
256
+ }
257
+
223
258
  return results
224
259
  }
225
260
 
@@ -229,6 +264,16 @@ export default class SessionManager {
229
264
 
230
265
  const unsubscribe = Invite.fromUser(userPubkey, this.nostrSubscribe, async (_invite) => {
231
266
  try {
267
+ const deviceId = (_invite instanceof Invite && _invite.deviceId) ? _invite.deviceId : 'unknown'
268
+
269
+ const userRecord = this.userRecords.get(userPubkey)
270
+ if (userRecord) {
271
+ const existingSessions = userRecord.getActiveSessions()
272
+ if (existingSessions.some(session => session.name === deviceId)) {
273
+ return // Already have session with this device
274
+ }
275
+ }
276
+
232
277
  const { session, event } = await _invite.accept(
233
278
  this.nostrSubscribe,
234
279
  getPublicKey(this.ourIdentityKey),
@@ -237,19 +282,35 @@ export default class SessionManager {
237
282
  this.nostrPublish(event)?.catch(() => {})
238
283
 
239
284
  // Store the new session
240
- let userRecord = this.userRecords.get(userPubkey)
241
- if (!userRecord) {
242
- userRecord = new UserRecord(userPubkey, this.nostrSubscribe)
243
- this.userRecords.set(userPubkey, userRecord)
285
+ let currentUserRecord = this.userRecords.get(userPubkey)
286
+ if (!currentUserRecord) {
287
+ currentUserRecord = new UserRecord(userPubkey, this.nostrSubscribe)
288
+ this.userRecords.set(userPubkey, currentUserRecord)
244
289
  }
245
- const deviceId = (_invite instanceof Invite && _invite.deviceId) ? _invite.deviceId : event.id || 'unknown'
290
+ currentUserRecord.upsertSession(deviceId, session)
246
291
  this.saveSession(userPubkey, deviceId, session)
247
292
 
248
- // Set up event handling for the new session
293
+ // Register all existing callbacks on the new session
249
294
  session.onEvent((_event: Rumor) => {
250
295
  this.internalSubscriptions.forEach(callback => callback(_event))
251
296
  })
252
297
 
298
+ const queuedMessages = this.messageQueue.get(userPubkey)
299
+ if (queuedMessages && queuedMessages.length > 0) {
300
+ setTimeout(async () => {
301
+ const currentQueuedMessages = this.messageQueue.get(userPubkey)
302
+ if (currentQueuedMessages && currentQueuedMessages.length > 0) {
303
+ const messagesToProcess = [...currentQueuedMessages]
304
+ this.messageQueue.delete(userPubkey)
305
+
306
+ for (const {event: queuedEvent, resolve} of messagesToProcess) {
307
+ const results = await this.sendEvent(userPubkey, queuedEvent)
308
+ resolve(results)
309
+ }
310
+ }
311
+ }, 1000) // Increased delay for CI compatibility
312
+ }
313
+
253
314
  // Return the event to be published
254
315
  return event
255
316
  } catch {
package/src/UserRecord.ts CHANGED
@@ -178,6 +178,7 @@ export class UserRecord {
178
178
  * Return all sessions that are currently considered *active*.
179
179
  * For now this means any session in a non-stale device record as well as
180
180
  * all sessions added through `addSession`.
181
+ * Prioritizes initiator sessions (can send first message) over responder sessions.
181
182
  */
182
183
  public getActiveSessions(): Session[] {
183
184
  const sessions: Session[] = [];
@@ -188,6 +189,15 @@ export class UserRecord {
188
189
  }
189
190
  }
190
191
 
192
+ sessions.sort((a, b) => {
193
+ const aCanSend = !!(a.state?.theirNextNostrPublicKey && a.state?.ourCurrentNostrKey);
194
+ const bCanSend = !!(b.state?.theirNextNostrPublicKey && b.state?.ourCurrentNostrKey);
195
+
196
+ if (aCanSend && !bCanSend) return -1; // a comes first
197
+ if (!aCanSend && bCanSend) return 1; // b comes first
198
+ return 0; // equal priority
199
+ });
200
+
191
201
  return sessions;
192
202
  }
193
203