From 128c7e78666bb3775c9d6496c3da005a9cd9c067 Mon Sep 17 00:00:00 2001 From: "@Bibo-dochex" Date: Mon, 31 Aug 2026 11:36:46 -0400 Subject: [PATCH] fix: remediate DOM-based XSS in PushTX - Refactor renderMessage to return HTMLElement and accept Node content - Add textMessage helper for plain-text messages - Replace innerHTML assignments with replaceChildren + DOM APIs - Stop reflecting raw network parameter in parseFragment error - Convert provider-error HTML construction to ProviderErrorsError class - Escape API-returned values in renderTxDetails via textContent - Add restrictive CSP meta tag to index.html - Rebuild website and single-file artifacts - Regenerate SHA256SUMS --- cc-implementation/SHA256SUMS | 22 +- .../build-single-file/index.html | 97 +---- cc-implementation/build/pushtx.js | 93 +---- cc-implementation/index.html | 4 + cc-implementation/src/main.ts | 335 +++++++++++------- 5 files changed, 234 insertions(+), 317 deletions(-) diff --git a/cc-implementation/SHA256SUMS b/cc-implementation/SHA256SUMS index 76c16d1..7a53293 100644 --- a/cc-implementation/SHA256SUMS +++ b/cc-implementation/SHA256SUMS @@ -1,14 +1,14 @@ -b9baf7ada4b80d2878b52ab0cf56f878aeb774aec62de88b8b02a168be82cbb5 ./index.html -528961798b8f5db3f50d0770d3bc209fd71ae2c859c833696d7ac6106aa69ed1 ./build-single-file/index.html -2b915af9a34ce84b58a6e1f276c574ed2abbfc31c1e84ee94cfa858666d075c2 ./package-lock.json -0ae5bf24ae009f15406a324b68804f217feb526a54dd8258c921c0e881b47b7c ./package.json -68df121854e628c7d84ee41b7d86875626cc342aa0c8b0f939af322eb4ba1723 ./tsconfig.json -39c8001f6300c1ff63e29639a8b513fa888e61a58053a19716ed6df497a48ed8 ./build/index.html -18920c92e08b5fc0b0a5d7ee575f08eecc1e47b4f1e8d892e8f17540072aac35 ./build/pushtx.js -31ebc58b766680c1000cabd7b7da7eeb943aff58ebc805beba608e15ffc7a3f6 ./build/pushtx.css 2ede67555dd622a2be580b3e15fdde6463413f63e79913f54faa75d819a4cc01 ./vite.config.ts -2bdc9fe7c30746da1546442b83fb693357603f411df930e86c740f4ad79fc275 ./src/main.ts -b41fd5552c271453ce7ee1c661e72495705e5da0e005828b17f4ad057ba91e87 ./src/types.ts -65996936fbb042915f7b74a200fcdde7e410f32a669b1ab9597cfaa4b0faddb5 ./src/vite-env.d.ts +e5d5594f5d0a14fbe4b038073b9bc9d040343272a536c51c31612d3fb6fff5ac ./build-single-file/index.html +6a2a7a9a445429aedd06173bf65c9d31e30256f0680d499f6b7cdc18a32e550b ./index.html +8f16321bfc6b41c04c9c48d20b47cbd1cfac4b089a7b355ccbed371c59f8a096 ./src/main.ts 4e6dd4e5d1689110a3645a7ee5f82fac8ec32d4aad8c00d906be60f64ebca678 ./src/style.css +b41fd5552c271453ce7ee1c661e72495705e5da0e005828b17f4ad057ba91e87 ./src/types.ts 54cc1fff898ecd3f437d82947889bbcab5f861904e61c9c1eea9f792a3f32582 ./src/config.ts +65996936fbb042915f7b74a200fcdde7e410f32a669b1ab9597cfaa4b0faddb5 ./src/vite-env.d.ts +68df121854e628c7d84ee41b7d86875626cc342aa0c8b0f939af322eb4ba1723 ./tsconfig.json +2b915af9a34ce84b58a6e1f276c574ed2abbfc31c1e84ee94cfa858666d075c2 ./package-lock.json +31ebc58b766680c1000cabd7b7da7eeb943aff58ebc805beba608e15ffc7a3f6 ./build/pushtx.css +a02328217505d49c7fd0df58b7baf2d6a4c25d558d4952dc253c1d6bc0a97727 ./build/index.html +3f0fbf0710fb7e682f57bbf1e2a60ee42f0c0b25c68776506ca7999017e64db3 ./build/pushtx.js +0ae5bf24ae009f15406a324b68804f217feb526a54dd8258c921c0e881b47b7c ./package.json diff --git a/cc-implementation/build-single-file/index.html b/cc-implementation/build-single-file/index.html index eac699c..68247dd 100644 --- a/cc-implementation/build-single-file/index.html +++ b/cc-implementation/build-single-file/index.html @@ -4,19 +4,23 @@ + COLDCARD NFC Push TX - diff --git a/cc-implementation/build/pushtx.js b/cc-implementation/build/pushtx.js index 52d129e..e588a65 100644 --- a/cc-implementation/build/pushtx.js +++ b/cc-implementation/build/pushtx.js @@ -1,15 +1,15 @@ -var Ws=Object.defineProperty;var js=(e,t,r)=>t in e?Ws(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Zt=(e,t,r)=>js(e,typeof t!="symbol"?t+"":t,r);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))n(i);new MutationObserver(i=>{for(const c of i)if(c.type==="childList")for(const s of c.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&n(s)}).observe(document,{childList:!0,subtree:!0});function r(i){const c={};return i.integrity&&(c.integrity=i.integrity),i.referrerPolicy&&(c.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?c.credentials="include":i.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function n(i){if(i.ep)return;i.ep=!0;const c=r(i);fetch(i.href,c)}})();function Vs(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var r=function n(){return this instanceof n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}),r}var lo={},se={},Vr={};Vr.byteLength=qs;Vr.toByteArray=Ys;Vr.fromByteArray=Zs;var $e=[],Pe=[],Gs=typeof Uint8Array<"u"?Uint8Array:Array,wn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var Lt=0,Xs=wn.length;Lt0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");r===-1&&(r=t);var n=r===t?0:4-r%4;return[r,n]}function qs(e){var t=yo(e),r=t[0],n=t[1];return(r+n)*3/4-n}function zs(e,t,r){return(t+r)*3/4-r}function Ys(e){var t,r=yo(e),n=r[0],i=r[1],c=new Gs(zs(e,n,i)),s=0,a=i>0?n-4:n,p;for(p=0;p>16&255,c[s++]=t>>8&255,c[s++]=t&255;return i===2&&(t=Pe[e.charCodeAt(p)]<<2|Pe[e.charCodeAt(p+1)]>>4,c[s++]=t&255),i===1&&(t=Pe[e.charCodeAt(p)]<<10|Pe[e.charCodeAt(p+1)]<<4|Pe[e.charCodeAt(p+2)]>>2,c[s++]=t>>8&255,c[s++]=t&255),c}function Js(e){return $e[e>>18&63]+$e[e>>12&63]+$e[e>>6&63]+$e[e&63]}function Qs(e,t,r){for(var n,i=[],c=t;ca?a:s+c));return n===1?(t=e[r-1],i.push($e[t>>2]+$e[t<<4&63]+"==")):n===2&&(t=(e[r-2]<<8)+e[r-1],i.push($e[t>>10]+$e[t>>4&63]+$e[t<<2&63]+"=")),i.join("")}var Vn={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */Vn.read=function(e,t,r,n,i){var c,s,a=i*8-n-1,p=(1<>1,f=-7,d=r?i-1:0,S=r?-1:1,y=e[t+d];for(d+=S,c=y&(1<<-f)-1,y>>=-f,f+=a;f>0;c=c*256+e[t+d],d+=S,f-=8);for(s=c&(1<<-f)-1,c>>=-f,f+=n;f>0;s=s*256+e[t+d],d+=S,f-=8);if(c===0)c=1-w;else{if(c===p)return s?NaN:(y?-1:1)*(1/0);s=s+Math.pow(2,n),c=c-w}return(y?-1:1)*s*Math.pow(2,c-n)};Vn.write=function(e,t,r,n,i,c){var s,a,p,w=c*8-i-1,f=(1<>1,S=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,y=n?0:c-1,_=n?1:-1,T=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=f):(s=Math.floor(Math.log(t)/Math.LN2),t*(p=Math.pow(2,-s))<1&&(s--,p*=2),s+d>=1?t+=S/p:t+=S*Math.pow(2,1-d),t*p>=2&&(s++,p/=2),s+d>=f?(a=0,s=f):s+d>=1?(a=(t*p-1)*Math.pow(2,i),s=s+d):(a=t*Math.pow(2,d-1)*Math.pow(2,i),s=0));i>=8;e[r+y]=a&255,y+=_,a/=256,i-=8);for(s=s<0;e[r+y]=s&255,y+=_,s/=256,w-=8);e[r+y-_]|=T*128};/*! +var Gs=Object.defineProperty;var Xs=(e,t,r)=>t in e?Gs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Lt=(e,t,r)=>Xs(e,typeof t!="symbol"?t+"":t,r);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))n(i);new MutationObserver(i=>{for(const c of i)if(c.type==="childList")for(const s of c.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&n(s)}).observe(document,{childList:!0,subtree:!0});function r(i){const c={};return i.integrity&&(c.integrity=i.integrity),i.referrerPolicy&&(c.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?c.credentials="include":i.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function n(i){if(i.ep)return;i.ep=!0;const c=r(i);fetch(i.href,c)}})();function qs(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var r=function n(){return this instanceof n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}),r}var wo={},se={},Gr={};Gr.byteLength=Js;Gr.toByteArray=Zs;Gr.fromByteArray=rc;var Me=[],Oe=[],zs=typeof Uint8Array<"u"?Uint8Array:Array,gn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var Mt=0,Ys=gn.length;Mt0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");r===-1&&(r=t);var n=r===t?0:4-r%4;return[r,n]}function Js(e){var t=go(e),r=t[0],n=t[1];return(r+n)*3/4-n}function Qs(e,t,r){return(t+r)*3/4-r}function Zs(e){var t,r=go(e),n=r[0],i=r[1],c=new zs(Qs(e,n,i)),s=0,a=i>0?n-4:n,p;for(p=0;p>16&255,c[s++]=t>>8&255,c[s++]=t&255;return i===2&&(t=Oe[e.charCodeAt(p)]<<2|Oe[e.charCodeAt(p+1)]>>4,c[s++]=t&255),i===1&&(t=Oe[e.charCodeAt(p)]<<10|Oe[e.charCodeAt(p+1)]<<4|Oe[e.charCodeAt(p+2)]>>2,c[s++]=t>>8&255,c[s++]=t&255),c}function ec(e){return Me[e>>18&63]+Me[e>>12&63]+Me[e>>6&63]+Me[e&63]}function tc(e,t,r){for(var n,i=[],c=t;ca?a:s+c));return n===1?(t=e[r-1],i.push(Me[t>>2]+Me[t<<4&63]+"==")):n===2&&(t=(e[r-2]<<8)+e[r-1],i.push(Me[t>>10]+Me[t>>4&63]+Me[t<<2&63]+"=")),i.join("")}var Gn={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */Gn.read=function(e,t,r,n,i){var c,s,a=i*8-n-1,p=(1<>1,f=-7,d=r?i-1:0,E=r?-1:1,y=e[t+d];for(d+=E,c=y&(1<<-f)-1,y>>=-f,f+=a;f>0;c=c*256+e[t+d],d+=E,f-=8);for(s=c&(1<<-f)-1,c>>=-f,f+=n;f>0;s=s*256+e[t+d],d+=E,f-=8);if(c===0)c=1-w;else{if(c===p)return s?NaN:(y?-1:1)*(1/0);s=s+Math.pow(2,n),c=c-w}return(y?-1:1)*s*Math.pow(2,c-n)};Gn.write=function(e,t,r,n,i,c){var s,a,p,w=c*8-i-1,f=(1<>1,E=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,y=n?0:c-1,_=n?1:-1,T=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=f):(s=Math.floor(Math.log(t)/Math.LN2),t*(p=Math.pow(2,-s))<1&&(s--,p*=2),s+d>=1?t+=E/p:t+=E*Math.pow(2,1-d),t*p>=2&&(s++,p/=2),s+d>=f?(a=0,s=f):s+d>=1?(a=(t*p-1)*Math.pow(2,i),s=s+d):(a=t*Math.pow(2,d-1)*Math.pow(2,i),s=0));i>=8;e[r+y]=a&255,y+=_,a/=256,i-=8);for(s=s<0;e[r+y]=s&255,y+=_,s/=256,w-=8);e[r+y-_]|=T*128};/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT - */(function(e){const t=Vr,r=Vn,n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=f,e.SlowBuffer=v,e.INSPECT_MAX_BYTES=50;const i=2147483647;e.kMaxLength=i;const{Uint8Array:c,ArrayBuffer:s,SharedArrayBuffer:a}=globalThis;f.TYPED_ARRAY_SUPPORT=p(),!f.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function p(){try{const h=new c(1),o={foo:function(){return 42}};return Object.setPrototypeOf(o,c.prototype),Object.setPrototypeOf(h,o),h.foo()===42}catch{return!1}}Object.defineProperty(f.prototype,"parent",{enumerable:!0,get:function(){if(f.isBuffer(this))return this.buffer}}),Object.defineProperty(f.prototype,"offset",{enumerable:!0,get:function(){if(f.isBuffer(this))return this.byteOffset}});function w(h){if(h>i)throw new RangeError('The value "'+h+'" is invalid for option "size"');const o=new c(h);return Object.setPrototypeOf(o,f.prototype),o}function f(h,o,u){if(typeof h=="number"){if(typeof o=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return _(h)}return d(h,o,u)}f.poolSize=8192;function d(h,o,u){if(typeof h=="string")return T(h,o);if(s.isView(h))return x(h);if(h==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof h);if(Ue(h,s)||h&&Ue(h.buffer,s)||typeof a<"u"&&(Ue(h,a)||h&&Ue(h.buffer,a)))return N(h,o,u);if(typeof h=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const l=h.valueOf&&h.valueOf();if(l!=null&&l!==h)return f.from(l,o,u);const g=k(h);if(g)return g;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof h[Symbol.toPrimitive]=="function")return f.from(h[Symbol.toPrimitive]("string"),o,u);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof h)}f.from=function(h,o,u){return d(h,o,u)},Object.setPrototypeOf(f.prototype,c.prototype),Object.setPrototypeOf(f,c);function S(h){if(typeof h!="number")throw new TypeError('"size" argument must be of type number');if(h<0)throw new RangeError('The value "'+h+'" is invalid for option "size"')}function y(h,o,u){return S(h),h<=0?w(h):o!==void 0?typeof u=="string"?w(h).fill(o,u):w(h).fill(o):w(h)}f.alloc=function(h,o,u){return y(h,o,u)};function _(h){return S(h),w(h<0?0:m(h)|0)}f.allocUnsafe=function(h){return _(h)},f.allocUnsafeSlow=function(h){return _(h)};function T(h,o){if((typeof o!="string"||o==="")&&(o="utf8"),!f.isEncoding(o))throw new TypeError("Unknown encoding: "+o);const u=I(h,o)|0;let l=w(u);const g=l.write(h,o);return g!==u&&(l=l.slice(0,g)),l}function P(h){const o=h.length<0?0:m(h.length)|0,u=w(o);for(let l=0;l=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return h|0}function v(h){return+h!=h&&(h=0),f.alloc(+h)}f.isBuffer=function(o){return o!=null&&o._isBuffer===!0&&o!==f.prototype},f.compare=function(o,u){if(Ue(o,c)&&(o=f.from(o,o.offset,o.byteLength)),Ue(u,c)&&(u=f.from(u,u.offset,u.byteLength)),!f.isBuffer(o)||!f.isBuffer(u))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(o===u)return 0;let l=o.length,g=u.length;for(let b=0,A=Math.min(l,g);bg.length?(f.isBuffer(A)||(A=f.from(A)),A.copy(g,b)):c.prototype.set.call(g,A,b);else if(f.isBuffer(A))A.copy(g,b);else throw new TypeError('"list" argument must be an Array of Buffers');b+=A.length}return g};function I(h,o){if(f.isBuffer(h))return h.length;if(s.isView(h)||Ue(h,s))return h.byteLength;if(typeof h!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof h);const u=h.length,l=arguments.length>2&&arguments[2]===!0;if(!l&&u===0)return 0;let g=!1;for(;;)switch(o){case"ascii":case"latin1":case"binary":return u;case"utf8":case"utf-8":return dn(h).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return u*2;case"hex":return u>>>1;case"base64":return Ii(h).length;default:if(g)return l?-1:dn(h).length;o=(""+o).toLowerCase(),g=!0}}f.byteLength=I;function C(h,o,u){let l=!1;if((o===void 0||o<0)&&(o=0),o>this.length||((u===void 0||u>this.length)&&(u=this.length),u<=0)||(u>>>=0,o>>>=0,u<=o))return"";for(h||(h="utf8");;)switch(h){case"hex":return Cs(this,o,u);case"utf8":case"utf-8":return ye(this,o,u);case"ascii":return pn(this,o,u);case"latin1":case"binary":return Ns(this,o,u);case"base64":return ne(this,o,u);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Hs(this,o,u);default:if(l)throw new TypeError("Unknown encoding: "+h);h=(h+"").toLowerCase(),l=!0}}f.prototype._isBuffer=!0;function M(h,o,u){const l=h[o];h[o]=h[u],h[u]=l}f.prototype.swap16=function(){const o=this.length;if(o%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let u=0;uu&&(o+=" ... "),""},n&&(f.prototype[n]=f.prototype.inspect),f.prototype.compare=function(o,u,l,g,b){if(Ue(o,c)&&(o=f.from(o,o.offset,o.byteLength)),!f.isBuffer(o))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof o);if(u===void 0&&(u=0),l===void 0&&(l=o?o.length:0),g===void 0&&(g=0),b===void 0&&(b=this.length),u<0||l>o.length||g<0||b>this.length)throw new RangeError("out of range index");if(g>=b&&u>=l)return 0;if(g>=b)return-1;if(u>=l)return 1;if(u>>>=0,l>>>=0,g>>>=0,b>>>=0,this===o)return 0;let A=b-g,$=l-u;const Q=Math.min(A,$),z=this.slice(g,b),Z=o.slice(u,l);for(let V=0;V2147483647?u=2147483647:u<-2147483648&&(u=-2147483648),u=+u,yn(u)&&(u=g?0:h.length-1),u<0&&(u=h.length+u),u>=h.length){if(g)return-1;u=h.length-1}else if(u<0)if(g)u=0;else return-1;if(typeof o=="string"&&(o=f.from(o,l)),f.isBuffer(o))return o.length===0?-1:R(h,o,u,l,g);if(typeof o=="number")return o=o&255,typeof c.prototype.indexOf=="function"?g?c.prototype.indexOf.call(h,o,u):c.prototype.lastIndexOf.call(h,o,u):R(h,[o],u,l,g);throw new TypeError("val must be string, number or Buffer")}function R(h,o,u,l,g){let b=1,A=h.length,$=o.length;if(l!==void 0&&(l=String(l).toLowerCase(),l==="ucs2"||l==="ucs-2"||l==="utf16le"||l==="utf-16le")){if(h.length<2||o.length<2)return-1;b=2,A/=2,$/=2,u/=2}function Q(Z,V){return b===1?Z[V]:Z.readUInt16BE(V*b)}let z;if(g){let Z=-1;for(z=u;zA&&(u=A-$),z=u;z>=0;z--){let Z=!0;for(let V=0;V<$;V++)if(Q(h,z+V)!==Q(o,V)){Z=!1;break}if(Z)return z}return-1}f.prototype.includes=function(o,u,l){return this.indexOf(o,u,l)!==-1},f.prototype.indexOf=function(o,u,l){return B(this,o,u,l,!0)},f.prototype.lastIndexOf=function(o,u,l){return B(this,o,u,l,!1)};function j(h,o,u,l){u=Number(u)||0;const g=h.length-u;l?(l=Number(l),l>g&&(l=g)):l=g;const b=o.length;l>b/2&&(l=b/2);let A;for(A=0;A>>0,isFinite(l)?(l=l>>>0,g===void 0&&(g="utf8")):(g=l,l=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const b=this.length-u;if((l===void 0||l>b)&&(l=b),o.length>0&&(l<0||u<0)||u>this.length)throw new RangeError("Attempt to write outside buffer bounds");g||(g="utf8");let A=!1;for(;;)switch(g){case"hex":return j(this,o,u,l);case"utf8":case"utf-8":return O(this,o,u,l);case"ascii":case"latin1":case"binary":return U(this,o,u,l);case"base64":return F(this,o,u,l);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return D(this,o,u,l);default:if(A)throw new TypeError("Unknown encoding: "+g);g=(""+g).toLowerCase(),A=!0}},f.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function ne(h,o,u){return o===0&&u===h.length?t.fromByteArray(h):t.fromByteArray(h.slice(o,u))}function ye(h,o,u){u=Math.min(h.length,u);const l=[];let g=o;for(;g239?4:b>223?3:b>191?2:1;if(g+$<=u){let Q,z,Z,V;switch($){case 1:b<128&&(A=b);break;case 2:Q=h[g+1],(Q&192)===128&&(V=(b&31)<<6|Q&63,V>127&&(A=V));break;case 3:Q=h[g+1],z=h[g+2],(Q&192)===128&&(z&192)===128&&(V=(b&15)<<12|(Q&63)<<6|z&63,V>2047&&(V<55296||V>57343)&&(A=V));break;case 4:Q=h[g+1],z=h[g+2],Z=h[g+3],(Q&192)===128&&(z&192)===128&&(Z&192)===128&&(V=(b&15)<<18|(Q&63)<<12|(z&63)<<6|Z&63,V>65535&&V<1114112&&(A=V))}}A===null?(A=65533,$=1):A>65535&&(A-=65536,l.push(A>>>10&1023|55296),A=56320|A&1023),l.push(A),g+=$}return br(l)}const Jt=4096;function br(h){const o=h.length;if(o<=Jt)return String.fromCharCode.apply(String,h);let u="",l=0;for(;ll)&&(u=l);let g="";for(let b=o;bl&&(o=l),u<0?(u+=l,u<0&&(u=0)):u>l&&(u=l),uu)throw new RangeError("Trying to access beyond buffer length")}f.prototype.readUintLE=f.prototype.readUIntLE=function(o,u,l){o=o>>>0,u=u>>>0,l||ce(o,u,this.length);let g=this[o],b=1,A=0;for(;++A>>0,u=u>>>0,l||ce(o,u,this.length);let g=this[o+--u],b=1;for(;u>0&&(b*=256);)g+=this[o+--u]*b;return g},f.prototype.readUint8=f.prototype.readUInt8=function(o,u){return o=o>>>0,u||ce(o,1,this.length),this[o]},f.prototype.readUint16LE=f.prototype.readUInt16LE=function(o,u){return o=o>>>0,u||ce(o,2,this.length),this[o]|this[o+1]<<8},f.prototype.readUint16BE=f.prototype.readUInt16BE=function(o,u){return o=o>>>0,u||ce(o,2,this.length),this[o]<<8|this[o+1]},f.prototype.readUint32LE=f.prototype.readUInt32LE=function(o,u){return o=o>>>0,u||ce(o,4,this.length),(this[o]|this[o+1]<<8|this[o+2]<<16)+this[o+3]*16777216},f.prototype.readUint32BE=f.prototype.readUInt32BE=function(o,u){return o=o>>>0,u||ce(o,4,this.length),this[o]*16777216+(this[o+1]<<16|this[o+2]<<8|this[o+3])},f.prototype.readBigUInt64LE=Ze(function(o){o=o>>>0,Ft(o,"offset");const u=this[o],l=this[o+7];(u===void 0||l===void 0)&&Qt(o,this.length-8);const g=u+this[++o]*2**8+this[++o]*2**16+this[++o]*2**24,b=this[++o]+this[++o]*2**8+this[++o]*2**16+l*2**24;return BigInt(g)+(BigInt(b)<>>0,Ft(o,"offset");const u=this[o],l=this[o+7];(u===void 0||l===void 0)&&Qt(o,this.length-8);const g=u*2**24+this[++o]*2**16+this[++o]*2**8+this[++o],b=this[++o]*2**24+this[++o]*2**16+this[++o]*2**8+l;return(BigInt(g)<>>0,u=u>>>0,l||ce(o,u,this.length);let g=this[o],b=1,A=0;for(;++A=b&&(g-=Math.pow(2,8*u)),g},f.prototype.readIntBE=function(o,u,l){o=o>>>0,u=u>>>0,l||ce(o,u,this.length);let g=u,b=1,A=this[o+--g];for(;g>0&&(b*=256);)A+=this[o+--g]*b;return b*=128,A>=b&&(A-=Math.pow(2,8*u)),A},f.prototype.readInt8=function(o,u){return o=o>>>0,u||ce(o,1,this.length),this[o]&128?(255-this[o]+1)*-1:this[o]},f.prototype.readInt16LE=function(o,u){o=o>>>0,u||ce(o,2,this.length);const l=this[o]|this[o+1]<<8;return l&32768?l|4294901760:l},f.prototype.readInt16BE=function(o,u){o=o>>>0,u||ce(o,2,this.length);const l=this[o+1]|this[o]<<8;return l&32768?l|4294901760:l},f.prototype.readInt32LE=function(o,u){return o=o>>>0,u||ce(o,4,this.length),this[o]|this[o+1]<<8|this[o+2]<<16|this[o+3]<<24},f.prototype.readInt32BE=function(o,u){return o=o>>>0,u||ce(o,4,this.length),this[o]<<24|this[o+1]<<16|this[o+2]<<8|this[o+3]},f.prototype.readBigInt64LE=Ze(function(o){o=o>>>0,Ft(o,"offset");const u=this[o],l=this[o+7];(u===void 0||l===void 0)&&Qt(o,this.length-8);const g=this[o+4]+this[o+5]*2**8+this[o+6]*2**16+(l<<24);return(BigInt(g)<>>0,Ft(o,"offset");const u=this[o],l=this[o+7];(u===void 0||l===void 0)&&Qt(o,this.length-8);const g=(u<<24)+this[++o]*2**16+this[++o]*2**8+this[++o];return(BigInt(g)<>>0,u||ce(o,4,this.length),r.read(this,o,!0,23,4)},f.prototype.readFloatBE=function(o,u){return o=o>>>0,u||ce(o,4,this.length),r.read(this,o,!1,23,4)},f.prototype.readDoubleLE=function(o,u){return o=o>>>0,u||ce(o,8,this.length),r.read(this,o,!0,52,8)},f.prototype.readDoubleBE=function(o,u){return o=o>>>0,u||ce(o,8,this.length),r.read(this,o,!1,52,8)};function Te(h,o,u,l,g,b){if(!f.isBuffer(h))throw new TypeError('"buffer" argument must be a Buffer instance');if(o>g||oh.length)throw new RangeError("Index out of range")}f.prototype.writeUintLE=f.prototype.writeUIntLE=function(o,u,l,g){if(o=+o,u=u>>>0,l=l>>>0,!g){const $=Math.pow(2,8*l)-1;Te(this,o,u,l,$,0)}let b=1,A=0;for(this[u]=o&255;++A>>0,l=l>>>0,!g){const $=Math.pow(2,8*l)-1;Te(this,o,u,l,$,0)}let b=l-1,A=1;for(this[u+b]=o&255;--b>=0&&(A*=256);)this[u+b]=o/A&255;return u+l},f.prototype.writeUint8=f.prototype.writeUInt8=function(o,u,l){return o=+o,u=u>>>0,l||Te(this,o,u,1,255,0),this[u]=o&255,u+1},f.prototype.writeUint16LE=f.prototype.writeUInt16LE=function(o,u,l){return o=+o,u=u>>>0,l||Te(this,o,u,2,65535,0),this[u]=o&255,this[u+1]=o>>>8,u+2},f.prototype.writeUint16BE=f.prototype.writeUInt16BE=function(o,u,l){return o=+o,u=u>>>0,l||Te(this,o,u,2,65535,0),this[u]=o>>>8,this[u+1]=o&255,u+2},f.prototype.writeUint32LE=f.prototype.writeUInt32LE=function(o,u,l){return o=+o,u=u>>>0,l||Te(this,o,u,4,4294967295,0),this[u+3]=o>>>24,this[u+2]=o>>>16,this[u+1]=o>>>8,this[u]=o&255,u+4},f.prototype.writeUint32BE=f.prototype.writeUInt32BE=function(o,u,l){return o=+o,u=u>>>0,l||Te(this,o,u,4,4294967295,0),this[u]=o>>>24,this[u+1]=o>>>16,this[u+2]=o>>>8,this[u+3]=o&255,u+4};function gi(h,o,u,l,g){Ti(o,l,g,h,u,7);let b=Number(o&BigInt(4294967295));h[u++]=b,b=b>>8,h[u++]=b,b=b>>8,h[u++]=b,b=b>>8,h[u++]=b;let A=Number(o>>BigInt(32)&BigInt(4294967295));return h[u++]=A,A=A>>8,h[u++]=A,A=A>>8,h[u++]=A,A=A>>8,h[u++]=A,u}function Ei(h,o,u,l,g){Ti(o,l,g,h,u,7);let b=Number(o&BigInt(4294967295));h[u+7]=b,b=b>>8,h[u+6]=b,b=b>>8,h[u+5]=b,b=b>>8,h[u+4]=b;let A=Number(o>>BigInt(32)&BigInt(4294967295));return h[u+3]=A,A=A>>8,h[u+2]=A,A=A>>8,h[u+1]=A,A=A>>8,h[u]=A,u+8}f.prototype.writeBigUInt64LE=Ze(function(o,u=0){return gi(this,o,u,BigInt(0),BigInt("0xffffffffffffffff"))}),f.prototype.writeBigUInt64BE=Ze(function(o,u=0){return Ei(this,o,u,BigInt(0),BigInt("0xffffffffffffffff"))}),f.prototype.writeIntLE=function(o,u,l,g){if(o=+o,u=u>>>0,!g){const Q=Math.pow(2,8*l-1);Te(this,o,u,l,Q-1,-Q)}let b=0,A=1,$=0;for(this[u]=o&255;++b>0)-$&255;return u+l},f.prototype.writeIntBE=function(o,u,l,g){if(o=+o,u=u>>>0,!g){const Q=Math.pow(2,8*l-1);Te(this,o,u,l,Q-1,-Q)}let b=l-1,A=1,$=0;for(this[u+b]=o&255;--b>=0&&(A*=256);)o<0&&$===0&&this[u+b+1]!==0&&($=1),this[u+b]=(o/A>>0)-$&255;return u+l},f.prototype.writeInt8=function(o,u,l){return o=+o,u=u>>>0,l||Te(this,o,u,1,127,-128),o<0&&(o=255+o+1),this[u]=o&255,u+1},f.prototype.writeInt16LE=function(o,u,l){return o=+o,u=u>>>0,l||Te(this,o,u,2,32767,-32768),this[u]=o&255,this[u+1]=o>>>8,u+2},f.prototype.writeInt16BE=function(o,u,l){return o=+o,u=u>>>0,l||Te(this,o,u,2,32767,-32768),this[u]=o>>>8,this[u+1]=o&255,u+2},f.prototype.writeInt32LE=function(o,u,l){return o=+o,u=u>>>0,l||Te(this,o,u,4,2147483647,-2147483648),this[u]=o&255,this[u+1]=o>>>8,this[u+2]=o>>>16,this[u+3]=o>>>24,u+4},f.prototype.writeInt32BE=function(o,u,l){return o=+o,u=u>>>0,l||Te(this,o,u,4,2147483647,-2147483648),o<0&&(o=4294967295+o+1),this[u]=o>>>24,this[u+1]=o>>>16,this[u+2]=o>>>8,this[u+3]=o&255,u+4},f.prototype.writeBigInt64LE=Ze(function(o,u=0){return gi(this,o,u,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),f.prototype.writeBigInt64BE=Ze(function(o,u=0){return Ei(this,o,u,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function mi(h,o,u,l,g,b){if(u+l>h.length)throw new RangeError("Index out of range");if(u<0)throw new RangeError("Index out of range")}function Si(h,o,u,l,g){return o=+o,u=u>>>0,g||mi(h,o,u,4),r.write(h,o,u,l,23,4),u+4}f.prototype.writeFloatLE=function(o,u,l){return Si(this,o,u,!0,l)},f.prototype.writeFloatBE=function(o,u,l){return Si(this,o,u,!1,l)};function bi(h,o,u,l,g){return o=+o,u=u>>>0,g||mi(h,o,u,8),r.write(h,o,u,l,52,8),u+8}f.prototype.writeDoubleLE=function(o,u,l){return bi(this,o,u,!0,l)},f.prototype.writeDoubleBE=function(o,u,l){return bi(this,o,u,!1,l)},f.prototype.copy=function(o,u,l,g){if(!f.isBuffer(o))throw new TypeError("argument should be a Buffer");if(l||(l=0),!g&&g!==0&&(g=this.length),u>=o.length&&(u=o.length),u||(u=0),g>0&&g=this.length)throw new RangeError("Index out of range");if(g<0)throw new RangeError("sourceEnd out of bounds");g>this.length&&(g=this.length),o.length-u>>0,l=l===void 0?this.length:l>>>0,o||(o=0);let b;if(typeof o=="number")for(b=u;b2**32?g=_i(String(u)):typeof u=="bigint"&&(g=String(u),(u>BigInt(2)**BigInt(32)||u<-(BigInt(2)**BigInt(32)))&&(g=_i(g)),g+="n"),l+=` It must be ${o}. Received ${g}`,l},RangeError);function _i(h){let o="",u=h.length;const l=h[0]==="-"?1:0;for(;u>=l+4;u-=3)o=`_${h.slice(u-3,u)}${o}`;return`${h.slice(0,u)}${o}`}function Rs(h,o,u){Ft(o,"offset"),(h[o]===void 0||h[o+u]===void 0)&&Qt(o,h.length-(u+1))}function Ti(h,o,u,l,g,b){if(h>u||h= 0${A} and < 2${A} ** ${(b+1)*8}${A}`:$=`>= -(2${A} ** ${(b+1)*8-1}${A}) and < 2 ** ${(b+1)*8-1}${A}`,new Rt.ERR_OUT_OF_RANGE("value",$,h)}Rs(l,g,b)}function Ft(h,o){if(typeof h!="number")throw new Rt.ERR_INVALID_ARG_TYPE(o,"number",h)}function Qt(h,o,u){throw Math.floor(h)!==h?(Ft(h,u),new Rt.ERR_OUT_OF_RANGE("offset","an integer",h)):o<0?new Rt.ERR_BUFFER_OUT_OF_BOUNDS:new Rt.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${o}`,h)}const Fs=/[^+/0-9A-Za-z-_]/g;function Ls(h){if(h=h.split("=")[0],h=h.trim().replace(Fs,""),h.length<2)return"";for(;h.length%4!==0;)h=h+"=";return h}function dn(h,o){o=o||1/0;let u;const l=h.length;let g=null;const b=[];for(let A=0;A55295&&u<57344){if(!g){if(u>56319){(o-=3)>-1&&b.push(239,191,189);continue}else if(A+1===l){(o-=3)>-1&&b.push(239,191,189);continue}g=u;continue}if(u<56320){(o-=3)>-1&&b.push(239,191,189),g=u;continue}u=(g-55296<<10|u-56320)+65536}else g&&(o-=3)>-1&&b.push(239,191,189);if(g=null,u<128){if((o-=1)<0)break;b.push(u)}else if(u<2048){if((o-=2)<0)break;b.push(u>>6|192,u&63|128)}else if(u<65536){if((o-=3)<0)break;b.push(u>>12|224,u>>6&63|128,u&63|128)}else if(u<1114112){if((o-=4)<0)break;b.push(u>>18|240,u>>12&63|128,u>>6&63|128,u&63|128)}else throw new Error("Invalid code point")}return b}function $s(h){const o=[];for(let u=0;u>8,g=u%256,b.push(g),b.push(l);return b}function Ii(h){return t.toByteArray(Ls(h))}function _r(h,o,u,l){let g;for(g=0;g=o.length||g>=h.length);++g)o[g+u]=h[g];return g}function Ue(h,o){return h instanceof o||h!=null&&h.constructor!=null&&h.constructor.name!=null&&h.constructor.name===o.name}function yn(h){return h!==h}const Ks=function(){const h="0123456789abcdef",o=new Array(256);for(let u=0;u<16;++u){const l=u*16;for(let g=0;g<16;++g)o[l+g]=h[u]+h[g]}return o}();function Ze(h){return typeof BigInt>"u"?Ds:h}function Ds(){throw new Error("BigInt not supported")}})(se);const E=se.Buffer,ec=se.Blob,tc=se.BlobOptions,wo=se.Buffer,rc=se.File,nc=se.FileOptions,ic=se.INSPECT_MAX_BYTES,oc=se.SlowBuffer,sc=se.TranscodeEncoding,cc=se.atob,uc=se.btoa,ac=se.constants,fc=se.isAscii,hc=se.isUtf8,pc=se.kMaxLength,lc=se.kStringMaxLength,dc=se.resolveObjectURL,yc=se.transcode,wc=Object.freeze(Object.defineProperty({__proto__:null,Blob:ec,BlobOptions:tc,Buffer:wo,File:rc,FileOptions:nc,INSPECT_MAX_BYTES:ic,SlowBuffer:oc,TranscodeEncoding:sc,atob:cc,btoa:uc,constants:ac,default:E,isAscii:fc,isUtf8:hc,kMaxLength:pc,kStringMaxLength:lc,resolveObjectURL:dc,transcode:yc},Symbol.toStringTag,{value:"Module"}));var ge={},ae={};Object.defineProperty(ae,"__esModule",{value:!0});ae.testnet=ae.regtest=ae.bitcoin=void 0;ae.bitcoin={messagePrefix:`Bitcoin Signed Message: + */(function(e){const t=Gr,r=Gn,n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=f,e.SlowBuffer=v,e.INSPECT_MAX_BYTES=50;const i=2147483647;e.kMaxLength=i;const{Uint8Array:c,ArrayBuffer:s,SharedArrayBuffer:a}=globalThis;f.TYPED_ARRAY_SUPPORT=p(),!f.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function p(){try{const h=new c(1),o={foo:function(){return 42}};return Object.setPrototypeOf(o,c.prototype),Object.setPrototypeOf(h,o),h.foo()===42}catch{return!1}}Object.defineProperty(f.prototype,"parent",{enumerable:!0,get:function(){if(f.isBuffer(this))return this.buffer}}),Object.defineProperty(f.prototype,"offset",{enumerable:!0,get:function(){if(f.isBuffer(this))return this.byteOffset}});function w(h){if(h>i)throw new RangeError('The value "'+h+'" is invalid for option "size"');const o=new c(h);return Object.setPrototypeOf(o,f.prototype),o}function f(h,o,u){if(typeof h=="number"){if(typeof o=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return _(h)}return d(h,o,u)}f.poolSize=8192;function d(h,o,u){if(typeof h=="string")return T(h,o);if(s.isView(h))return x(h);if(h==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof h);if(Ue(h,s)||h&&Ue(h.buffer,s)||typeof a<"u"&&(Ue(h,a)||h&&Ue(h.buffer,a)))return U(h,o,u);if(typeof h=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const l=h.valueOf&&h.valueOf();if(l!=null&&l!==h)return f.from(l,o,u);const g=I(h);if(g)return g;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof h[Symbol.toPrimitive]=="function")return f.from(h[Symbol.toPrimitive]("string"),o,u);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof h)}f.from=function(h,o,u){return d(h,o,u)},Object.setPrototypeOf(f.prototype,c.prototype),Object.setPrototypeOf(f,c);function E(h){if(typeof h!="number")throw new TypeError('"size" argument must be of type number');if(h<0)throw new RangeError('The value "'+h+'" is invalid for option "size"')}function y(h,o,u){return E(h),h<=0?w(h):o!==void 0?typeof u=="string"?w(h).fill(o,u):w(h).fill(o):w(h)}f.alloc=function(h,o,u){return y(h,o,u)};function _(h){return E(h),w(h<0?0:S(h)|0)}f.allocUnsafe=function(h){return _(h)},f.allocUnsafeSlow=function(h){return _(h)};function T(h,o){if((typeof o!="string"||o==="")&&(o="utf8"),!f.isEncoding(o))throw new TypeError("Unknown encoding: "+o);const u=k(h,o)|0;let l=w(u);const g=l.write(h,o);return g!==u&&(l=l.slice(0,g)),l}function A(h){const o=h.length<0?0:S(h.length)|0,u=w(o);for(let l=0;l=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return h|0}function v(h){return+h!=h&&(h=0),f.alloc(+h)}f.isBuffer=function(o){return o!=null&&o._isBuffer===!0&&o!==f.prototype},f.compare=function(o,u){if(Ue(o,c)&&(o=f.from(o,o.offset,o.byteLength)),Ue(u,c)&&(u=f.from(u,u.offset,u.byteLength)),!f.isBuffer(o)||!f.isBuffer(u))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(o===u)return 0;let l=o.length,g=u.length;for(let b=0,P=Math.min(l,g);bg.length?(f.isBuffer(P)||(P=f.from(P)),P.copy(g,b)):c.prototype.set.call(g,P,b);else if(f.isBuffer(P))P.copy(g,b);else throw new TypeError('"list" argument must be an Array of Buffers');b+=P.length}return g};function k(h,o){if(f.isBuffer(h))return h.length;if(s.isView(h)||Ue(h,s))return h.byteLength;if(typeof h!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof h);const u=h.length,l=arguments.length>2&&arguments[2]===!0;if(!l&&u===0)return 0;let g=!1;for(;;)switch(o){case"ascii":case"latin1":case"binary":return u;case"utf8":case"utf-8":return yn(h).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return u*2;case"hex":return u>>>1;case"base64":return ki(h).length;default:if(g)return l?-1:yn(h).length;o=(""+o).toLowerCase(),g=!0}}f.byteLength=k;function N(h,o,u){let l=!1;if((o===void 0||o<0)&&(o=0),o>this.length||((u===void 0||u>this.length)&&(u=this.length),u<=0)||(u>>>=0,o>>>=0,u<=o))return"";for(h||(h="utf8");;)switch(h){case"hex":return Fs(this,o,u);case"utf8":case"utf-8":return ye(this,o,u);case"ascii":return ln(this,o,u);case"latin1":case"binary":return Rs(this,o,u);case"base64":return ne(this,o,u);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ls(this,o,u);default:if(l)throw new TypeError("Unknown encoding: "+h);h=(h+"").toLowerCase(),l=!0}}f.prototype._isBuffer=!0;function $(h,o,u){const l=h[o];h[o]=h[u],h[u]=l}f.prototype.swap16=function(){const o=this.length;if(o%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let u=0;uu&&(o+=" ... "),""},n&&(f.prototype[n]=f.prototype.inspect),f.prototype.compare=function(o,u,l,g,b){if(Ue(o,c)&&(o=f.from(o,o.offset,o.byteLength)),!f.isBuffer(o))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof o);if(u===void 0&&(u=0),l===void 0&&(l=o?o.length:0),g===void 0&&(g=0),b===void 0&&(b=this.length),u<0||l>o.length||g<0||b>this.length)throw new RangeError("out of range index");if(g>=b&&u>=l)return 0;if(g>=b)return-1;if(u>=l)return 1;if(u>>>=0,l>>>=0,g>>>=0,b>>>=0,this===o)return 0;let P=b-g,M=l-u;const Q=Math.min(P,M),z=this.slice(g,b),Z=o.slice(u,l);for(let V=0;V2147483647?u=2147483647:u<-2147483648&&(u=-2147483648),u=+u,wn(u)&&(u=g?0:h.length-1),u<0&&(u=h.length+u),u>=h.length){if(g)return-1;u=h.length-1}else if(u<0)if(g)u=0;else return-1;if(typeof o=="string"&&(o=f.from(o,l)),f.isBuffer(o))return o.length===0?-1:R(h,o,u,l,g);if(typeof o=="number")return o=o&255,typeof c.prototype.indexOf=="function"?g?c.prototype.indexOf.call(h,o,u):c.prototype.lastIndexOf.call(h,o,u):R(h,[o],u,l,g);throw new TypeError("val must be string, number or Buffer")}function R(h,o,u,l,g){let b=1,P=h.length,M=o.length;if(l!==void 0&&(l=String(l).toLowerCase(),l==="ucs2"||l==="ucs-2"||l==="utf16le"||l==="utf-16le")){if(h.length<2||o.length<2)return-1;b=2,P/=2,M/=2,u/=2}function Q(Z,V){return b===1?Z[V]:Z.readUInt16BE(V*b)}let z;if(g){let Z=-1;for(z=u;zP&&(u=P-M),z=u;z>=0;z--){let Z=!0;for(let V=0;Vg&&(l=g)):l=g;const b=o.length;l>b/2&&(l=b/2);let P;for(P=0;P>>0,isFinite(l)?(l=l>>>0,g===void 0&&(g="utf8")):(g=l,l=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const b=this.length-u;if((l===void 0||l>b)&&(l=b),o.length>0&&(l<0||u<0)||u>this.length)throw new RangeError("Attempt to write outside buffer bounds");g||(g="utf8");let P=!1;for(;;)switch(g){case"hex":return j(this,o,u,l);case"utf8":case"utf-8":return O(this,o,u,l);case"ascii":case"latin1":case"binary":return C(this,o,u,l);case"base64":return F(this,o,u,l);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return D(this,o,u,l);default:if(P)throw new TypeError("Unknown encoding: "+g);g=(""+g).toLowerCase(),P=!0}},f.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function ne(h,o,u){return o===0&&u===h.length?t.fromByteArray(h):t.fromByteArray(h.slice(o,u))}function ye(h,o,u){u=Math.min(h.length,u);const l=[];let g=o;for(;g239?4:b>223?3:b>191?2:1;if(g+M<=u){let Q,z,Z,V;switch(M){case 1:b<128&&(P=b);break;case 2:Q=h[g+1],(Q&192)===128&&(V=(b&31)<<6|Q&63,V>127&&(P=V));break;case 3:Q=h[g+1],z=h[g+2],(Q&192)===128&&(z&192)===128&&(V=(b&15)<<12|(Q&63)<<6|z&63,V>2047&&(V<55296||V>57343)&&(P=V));break;case 4:Q=h[g+1],z=h[g+2],Z=h[g+3],(Q&192)===128&&(z&192)===128&&(Z&192)===128&&(V=(b&15)<<18|(Q&63)<<12|(z&63)<<6|Z&63,V>65535&&V<1114112&&(P=V))}}P===null?(P=65533,M=1):P>65535&&(P-=65536,l.push(P>>>10&1023|55296),P=56320|P&1023),l.push(P),g+=M}return Sr(l)}const Jt=4096;function Sr(h){const o=h.length;if(o<=Jt)return String.fromCharCode.apply(String,h);let u="",l=0;for(;ll)&&(u=l);let g="";for(let b=o;bl&&(o=l),u<0?(u+=l,u<0&&(u=0)):u>l&&(u=l),uu)throw new RangeError("Trying to access beyond buffer length")}f.prototype.readUintLE=f.prototype.readUIntLE=function(o,u,l){o=o>>>0,u=u>>>0,l||ce(o,u,this.length);let g=this[o],b=1,P=0;for(;++P>>0,u=u>>>0,l||ce(o,u,this.length);let g=this[o+--u],b=1;for(;u>0&&(b*=256);)g+=this[o+--u]*b;return g},f.prototype.readUint8=f.prototype.readUInt8=function(o,u){return o=o>>>0,u||ce(o,1,this.length),this[o]},f.prototype.readUint16LE=f.prototype.readUInt16LE=function(o,u){return o=o>>>0,u||ce(o,2,this.length),this[o]|this[o+1]<<8},f.prototype.readUint16BE=f.prototype.readUInt16BE=function(o,u){return o=o>>>0,u||ce(o,2,this.length),this[o]<<8|this[o+1]},f.prototype.readUint32LE=f.prototype.readUInt32LE=function(o,u){return o=o>>>0,u||ce(o,4,this.length),(this[o]|this[o+1]<<8|this[o+2]<<16)+this[o+3]*16777216},f.prototype.readUint32BE=f.prototype.readUInt32BE=function(o,u){return o=o>>>0,u||ce(o,4,this.length),this[o]*16777216+(this[o+1]<<16|this[o+2]<<8|this[o+3])},f.prototype.readBigUInt64LE=Ze(function(o){o=o>>>0,Ft(o,"offset");const u=this[o],l=this[o+7];(u===void 0||l===void 0)&&Qt(o,this.length-8);const g=u+this[++o]*2**8+this[++o]*2**16+this[++o]*2**24,b=this[++o]+this[++o]*2**8+this[++o]*2**16+l*2**24;return BigInt(g)+(BigInt(b)<>>0,Ft(o,"offset");const u=this[o],l=this[o+7];(u===void 0||l===void 0)&&Qt(o,this.length-8);const g=u*2**24+this[++o]*2**16+this[++o]*2**8+this[++o],b=this[++o]*2**24+this[++o]*2**16+this[++o]*2**8+l;return(BigInt(g)<>>0,u=u>>>0,l||ce(o,u,this.length);let g=this[o],b=1,P=0;for(;++P=b&&(g-=Math.pow(2,8*u)),g},f.prototype.readIntBE=function(o,u,l){o=o>>>0,u=u>>>0,l||ce(o,u,this.length);let g=u,b=1,P=this[o+--g];for(;g>0&&(b*=256);)P+=this[o+--g]*b;return b*=128,P>=b&&(P-=Math.pow(2,8*u)),P},f.prototype.readInt8=function(o,u){return o=o>>>0,u||ce(o,1,this.length),this[o]&128?(255-this[o]+1)*-1:this[o]},f.prototype.readInt16LE=function(o,u){o=o>>>0,u||ce(o,2,this.length);const l=this[o]|this[o+1]<<8;return l&32768?l|4294901760:l},f.prototype.readInt16BE=function(o,u){o=o>>>0,u||ce(o,2,this.length);const l=this[o+1]|this[o]<<8;return l&32768?l|4294901760:l},f.prototype.readInt32LE=function(o,u){return o=o>>>0,u||ce(o,4,this.length),this[o]|this[o+1]<<8|this[o+2]<<16|this[o+3]<<24},f.prototype.readInt32BE=function(o,u){return o=o>>>0,u||ce(o,4,this.length),this[o]<<24|this[o+1]<<16|this[o+2]<<8|this[o+3]},f.prototype.readBigInt64LE=Ze(function(o){o=o>>>0,Ft(o,"offset");const u=this[o],l=this[o+7];(u===void 0||l===void 0)&&Qt(o,this.length-8);const g=this[o+4]+this[o+5]*2**8+this[o+6]*2**16+(l<<24);return(BigInt(g)<>>0,Ft(o,"offset");const u=this[o],l=this[o+7];(u===void 0||l===void 0)&&Qt(o,this.length-8);const g=(u<<24)+this[++o]*2**16+this[++o]*2**8+this[++o];return(BigInt(g)<>>0,u||ce(o,4,this.length),r.read(this,o,!0,23,4)},f.prototype.readFloatBE=function(o,u){return o=o>>>0,u||ce(o,4,this.length),r.read(this,o,!1,23,4)},f.prototype.readDoubleLE=function(o,u){return o=o>>>0,u||ce(o,8,this.length),r.read(this,o,!0,52,8)},f.prototype.readDoubleBE=function(o,u){return o=o>>>0,u||ce(o,8,this.length),r.read(this,o,!1,52,8)};function Te(h,o,u,l,g,b){if(!f.isBuffer(h))throw new TypeError('"buffer" argument must be a Buffer instance');if(o>g||oh.length)throw new RangeError("Index out of range")}f.prototype.writeUintLE=f.prototype.writeUIntLE=function(o,u,l,g){if(o=+o,u=u>>>0,l=l>>>0,!g){const M=Math.pow(2,8*l)-1;Te(this,o,u,l,M,0)}let b=1,P=0;for(this[u]=o&255;++P>>0,l=l>>>0,!g){const M=Math.pow(2,8*l)-1;Te(this,o,u,l,M,0)}let b=l-1,P=1;for(this[u+b]=o&255;--b>=0&&(P*=256);)this[u+b]=o/P&255;return u+l},f.prototype.writeUint8=f.prototype.writeUInt8=function(o,u,l){return o=+o,u=u>>>0,l||Te(this,o,u,1,255,0),this[u]=o&255,u+1},f.prototype.writeUint16LE=f.prototype.writeUInt16LE=function(o,u,l){return o=+o,u=u>>>0,l||Te(this,o,u,2,65535,0),this[u]=o&255,this[u+1]=o>>>8,u+2},f.prototype.writeUint16BE=f.prototype.writeUInt16BE=function(o,u,l){return o=+o,u=u>>>0,l||Te(this,o,u,2,65535,0),this[u]=o>>>8,this[u+1]=o&255,u+2},f.prototype.writeUint32LE=f.prototype.writeUInt32LE=function(o,u,l){return o=+o,u=u>>>0,l||Te(this,o,u,4,4294967295,0),this[u+3]=o>>>24,this[u+2]=o>>>16,this[u+1]=o>>>8,this[u]=o&255,u+4},f.prototype.writeUint32BE=f.prototype.writeUInt32BE=function(o,u,l){return o=+o,u=u>>>0,l||Te(this,o,u,4,4294967295,0),this[u]=o>>>24,this[u+1]=o>>>16,this[u+2]=o>>>8,this[u+3]=o&255,u+4};function mi(h,o,u,l,g){Ii(o,l,g,h,u,7);let b=Number(o&BigInt(4294967295));h[u++]=b,b=b>>8,h[u++]=b,b=b>>8,h[u++]=b,b=b>>8,h[u++]=b;let P=Number(o>>BigInt(32)&BigInt(4294967295));return h[u++]=P,P=P>>8,h[u++]=P,P=P>>8,h[u++]=P,P=P>>8,h[u++]=P,u}function Ei(h,o,u,l,g){Ii(o,l,g,h,u,7);let b=Number(o&BigInt(4294967295));h[u+7]=b,b=b>>8,h[u+6]=b,b=b>>8,h[u+5]=b,b=b>>8,h[u+4]=b;let P=Number(o>>BigInt(32)&BigInt(4294967295));return h[u+3]=P,P=P>>8,h[u+2]=P,P=P>>8,h[u+1]=P,P=P>>8,h[u]=P,u+8}f.prototype.writeBigUInt64LE=Ze(function(o,u=0){return mi(this,o,u,BigInt(0),BigInt("0xffffffffffffffff"))}),f.prototype.writeBigUInt64BE=Ze(function(o,u=0){return Ei(this,o,u,BigInt(0),BigInt("0xffffffffffffffff"))}),f.prototype.writeIntLE=function(o,u,l,g){if(o=+o,u=u>>>0,!g){const Q=Math.pow(2,8*l-1);Te(this,o,u,l,Q-1,-Q)}let b=0,P=1,M=0;for(this[u]=o&255;++b>0)-M&255;return u+l},f.prototype.writeIntBE=function(o,u,l,g){if(o=+o,u=u>>>0,!g){const Q=Math.pow(2,8*l-1);Te(this,o,u,l,Q-1,-Q)}let b=l-1,P=1,M=0;for(this[u+b]=o&255;--b>=0&&(P*=256);)o<0&&M===0&&this[u+b+1]!==0&&(M=1),this[u+b]=(o/P>>0)-M&255;return u+l},f.prototype.writeInt8=function(o,u,l){return o=+o,u=u>>>0,l||Te(this,o,u,1,127,-128),o<0&&(o=255+o+1),this[u]=o&255,u+1},f.prototype.writeInt16LE=function(o,u,l){return o=+o,u=u>>>0,l||Te(this,o,u,2,32767,-32768),this[u]=o&255,this[u+1]=o>>>8,u+2},f.prototype.writeInt16BE=function(o,u,l){return o=+o,u=u>>>0,l||Te(this,o,u,2,32767,-32768),this[u]=o>>>8,this[u+1]=o&255,u+2},f.prototype.writeInt32LE=function(o,u,l){return o=+o,u=u>>>0,l||Te(this,o,u,4,2147483647,-2147483648),this[u]=o&255,this[u+1]=o>>>8,this[u+2]=o>>>16,this[u+3]=o>>>24,u+4},f.prototype.writeInt32BE=function(o,u,l){return o=+o,u=u>>>0,l||Te(this,o,u,4,2147483647,-2147483648),o<0&&(o=4294967295+o+1),this[u]=o>>>24,this[u+1]=o>>>16,this[u+2]=o>>>8,this[u+3]=o&255,u+4},f.prototype.writeBigInt64LE=Ze(function(o,u=0){return mi(this,o,u,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),f.prototype.writeBigInt64BE=Ze(function(o,u=0){return Ei(this,o,u,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Si(h,o,u,l,g,b){if(u+l>h.length)throw new RangeError("Index out of range");if(u<0)throw new RangeError("Index out of range")}function bi(h,o,u,l,g){return o=+o,u=u>>>0,g||Si(h,o,u,4),r.write(h,o,u,l,23,4),u+4}f.prototype.writeFloatLE=function(o,u,l){return bi(this,o,u,!0,l)},f.prototype.writeFloatBE=function(o,u,l){return bi(this,o,u,!1,l)};function _i(h,o,u,l,g){return o=+o,u=u>>>0,g||Si(h,o,u,8),r.write(h,o,u,l,52,8),u+8}f.prototype.writeDoubleLE=function(o,u,l){return _i(this,o,u,!0,l)},f.prototype.writeDoubleBE=function(o,u,l){return _i(this,o,u,!1,l)},f.prototype.copy=function(o,u,l,g){if(!f.isBuffer(o))throw new TypeError("argument should be a Buffer");if(l||(l=0),!g&&g!==0&&(g=this.length),u>=o.length&&(u=o.length),u||(u=0),g>0&&g=this.length)throw new RangeError("Index out of range");if(g<0)throw new RangeError("sourceEnd out of bounds");g>this.length&&(g=this.length),o.length-u>>0,l=l===void 0?this.length:l>>>0,o||(o=0);let b;if(typeof o=="number")for(b=u;b2**32?g=Ti(String(u)):typeof u=="bigint"&&(g=String(u),(u>BigInt(2)**BigInt(32)||u<-(BigInt(2)**BigInt(32)))&&(g=Ti(g)),g+="n"),l+=` It must be ${o}. Received ${g}`,l},RangeError);function Ti(h){let o="",u=h.length;const l=h[0]==="-"?1:0;for(;u>=l+4;u-=3)o=`_${h.slice(u-3,u)}${o}`;return`${h.slice(0,u)}${o}`}function Ms(h,o,u){Ft(o,"offset"),(h[o]===void 0||h[o+u]===void 0)&&Qt(o,h.length-(u+1))}function Ii(h,o,u,l,g,b){if(h>u||h= 0${P} and < 2${P} ** ${(b+1)*8}${P}`:M=`>= -(2${P} ** ${(b+1)*8-1}${P}) and < 2 ** ${(b+1)*8-1}${P}`,new Rt.ERR_OUT_OF_RANGE("value",M,h)}Ms(l,g,b)}function Ft(h,o){if(typeof h!="number")throw new Rt.ERR_INVALID_ARG_TYPE(o,"number",h)}function Qt(h,o,u){throw Math.floor(h)!==h?(Ft(h,u),new Rt.ERR_OUT_OF_RANGE("offset","an integer",h)):o<0?new Rt.ERR_BUFFER_OUT_OF_BOUNDS:new Rt.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${o}`,h)}const $s=/[^+/0-9A-Za-z-_]/g;function Ks(h){if(h=h.split("=")[0],h=h.trim().replace($s,""),h.length<2)return"";for(;h.length%4!==0;)h=h+"=";return h}function yn(h,o){o=o||1/0;let u;const l=h.length;let g=null;const b=[];for(let P=0;P55295&&u<57344){if(!g){if(u>56319){(o-=3)>-1&&b.push(239,191,189);continue}else if(P+1===l){(o-=3)>-1&&b.push(239,191,189);continue}g=u;continue}if(u<56320){(o-=3)>-1&&b.push(239,191,189),g=u;continue}u=(g-55296<<10|u-56320)+65536}else g&&(o-=3)>-1&&b.push(239,191,189);if(g=null,u<128){if((o-=1)<0)break;b.push(u)}else if(u<2048){if((o-=2)<0)break;b.push(u>>6|192,u&63|128)}else if(u<65536){if((o-=3)<0)break;b.push(u>>12|224,u>>6&63|128,u&63|128)}else if(u<1114112){if((o-=4)<0)break;b.push(u>>18|240,u>>12&63|128,u>>6&63|128,u&63|128)}else throw new Error("Invalid code point")}return b}function Ds(h){const o=[];for(let u=0;u>8,g=u%256,b.push(g),b.push(l);return b}function ki(h){return t.toByteArray(Ks(h))}function br(h,o,u,l){let g;for(g=0;g=o.length||g>=h.length);++g)o[g+u]=h[g];return g}function Ue(h,o){return h instanceof o||h!=null&&h.constructor!=null&&h.constructor.name!=null&&h.constructor.name===o.name}function wn(h){return h!==h}const js=function(){const h="0123456789abcdef",o=new Array(256);for(let u=0;u<16;++u){const l=u*16;for(let g=0;g<16;++g)o[l+g]=h[u]+h[g]}return o}();function Ze(h){return typeof BigInt>"u"?Vs:h}function Vs(){throw new Error("BigInt not supported")}})(se);const m=se.Buffer,nc=se.Blob,ic=se.BlobOptions,mo=se.Buffer,oc=se.File,sc=se.FileOptions,cc=se.INSPECT_MAX_BYTES,uc=se.SlowBuffer,ac=se.TranscodeEncoding,fc=se.atob,hc=se.btoa,pc=se.constants,lc=se.isAscii,dc=se.isUtf8,yc=se.kMaxLength,wc=se.kStringMaxLength,gc=se.resolveObjectURL,mc=se.transcode,Ec=Object.freeze(Object.defineProperty({__proto__:null,Blob:nc,BlobOptions:ic,Buffer:mo,File:oc,FileOptions:sc,INSPECT_MAX_BYTES:cc,SlowBuffer:uc,TranscodeEncoding:ac,atob:fc,btoa:hc,constants:pc,default:m,isAscii:lc,isUtf8:dc,kMaxLength:yc,kStringMaxLength:wc,resolveObjectURL:gc,transcode:mc},Symbol.toStringTag,{value:"Module"}));var ge={},ae={};Object.defineProperty(ae,"__esModule",{value:!0});ae.testnet=ae.regtest=ae.bitcoin=void 0;ae.bitcoin={messagePrefix:`Bitcoin Signed Message: `,bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128};ae.regtest={messagePrefix:`Bitcoin Signed Message: `,bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};ae.testnet={messagePrefix:`Bitcoin Signed Message: -`,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var gn={},Gr={},En={},ze={};Object.defineProperty(ze,"__esModule",{value:!0});ze.encode=ze.decode=ze.check=void 0;function gc(e){if(e.length<8||e.length>72||e[0]!==48||e[1]!==e.length-2||e[2]!==2)return!1;const t=e[3];if(t===0||5+t>=e.length||e[4+t]!==2)return!1;const r=e[5+t];return!(r===0||6+t+r!==e.length||e[4]&128||t>1&&e[4]===0&&!(e[5]&128)||e[t+6]&128||r>1&&e[t+6]===0&&!(e[t+7]&128))}ze.check=gc;function Ec(e){if(e.length<8)throw new Error("DER sequence length is too short");if(e.length>72)throw new Error("DER sequence length is too long");if(e[0]!==48)throw new Error("Expected DER sequence");if(e[1]!==e.length-2)throw new Error("DER sequence length is invalid");if(e[2]!==2)throw new Error("Expected DER integer");const t=e[3];if(t===0)throw new Error("R length is zero");if(5+t>=e.length)throw new Error("R length is too long");if(e[4+t]!==2)throw new Error("Expected DER integer (2)");const r=e[5+t];if(r===0)throw new Error("S length is zero");if(6+t+r!==e.length)throw new Error("S length is invalid");if(e[4]&128)throw new Error("R value is negative");if(t>1&&e[4]===0&&!(e[5]&128))throw new Error("R value excessively padded");if(e[t+6]&128)throw new Error("S value is negative");if(r>1&&e[t+6]===0&&!(e[t+7]&128))throw new Error("S value excessively padded");return{r:e.slice(4,4+t),s:e.slice(6+t)}}ze.decode=Ec;function mc(e,t){const r=e.length,n=t.length;if(r===0)throw new Error("R length is zero");if(n===0)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(n>33)throw new Error("S length is too long");if(e[0]&128)throw new Error("R value is negative");if(t[0]&128)throw new Error("S value is negative");if(r>1&&e[0]===0&&!(e[1]&128))throw new Error("R value excessively padded");if(n>1&&t[0]===0&&!(t[1]&128))throw new Error("S value excessively padded");const i=E.allocUnsafe(6+r+n);return i[0]=48,i[1]=i.length-2,i[2]=2,i[3]=e.length,e.copy(i,4),i[4+r]=2,i[5+r]=t.length,t.copy(i,6+r),i}ze.encode=mc;var ft={};Object.defineProperty(ft,"__esModule",{value:!0});ft.REVERSE_OPS=ft.OPS=void 0;const Fn={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_LEFT:128,OP_RIGHT:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_CHECKLOCKTIMEVERIFY:177,OP_NOP3:178,OP_CHECKSEQUENCEVERIFY:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_CHECKSIGADD:186,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255};ft.OPS=Fn;const go={};ft.REVERSE_OPS=go;for(const e of Object.keys(Fn)){const t=Fn[e];go[t]=e}var ut={};Object.defineProperty(ut,"__esModule",{value:!0});ut.decode=ut.encode=ut.encodingLength=void 0;const ct=ft;function Eo(e){return ee.length)return null;n=e.readUInt8(t+1),i=2}else if(r===ct.OPS.OP_PUSHDATA2){if(t+3>e.length)return null;n=e.readUInt16LE(t+1),i=3}else{if(t+5>e.length)return null;if(r!==ct.OPS.OP_PUSHDATA4)throw new Error("Unexpected opcode");n=e.readUInt32LE(t+1),i=5}return{opcode:r,number:n,size:i}}ut.decode=bc;var zt={};Object.defineProperty(zt,"__esModule",{value:!0});zt.encode=zt.decode=void 0;function _c(e,t,r){t=t||4,r=r===void 0?!0:r;const n=e.length;if(n===0)return 0;if(n>t)throw new TypeError("Script number overflow");if(r&&!(e[n-1]&127)&&(n<=1||!(e[n-2]&128)))throw new Error("Non-minimally encoded script number");if(n===5){const c=e.readUInt32LE(0),s=e.readUInt8(4);return s&128?-((s&-129)*4294967296+c):s*4294967296+c}let i=0;for(let c=0;c2147483647?5:e>8388607?4:e>32767?3:e>127?2:e>0?1:0}function Ic(e){let t=Math.abs(e);const r=Tc(t),n=E.allocUnsafe(r),i=e<0;for(let c=0;c>=8;return n[r-1]&128?n.writeUInt8(i?128:0,r-1):i&&(n[r-1]|=128),n}zt.encode=Ic;var dt={},de={};const Xr=Vs(wc);var yr={Array:function(e){return e!=null&&e.constructor===Array},Boolean:function(e){return typeof e=="boolean"},Function:function(e){return typeof e=="function"},Nil:function(e){return e==null},Number:function(e){return typeof e=="number"},Object:function(e){return typeof e=="object"},String:function(e){return typeof e=="string"},"":function(){return!0}};yr.Null=yr.Nil;for(var ki in yr)yr[ki].toJSON=(function(e){return e}).bind(null,ki);var Gn=yr,gt=Gn;function mo(e){return e.name||e.toString().match(/function (.*?)\s*\(/)[1]}function Xn(e){return gt.Nil(e)?"":mo(e.constructor)}function kc(e){return gt.Function(e)?"":gt.String(e)?JSON.stringify(e):e&>.Object(e)?"":e}function qn(e,t){Error.captureStackTrace&&Error.captureStackTrace(e,t)}function Fr(e){return gt.Function(e)?e.toJSON?e.toJSON():mo(e):gt.Array(e)?"Array":e&>.Object(e)?"Object":e!==void 0?e:""}function So(e,t,r){var n=kc(t);return"Expected "+Fr(e)+", got"+(r!==""?" "+r:"")+(n!==""?" "+n:"")}function Je(e,t,r){r=r||Xn(t),this.message=So(e,t,r),qn(this,Je),this.__type=e,this.__value=t,this.__valueTypeName=r}Je.prototype=Object.create(Error.prototype);Je.prototype.constructor=Je;function Ac(e,t,r,n,i){var c='" of type ';return t==="key"&&(c='" with key type '),So('property "'+Fr(r)+c+Fr(e),n,i)}function Gt(e,t,r,n,i){e?(i=i||Xn(n),this.message=Ac(e,r,t,n,i)):this.message='Unexpected property "'+t+'"',qn(this,Je),this.__label=r,this.__property=t,this.__type=e,this.__value=n,this.__valueTypeName=i}Gt.prototype=Object.create(Error.prototype);Gt.prototype.constructor=Je;function Oc(e,t){return new Je(e,{},t)}function Pc(e,t,r){return e instanceof Gt?(t=t+"."+e.__property,e=new Gt(e.__type,t,e.__label,e.__value,e.__valueTypeName)):e instanceof Je&&(e=new Gt(e.__type,t,r,e.__value,e.__valueTypeName)),qn(e),e}var bo={TfTypeError:Je,TfPropertyTypeError:Gt,tfCustomError:Oc,tfSubError:Pc,tfJSON:Fr,getValueTypeName:Xn},mn,Ai;function vc(){if(Ai)return mn;Ai=1;var e=Gn,t=bo;function r(I){return E.isBuffer(I)}function n(I){return typeof I=="string"&&/^([0-9a-f]{2})+$/i.test(I)}function i(I,C){var M=I.toJSON();function B(R){if(!I(R))return!1;if(R.length===C)return!0;throw t.tfCustomError(M+"(Length: "+C+")",M+"(Length: "+R.length+")")}return B.toJSON=function(){return M},B}var c=i.bind(null,e.Array),s=i.bind(null,r),a=i.bind(null,n),p=i.bind(null,e.String);function w(I,C,M){M=M||e.Number;function B(R,j){return M(R,j)&&R>I&&R>24===I}function y(I){return I<<16>>16===I}function _(I){return(I|0)===I}function T(I){return typeof I=="number"&&I>=-f&&I<=f&&Math.floor(I)===I}function P(I){return(I&255)===I}function x(I){return(I&65535)===I}function N(I){return I>>>0===I}function k(I){return typeof I=="number"&&I>=0&&I<=f&&Math.floor(I)===I}var m={ArrayN:c,Buffer:r,BufferN:s,Finite:d,Hex:n,HexN:a,Int8:S,Int16:y,Int32:_,Int53:T,Range:w,StringN:p,UInt8:P,UInt16:x,UInt32:N,UInt53:k};for(var v in m)m[v].toJSON=(function(I){return I}).bind(null,v);return mn=m,mn}var gr=bo,le=Gn,We=gr.tfJSON,_o=gr.TfTypeError,To=gr.TfPropertyTypeError,er=gr.tfSubError,Bc=gr.getValueTypeName,qe={arrayOf:function(t,r){t=Le(t),r=r||{};function n(i,c){return!le.Array(i)||le.Nil(i)||r.minLength!==void 0&&i.lengthr.maxLength||r.length!==void 0&&i.length!==r.length?!1:i.every(function(s,a){try{return be(t,s,c)}catch(p){throw er(p,a)}})}return n.toJSON=function(){var i="["+We(t)+"]";return r.length!==void 0?i+="{"+r.length+"}":(r.minLength!==void 0||r.maxLength!==void 0)&&(i+="{"+(r.minLength===void 0?0:r.minLength)+","+(r.maxLength===void 0?1/0:r.maxLength)+"}"),i},n},maybe:function e(t){t=Le(t);function r(n,i){return le.Nil(n)||t(n,i,e)}return r.toJSON=function(){return"?"+We(t)},r},map:function(t,r){t=Le(t),r&&(r=Le(r));function n(i,c){if(!le.Object(i)||le.Nil(i))return!1;for(var s in i){try{r&&be(r,s,c)}catch(p){throw er(p,s,"key")}try{var a=i[s];be(t,a,c)}catch(p){throw er(p,s)}}return!0}return r?n.toJSON=function(){return"{"+We(r)+": "+We(t)+"}"}:n.toJSON=function(){return"{"+We(t)+"}"},n},object:function(t){var r={};for(var n in t)r[n]=Le(t[n]);function i(c,s){if(!le.Object(c)||le.Nil(c))return!1;var a;try{for(a in r){var p=r[a],w=c[a];be(p,w,s)}}catch(f){throw er(f,a)}if(s){for(a in c)if(!r[a])throw new To(void 0,a)}return!0}return i.toJSON=function(){return We(r)},i},anyOf:function(){var t=[].slice.call(arguments).map(Le);function r(n,i){return t.some(function(c){try{return be(c,n,i)}catch{return!1}})}return r.toJSON=function(){return t.map(We).join("|")},r},allOf:function(){var t=[].slice.call(arguments).map(Le);function r(n,i){return t.every(function(c){try{return be(c,n,i)}catch{return!1}})}return r.toJSON=function(){return t.map(We).join(" & ")},r},quacksLike:function(t){function r(n){return t===Bc(n)}return r.toJSON=function(){return t},r},tuple:function(){var t=[].slice.call(arguments).map(Le);function r(n,i){return le.Nil(n)||le.Nil(n.length)||i&&n.length!==t.length?!1:t.every(function(c,s){try{return be(c,n[s],i)}catch(a){throw er(a,s)}})}return r.toJSON=function(){return"("+t.map(We).join(", ")+")"},r},value:function(t){function r(n){return n===t}return r.toJSON=function(){return t},r}};qe.oneOf=qe.anyOf;function Le(e){if(le.String(e))return e[0]==="?"?qe.maybe(e.slice(1)):le[e]||qe.quacksLike(e);if(e&&le.Object(e)){if(le.Array(e)){if(e.length!==1)throw new TypeError("Expected compile() parameter of type Array of length 1");return qe.arrayOf(e[0])}return qe.object(e)}else if(le.Function(e))return e;return qe.value(e)}function be(e,t,r,n){if(le.Function(e)){if(e(t,r))return!0;throw new _o(n||e,t)}return be(Le(e),t,r)}for(var at in le)be[at]=le[at];for(at in qe)be[at]=qe[at];var Oi=vc();for(at in Oi)be[at]=Oi[at];be.compile=Le;be.TfTypeError=_o;be.TfPropertyTypeError=To;var xc=be;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.oneOf=e.Null=e.BufferN=e.Function=e.UInt32=e.UInt8=e.tuple=e.maybe=e.Hex=e.Buffer=e.String=e.Boolean=e.Array=e.Number=e.Hash256bit=e.Hash160bit=e.Buffer256bit=e.isTaptree=e.isTapleaf=e.TAPLEAF_VERSION_MASK=e.Satoshi=e.isPoint=e.stacksEqual=e.typeforce=void 0;const t=Xr;e.typeforce=xc;const r=t.Buffer.alloc(32,0),n=t.Buffer.from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f","hex");function i(f,d){return f.length!==d.length?!1:f.every((S,y)=>S.equals(d[y]))}e.stacksEqual=i;function c(f){if(!t.Buffer.isBuffer(f)||f.length<33)return!1;const d=f[0],S=f.slice(1,33);if(S.compare(r)===0||S.compare(n)>=0)return!1;if((d===2||d===3)&&f.length===33)return!0;const y=f.slice(33);return y.compare(r)===0||y.compare(n)>=0?!1:d===4&&f.length===65}e.isPoint=c;const s=21*1e14;function a(f){return e.typeforce.UInt53(f)&&f<=s}e.Satoshi=a,e.TAPLEAF_VERSION_MASK=254;function p(f){return!f||!("output"in f)||!t.Buffer.isBuffer(f.output)?!1:f.version!==void 0?(f.version&e.TAPLEAF_VERSION_MASK)===f.version:!0}e.isTapleaf=p;function w(f){return(0,e.Array)(f)?f.length!==2?!1:f.every(d=>w(d)):p(f)}e.isTaptree=w,e.Buffer256bit=e.typeforce.BufferN(32),e.Hash160bit=e.typeforce.BufferN(20),e.Hash256bit=e.typeforce.BufferN(32),e.Number=e.typeforce.Number,e.Array=e.typeforce.Array,e.Boolean=e.typeforce.Boolean,e.String=e.typeforce.String,e.Buffer=e.typeforce.Buffer,e.Hex=e.typeforce.Hex,e.maybe=e.typeforce.maybe,e.tuple=e.typeforce.tuple,e.UInt8=e.typeforce.UInt8,e.UInt32=e.typeforce.UInt32,e.Function=e.typeforce.Function,e.BufferN=e.typeforce.BufferN,e.Null=e.typeforce.Null,e.oneOf=e.typeforce.oneOf})(de);var Pi;function Uc(){if(Pi)return dt;Pi=1,Object.defineProperty(dt,"__esModule",{value:!0}),dt.encode=dt.decode=void 0;const e=ze,t=_e(),r=de,{typeforce:n}=r,i=E.alloc(1,0);function c(w){let f=0;for(;w[f]===0;)++f;return f===w.length?i:(w=w.slice(f),w[0]&128?E.concat([i,w],1+w.length):w)}function s(w){w[0]===0&&(w=w.slice(1));const f=E.alloc(32,0),d=Math.max(0,32-w.length);return w.copy(f,d),f}function a(w){const f=w.readUInt8(w.length-1);if(!(0,t.isDefinedHashType)(f))throw new Error("Invalid hashType "+f);const d=e.decode(w.slice(0,-1)),S=s(d.r),y=s(d.s);return{signature:E.concat([S,y],64),hashType:f}}dt.decode=a;function p(w,f){if(n({signature:r.BufferN(64),hashType:r.UInt8},{signature:w,hashType:f}),!(0,t.isDefinedHashType)(f))throw new Error("Invalid hashType "+f);const d=E.allocUnsafe(1);d.writeUInt8(f,0);const S=c(w.slice(0,32)),y=c(w.slice(32,64));return E.concat([e.encode(S,y),d])}return dt.encode=p,dt}var vi;function _e(){return vi||(vi=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.signature=e.number=e.isCanonicalScriptSignature=e.isDefinedHashType=e.isCanonicalPubKey=e.toStack=e.fromASM=e.toASM=e.decompile=e.compile=e.countNonPushOnlyOPs=e.isPushOnly=e.OPS=void 0;const t=ze,r=ft;Object.defineProperty(e,"OPS",{enumerable:!0,get:function(){return r.OPS}});const n=ut,i=zt,c=Uc(),s=de,{typeforce:a}=s,p=r.OPS.OP_RESERVED;function w(B){return s.Number(B)&&(B===r.OPS.OP_0||B>=r.OPS.OP_1&&B<=r.OPS.OP_16||B===r.OPS.OP_1NEGATE)}function f(B){return s.Buffer(B)||w(B)}function d(B){return s.Array(B)&&B.every(f)}e.isPushOnly=d;function S(B){return B.length-B.filter(f).length}e.countNonPushOnlyOPs=S;function y(B){if(B.length===0)return r.OPS.OP_0;if(B.length===1){if(B[0]>=1&&B[0]<=16)return p+B[0];if(B[0]===129)return r.OPS.OP_1NEGATE}}function _(B){return E.isBuffer(B)}function T(B){return s.Array(B)}function P(B){return E.isBuffer(B)}function x(B){if(_(B))return B;a(s.Array,B);const R=B.reduce((U,F)=>P(F)?F.length===1&&y(F)!==void 0?U+1:U+n.encodingLength(F.length)+F.length:U+1,0),j=E.allocUnsafe(R);let O=0;if(B.forEach(U=>{if(P(U)){const F=y(U);if(F!==void 0){j.writeUInt8(F,O),O+=1;return}O+=n.encode(j,U.length,O),U.copy(j,O),O+=U.length}else j.writeUInt8(U,O),O+=1}),O!==j.length)throw new Error("Could not decode chunks");return j}e.compile=x;function N(B){if(T(B))return B;a(s.Buffer,B);const R=[];let j=0;for(;jr.OPS.OP_0&&O<=r.OPS.OP_PUSHDATA4){const U=n.decode(B,j);if(U===null||(j+=U.size,j+U.number>B.length))return null;const F=B.slice(j,j+U.number);j+=U.number;const D=y(F);D!==void 0?R.push(D):R.push(F)}else R.push(O),j+=1}return R}e.decompile=N;function k(B){if(_(B)&&(B=N(B)),!B)throw new Error("Could not convert invalid chunks to ASM");return B.map(R=>{if(P(R)){const j=y(R);if(j===void 0)return R.toString("hex");R=j}return r.REVERSE_OPS[R]}).join(" ")}e.toASM=k;function m(B){return a(s.String,B),x(B.split(" ").map(R=>r.OPS[R]!==void 0?r.OPS[R]:(a(s.Hex,R),E.from(R,"hex"))))}e.fromASM=m;function v(B){return B=N(B),a(d,B),B.map(R=>P(R)?R:R===r.OPS.OP_0?E.allocUnsafe(0):i.encode(R-p))}e.toStack=v;function I(B){return s.isPoint(B)}e.isCanonicalPubKey=I;function C(B){const R=B&-129;return R>0&&R<4}e.isDefinedHashType=C;function M(B){return!E.isBuffer(B)||!C(B[B.length-1])?!1:t.check(B.slice(0,-1))}e.isCanonicalScriptSignature=M,e.number=i,e.signature=c}(En)),En}var ke={};Object.defineProperty(ke,"__esModule",{value:!0});ke.value=ke.prop=void 0;function Nc(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){const n=r.call(this);return this[t]=n,n},set(n){Object.defineProperty(this,t,{configurable:!0,enumerable:!0,value:n,writable:!0})}})}ke.prop=Nc;function Cc(e){let t;return()=>(t!==void 0||(t=e()),t)}ke.value=Cc;Object.defineProperty(Gr,"__esModule",{value:!0});Gr.p2data=void 0;const Hc=ae,Ur=_e(),Ne=de,Bi=ke,xi=Ur.OPS;function Rc(e,t){if(!e.data&&!e.output)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,Ne.typeforce)({network:Ne.typeforce.maybe(Ne.typeforce.Object),output:Ne.typeforce.maybe(Ne.typeforce.Buffer),data:Ne.typeforce.maybe(Ne.typeforce.arrayOf(Ne.typeforce.Buffer))},e);const n={name:"embed",network:e.network||Hc.bitcoin};if(Bi.prop(n,"output",()=>{if(e.data)return Ur.compile([xi.OP_RETURN].concat(e.data))}),Bi.prop(n,"data",()=>{if(e.output)return Ur.decompile(e.output).slice(1)}),t.validate&&e.output){const i=Ur.decompile(e.output);if(i[0]!==xi.OP_RETURN)throw new TypeError("Output is invalid");if(!i.slice(1).every(Ne.typeforce.Buffer))throw new TypeError("Output is invalid");if(e.data&&!(0,Ne.stacksEqual)(e.data,n.data))throw new TypeError("Data mismatch")}return Object.assign(n,e)}Gr.p2data=Rc;var qr={};Object.defineProperty(qr,"__esModule",{value:!0});qr.p2ms=void 0;const Fc=ae,Dt=_e(),ee=de,et=ke,Wt=Dt.OPS,Tr=Wt.OP_RESERVED;function Lc(e,t){if(!e.input&&!e.output&&!(e.pubkeys&&e.m!==void 0)&&!e.signatures)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{});function r(p){return Dt.isCanonicalScriptSignature(p)||(t.allowIncomplete&&p===Wt.OP_0)!==void 0}(0,ee.typeforce)({network:ee.typeforce.maybe(ee.typeforce.Object),m:ee.typeforce.maybe(ee.typeforce.Number),n:ee.typeforce.maybe(ee.typeforce.Number),output:ee.typeforce.maybe(ee.typeforce.Buffer),pubkeys:ee.typeforce.maybe(ee.typeforce.arrayOf(ee.isPoint)),signatures:ee.typeforce.maybe(ee.typeforce.arrayOf(r)),input:ee.typeforce.maybe(ee.typeforce.Buffer)},e);const i={network:e.network||Fc.bitcoin};let c=[],s=!1;function a(p){s||(s=!0,c=Dt.decompile(p),i.m=c[0]-Tr,i.n=c[c.length-2]-Tr,i.pubkeys=c.slice(1,-2))}if(et.prop(i,"output",()=>{if(e.m&&i.n&&e.pubkeys)return Dt.compile([].concat(Tr+e.m,e.pubkeys,Tr+i.n,Wt.OP_CHECKMULTISIG))}),et.prop(i,"m",()=>{if(i.output)return a(i.output),i.m}),et.prop(i,"n",()=>{if(i.pubkeys)return i.pubkeys.length}),et.prop(i,"pubkeys",()=>{if(e.output)return a(e.output),i.pubkeys}),et.prop(i,"signatures",()=>{if(e.input)return Dt.decompile(e.input).slice(1)}),et.prop(i,"input",()=>{if(e.signatures)return Dt.compile([Wt.OP_0].concat(e.signatures))}),et.prop(i,"witness",()=>{if(i.input)return[]}),et.prop(i,"name",()=>{if(!(!i.m||!i.n))return`p2ms(${i.m} of ${i.n})`}),t.validate){if(e.output){if(a(e.output),!ee.typeforce.Number(c[0]))throw new TypeError("Output is invalid");if(!ee.typeforce.Number(c[c.length-2]))throw new TypeError("Output is invalid");if(c[c.length-1]!==Wt.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(i.m<=0||i.n>16||i.m>i.n||i.n!==c.length-3)throw new TypeError("Output is invalid");if(!i.pubkeys.every(p=>(0,ee.isPoint)(p)))throw new TypeError("Output is invalid");if(e.m!==void 0&&e.m!==i.m)throw new TypeError("m mismatch");if(e.n!==void 0&&e.n!==i.n)throw new TypeError("n mismatch");if(e.pubkeys&&!(0,ee.stacksEqual)(e.pubkeys,i.pubkeys))throw new TypeError("Pubkeys mismatch")}if(e.pubkeys){if(e.n!==void 0&&e.n!==e.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(i.n=e.pubkeys.length,i.ni.m)throw new TypeError("Too many signatures provided")}if(e.input){if(e.input[0]!==Wt.OP_0)throw new TypeError("Input is invalid");if(i.signatures.length===0||!i.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(e.signatures&&!(0,ee.stacksEqual)(e.signatures,i.signatures))throw new TypeError("Signature mismatch");if(e.m!==void 0&&e.m!==e.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(i,e)}qr.p2ms=Lc;var zr={};Object.defineProperty(zr,"__esModule",{value:!0});zr.p2pk=void 0;const $c=ae,jt=_e(),Be=de,$t=ke,Ui=jt.OPS;function Mc(e,t){if(!e.input&&!e.output&&!e.pubkey&&!e.input&&!e.signature)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,Be.typeforce)({network:Be.typeforce.maybe(Be.typeforce.Object),output:Be.typeforce.maybe(Be.typeforce.Buffer),pubkey:Be.typeforce.maybe(Be.isPoint),signature:Be.typeforce.maybe(jt.isCanonicalScriptSignature),input:Be.typeforce.maybe(Be.typeforce.Buffer)},e);const r=$t.value(()=>jt.decompile(e.input)),i={name:"p2pk",network:e.network||$c.bitcoin};if($t.prop(i,"output",()=>{if(e.pubkey)return jt.compile([e.pubkey,Ui.OP_CHECKSIG])}),$t.prop(i,"pubkey",()=>{if(e.output)return e.output.slice(1,-1)}),$t.prop(i,"signature",()=>{if(e.input)return r()[0]}),$t.prop(i,"input",()=>{if(e.signature)return jt.compile([e.signature])}),$t.prop(i,"witness",()=>{if(i.input)return[]}),t.validate){if(e.output){if(e.output[e.output.length-1]!==Ui.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!(0,Be.isPoint)(i.pubkey))throw new TypeError("Output pubkey is invalid");if(e.pubkey&&!e.pubkey.equals(i.pubkey))throw new TypeError("Pubkey mismatch")}if(e.signature&&e.input&&!e.input.equals(i.input))throw new TypeError("Signature mismatch");if(e.input){if(r().length!==1)throw new TypeError("Input is invalid");if(!jt.isCanonicalScriptSignature(i.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(i,e)}zr.p2pk=Mc;var Yr={},Ke={},Yt={},Me={},ue={};Object.defineProperty(ue,"__esModule",{value:!0});ue.output=ue.exists=ue.hash=ue.bytes=ue.bool=ue.number=ue.isBytes=void 0;function Lr(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}ue.number=Lr;function Io(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}ue.bool=Io;function ko(e){return e instanceof Uint8Array||e!=null&&typeof e=="object"&&e.constructor.name==="Uint8Array"}ue.isBytes=ko;function zn(e,...t){if(!ko(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}`)}ue.bytes=zn;function Ao(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Lr(e.outputLen),Lr(e.blockLen)}ue.hash=Ao;function Oo(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")}ue.exists=Oo;function Po(e,t){zn(e);const r=t.outputLen;if(e.lengthnew Uint8Array(O.buffer,O.byteOffset,O.byteLength);e.u8=i;const c=O=>new Uint32Array(O.buffer,O.byteOffset,Math.floor(O.byteLength/4));e.u32=c;const s=O=>new DataView(O.buffer,O.byteOffset,O.byteLength);e.createView=s;const a=(O,U)=>O<<32-U|O>>>U;e.rotr=a;const p=(O,U)=>O<>>32-U>>>0;e.rotl=p,e.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;const w=O=>O<<24&4278190080|O<<8&16711680|O>>>8&65280|O>>>24&255;e.byteSwap=w,e.byteSwapIfBE=e.isLE?O=>O:O=>(0,e.byteSwap)(O);function f(O){for(let U=0;UU.toString(16).padStart(2,"0"));function S(O){(0,r.bytes)(O);let U="";for(let F=0;F=y._0&&O<=y._9)return O-y._0;if(O>=y._A&&O<=y._F)return O-(y._A-10);if(O>=y._a&&O<=y._f)return O-(y._a-10)}function T(O){if(typeof O!="string")throw new Error("hex string expected, got "+typeof O);const U=O.length,F=U/2;if(U%2)throw new Error("padded hex string expected, got unpadded hex of length "+U);const D=new Uint8Array(F);for(let ne=0,ye=0;ne{};e.nextTick=P;async function x(O,U,F){let D=Date.now();for(let ne=0;ne=0&&yeO().update(k(D)).digest(),F=O();return U.outputLen=F.outputLen,U.blockLen=F.blockLen,U.create=()=>O(),U}e.wrapConstructor=M;function B(O){const U=(D,ne)=>O(ne).update(k(D)).digest(),F=O({});return U.outputLen=F.outputLen,U.blockLen=F.blockLen,U.create=D=>O(D),U}e.wrapConstructorWithOpts=B;function R(O){const U=(D,ne)=>O(ne).update(k(D)).digest(),F=O({});return U.outputLen=F.outputLen,U.blockLen=F.blockLen,U.create=D=>O(D),U}e.wrapXOFConstructorWithOpts=R;function j(O=32){if(t.crypto&&typeof t.crypto.getRandomValues=="function")return t.crypto.getRandomValues(new Uint8Array(O));throw new Error("crypto.getRandomValues must be defined")}e.randomBytes=j})(Er);Object.defineProperty(Me,"__esModule",{value:!0});Me.HashMD=Me.Maj=Me.Chi=void 0;const Sn=ue,tr=Er;function Dc(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);const i=BigInt(32),c=BigInt(4294967295),s=Number(r>>i&c),a=Number(r&c),p=n?4:0,w=n?0:4;e.setUint32(t+p,s,n),e.setUint32(t+w,a,n)}const Wc=(e,t,r)=>e&t^~e&r;Me.Chi=Wc;const jc=(e,t,r)=>e&t^e&r^t&r;Me.Maj=jc;class Vc extends tr.Hash{constructor(t,r,n,i){super(),this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=(0,tr.createView)(this.buffer)}update(t){(0,Sn.exists)(this);const{view:r,buffer:n,blockLen:i}=this;t=(0,tr.toBytes)(t);const c=t.length;for(let s=0;si-s&&(this.process(n,0),s=0);for(let d=s;df.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;dt)),qc=vo.map(e=>(9*e+5)%16);let Yn=[vo],Jn=[qc];for(let e=0;e<4;e++)for(let t of[Yn,Jn])t.push(t[e].map(r=>Xc[r]));const Bo=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(e=>new Uint8Array(e)),zc=Yn.map((e,t)=>e.map(r=>Bo[t][r])),Yc=Jn.map((e,t)=>e.map(r=>Bo[t][r])),Jc=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),Qc=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]);function Ni(e,t,r,n){return e===0?t^r^n:e===1?t&r|~t&n:e===2?(t|~r)^n:e===3?t&n|r&~n:t^(r|~n)}const Ir=new Uint32Array(16);class xo extends Gc.HashMD{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:t,h1:r,h2:n,h3:i,h4:c}=this;return[t,r,n,i,c]}set(t,r,n,i,c){this.h0=t|0,this.h1=r|0,this.h2=n|0,this.h3=i|0,this.h4=c|0}process(t,r){for(let y=0;y<16;y++,r+=4)Ir[y]=t.getUint32(r,!0);let n=this.h0|0,i=n,c=this.h1|0,s=c,a=this.h2|0,p=a,w=this.h3|0,f=w,d=this.h4|0,S=d;for(let y=0;y<5;y++){const _=4-y,T=Jc[y],P=Qc[y],x=Yn[y],N=Jn[y],k=zc[y],m=Yc[y];for(let v=0;v<16;v++){const I=(0,cr.rotl)(n+Ni(y,c,a,w)+Ir[x[v]]+T,k[v])+d|0;n=d,d=w,w=(0,cr.rotl)(a,10)|0,a=c,c=I}for(let v=0;v<16;v++){const I=(0,cr.rotl)(i+Ni(_,s,p,f)+Ir[N[v]]+P,m[v])+S|0;i=S,S=f,f=(0,cr.rotl)(p,10)|0,p=s,s=I}}this.set(this.h1+a+f|0,this.h2+w+S|0,this.h3+d+i|0,this.h4+n+s|0,this.h0+c+p|0)}roundClean(){Ir.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}}Yt.RIPEMD160=xo;Yt.ripemd160=(0,cr.wrapConstructor)(()=>new xo);var Qr={};Object.defineProperty(Qr,"__esModule",{value:!0});Qr.sha1=void 0;const bn=Me,Nr=Er,rr=new Uint32Array([1732584193,4023233417,2562383102,271733878,3285377520]),tt=new Uint32Array(80);class Zc extends bn.HashMD{constructor(){super(64,20,8,!1),this.A=rr[0]|0,this.B=rr[1]|0,this.C=rr[2]|0,this.D=rr[3]|0,this.E=rr[4]|0}get(){const{A:t,B:r,C:n,D:i,E:c}=this;return[t,r,n,i,c]}set(t,r,n,i,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=c|0}process(t,r){for(let p=0;p<16;p++,r+=4)tt[p]=t.getUint32(r,!1);for(let p=16;p<80;p++)tt[p]=(0,Nr.rotl)(tt[p-3]^tt[p-8]^tt[p-14]^tt[p-16],1);let{A:n,B:i,C:c,D:s,E:a}=this;for(let p=0;p<80;p++){let w,f;p<20?(w=(0,bn.Chi)(i,c,s),f=1518500249):p<40?(w=i^c^s,f=1859775393):p<60?(w=(0,bn.Maj)(i,c,s),f=2400959708):(w=i^c^s,f=3395469782);const d=(0,Nr.rotl)(n,5)+w+a+f+tt[p]|0;a=s,s=c,c=(0,Nr.rotl)(i,30),i=n,n=d}n=n+this.A|0,i=i+this.B|0,c=c+this.C|0,s=s+this.D|0,a=a+this.E|0,this.set(n,i,c,s,a)}roundClean(){tt.fill(0)}destroy(){this.set(0,0,0,0,0),this.buffer.fill(0)}}Qr.sha1=(0,Nr.wrapConstructor)(()=>new Zc);var mt={};Object.defineProperty(mt,"__esModule",{value:!0});mt.sha224=mt.sha256=void 0;const _n=Me,Oe=Er,eu=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]),rt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),nt=new Uint32Array(64);class Uo extends _n.HashMD{constructor(){super(64,32,8,!1),this.A=rt[0]|0,this.B=rt[1]|0,this.C=rt[2]|0,this.D=rt[3]|0,this.E=rt[4]|0,this.F=rt[5]|0,this.G=rt[6]|0,this.H=rt[7]|0}get(){const{A:t,B:r,C:n,D:i,E:c,F:s,G:a,H:p}=this;return[t,r,n,i,c,s,a,p]}set(t,r,n,i,c,s,a,p){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=c|0,this.F=s|0,this.G=a|0,this.H=p|0}process(t,r){for(let d=0;d<16;d++,r+=4)nt[d]=t.getUint32(r,!1);for(let d=16;d<64;d++){const S=nt[d-15],y=nt[d-2],_=(0,Oe.rotr)(S,7)^(0,Oe.rotr)(S,18)^S>>>3,T=(0,Oe.rotr)(y,17)^(0,Oe.rotr)(y,19)^y>>>10;nt[d]=T+nt[d-7]+_+nt[d-16]|0}let{A:n,B:i,C:c,D:s,E:a,F:p,G:w,H:f}=this;for(let d=0;d<64;d++){const S=(0,Oe.rotr)(a,6)^(0,Oe.rotr)(a,11)^(0,Oe.rotr)(a,25),y=f+S+(0,_n.Chi)(a,p,w)+eu[d]+nt[d]|0,T=((0,Oe.rotr)(n,2)^(0,Oe.rotr)(n,13)^(0,Oe.rotr)(n,22))+(0,_n.Maj)(n,i,c)|0;f=w,w=p,p=a,a=s+y|0,s=c,c=i,i=n,n=y+T|0}n=n+this.A|0,i=i+this.B|0,c=c+this.C|0,s=s+this.D|0,a=a+this.E|0,p=p+this.F|0,w=w+this.G|0,f=f+this.H|0,this.set(n,i,c,s,a,p,w,f)}roundClean(){nt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}class tu extends Uo{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}}mt.sha256=(0,Oe.wrapConstructor)(()=>new Uo);mt.sha224=(0,Oe.wrapConstructor)(()=>new tu);(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.taggedHash=e.TAGGED_HASH_PREFIXES=e.TAGS=e.hash256=e.hash160=e.sha256=e.sha1=e.ripemd160=void 0;const t=Yt,r=Qr,n=mt;function i(f){return E.from((0,t.ripemd160)(Uint8Array.from(f)))}e.ripemd160=i;function c(f){return E.from((0,r.sha1)(Uint8Array.from(f)))}e.sha1=c;function s(f){return E.from((0,n.sha256)(Uint8Array.from(f)))}e.sha256=s;function a(f){return E.from((0,t.ripemd160)((0,n.sha256)(Uint8Array.from(f))))}e.hash160=a;function p(f){return E.from((0,n.sha256)((0,n.sha256)(Uint8Array.from(f))))}e.hash256=p,e.TAGS=["BIP0340/challenge","BIP0340/aux","BIP0340/nonce","TapLeaf","TapBranch","TapSighash","TapTweak","KeyAgg list","KeyAgg coefficient"],e.TAGGED_HASH_PREFIXES={"BIP0340/challenge":E.from([123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124,123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124]),"BIP0340/aux":E.from([241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144,241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144]),"BIP0340/nonce":E.from([7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47,7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47]),TapLeaf:E.from([174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238,174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238]),TapBranch:E.from([25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21,25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21]),TapSighash:E.from([244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49,244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49]),TapTweak:E.from([232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233,232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233]),"KeyAgg list":E.from([72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240,72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240]),"KeyAgg coefficient":E.from([191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129,191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129])};function w(f,d){return s(E.concat([e.TAGGED_HASH_PREFIXES[f],d]))}e.taggedHash=w})(Ke);function ru(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r>>0,k=new Uint8Array(N);P!==x;){for(var m=y[P],v=0,I=N-1;(m!==0||v>>0,k[I]=m%s>>>0,m=m/s>>>0;if(m!==0)throw new Error("Non-zero carry");T=v,P++}for(var C=N-T;C!==N&&k[C]===0;)C++;for(var M=a.repeat(_);C>>0,N=new Uint8Array(x);y[_];){var k=t[y.charCodeAt(_)];if(k===255)return;for(var m=0,v=x-1;(k!==0||m>>0,N[v]=k%256>>>0,k=k/256>>>0;if(k!==0)throw new Error("Non-zero carry");P=m,_++}for(var I=x-P;I!==x&&N[I]===0;)I++;for(var C=new Uint8Array(T+(x-I)),M=T;I!==x;)C[M++]=N[I++];return C}function S(y){var _=d(y);if(_)return _;throw new Error("Non-base"+s+" character")}return{encode:f,decodeUnsafe:d,decode:S}}var nu=ru;const iu=nu,ou="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";var su=iu(ou),Tn=su,cu=function(e){function t(c){var s=Uint8Array.from(c),a=e(s),p=s.length+4,w=new Uint8Array(p);return w.set(s,0),w.set(a.subarray(0,4),s.length),Tn.encode(w,p)}function r(c){var s=c.slice(0,-4),a=c.slice(-4),p=e(s);if(!(a[0]^p[0]|a[1]^p[1]|a[2]^p[2]|a[3]^p[3]))return s}function n(c){var s=Tn.decodeUnsafe(c);if(s)return r(s)}function i(c){var s=Tn.decode(c),a=r(s);if(!a)throw new Error("Invalid checksum");return a}return{encode:t,decode:i,decodeUnsafe:n}},{sha256:Ci}=mt,uu=cu;function au(e){return Ci(Ci(e))}var Qn=uu(au);Object.defineProperty(Yr,"__esModule",{value:!0});Yr.p2pkh=void 0;const In=Ke,fu=ae,Vt=_e(),Ee=de,je=ke,Hi=Qn,it=Vt.OPS;function hu(e,t){if(!e.address&&!e.hash&&!e.output&&!e.pubkey&&!e.input)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,Ee.typeforce)({network:Ee.typeforce.maybe(Ee.typeforce.Object),address:Ee.typeforce.maybe(Ee.typeforce.String),hash:Ee.typeforce.maybe(Ee.typeforce.BufferN(20)),output:Ee.typeforce.maybe(Ee.typeforce.BufferN(25)),pubkey:Ee.typeforce.maybe(Ee.isPoint),signature:Ee.typeforce.maybe(Vt.isCanonicalScriptSignature),input:Ee.typeforce.maybe(Ee.typeforce.Buffer)},e);const r=je.value(()=>{const s=E.from(Hi.decode(e.address)),a=s.readUInt8(0),p=s.slice(1);return{version:a,hash:p}}),n=je.value(()=>Vt.decompile(e.input)),i=e.network||fu.bitcoin,c={name:"p2pkh",network:i};if(je.prop(c,"address",()=>{if(!c.hash)return;const s=E.allocUnsafe(21);return s.writeUInt8(i.pubKeyHash,0),c.hash.copy(s,1),Hi.encode(s)}),je.prop(c,"hash",()=>{if(e.output)return e.output.slice(3,23);if(e.address)return r().hash;if(e.pubkey||c.pubkey)return In.hash160(e.pubkey||c.pubkey)}),je.prop(c,"output",()=>{if(c.hash)return Vt.compile([it.OP_DUP,it.OP_HASH160,c.hash,it.OP_EQUALVERIFY,it.OP_CHECKSIG])}),je.prop(c,"pubkey",()=>{if(e.input)return n()[1]}),je.prop(c,"signature",()=>{if(e.input)return n()[0]}),je.prop(c,"input",()=>{if(e.pubkey&&e.signature)return Vt.compile([e.signature,e.pubkey])}),je.prop(c,"witness",()=>{if(c.input)return[]}),t.validate){let s=E.from([]);if(e.address){if(r().version!==i.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(r().hash.length!==20)throw new TypeError("Invalid address");s=r().hash}if(e.hash){if(s.length>0&&!s.equals(e.hash))throw new TypeError("Hash mismatch");s=e.hash}if(e.output){if(e.output.length!==25||e.output[0]!==it.OP_DUP||e.output[1]!==it.OP_HASH160||e.output[2]!==20||e.output[23]!==it.OP_EQUALVERIFY||e.output[24]!==it.OP_CHECKSIG)throw new TypeError("Output is invalid");const a=e.output.slice(3,23);if(s.length>0&&!s.equals(a))throw new TypeError("Hash mismatch");s=a}if(e.pubkey){const a=In.hash160(e.pubkey);if(s.length>0&&!s.equals(a))throw new TypeError("Hash mismatch");s=a}if(e.input){const a=n();if(a.length!==2)throw new TypeError("Input is invalid");if(!Vt.isCanonicalScriptSignature(a[0]))throw new TypeError("Input has invalid signature");if(!(0,Ee.isPoint)(a[1]))throw new TypeError("Input has invalid pubkey");if(e.signature&&!e.signature.equals(a[0]))throw new TypeError("Signature mismatch");if(e.pubkey&&!e.pubkey.equals(a[1]))throw new TypeError("Pubkey mismatch");const p=In.hash160(a[1]);if(s.length>0&&!s.equals(p))throw new TypeError("Hash mismatch")}}return Object.assign(c,e)}Yr.p2pkh=hu;var Zr={};Object.defineProperty(Zr,"__esModule",{value:!0});Zr.p2sh=void 0;const Ri=Ke,pu=ae,Re=_e(),X=de,Ce=ke,Fi=Qn,nr=Re.OPS;function lu(e,t){if(!e.address&&!e.hash&&!e.output&&!e.redeem&&!e.input)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,X.typeforce)({network:X.typeforce.maybe(X.typeforce.Object),address:X.typeforce.maybe(X.typeforce.String),hash:X.typeforce.maybe(X.typeforce.BufferN(20)),output:X.typeforce.maybe(X.typeforce.BufferN(23)),redeem:X.typeforce.maybe({network:X.typeforce.maybe(X.typeforce.Object),output:X.typeforce.maybe(X.typeforce.Buffer),input:X.typeforce.maybe(X.typeforce.Buffer),witness:X.typeforce.maybe(X.typeforce.arrayOf(X.typeforce.Buffer))}),input:X.typeforce.maybe(X.typeforce.Buffer),witness:X.typeforce.maybe(X.typeforce.arrayOf(X.typeforce.Buffer))},e);let r=e.network;r||(r=e.redeem&&e.redeem.network||pu.bitcoin);const n={network:r},i=Ce.value(()=>{const a=E.from(Fi.decode(e.address)),p=a.readUInt8(0),w=a.slice(1);return{version:p,hash:w}}),c=Ce.value(()=>Re.decompile(e.input)),s=Ce.value(()=>{const a=c(),p=a[a.length-1];return{network:r,output:p===nr.OP_FALSE?E.from([]):p,input:Re.compile(a.slice(0,-1)),witness:e.witness||[]}});if(Ce.prop(n,"address",()=>{if(!n.hash)return;const a=E.allocUnsafe(21);return a.writeUInt8(n.network.scriptHash,0),n.hash.copy(a,1),Fi.encode(a)}),Ce.prop(n,"hash",()=>{if(e.output)return e.output.slice(2,22);if(e.address)return i().hash;if(n.redeem&&n.redeem.output)return Ri.hash160(n.redeem.output)}),Ce.prop(n,"output",()=>{if(n.hash)return Re.compile([nr.OP_HASH160,n.hash,nr.OP_EQUAL])}),Ce.prop(n,"redeem",()=>{if(e.input)return s()}),Ce.prop(n,"input",()=>{if(!(!e.redeem||!e.redeem.input||!e.redeem.output))return Re.compile([].concat(Re.decompile(e.redeem.input),e.redeem.output))}),Ce.prop(n,"witness",()=>{if(n.redeem&&n.redeem.witness)return n.redeem.witness;if(n.input)return[]}),Ce.prop(n,"name",()=>{const a=["p2sh"];return n.redeem!==void 0&&n.redeem.name!==void 0&&a.push(n.redeem.name),a.join("-")}),t.validate){let a=E.from([]);if(e.address){if(i().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(i().hash.length!==20)throw new TypeError("Invalid address");a=i().hash}if(e.hash){if(a.length>0&&!a.equals(e.hash))throw new TypeError("Hash mismatch");a=e.hash}if(e.output){if(e.output.length!==23||e.output[0]!==nr.OP_HASH160||e.output[1]!==20||e.output[22]!==nr.OP_EQUAL)throw new TypeError("Output is invalid");const w=e.output.slice(2,22);if(a.length>0&&!a.equals(w))throw new TypeError("Hash mismatch");a=w}const p=w=>{if(w.output){const f=Re.decompile(w.output);if(!f||f.length<1)throw new TypeError("Redeem.output too short");if(w.output.byteLength>520)throw new TypeError("Redeem.output unspendable if larger than 520 bytes");if(Re.countNonPushOnlyOPs(f)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const d=Ri.hash160(w.output);if(a.length>0&&!a.equals(d))throw new TypeError("Hash mismatch");a=d}if(w.input){const f=w.input.length>0,d=w.witness&&w.witness.length>0;if(!f&&!d)throw new TypeError("Empty input");if(f&&d)throw new TypeError("Input and witness provided");if(f){const S=Re.decompile(w.input);if(!Re.isPushOnly(S))throw new TypeError("Non push-only scriptSig")}}};if(e.input){const w=c();if(!w||w.length<1)throw new TypeError("Input too short");if(!E.isBuffer(s().output))throw new TypeError("Input is invalid");p(s())}if(e.redeem){if(e.redeem.network&&e.redeem.network!==r)throw new TypeError("Network mismatch");if(e.input){const w=s();if(e.redeem.output&&!e.redeem.output.equals(w.output))throw new TypeError("Redeem.output mismatch");if(e.redeem.input&&!e.redeem.input.equals(w.input))throw new TypeError("Redeem.input mismatch")}p(e.redeem)}if(e.witness&&e.redeem&&e.redeem.witness&&!(0,X.stacksEqual)(e.redeem.witness,e.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,e)}Zr.p2sh=lu;var en={},Qe={};Object.defineProperty(Qe,"__esModule",{value:!0});Qe.bech32m=Qe.bech32=void 0;const $r="qpzry9x8gf2tvdw0s3jn54khce6mua7l",No={};for(let e=0;e<$r.length;e++){const t=$r.charAt(e);No[t]=e}function Xt(e){const t=e>>25;return(e&33554431)<<5^-(t>>0&1)&996825010^-(t>>1&1)&642813549^-(t>>2&1)&513874426^-(t>>3&1)&1027748829^-(t>>4&1)&705979059}function Li(e){let t=1;for(let r=0;r126)return"Invalid prefix ("+e+")";t=Xt(t)^n>>5}t=Xt(t);for(let r=0;r=r;)c-=r,a.push(i>>c&s);if(n)c>0&&a.push(i<=t)return"Excess padding";if(i<p)throw new TypeError("Exceeds length limit");s=s.toLowerCase();let w=Li(s);if(typeof w=="string")throw new Error(w);let f=s+"1";for(let d=0;d>5)throw new Error("Non 5-bit word");w=Xt(w)^S,f+=$r.charAt(S)}for(let d=0;d<6;++d)w=Xt(w);w^=t;for(let d=0;d<6;++d){const S=w>>(5-d)*5&31;f+=$r.charAt(S)}return f}function n(s,a){if(a=a||90,s.length<8)return s+" too short";if(s.length>a)return"Exceeds length limit";const p=s.toLowerCase(),w=s.toUpperCase();if(s!==p&&s!==w)return"Mixed-case string "+s;s=p;const f=s.lastIndexOf("1");if(f===-1)return"No separator character for "+s;if(f===0)return"Missing prefix for "+s;const d=s.slice(0,f),S=s.slice(f+1);if(S.length<6)return"Data too short";let y=Li(d);if(typeof y=="string")return y;const _=[];for(let T=0;T=S.length)&&_.push(x)}return y!==t?"Invalid checksum for "+s:{prefix:d,words:_}}function i(s,a){const p=n(s,a);if(typeof p=="object")return p}function c(s,a){const p=n(s,a);if(typeof p=="object")return p;throw new Error(p)}return{decodeUnsafe:i,decode:c,encode:r,toWords:du,fromWordsUnsafe:yu,fromWords:wu}}Qe.bech32=Co("bech32");Qe.bech32m=Co("bech32m");Object.defineProperty(en,"__esModule",{value:!0});en.p2wpkh=void 0;const kn=Ke,gu=ae,Cr=_e(),ie=de,ot=ke,kr=Qe,$i=Cr.OPS,Eu=E.alloc(0);function mu(e,t){if(!e.address&&!e.hash&&!e.output&&!e.pubkey&&!e.witness)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,ie.typeforce)({address:ie.typeforce.maybe(ie.typeforce.String),hash:ie.typeforce.maybe(ie.typeforce.BufferN(20)),input:ie.typeforce.maybe(ie.typeforce.BufferN(0)),network:ie.typeforce.maybe(ie.typeforce.Object),output:ie.typeforce.maybe(ie.typeforce.BufferN(22)),pubkey:ie.typeforce.maybe(ie.isPoint),signature:ie.typeforce.maybe(Cr.isCanonicalScriptSignature),witness:ie.typeforce.maybe(ie.typeforce.arrayOf(ie.typeforce.Buffer))},e);const r=ot.value(()=>{const c=kr.bech32.decode(e.address),s=c.words.shift(),a=kr.bech32.fromWords(c.words);return{version:s,prefix:c.prefix,data:E.from(a)}}),n=e.network||gu.bitcoin,i={name:"p2wpkh",network:n};if(ot.prop(i,"address",()=>{if(!i.hash)return;const c=kr.bech32.toWords(i.hash);return c.unshift(0),kr.bech32.encode(n.bech32,c)}),ot.prop(i,"hash",()=>{if(e.output)return e.output.slice(2,22);if(e.address)return r().data;if(e.pubkey||i.pubkey)return kn.hash160(e.pubkey||i.pubkey)}),ot.prop(i,"output",()=>{if(i.hash)return Cr.compile([$i.OP_0,i.hash])}),ot.prop(i,"pubkey",()=>{if(e.pubkey)return e.pubkey;if(e.witness)return e.witness[1]}),ot.prop(i,"signature",()=>{if(e.witness)return e.witness[0]}),ot.prop(i,"input",()=>{if(i.witness)return Eu}),ot.prop(i,"witness",()=>{if(e.pubkey&&e.signature)return[e.signature,e.pubkey]}),t.validate){let c=E.from([]);if(e.address){if(n&&n.bech32!==r().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(r().version!==0)throw new TypeError("Invalid address version");if(r().data.length!==20)throw new TypeError("Invalid address data");c=r().data}if(e.hash){if(c.length>0&&!c.equals(e.hash))throw new TypeError("Hash mismatch");c=e.hash}if(e.output){if(e.output.length!==22||e.output[0]!==$i.OP_0||e.output[1]!==20)throw new TypeError("Output is invalid");if(c.length>0&&!c.equals(e.output.slice(2)))throw new TypeError("Hash mismatch");c=e.output.slice(2)}if(e.pubkey){const s=kn.hash160(e.pubkey);if(c.length>0&&!c.equals(s))throw new TypeError("Hash mismatch");if(c=s,!(0,ie.isPoint)(e.pubkey)||e.pubkey.length!==33)throw new TypeError("Invalid pubkey for p2wpkh")}if(e.witness){if(e.witness.length!==2)throw new TypeError("Witness is invalid");if(!Cr.isCanonicalScriptSignature(e.witness[0]))throw new TypeError("Witness has invalid signature");if(!(0,ie.isPoint)(e.witness[1])||e.witness[1].length!==33)throw new TypeError("Witness has invalid pubkey");if(e.signature&&!e.signature.equals(e.witness[0]))throw new TypeError("Signature mismatch");if(e.pubkey&&!e.pubkey.equals(e.witness[1]))throw new TypeError("Pubkey mismatch");const s=kn.hash160(e.witness[1]);if(c.length>0&&!c.equals(s))throw new TypeError("Hash mismatch")}}return Object.assign(i,e)}en.p2wpkh=mu;var tn={};Object.defineProperty(tn,"__esModule",{value:!0});tn.p2wsh=void 0;const Mi=Ke,Su=ae,Xe=_e(),G=de,Ve=ke,Ar=Qe,Ki=Xe.OPS,An=E.alloc(0);function Or(e){return!!(E.isBuffer(e)&&e.length===65&&e[0]===4&&(0,G.isPoint)(e))}function bu(e,t){if(!e.address&&!e.hash&&!e.output&&!e.redeem&&!e.witness)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,G.typeforce)({network:G.typeforce.maybe(G.typeforce.Object),address:G.typeforce.maybe(G.typeforce.String),hash:G.typeforce.maybe(G.typeforce.BufferN(32)),output:G.typeforce.maybe(G.typeforce.BufferN(34)),redeem:G.typeforce.maybe({input:G.typeforce.maybe(G.typeforce.Buffer),network:G.typeforce.maybe(G.typeforce.Object),output:G.typeforce.maybe(G.typeforce.Buffer),witness:G.typeforce.maybe(G.typeforce.arrayOf(G.typeforce.Buffer))}),input:G.typeforce.maybe(G.typeforce.BufferN(0)),witness:G.typeforce.maybe(G.typeforce.arrayOf(G.typeforce.Buffer))},e);const r=Ve.value(()=>{const s=Ar.bech32.decode(e.address),a=s.words.shift(),p=Ar.bech32.fromWords(s.words);return{version:a,prefix:s.prefix,data:E.from(p)}}),n=Ve.value(()=>Xe.decompile(e.redeem.input));let i=e.network;i||(i=e.redeem&&e.redeem.network||Su.bitcoin);const c={network:i};if(Ve.prop(c,"address",()=>{if(!c.hash)return;const s=Ar.bech32.toWords(c.hash);return s.unshift(0),Ar.bech32.encode(i.bech32,s)}),Ve.prop(c,"hash",()=>{if(e.output)return e.output.slice(2);if(e.address)return r().data;if(c.redeem&&c.redeem.output)return Mi.sha256(c.redeem.output)}),Ve.prop(c,"output",()=>{if(c.hash)return Xe.compile([Ki.OP_0,c.hash])}),Ve.prop(c,"redeem",()=>{if(e.witness)return{output:e.witness[e.witness.length-1],input:An,witness:e.witness.slice(0,-1)}}),Ve.prop(c,"input",()=>{if(c.witness)return An}),Ve.prop(c,"witness",()=>{if(e.redeem&&e.redeem.input&&e.redeem.input.length>0&&e.redeem.output&&e.redeem.output.length>0){const s=Xe.toStack(n());return c.redeem=Object.assign({witness:s},e.redeem),c.redeem.input=An,[].concat(s,e.redeem.output)}if(e.redeem&&e.redeem.output&&e.redeem.witness)return[].concat(e.redeem.witness,e.redeem.output)}),Ve.prop(c,"name",()=>{const s=["p2wsh"];return c.redeem!==void 0&&c.redeem.name!==void 0&&s.push(c.redeem.name),s.join("-")}),t.validate){let s=E.from([]);if(e.address){if(r().prefix!==i.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(r().version!==0)throw new TypeError("Invalid address version");if(r().data.length!==32)throw new TypeError("Invalid address data");s=r().data}if(e.hash){if(s.length>0&&!s.equals(e.hash))throw new TypeError("Hash mismatch");s=e.hash}if(e.output){if(e.output.length!==34||e.output[0]!==Ki.OP_0||e.output[1]!==32)throw new TypeError("Output is invalid");const a=e.output.slice(2);if(s.length>0&&!s.equals(a))throw new TypeError("Hash mismatch");s=a}if(e.redeem){if(e.redeem.network&&e.redeem.network!==i)throw new TypeError("Network mismatch");if(e.redeem.input&&e.redeem.input.length>0&&e.redeem.witness&&e.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(e.redeem.output){const a=Xe.decompile(e.redeem.output);if(!a||a.length<1)throw new TypeError("Redeem.output is invalid");if(e.redeem.output.byteLength>3600)throw new TypeError("Redeem.output unspendable if larger than 3600 bytes");if(Xe.countNonPushOnlyOPs(a)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const p=Mi.sha256(e.redeem.output);if(s.length>0&&!s.equals(p))throw new TypeError("Hash mismatch");s=p}if(e.redeem.input&&!Xe.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(e.witness&&e.redeem.witness&&!(0,G.stacksEqual)(e.witness,e.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(e.redeem.input&&n().some(Or)||e.redeem.output&&(Xe.decompile(e.redeem.output)||[]).some(Or))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(e.witness&&e.witness.length>0){const a=e.witness[e.witness.length-1];if(e.redeem&&e.redeem.output&&!e.redeem.output.equals(a))throw new TypeError("Witness and redeem.output mismatch");if(e.witness.some(Or)||(Xe.decompile(a)||[]).some(Or))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(c,e)}tn.p2wsh=bu;var ir={},ht={};Object.defineProperty(ht,"__esModule",{value:!0});ht.getEccLib=ht.initEccLib=void 0;const pr={};function _u(e){e?e!==pr.eccLib&&(Iu(e),pr.eccLib=e):pr.eccLib=e}ht.initEccLib=_u;function Tu(){if(!pr.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return pr.eccLib}ht.getEccLib=Tu;const Ge=e=>E.from(e,"hex");function Iu(e){Ae(typeof e.isXOnlyPoint=="function"),Ae(e.isXOnlyPoint(Ge("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),Ae(e.isXOnlyPoint(Ge("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),Ae(e.isXOnlyPoint(Ge("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),Ae(e.isXOnlyPoint(Ge("0000000000000000000000000000000000000000000000000000000000000001"))),Ae(!e.isXOnlyPoint(Ge("0000000000000000000000000000000000000000000000000000000000000000"))),Ae(!e.isXOnlyPoint(Ge("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),Ae(typeof e.xOnlyPointAddTweak=="function"),ku.forEach(t=>{const r=e.xOnlyPointAddTweak(Ge(t.pubkey),Ge(t.tweak));t.result===null?Ae(r===null):(Ae(r!==null),Ae(r.parity===t.parity),Ae(E.from(r.xOnlyPubkey).equals(Ge(t.result))))})}function Ae(e){if(!e)throw new Error("ecc library invalid")}const ku=[{pubkey:"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",tweak:"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140",parity:-1,result:null},{pubkey:"1617d38ed8d8657da4d4761e8057bc396ea9e4b9d29776d4be096016dbd2509b",tweak:"a8397a935f0dfceba6ba9618f6451ef4d80637abf4e6af2669fbc9de6a8fd2ac",parity:1,result:"e478f99dab91052ab39a33ea35fd5e6e4933f4d28023cd597c9a1f6760346adf"},{pubkey:"2c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991",tweak:"823c3cd2142744b075a87eade7e1b8678ba308d566226a0056ca2b7a76f86b47",parity:0,result:"9534f8dc8c6deda2dc007655981c78b49c5d96c778fbf363462a11ec9dfd948c"}];var rn={},oe={},Ln={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh */(function(e,t){var r=Xr,n=r.Buffer;function i(s,a){for(var p in s)a[p]=s[p]}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=c);function c(s,a,p){return n(s,a,p)}c.prototype=Object.create(n.prototype),i(n,c),c.from=function(s,a,p){if(typeof s=="number")throw new TypeError("Argument must not be a number");return n(s,a,p)},c.alloc=function(s,a,p){if(typeof s!="number")throw new TypeError("Argument must be a number");var w=n(s);return a!==void 0?typeof p=="string"?w.fill(a,p):w.fill(a):w.fill(0),w},c.allocUnsafe=function(s){if(typeof s!="number")throw new TypeError("Argument must be a number");return n(s)},c.allocUnsafeSlow=function(s){if(typeof s!="number")throw new TypeError("Argument must be a number");return r.SlowBuffer(s)}})(Ln,Ln.exports);var Au=Ln.exports,$n=Au.Buffer,Ou=9007199254740991;function ei(e){if(e<0||e>Ou||e%1!==0)throw new RangeError("value out of range")}function ur(e,t,r){if(ei(e),t||(t=$n.allocUnsafe(Ho(e))),!$n.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");return r||(r=0),e<253?(t.writeUInt8(e,r),ur.bytes=1):e<=65535?(t.writeUInt8(253,r),t.writeUInt16LE(e,r+1),ur.bytes=3):e<=4294967295?(t.writeUInt8(254,r),t.writeUInt32LE(e,r+1),ur.bytes=5):(t.writeUInt8(255,r),t.writeUInt32LE(e>>>0,r+1),t.writeUInt32LE(e/4294967296|0,r+5),ur.bytes=9),t}function ar(e,t){if(!$n.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");t||(t=0);var r=e.readUInt8(t);if(r<253)return ar.bytes=1,r;if(r===253)return ar.bytes=3,e.readUInt16LE(t+1);if(r===254)return ar.bytes=5,e.readUInt32LE(t+1);ar.bytes=9;var n=e.readUInt32LE(t+1),i=e.readUInt32LE(t+5),c=i*4294967296+n;return ei(c),c}function Ho(e){return ei(e),e<253?1:e<=65535?3:e<=4294967295?5:9}var Pu={encode:ur,decode:ar,encodingLength:Ho};Object.defineProperty(oe,"__esModule",{value:!0});oe.BufferReader=oe.BufferWriter=oe.cloneBuffer=oe.reverseBuffer=oe.writeUInt64LE=oe.readUInt64LE=oe.varuint=void 0;const Et=de,{typeforce:Ro}=Et,wr=Pu;oe.varuint=wr;function Fo(e,t){if(typeof e!="number")throw new Error("cannot write a non-number as a number");if(e<0)throw new Error("specified a negative value for writing an unsigned value");if(e>t)throw new Error("RangeError: value out of range");if(Math.floor(e)!==e)throw new Error("value has a fractional component")}function Lo(e,t){const r=e.readUInt32LE(t);let n=e.readUInt32LE(t+4);return n*=4294967296,Fo(n+r,9007199254740991),n+r}oe.readUInt64LE=Lo;function $o(e,t,r){return Fo(t,9007199254740991),e.writeInt32LE(t&-1,r),e.writeUInt32LE(Math.floor(t/4294967296),r+4),r+8}oe.writeUInt64LE=$o;function vu(e){if(e.length<1)return e;let t=e.length-1,r=0;for(let n=0;nthis.writeVarSlice(r))}end(){if(this.buffer.length===this.offset)return this.buffer;throw new Error(`buffer size ${this.buffer.length}, offset ${this.offset}`)}}oe.BufferWriter=ti;class xu{constructor(t,r=0){this.buffer=t,this.offset=r,Ro(Et.tuple(Et.Buffer,Et.UInt32),[t,r])}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=Lo(this.buffer,this.offset);return this.offset+=8,t}readVarInt(){const t=wr.decode(this.buffer,this.offset);return this.offset+=wr.decode.bytes,t}readSlice(t){if(this.buffer.length"left"in T&&"right"in T;function a(T,P){if(T.length<33)throw new TypeError(`The control-block length is too small. Got ${T.length}, expected min 33.`);const x=(T.length-33)/32;let N=P;for(let k=0;kk.hash.compare(m.hash));const[x,N]=P;return{hash:y(x.hash,N.hash),left:x,right:N}}e.toHashTree=p;function w(T,P){if(s(T)){const x=w(T.left,P);if(x!==void 0)return[...x,T.right.hash];const N=w(T.right,P);if(N!==void 0)return[...N,T.left.hash]}else if(T.hash.equals(P))return[]}e.findScriptPath=w;function f(T){const P=T.version||e.LEAF_VERSION_TAPSCRIPT;return n.taggedHash("TapLeaf",t.Buffer.concat([t.Buffer.from([P]),_(T.output)]))}e.tapleafHash=f;function d(T,P){return n.taggedHash("TapTweak",t.Buffer.concat(P?[T,P]:[T]))}e.tapTweakHash=d;function S(T,P){if(!t.Buffer.isBuffer(T)||T.length!==32||P&&P.length!==32)return null;const x=d(T,P),N=(0,r.getEccLib)().xOnlyPointAddTweak(T,x);return!N||N.xOnlyPubkey===null?null:{parity:N.parity,x:t.Buffer.from(N.xOnlyPubkey)}}e.tweakKey=S;function y(T,P){return n.taggedHash("TapBranch",t.Buffer.concat([T,P]))}function _(T){const P=i.varuint.encodingLength(T.length),x=t.Buffer.allocUnsafe(P);return i.varuint.encode(T.length,x),t.Buffer.concat([x,T])}})(rn);var Di;function Uu(){if(Di)return ir;Di=1,Object.defineProperty(ir,"__esModule",{value:!0}),ir.p2tr=void 0;const e=Xr,t=ae,r=_e(),n=de,i=ht,c=rn,s=ke,a=Qe,p=ri(),w=r.OPS,f=1,d=80;function S(y,_){if(!y.address&&!y.output&&!y.pubkey&&!y.internalPubkey&&!(y.witness&&y.witness.length>1))throw new TypeError("Not enough data");_=Object.assign({validate:!0},_||{}),(0,n.typeforce)({address:n.typeforce.maybe(n.typeforce.String),input:n.typeforce.maybe(n.typeforce.BufferN(0)),network:n.typeforce.maybe(n.typeforce.Object),output:n.typeforce.maybe(n.typeforce.BufferN(34)),internalPubkey:n.typeforce.maybe(n.typeforce.BufferN(32)),hash:n.typeforce.maybe(n.typeforce.BufferN(32)),pubkey:n.typeforce.maybe(n.typeforce.BufferN(32)),signature:n.typeforce.maybe(n.typeforce.anyOf(n.typeforce.BufferN(64),n.typeforce.BufferN(65))),witness:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer)),scriptTree:n.typeforce.maybe(n.isTaptree),redeem:n.typeforce.maybe({output:n.typeforce.maybe(n.typeforce.Buffer),redeemVersion:n.typeforce.maybe(n.typeforce.Number),witness:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer))}),redeemVersion:n.typeforce.maybe(n.typeforce.Number)},y);const T=s.value(()=>(0,p.fromBech32)(y.address)),P=s.value(()=>{if(!(!y.witness||!y.witness.length))return y.witness.length>=2&&y.witness[y.witness.length-1][0]===d?y.witness.slice(0,-1):y.witness.slice()}),x=s.value(()=>{if(y.scriptTree)return(0,c.toHashTree)(y.scriptTree);if(y.hash)return{hash:y.hash}}),N=y.network||t.bitcoin,k={name:"p2tr",network:N};if(s.prop(k,"address",()=>{if(!k.pubkey)return;const m=a.bech32m.toWords(k.pubkey);return m.unshift(f),a.bech32m.encode(N.bech32,m)}),s.prop(k,"hash",()=>{const m=x();if(m)return m.hash;const v=P();if(v&&v.length>1){const I=v[v.length-1],C=I[0]&n.TAPLEAF_VERSION_MASK,M=v[v.length-2],B=(0,c.tapleafHash)({output:M,version:C});return(0,c.rootHashFromPath)(I,B)}return null}),s.prop(k,"output",()=>{if(k.pubkey)return r.compile([w.OP_1,k.pubkey])}),s.prop(k,"redeemVersion",()=>y.redeemVersion?y.redeemVersion:y.redeem&&y.redeem.redeemVersion!==void 0&&y.redeem.redeemVersion!==null?y.redeem.redeemVersion:c.LEAF_VERSION_TAPSCRIPT),s.prop(k,"redeem",()=>{const m=P();if(!(!m||m.length<2))return{output:m[m.length-2],witness:m.slice(0,-2),redeemVersion:m[m.length-1][0]&n.TAPLEAF_VERSION_MASK}}),s.prop(k,"pubkey",()=>{if(y.pubkey)return y.pubkey;if(y.output)return y.output.slice(2);if(y.address)return T().data;if(k.internalPubkey){const m=(0,c.tweakKey)(k.internalPubkey,k.hash);if(m)return m.x}}),s.prop(k,"internalPubkey",()=>{if(y.internalPubkey)return y.internalPubkey;const m=P();if(m&&m.length>1)return m[m.length-1].slice(1,33)}),s.prop(k,"signature",()=>{if(y.signature)return y.signature;const m=P();if(!(!m||m.length!==1))return m[0]}),s.prop(k,"witness",()=>{if(y.witness)return y.witness;const m=x();if(m&&y.redeem&&y.redeem.output&&y.internalPubkey){const v=(0,c.tapleafHash)({output:y.redeem.output,version:k.redeemVersion}),I=(0,c.findScriptPath)(m,v);if(!I)return;const C=(0,c.tweakKey)(y.internalPubkey,m.hash);if(!C)return;const M=e.Buffer.concat([e.Buffer.from([k.redeemVersion|C.parity]),y.internalPubkey].concat(I));return[y.redeem.output,M]}if(y.signature)return[y.signature]}),_.validate){let m=e.Buffer.from([]);if(y.address){if(N&&N.bech32!==T().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(T().version!==f)throw new TypeError("Invalid address version");if(T().data.length!==32)throw new TypeError("Invalid address data");m=T().data}if(y.pubkey){if(m.length>0&&!m.equals(y.pubkey))throw new TypeError("Pubkey mismatch");m=y.pubkey}if(y.output){if(y.output.length!==34||y.output[0]!==w.OP_1||y.output[1]!==32)throw new TypeError("Output is invalid");if(m.length>0&&!m.equals(y.output.slice(2)))throw new TypeError("Pubkey mismatch");m=y.output.slice(2)}if(y.internalPubkey){const C=(0,c.tweakKey)(y.internalPubkey,k.hash);if(m.length>0&&!m.equals(C.x))throw new TypeError("Pubkey mismatch");m=C.x}if(m&&m.length&&!(0,i.getEccLib)().isXOnlyPoint(m))throw new TypeError("Invalid pubkey for p2tr");const v=x();if(y.hash&&v&&!y.hash.equals(v.hash))throw new TypeError("Hash mismatch");if(y.redeem&&y.redeem.output&&v){const C=(0,c.tapleafHash)({output:y.redeem.output,version:k.redeemVersion});if(!(0,c.findScriptPath)(v,C))throw new TypeError("Redeem script not in tree")}const I=P();if(y.redeem&&k.redeem){if(y.redeem.redeemVersion&&y.redeem.redeemVersion!==k.redeem.redeemVersion)throw new TypeError("Redeem.redeemVersion and witness mismatch");if(y.redeem.output){if(r.decompile(y.redeem.output).length===0)throw new TypeError("Redeem.output is invalid");if(k.redeem.output&&!y.redeem.output.equals(k.redeem.output))throw new TypeError("Redeem.output and witness mismatch")}if(y.redeem.witness&&k.redeem.witness&&!(0,n.stacksEqual)(y.redeem.witness,k.redeem.witness))throw new TypeError("Redeem.witness and witness mismatch")}if(I&&I.length)if(I.length===1){if(y.signature&&!y.signature.equals(I[0]))throw new TypeError("Signature mismatch")}else{const C=I[I.length-1];if(C.length<33)throw new TypeError(`The control-block length is too small. Got ${C.length}, expected min 33.`);if((C.length-33)%32!==0)throw new TypeError(`The control-block length of ${C.length} is incorrect!`);const M=(C.length-33)/32;if(M>128)throw new TypeError(`The script path is too long. Got ${M}, expected max 128.`);const B=C.slice(1,33);if(y.internalPubkey&&!y.internalPubkey.equals(B))throw new TypeError("Internal pubkey mismatch");if(!(0,i.getEccLib)().isXOnlyPoint(B))throw new TypeError("Invalid internalPubkey for p2tr witness");const R=C[0]&n.TAPLEAF_VERSION_MASK,j=I[I.length-2],O=(0,c.tapleafHash)({output:j,version:R}),U=(0,c.rootHashFromPath)(C,O),F=(0,c.tweakKey)(B,U);if(!F)throw new TypeError("Invalid outputKey for p2tr witness");if(m.length&&!m.equals(F.x))throw new TypeError("Pubkey mismatch for p2tr witness");if(F.parity!==(C[0]&1))throw new Error("Incorrect parity")}}return Object.assign(k,y)}return ir.p2tr=S,ir}var Wi;function mr(){return Wi||(Wi=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.p2tr=e.p2wsh=e.p2wpkh=e.p2sh=e.p2pkh=e.p2pk=e.p2ms=e.embed=void 0;const t=Gr;Object.defineProperty(e,"embed",{enumerable:!0,get:function(){return t.p2data}});const r=qr;Object.defineProperty(e,"p2ms",{enumerable:!0,get:function(){return r.p2ms}});const n=zr;Object.defineProperty(e,"p2pk",{enumerable:!0,get:function(){return n.p2pk}});const i=Yr;Object.defineProperty(e,"p2pkh",{enumerable:!0,get:function(){return i.p2pkh}});const c=Zr;Object.defineProperty(e,"p2sh",{enumerable:!0,get:function(){return c.p2sh}});const s=en;Object.defineProperty(e,"p2wpkh",{enumerable:!0,get:function(){return s.p2wpkh}});const a=tn;Object.defineProperty(e,"p2wsh",{enumerable:!0,get:function(){return a.p2wsh}});const p=Uu();Object.defineProperty(e,"p2tr",{enumerable:!0,get:function(){return p.p2tr}})}(gn)),gn}var ji;function ri(){if(ji)return ge;ji=1,Object.defineProperty(ge,"__esModule",{value:!0}),ge.toOutputScript=ge.fromOutputScript=ge.toBech32=ge.toBase58Check=ge.fromBech32=ge.fromBase58Check=void 0;const e=ae,t=mr(),r=_e(),n=de,i=Qe,c=Qn,s=40,a=2,p=16,w=2,f=80,d="WARNING: Sending to a future segwit version address can lead to loss of funds. End users MUST be warned carefully in the GUI and asked if they wish to proceed with caution. Wallets should verify the segwit version from the output of fromBech32, then decide when it is safe to use which version of segwit.";function S(k,m){const v=k.slice(2);if(v.lengths)throw new TypeError("Invalid program length for segwit address");const I=k[0]-f;if(Ip)throw new TypeError("Invalid version for segwit address");if(k[1]!==v.length)throw new TypeError("Invalid script for segwit address");return console.warn(d),P(v,I,m.bech32)}function y(k){const m=E.from(c.decode(k));if(m.length<21)throw new TypeError(k+" is too short");if(m.length>21)throw new TypeError(k+" is too long");const v=m.readUInt8(0),I=m.slice(1);return{version:v,hash:I}}ge.fromBase58Check=y;function _(k){let m,v;try{m=i.bech32.decode(k)}catch{}if(m){if(v=m.words[0],v!==0)throw new TypeError(k+" uses wrong encoding")}else if(m=i.bech32m.decode(k),v=m.words[0],v===0)throw new TypeError(k+" uses wrong encoding");const I=i.bech32.fromWords(m.words.slice(1));return{version:v,prefix:m.prefix,data:E.from(I)}}ge.fromBech32=_;function T(k,m){(0,n.typeforce)((0,n.tuple)(n.Hash160bit,n.UInt8),arguments);const v=E.allocUnsafe(21);return v.writeUInt8(m,0),k.copy(v,1),c.encode(v)}ge.toBase58Check=T;function P(k,m,v){const I=i.bech32.toWords(k);return I.unshift(m),m===0?i.bech32.encode(v,I):i.bech32m.encode(v,I)}ge.toBech32=P;function x(k,m){m=m||e.bitcoin;try{return t.p2pkh({output:k,network:m}).address}catch{}try{return t.p2sh({output:k,network:m}).address}catch{}try{return t.p2wpkh({output:k,network:m}).address}catch{}try{return t.p2wsh({output:k,network:m}).address}catch{}try{return t.p2tr({output:k,network:m}).address}catch{}try{return S(k,m)}catch{}throw new Error(r.toASM(k)+" has no matching Address")}ge.fromOutputScript=x;function N(k,m){m=m||e.bitcoin;let v,I;try{v=y(k)}catch{}if(v){if(v.version===m.pubKeyHash)return t.p2pkh({hash:v.hash}).output;if(v.version===m.scriptHash)return t.p2sh({hash:v.hash}).output}else{try{I=_(k)}catch{}if(I){if(I.prefix!==m.bech32)throw new Error(k+" has an invalid prefix");if(I.version===0){if(I.data.length===20)return t.p2wpkh({hash:I.data}).output;if(I.data.length===32)return t.p2wsh({hash:I.data}).output}else if(I.version===1){if(I.data.length===32)return t.p2tr({pubkey:I.data}).output}else if(I.version>=w&&I.version<=p&&I.data.length>=a&&I.data.length<=s)return console.warn(d),r.compile([I.version+f,I.data])}}throw new Error(k+" has no matching Script")}return ge.toOutputScript=N,ge}var nn={},on={};Object.defineProperty(on,"__esModule",{value:!0});on.fastMerkleRoot=void 0;function Nu(e,t){if(!Array.isArray(e))throw TypeError("Expected values Array");if(typeof t!="function")throw TypeError("Expected digest Function");let r=e.length;const n=e.concat();for(;r>1;){let i=0;for(let c=0;cr+Fe(n),0)}const st=E.allocUnsafe(0),Gi=[],On=E.from("0000000000000000000000000000000000000000000000000000000000000000","hex"),Xi=E.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),Ru=E.from("ffffffffffffffff","hex"),Fu={script:st,valueBuffer:Ru};function Lu(e){return e.value!==void 0}class L{constructor(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}static fromBuffer(t,r){const n=new te.BufferReader(t),i=new L;i.version=n.readInt32();const c=n.readUInt8(),s=n.readUInt8();let a=!1;c===L.ADVANCED_TRANSACTION_MARKER&&s===L.ADVANCED_TRANSACTION_FLAG?a=!0:n.offset-=2;const p=n.readVarInt();for(let f=0;ft.witness.length!==0)}weight(){const t=this.byteLength(!1),r=this.byteLength(!0);return t*3+r}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(t=!0){const r=t&&this.hasWitnesses();return(r?10:8)+te.varuint.encodingLength(this.ins.length)+te.varuint.encodingLength(this.outs.length)+this.ins.reduce((n,i)=>n+40+Fe(i.script),0)+this.outs.reduce((n,i)=>n+8+Fe(i.script),0)+(r?this.ins.reduce((n,i)=>n+Hu(i.witness),0):0)}clone(){const t=new L;return t.version=this.version,t.locktime=this.locktime,t.ins=this.ins.map(r=>({hash:r.hash,index:r.index,script:r.script,sequence:r.sequence,witness:r.witness})),t.outs=this.outs.map(r=>({script:r.script,value:r.value})),t}hashForSignature(t,r,n){if(He(K.tuple(K.UInt32,K.Buffer,K.Number),arguments),t>=this.ins.length)return Xi;const i=Vi.compile(Vi.decompile(r).filter(a=>a!==Cu.OPS.OP_CODESEPARATOR)),c=this.clone();if((n&31)===L.SIGHASH_NONE)c.outs=[],c.ins.forEach((a,p)=>{p!==t&&(a.sequence=0)});else if((n&31)===L.SIGHASH_SINGLE){if(t>=this.outs.length)return Xi;c.outs.length=t+1;for(let a=0;a{p!==t&&(a.sequence=0)})}n&L.SIGHASH_ANYONECANPAY?(c.ins=[c.ins[t]],c.ins[0].script=i):(c.ins.forEach(a=>{a.script=st}),c.ins[t].script=i);const s=E.allocUnsafe(c.byteLength(!1)+4);return s.writeInt32LE(n,s.length-4),c.__toBuffer(s,0,!1),me.hash256(s)}hashForWitnessV1(t,r,n,i,c,s){if(He(K.tuple(K.UInt32,He.arrayOf(K.Buffer),He.arrayOf(K.Satoshi),K.UInt32),arguments),n.length!==this.ins.length||r.length!==this.ins.length)throw new Error("Must supply prevout script and value for all inputs");const a=i===L.SIGHASH_DEFAULT?L.SIGHASH_ALL:i&L.SIGHASH_OUTPUT_MASK,w=(i&L.SIGHASH_INPUT_MASK)===L.SIGHASH_ANYONECANPAY,f=a===L.SIGHASH_NONE,d=a===L.SIGHASH_SINGLE;let S=st,y=st,_=st,T=st,P=st;if(!w){let m=te.BufferWriter.withCapacity(36*this.ins.length);this.ins.forEach(v=>{m.writeSlice(v.hash),m.writeUInt32(v.index)}),S=me.sha256(m.end()),m=te.BufferWriter.withCapacity(8*this.ins.length),n.forEach(v=>m.writeUInt64(v)),y=me.sha256(m.end()),m=te.BufferWriter.withCapacity(r.map(Fe).reduce((v,I)=>v+I)),r.forEach(v=>m.writeVarSlice(v)),_=me.sha256(m.end()),m=te.BufferWriter.withCapacity(4*this.ins.length),this.ins.forEach(v=>m.writeUInt32(v.sequence)),T=me.sha256(m.end())}if(f||d){if(d&&t8+Fe(I.script)).reduce((I,C)=>I+C),v=te.BufferWriter.withCapacity(m);this.outs.forEach(I=>{v.writeUInt64(I.value),v.writeVarSlice(I.script)}),P=me.sha256(v.end())}const x=(c?2:0)+(s?1:0),N=174-(w?49:0)-(f?32:0)+(s?32:0)+(c?37:0),k=te.BufferWriter.withCapacity(N);if(k.writeUInt8(i),k.writeInt32(this.version),k.writeUInt32(this.locktime),k.writeSlice(S),k.writeSlice(y),k.writeSlice(_),k.writeSlice(T),f||d||k.writeSlice(P),k.writeUInt8(x),w){const m=this.ins[t];k.writeSlice(m.hash),k.writeUInt32(m.index),k.writeUInt64(n[t]),k.writeVarSlice(r[t]),k.writeUInt32(m.sequence)}else k.writeUInt32(t);if(s){const m=te.BufferWriter.withCapacity(Fe(s));m.writeVarSlice(s),k.writeSlice(me.sha256(m.end()))}return d&&k.writeSlice(P),c&&(k.writeSlice(c),k.writeUInt8(0),k.writeUInt32(4294967295)),me.taggedHash("TapSighash",E.concat([E.from([0]),k.end()]))}hashForWitnessV0(t,r,n,i){He(K.tuple(K.UInt32,K.Buffer,K.Satoshi,K.UInt32),arguments);let c=E.from([]),s,a=On,p=On,w=On;if(i&L.SIGHASH_ANYONECANPAY||(c=E.allocUnsafe(36*this.ins.length),s=new te.BufferWriter(c,0),this.ins.forEach(d=>{s.writeSlice(d.hash),s.writeUInt32(d.index)}),p=me.hash256(c)),!(i&L.SIGHASH_ANYONECANPAY)&&(i&31)!==L.SIGHASH_SINGLE&&(i&31)!==L.SIGHASH_NONE&&(c=E.allocUnsafe(4*this.ins.length),s=new te.BufferWriter(c,0),this.ins.forEach(d=>{s.writeUInt32(d.sequence)}),w=me.hash256(c)),(i&31)!==L.SIGHASH_SINGLE&&(i&31)!==L.SIGHASH_NONE){const d=this.outs.reduce((S,y)=>S+8+Fe(y.script),0);c=E.allocUnsafe(d),s=new te.BufferWriter(c,0),this.outs.forEach(S=>{s.writeUInt64(S.value),s.writeVarSlice(S.script)}),a=me.hash256(c)}else if((i&31)===L.SIGHASH_SINGLE&&t{i.writeSlice(s.hash),i.writeUInt32(s.index),i.writeVarSlice(s.script),i.writeUInt32(s.sequence)}),i.writeVarInt(this.outs.length),this.outs.forEach(s=>{Lu(s)?i.writeUInt64(s.value):i.writeSlice(s.valueBuffer),i.writeVarSlice(s.script)}),c&&this.ins.forEach(s=>{i.writeVector(s.witness)}),i.writeUInt32(this.locktime),r!==void 0?t.slice(r,i.offset):t}}lt.Transaction=L;L.DEFAULT_SEQUENCE=4294967295;L.SIGHASH_DEFAULT=0;L.SIGHASH_ALL=1;L.SIGHASH_NONE=2;L.SIGHASH_SINGLE=3;L.SIGHASH_ANYONECANPAY=128;L.SIGHASH_OUTPUT_MASK=3;L.SIGHASH_INPUT_MASK=128;L.ADVANCED_TRANSACTION_MARKER=0;L.ADVANCED_TRANSACTION_FLAG=1;Object.defineProperty(nn,"__esModule",{value:!0});nn.Block=void 0;const yt=oe,Pn=Ke,$u=on,Mu=lt,Mo=de,{typeforce:Ku}=Mo,vn=new TypeError("Cannot compute merkle root for zero transactions"),qi=new TypeError("Cannot compute witness commit for non-segwit block");class wt{constructor(){this.version=1,this.prevHash=void 0,this.merkleRoot=void 0,this.timestamp=0,this.witnessCommit=void 0,this.bits=0,this.nonce=0,this.transactions=void 0}static fromBuffer(t){if(t.length<80)throw new Error("Buffer too small (< 80 bytes)");const r=new yt.BufferReader(t),n=new wt;if(n.version=r.readInt32(),n.prevHash=r.readSlice(32),n.merkleRoot=r.readSlice(32),n.timestamp=r.readUInt32(),n.bits=r.readUInt32(),n.nonce=r.readUInt32(),t.length===80)return n;const i=()=>{const a=Mu.Transaction.fromBuffer(r.buffer.slice(r.offset),!0);return r.offset+=a.byteLength(),a},c=r.readVarInt();n.transactions=[];for(let a=0;a>24)-3,n=t&8388607,i=E.alloc(32,0);return i.writeUIntBE(n,29-r,3),i}static calculateMerkleRoot(t,r){if(Ku([{getHash:Mo.Function}],t),t.length===0)throw vn;if(r&&!zi(t))throw qi;const n=t.map(c=>c.getHash(r)),i=(0,$u.fastMerkleRoot)(n,Pn.hash256);return r?Pn.hash256(E.concat([i,t[0].ins[0].witness[0]])):i}getWitnessCommit(){if(!zi(this.transactions))return null;const t=this.transactions[0].outs.filter(n=>n.script.slice(0,6).equals(E.from("6a24aa21a9ed","hex"))).map(n=>n.script.slice(6,38));if(t.length===0)return null;const r=t[t.length-1];return r instanceof E&&r.length===32?r:null}hasWitnessCommit(){return this.witnessCommit instanceof E&&this.witnessCommit.length===32||this.getWitnessCommit()!==null}hasWitness(){return Du(this.transactions)}weight(){const t=this.byteLength(!1,!1),r=this.byteLength(!1,!0);return t*3+r}byteLength(t,r=!0){return t||!this.transactions?80:80+yt.varuint.encodingLength(this.transactions.length)+this.transactions.reduce((n,i)=>n+i.byteLength(r),0)}getHash(){return Pn.hash256(this.toBuffer(!0))}getId(){return(0,yt.reverseBuffer)(this.getHash()).toString("hex")}getUTCDate(){const t=new Date(0);return t.setUTCSeconds(this.timestamp),t}toBuffer(t){const r=E.allocUnsafe(this.byteLength(t)),n=new yt.BufferWriter(r);return n.writeInt32(this.version),n.writeSlice(this.prevHash),n.writeSlice(this.merkleRoot),n.writeUInt32(this.timestamp),n.writeUInt32(this.bits),n.writeUInt32(this.nonce),t||!this.transactions||(yt.varuint.encode(this.transactions.length,r,n.offset),n.offset+=yt.varuint.encode.bytes,this.transactions.forEach(i=>{const c=i.byteLength();i.toBuffer(r,n.offset),n.offset+=c})),r}toHex(t){return this.toBuffer(t).toString("hex")}checkTxRoots(){const t=this.hasWitnessCommit();return!t&&this.hasWitness()?!1:this.__checkMerkleRoot()&&(t?this.__checkWitnessCommit():!0)}checkProofOfWork(){const t=(0,yt.reverseBuffer)(this.getHash()),r=wt.calculateTarget(this.bits);return t.compare(r)<=0}__checkMerkleRoot(){if(!this.transactions)throw vn;const t=wt.calculateMerkleRoot(this.transactions);return this.merkleRoot.compare(t)===0}__checkWitnessCommit(){if(!this.transactions)throw vn;if(!this.hasWitnessCommit())throw qi;const t=wt.calculateMerkleRoot(this.transactions,!0);return this.witnessCommit.compare(t)===0}}nn.Block=wt;function zi(e){return e instanceof Array&&e[0]&&e[0].ins&&e[0].ins instanceof Array&&e[0].ins[0]&&e[0].ins[0].witness&&e[0].ins[0].witness instanceof Array&&e[0].ins[0].witness.length>0}function Du(e){return e instanceof Array&&e.some(t=>typeof t=="object"&&t.ins instanceof Array&&t.ins.some(r=>typeof r=="object"&&r.witness instanceof Array&&r.witness.length>0))}var sn={},ni={},ii={},oi={},Sr={},St={},fe={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),function(t){t[t.UNSIGNED_TX=0]="UNSIGNED_TX",t[t.GLOBAL_XPUB=1]="GLOBAL_XPUB"}(e.GlobalTypes||(e.GlobalTypes={})),e.GLOBAL_TYPE_NAMES=["unsignedTx","globalXpub"],function(t){t[t.NON_WITNESS_UTXO=0]="NON_WITNESS_UTXO",t[t.WITNESS_UTXO=1]="WITNESS_UTXO",t[t.PARTIAL_SIG=2]="PARTIAL_SIG",t[t.SIGHASH_TYPE=3]="SIGHASH_TYPE",t[t.REDEEM_SCRIPT=4]="REDEEM_SCRIPT",t[t.WITNESS_SCRIPT=5]="WITNESS_SCRIPT",t[t.BIP32_DERIVATION=6]="BIP32_DERIVATION",t[t.FINAL_SCRIPTSIG=7]="FINAL_SCRIPTSIG",t[t.FINAL_SCRIPTWITNESS=8]="FINAL_SCRIPTWITNESS",t[t.POR_COMMITMENT=9]="POR_COMMITMENT",t[t.TAP_KEY_SIG=19]="TAP_KEY_SIG",t[t.TAP_SCRIPT_SIG=20]="TAP_SCRIPT_SIG",t[t.TAP_LEAF_SCRIPT=21]="TAP_LEAF_SCRIPT",t[t.TAP_BIP32_DERIVATION=22]="TAP_BIP32_DERIVATION",t[t.TAP_INTERNAL_KEY=23]="TAP_INTERNAL_KEY",t[t.TAP_MERKLE_ROOT=24]="TAP_MERKLE_ROOT"}(e.InputTypes||(e.InputTypes={})),e.INPUT_TYPE_NAMES=["nonWitnessUtxo","witnessUtxo","partialSig","sighashType","redeemScript","witnessScript","bip32Derivation","finalScriptSig","finalScriptWitness","porCommitment","tapKeySig","tapScriptSig","tapLeafScript","tapBip32Derivation","tapInternalKey","tapMerkleRoot"],function(t){t[t.REDEEM_SCRIPT=0]="REDEEM_SCRIPT",t[t.WITNESS_SCRIPT=1]="WITNESS_SCRIPT",t[t.BIP32_DERIVATION=2]="BIP32_DERIVATION",t[t.TAP_INTERNAL_KEY=5]="TAP_INTERNAL_KEY",t[t.TAP_TREE=6]="TAP_TREE",t[t.TAP_BIP32_DERIVATION=7]="TAP_BIP32_DERIVATION"}(e.OutputTypes||(e.OutputTypes={})),e.OUTPUT_TYPE_NAMES=["redeemScript","witnessScript","bip32Derivation","tapInternalKey","tapTree","tapBip32Derivation"]})(fe);var bt={};Object.defineProperty(bt,"__esModule",{value:!0});const Ko=fe,Wu=e=>[...Array(e).keys()];function ju(e){if(e.key[0]!==Ko.GlobalTypes.GLOBAL_XPUB)throw new Error("Decode Error: could not decode globalXpub with key 0x"+e.key.toString("hex"));if(e.key.length!==79||![2,3].includes(e.key[46]))throw new Error("Decode Error: globalXpub has invalid extended pubkey in key 0x"+e.key.toString("hex"));if(e.value.length/4%1!==0)throw new Error("Decode Error: Global GLOBAL_XPUB value length should be multiple of 4");const t=e.key.slice(1),r={masterFingerprint:e.value.slice(0,4),extendedPubkey:t,path:"m"};for(const n of Wu(e.value.length/4-1)){const i=e.value.readUInt32LE(n*4+4),c=!!(i&2147483648),s=i&2147483647;r.path+="/"+s.toString(10)+(c?"'":"")}return r}bt.decode=ju;function Vu(e){const t=E.from([Ko.GlobalTypes.GLOBAL_XPUB]),r=E.concat([t,e.extendedPubkey]),n=e.path.split("/"),i=E.allocUnsafe(n.length*4);e.masterFingerprint.copy(i,0);let c=4;return n.slice(1).forEach(s=>{const a=s.slice(-1)==="'";let p=2147483647&parseInt(a?s.slice(0,-1):s,10);a&&(p+=2147483648),i.writeUInt32LE(p,c),c+=4}),{key:r,value:i}}bt.encode=Vu;bt.expected="{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }";function Gu(e){const t=e.extendedPubkey,r=e.masterFingerprint,n=e.path;return E.isBuffer(t)&&t.length===78&&[2,3].indexOf(t[45])>-1&&E.isBuffer(r)&&r.length===4&&typeof n=="string"&&!!n.match(/^m(\/\d+'?)*$/)}bt.check=Gu;function Xu(e,t,r){const n=t.extendedPubkey.toString("hex");return r.has(n)?!1:(r.add(n),e.filter(i=>i.extendedPubkey.equals(t.extendedPubkey)).length===0)}bt.canAddToArray=Xu;var si={};Object.defineProperty(si,"__esModule",{value:!0});const qu=fe;function zu(e){return{key:E.from([qu.GlobalTypes.UNSIGNED_TX]),value:e.toBuffer()}}si.encode=zu;var _t={};Object.defineProperty(_t,"__esModule",{value:!0});const Do=fe;function Yu(e){if(e.key[0]!==Do.InputTypes.FINAL_SCRIPTSIG)throw new Error("Decode Error: could not decode finalScriptSig with key 0x"+e.key.toString("hex"));return e.value}_t.decode=Yu;function Ju(e){return{key:E.from([Do.InputTypes.FINAL_SCRIPTSIG]),value:e}}_t.encode=Ju;_t.expected="Buffer";function Qu(e){return E.isBuffer(e)}_t.check=Qu;function Zu(e,t){return!!e&&!!t&&e.finalScriptSig===void 0}_t.canAdd=Zu;var Tt={};Object.defineProperty(Tt,"__esModule",{value:!0});const Wo=fe;function ea(e){if(e.key[0]!==Wo.InputTypes.FINAL_SCRIPTWITNESS)throw new Error("Decode Error: could not decode finalScriptWitness with key 0x"+e.key.toString("hex"));return e.value}Tt.decode=ea;function ta(e){return{key:E.from([Wo.InputTypes.FINAL_SCRIPTWITNESS]),value:e}}Tt.encode=ta;Tt.expected="Buffer";function ra(e){return E.isBuffer(e)}Tt.check=ra;function na(e,t){return!!e&&!!t&&e.finalScriptWitness===void 0}Tt.canAdd=na;var It={};Object.defineProperty(It,"__esModule",{value:!0});const jo=fe;function ia(e){if(e.key[0]!==jo.InputTypes.NON_WITNESS_UTXO)throw new Error("Decode Error: could not decode nonWitnessUtxo with key 0x"+e.key.toString("hex"));return e.value}It.decode=ia;function oa(e){return{key:E.from([jo.InputTypes.NON_WITNESS_UTXO]),value:e}}It.encode=oa;It.expected="Buffer";function sa(e){return E.isBuffer(e)}It.check=sa;function ca(e,t){return!!e&&!!t&&e.nonWitnessUtxo===void 0}It.canAdd=ca;var kt={};Object.defineProperty(kt,"__esModule",{value:!0});const Vo=fe;function ua(e){if(e.key[0]!==Vo.InputTypes.PARTIAL_SIG)throw new Error("Decode Error: could not decode partialSig with key 0x"+e.key.toString("hex"));if(!(e.key.length===34||e.key.length===66)||![2,3,4].includes(e.key[1]))throw new Error("Decode Error: partialSig has invalid pubkey in key 0x"+e.key.toString("hex"));return{pubkey:e.key.slice(1),signature:e.value}}kt.decode=ua;function aa(e){const t=E.from([Vo.InputTypes.PARTIAL_SIG]);return{key:E.concat([t,e.pubkey]),value:e.signature}}kt.encode=aa;kt.expected="{ pubkey: Buffer; signature: Buffer; }";function fa(e){return E.isBuffer(e.pubkey)&&E.isBuffer(e.signature)&&[33,65].includes(e.pubkey.length)&&[2,3,4].includes(e.pubkey[0])&&ha(e.signature)}kt.check=fa;function ha(e){if(!E.isBuffer(e)||e.length<9||e[0]!==48||e.length!==e[1]+3||e[2]!==2)return!1;const t=e[3];if(t>33||t<1||e[3+t+1]!==2)return!1;const r=e[3+t+2];return!(r>33||r<1||e.length!==3+t+2+r+2)}function pa(e,t,r){const n=t.pubkey.toString("hex");return r.has(n)?!1:(r.add(n),e.filter(i=>i.pubkey.equals(t.pubkey)).length===0)}kt.canAddToArray=pa;var At={};Object.defineProperty(At,"__esModule",{value:!0});const Go=fe;function la(e){if(e.key[0]!==Go.InputTypes.POR_COMMITMENT)throw new Error("Decode Error: could not decode porCommitment with key 0x"+e.key.toString("hex"));return e.value.toString("utf8")}At.decode=la;function da(e){return{key:E.from([Go.InputTypes.POR_COMMITMENT]),value:E.from(e,"utf8")}}At.encode=da;At.expected="string";function ya(e){return typeof e=="string"}At.check=ya;function wa(e,t){return!!e&&!!t&&e.porCommitment===void 0}At.canAdd=wa;var Ot={};Object.defineProperty(Ot,"__esModule",{value:!0});const Xo=fe;function ga(e){if(e.key[0]!==Xo.InputTypes.SIGHASH_TYPE)throw new Error("Decode Error: could not decode sighashType with key 0x"+e.key.toString("hex"));return e.value.readUInt32LE(0)}Ot.decode=ga;function Ea(e){const t=E.from([Xo.InputTypes.SIGHASH_TYPE]),r=E.allocUnsafe(4);return r.writeUInt32LE(e,0),{key:t,value:r}}Ot.encode=Ea;Ot.expected="number";function ma(e){return typeof e=="number"}Ot.check=ma;function Sa(e,t){return!!e&&!!t&&e.sighashType===void 0}Ot.canAdd=Sa;var Pt={};Object.defineProperty(Pt,"__esModule",{value:!0});const qo=fe;function ba(e){if(e.key[0]!==qo.InputTypes.TAP_KEY_SIG||e.key.length!==1)throw new Error("Decode Error: could not decode tapKeySig with key 0x"+e.key.toString("hex"));if(!zo(e.value))throw new Error("Decode Error: tapKeySig not a valid 64-65-byte BIP340 signature");return e.value}Pt.decode=ba;function _a(e){return{key:E.from([qo.InputTypes.TAP_KEY_SIG]),value:e}}Pt.encode=_a;Pt.expected="Buffer";function zo(e){return E.isBuffer(e)&&(e.length===64||e.length===65)}Pt.check=zo;function Ta(e,t){return!!e&&!!t&&e.tapKeySig===void 0}Pt.canAdd=Ta;var vt={};Object.defineProperty(vt,"__esModule",{value:!0});const Yo=fe;function Ia(e){if(e.key[0]!==Yo.InputTypes.TAP_LEAF_SCRIPT)throw new Error("Decode Error: could not decode tapLeafScript with key 0x"+e.key.toString("hex"));if((e.key.length-2)%32!==0)throw new Error("Decode Error: tapLeafScript has invalid control block in key 0x"+e.key.toString("hex"));const t=e.value[e.value.length-1];if((e.key[1]&254)!==t)throw new Error("Decode Error: tapLeafScript bad leaf version in key 0x"+e.key.toString("hex"));const r=e.value.slice(0,-1);return{controlBlock:e.key.slice(1),script:r,leafVersion:t}}vt.decode=Ia;function ka(e){const t=E.from([Yo.InputTypes.TAP_LEAF_SCRIPT]),r=E.from([e.leafVersion]);return{key:E.concat([t,e.controlBlock]),value:E.concat([e.script,r])}}vt.encode=ka;vt.expected="{ controlBlock: Buffer; leafVersion: number, script: Buffer; }";function Aa(e){return E.isBuffer(e.controlBlock)&&(e.controlBlock.length-1)%32===0&&(e.controlBlock[0]&254)===e.leafVersion&&E.isBuffer(e.script)}vt.check=Aa;function Oa(e,t,r){const n=t.controlBlock.toString("hex");return r.has(n)?!1:(r.add(n),e.filter(i=>i.controlBlock.equals(t.controlBlock)).length===0)}vt.canAddToArray=Oa;var Bt={};Object.defineProperty(Bt,"__esModule",{value:!0});const Jo=fe;function Pa(e){if(e.key[0]!==Jo.InputTypes.TAP_MERKLE_ROOT||e.key.length!==1)throw new Error("Decode Error: could not decode tapMerkleRoot with key 0x"+e.key.toString("hex"));if(!Qo(e.value))throw new Error("Decode Error: tapMerkleRoot not a 32-byte hash");return e.value}Bt.decode=Pa;function va(e){return{key:E.from([Jo.InputTypes.TAP_MERKLE_ROOT]),value:e}}Bt.encode=va;Bt.expected="Buffer";function Qo(e){return E.isBuffer(e)&&e.length===32}Bt.check=Qo;function Ba(e,t){return!!e&&!!t&&e.tapMerkleRoot===void 0}Bt.canAdd=Ba;var xt={};Object.defineProperty(xt,"__esModule",{value:!0});const Zo=fe;function xa(e){if(e.key[0]!==Zo.InputTypes.TAP_SCRIPT_SIG)throw new Error("Decode Error: could not decode tapScriptSig with key 0x"+e.key.toString("hex"));if(e.key.length!==65)throw new Error("Decode Error: tapScriptSig has invalid key 0x"+e.key.toString("hex"));if(e.value.length!==64&&e.value.length!==65)throw new Error("Decode Error: tapScriptSig has invalid signature in key 0x"+e.key.toString("hex"));const t=e.key.slice(1,33),r=e.key.slice(33);return{pubkey:t,leafHash:r,signature:e.value}}xt.decode=xa;function Ua(e){const t=E.from([Zo.InputTypes.TAP_SCRIPT_SIG]);return{key:E.concat([t,e.pubkey,e.leafHash]),value:e.signature}}xt.encode=Ua;xt.expected="{ pubkey: Buffer; leafHash: Buffer; signature: Buffer; }";function Na(e){return E.isBuffer(e.pubkey)&&E.isBuffer(e.leafHash)&&E.isBuffer(e.signature)&&e.pubkey.length===32&&e.leafHash.length===32&&(e.signature.length===64||e.signature.length===65)}xt.check=Na;function Ca(e,t,r){const n=t.pubkey.toString("hex")+t.leafHash.toString("hex");return r.has(n)?!1:(r.add(n),e.filter(i=>i.pubkey.equals(t.pubkey)&&i.leafHash.equals(t.leafHash)).length===0)}xt.canAddToArray=Ca;var Ut={},De={},xe={};Object.defineProperty(xe,"__esModule",{value:!0});const Ha=9007199254740991;function ci(e){if(e<0||e>Ha||e%1!==0)throw new RangeError("value out of range")}function fr(e,t,r){if(ci(e),t||(t=E.allocUnsafe(es(e))),!E.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");return r||(r=0),e<253?(t.writeUInt8(e,r),Object.assign(fr,{bytes:1})):e<=65535?(t.writeUInt8(253,r),t.writeUInt16LE(e,r+1),Object.assign(fr,{bytes:3})):e<=4294967295?(t.writeUInt8(254,r),t.writeUInt32LE(e,r+1),Object.assign(fr,{bytes:5})):(t.writeUInt8(255,r),t.writeUInt32LE(e>>>0,r+1),t.writeUInt32LE(e/4294967296|0,r+5),Object.assign(fr,{bytes:9})),t}xe.encode=fr;function hr(e,t){if(!E.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");t||(t=0);const r=e.readUInt8(t);if(r<253)return Object.assign(hr,{bytes:1}),r;if(r===253)return Object.assign(hr,{bytes:3}),e.readUInt16LE(t+1);if(r===254)return Object.assign(hr,{bytes:5}),e.readUInt32LE(t+1);{Object.assign(hr,{bytes:9});const n=e.readUInt32LE(t+1),c=e.readUInt32LE(t+5)*4294967296+n;return ci(c),c}}xe.decode=hr;function es(e){return ci(e),e<253?1:e<=65535?3:e<=4294967295?5:9}xe.encodingLength=es;Object.defineProperty(De,"__esModule",{value:!0});const Pr=xe;De.range=e=>[...Array(e).keys()];function Ra(e){if(e.length<1)return e;let t=e.length-1,r=0;for(let n=0;nt)throw new Error("RangeError: value out of range");if(Math.floor(e)!==e)throw new Error("value has a fractional component")}function La(e,t){const r=e.readUInt32LE(t);let n=e.readUInt32LE(t+4);return n*=4294967296,rs(n+r,9007199254740991),n+r}De.readUInt64LE=La;function $a(e,t,r){return rs(t,9007199254740991),e.writeInt32LE(t&-1,r),e.writeUInt32LE(Math.floor(t/4294967296),r+4),r+8}De.writeUInt64LE=$a;Object.defineProperty(Ut,"__esModule",{value:!0});const ns=fe,is=De,Mr=xe;function Ma(e){if(e.key[0]!==ns.InputTypes.WITNESS_UTXO)throw new Error("Decode Error: could not decode witnessUtxo with key 0x"+e.key.toString("hex"));const t=is.readUInt64LE(e.value,0);let r=8;const n=Mr.decode(e.value,r);r+=Mr.encodingLength(n);const i=e.value.slice(r);if(i.length!==n)throw new Error("Decode Error: WITNESS_UTXO script is not proper length");return{script:i,value:t}}Ut.decode=Ma;function Ka(e){const{script:t,value:r}=e,n=Mr.encodingLength(t.length),i=E.allocUnsafe(8+n+t.length);return is.writeUInt64LE(i,r,0),Mr.encode(t.length,i,8),t.copy(i,8+n),{key:E.from([ns.InputTypes.WITNESS_UTXO]),value:i}}Ut.encode=Ka;Ut.expected="{ script: Buffer; value: number; }";function Da(e){return E.isBuffer(e.script)&&typeof e.value=="number"}Ut.check=Da;function Wa(e,t){return!!e&&!!t&&e.witnessUtxo===void 0}Ut.canAdd=Wa;var Nt={};Object.defineProperty(Nt,"__esModule",{value:!0});const os=fe,Mn=xe;function ja(e){if(e.key[0]!==os.OutputTypes.TAP_TREE||e.key.length!==1)throw new Error("Decode Error: could not decode tapTree with key 0x"+e.key.toString("hex"));let t=0;const r=[];for(;t[E.of(n.depth,n.leafVersion),Mn.encode(n.script.length),n.script]));return{key:t,value:E.concat(r)}}Nt.encode=Va;Nt.expected="{ leaves: [{ depth: number; leafVersion: number, script: Buffer; }] }";function Ga(e){return Array.isArray(e.leaves)&&e.leaves.every(t=>t.depth>=0&&t.depth<=128&&(t.leafVersion&254)===t.leafVersion&&E.isBuffer(t.script))}Nt.check=Ga;function Xa(e,t){return!!e&&!!t&&e.tapTree===void 0}Nt.canAdd=Xa;var cn={};Object.defineProperty(cn,"__esModule",{value:!0});const qa=e=>[...Array(e).keys()],za=e=>e.length===33&&[2,3].includes(e[0])||e.length===65&&e[0]===4;function Ya(e,t=za){function r(a){if(a.key[0]!==e)throw new Error("Decode Error: could not decode bip32Derivation with key 0x"+a.key.toString("hex"));const p=a.key.slice(1);if(!t(p))throw new Error("Decode Error: bip32Derivation has invalid pubkey in key 0x"+a.key.toString("hex"));if(a.value.length/4%1!==0)throw new Error("Decode Error: Input BIP32_DERIVATION value length should be multiple of 4");const w={masterFingerprint:a.value.slice(0,4),pubkey:p,path:"m"};for(const f of qa(a.value.length/4-1)){const d=a.value.readUInt32LE(f*4+4),S=!!(d&2147483648),y=d&2147483647;w.path+="/"+y.toString(10)+(S?"'":"")}return w}function n(a){const p=E.from([e]),w=E.concat([p,a.pubkey]),f=a.path.split("/"),d=E.allocUnsafe(f.length*4);a.masterFingerprint.copy(d,0);let S=4;return f.slice(1).forEach(y=>{const _=y.slice(-1)==="'";let T=2147483647&parseInt(_?y.slice(0,-1):y,10);_&&(T+=2147483648),d.writeUInt32LE(T,S),S+=4}),{key:w,value:d}}const i="{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }";function c(a){return E.isBuffer(a.pubkey)&&E.isBuffer(a.masterFingerprint)&&typeof a.path=="string"&&t(a.pubkey)&&a.masterFingerprint.length===4}function s(a,p,w){const f=p.pubkey.toString("hex");return w.has(f)?!1:(w.add(f),a.filter(d=>d.pubkey.equals(p.pubkey)).length===0)}return{decode:r,encode:n,check:c,expected:i,canAddToArray:s}}cn.makeConverter=Ya;var ui={};Object.defineProperty(ui,"__esModule",{value:!0});function Ja(e){return t;function t(r){let n;if(e.includes(r.key[0])&&(n=r.key.slice(1),!(n.length===33||n.length===65)||![2,3,4].includes(n[0])))throw new Error("Format Error: invalid pubkey in key 0x"+r.key.toString("hex"));return n}}ui.makeChecker=Ja;var ai={};Object.defineProperty(ai,"__esModule",{value:!0});function Qa(e){function t(s){if(s.key[0]!==e)throw new Error("Decode Error: could not decode redeemScript with key 0x"+s.key.toString("hex"));return s.value}function r(s){return{key:E.from([e]),value:s}}const n="Buffer";function i(s){return E.isBuffer(s)}function c(s,a){return!!s&&!!a&&s.redeemScript===void 0}return{decode:t,encode:r,check:i,expected:n,canAdd:c}}ai.makeConverter=Qa;var fi={};Object.defineProperty(fi,"__esModule",{value:!0});const vr=xe,Za=cn,ef=e=>e.length===32;function tf(e){const t=Za.makeConverter(e,ef);function r(s){const a=vr.decode(s.value),p=vr.encodingLength(a),w=t.decode({key:s.key,value:s.value.slice(p+a*32)}),f=new Array(a);for(let d=0,S=p;dE.isBuffer(a)&&a.length===32)&&t.check(s)}return{decode:r,encode:n,check:c,expected:i,canAddToArray:t.canAddToArray}}fi.makeConverter=tf;var hi={};Object.defineProperty(hi,"__esModule",{value:!0});function rf(e){function t(s){if(s.key[0]!==e||s.key.length!==1)throw new Error("Decode Error: could not decode tapInternalKey with key 0x"+s.key.toString("hex"));if(s.value.length!==32)throw new Error("Decode Error: tapInternalKey not a 32-byte x-only pubkey");return s.value}function r(s){return{key:E.from([e]),value:s}}const n="Buffer";function i(s){return E.isBuffer(s)&&s.length===32}function c(s,a){return!!s&&!!a&&s.tapInternalKey===void 0}return{decode:t,encode:r,check:i,expected:n,canAdd:c}}hi.makeConverter=rf;var pi={};Object.defineProperty(pi,"__esModule",{value:!0});function nf(e){function t(s){if(s.key[0]!==e)throw new Error("Decode Error: could not decode witnessScript with key 0x"+s.key.toString("hex"));return s.value}function r(s){return{key:E.from([e]),value:s}}const n="Buffer";function i(s){return E.isBuffer(s)}function c(s,a){return!!s&&!!a&&s.witnessScript===void 0}return{decode:t,encode:r,check:i,expected:n,canAdd:c}}pi.makeConverter=nf;Object.defineProperty(St,"__esModule",{value:!0});const Ie=fe,of=bt,sf=si,cf=_t,uf=Tt,af=It,ff=kt,hf=At,pf=Ot,lf=Pt,df=vt,yf=Bt,wf=xt,gf=Ut,Ef=Nt,ss=cn,li=ui,cs=ai,us=fi,as=hi,fs=pi,mf={unsignedTx:sf,globalXpub:of,checkPubkey:li.makeChecker([])};St.globals=mf;const Sf={nonWitnessUtxo:af,partialSig:ff,sighashType:pf,finalScriptSig:cf,finalScriptWitness:uf,porCommitment:hf,witnessUtxo:gf,bip32Derivation:ss.makeConverter(Ie.InputTypes.BIP32_DERIVATION),redeemScript:cs.makeConverter(Ie.InputTypes.REDEEM_SCRIPT),witnessScript:fs.makeConverter(Ie.InputTypes.WITNESS_SCRIPT),checkPubkey:li.makeChecker([Ie.InputTypes.PARTIAL_SIG,Ie.InputTypes.BIP32_DERIVATION]),tapKeySig:lf,tapScriptSig:wf,tapLeafScript:df,tapBip32Derivation:us.makeConverter(Ie.InputTypes.TAP_BIP32_DERIVATION),tapInternalKey:as.makeConverter(Ie.InputTypes.TAP_INTERNAL_KEY),tapMerkleRoot:yf};St.inputs=Sf;const bf={bip32Derivation:ss.makeConverter(Ie.OutputTypes.BIP32_DERIVATION),redeemScript:cs.makeConverter(Ie.OutputTypes.REDEEM_SCRIPT),witnessScript:fs.makeConverter(Ie.OutputTypes.WITNESS_SCRIPT),checkPubkey:li.makeChecker([Ie.OutputTypes.BIP32_DERIVATION]),tapBip32Derivation:us.makeConverter(Ie.OutputTypes.TAP_BIP32_DERIVATION),tapTree:Ef,tapInternalKey:as.makeConverter(Ie.OutputTypes.TAP_INTERNAL_KEY)};St.outputs=bf;Object.defineProperty(Sr,"__esModule",{value:!0});const q=St,Kr=De,Yi=xe,H=fe;function _f(e,t){let r=0;function n(){const P=Yi.decode(e,r);r+=Yi.encodingLength(P);const x=e.slice(r,r+P);return r+=P,x}function i(){const P=e.readUInt32BE(r);return r+=4,P}function c(){const P=e.readUInt8(r);return r+=1,P}function s(){const P=n(),x=n();return{key:P,value:x}}function a(){if(r>=e.length)throw new Error("Format Error: Unexpected End of PSBT");const P=e.readUInt8(r)===0;return P&&r++,P}if(i()!==1886610036)throw new Error("Format Error: Invalid Magic Number");if(c()!==255)throw new Error("Format Error: Magic Number must be followed by 0xff separator");const p=[],w={};for(;!a();){const P=s(),x=P.key.toString("hex");if(w[x])throw new Error("Format Error: Keys must be unique for global keymap: key "+x);w[x]=1,p.push(P)}const f=p.filter(P=>P.key[0]===H.GlobalTypes.UNSIGNED_TX);if(f.length!==1)throw new Error("Format Error: Only one UNSIGNED_TX allowed");const d=t(f[0].value),{inputCount:S,outputCount:y}=d.getInputOutputCounts(),_=[],T=[];for(const P of Kr.range(S)){const x={},N=[];for(;!a();){const k=s(),m=k.key.toString("hex");if(x[m])throw new Error("Format Error: Keys must be unique for each input: input index "+P+" key "+m);x[m]=1,N.push(k)}_.push(N)}for(const P of Kr.range(y)){const x={},N=[];for(;!a();){const k=s(),m=k.key.toString("hex");if(x[m])throw new Error("Format Error: Keys must be unique for each output: output index "+P+" key "+m);x[m]=1,N.push(k)}T.push(N)}return hs(d,{globalMapKeyVals:p,inputKeyVals:_,outputKeyVals:T})}Sr.psbtFromBuffer=_f;function pe(e,t,r){if(!t.equals(E.from([r])))throw new Error(`Format Error: Invalid ${e} key: ${t.toString("hex")}`)}Sr.checkKeyBuffer=pe;function hs(e,{globalMapKeyVals:t,inputKeyVals:r,outputKeyVals:n}){const i={unsignedTx:e};let c=0;for(const f of t)switch(f.key[0]){case H.GlobalTypes.UNSIGNED_TX:if(pe("global",f.key,H.GlobalTypes.UNSIGNED_TX),c>0)throw new Error("Format Error: GlobalMap has multiple UNSIGNED_TX");c++;break;case H.GlobalTypes.GLOBAL_XPUB:i.globalXpub===void 0&&(i.globalXpub=[]),i.globalXpub.push(q.globals.globalXpub.decode(f));break;default:i.unknownKeyVals||(i.unknownKeyVals=[]),i.unknownKeyVals.push(f)}const s=r.length,a=n.length,p=[],w=[];for(const f of Kr.range(s)){const d={};for(const S of r[f])switch(q.inputs.checkPubkey(S),S.key[0]){case H.InputTypes.NON_WITNESS_UTXO:if(pe("input",S.key,H.InputTypes.NON_WITNESS_UTXO),d.nonWitnessUtxo!==void 0)throw new Error("Format Error: Input has multiple NON_WITNESS_UTXO");d.nonWitnessUtxo=q.inputs.nonWitnessUtxo.decode(S);break;case H.InputTypes.WITNESS_UTXO:if(pe("input",S.key,H.InputTypes.WITNESS_UTXO),d.witnessUtxo!==void 0)throw new Error("Format Error: Input has multiple WITNESS_UTXO");d.witnessUtxo=q.inputs.witnessUtxo.decode(S);break;case H.InputTypes.PARTIAL_SIG:d.partialSig===void 0&&(d.partialSig=[]),d.partialSig.push(q.inputs.partialSig.decode(S));break;case H.InputTypes.SIGHASH_TYPE:if(pe("input",S.key,H.InputTypes.SIGHASH_TYPE),d.sighashType!==void 0)throw new Error("Format Error: Input has multiple SIGHASH_TYPE");d.sighashType=q.inputs.sighashType.decode(S);break;case H.InputTypes.REDEEM_SCRIPT:if(pe("input",S.key,H.InputTypes.REDEEM_SCRIPT),d.redeemScript!==void 0)throw new Error("Format Error: Input has multiple REDEEM_SCRIPT");d.redeemScript=q.inputs.redeemScript.decode(S);break;case H.InputTypes.WITNESS_SCRIPT:if(pe("input",S.key,H.InputTypes.WITNESS_SCRIPT),d.witnessScript!==void 0)throw new Error("Format Error: Input has multiple WITNESS_SCRIPT");d.witnessScript=q.inputs.witnessScript.decode(S);break;case H.InputTypes.BIP32_DERIVATION:d.bip32Derivation===void 0&&(d.bip32Derivation=[]),d.bip32Derivation.push(q.inputs.bip32Derivation.decode(S));break;case H.InputTypes.FINAL_SCRIPTSIG:pe("input",S.key,H.InputTypes.FINAL_SCRIPTSIG),d.finalScriptSig=q.inputs.finalScriptSig.decode(S);break;case H.InputTypes.FINAL_SCRIPTWITNESS:pe("input",S.key,H.InputTypes.FINAL_SCRIPTWITNESS),d.finalScriptWitness=q.inputs.finalScriptWitness.decode(S);break;case H.InputTypes.POR_COMMITMENT:pe("input",S.key,H.InputTypes.POR_COMMITMENT),d.porCommitment=q.inputs.porCommitment.decode(S);break;case H.InputTypes.TAP_KEY_SIG:pe("input",S.key,H.InputTypes.TAP_KEY_SIG),d.tapKeySig=q.inputs.tapKeySig.decode(S);break;case H.InputTypes.TAP_SCRIPT_SIG:d.tapScriptSig===void 0&&(d.tapScriptSig=[]),d.tapScriptSig.push(q.inputs.tapScriptSig.decode(S));break;case H.InputTypes.TAP_LEAF_SCRIPT:d.tapLeafScript===void 0&&(d.tapLeafScript=[]),d.tapLeafScript.push(q.inputs.tapLeafScript.decode(S));break;case H.InputTypes.TAP_BIP32_DERIVATION:d.tapBip32Derivation===void 0&&(d.tapBip32Derivation=[]),d.tapBip32Derivation.push(q.inputs.tapBip32Derivation.decode(S));break;case H.InputTypes.TAP_INTERNAL_KEY:pe("input",S.key,H.InputTypes.TAP_INTERNAL_KEY),d.tapInternalKey=q.inputs.tapInternalKey.decode(S);break;case H.InputTypes.TAP_MERKLE_ROOT:pe("input",S.key,H.InputTypes.TAP_MERKLE_ROOT),d.tapMerkleRoot=q.inputs.tapMerkleRoot.decode(S);break;default:d.unknownKeyVals||(d.unknownKeyVals=[]),d.unknownKeyVals.push(S)}p.push(d)}for(const f of Kr.range(a)){const d={};for(const S of n[f])switch(q.outputs.checkPubkey(S),S.key[0]){case H.OutputTypes.REDEEM_SCRIPT:if(pe("output",S.key,H.OutputTypes.REDEEM_SCRIPT),d.redeemScript!==void 0)throw new Error("Format Error: Output has multiple REDEEM_SCRIPT");d.redeemScript=q.outputs.redeemScript.decode(S);break;case H.OutputTypes.WITNESS_SCRIPT:if(pe("output",S.key,H.OutputTypes.WITNESS_SCRIPT),d.witnessScript!==void 0)throw new Error("Format Error: Output has multiple WITNESS_SCRIPT");d.witnessScript=q.outputs.witnessScript.decode(S);break;case H.OutputTypes.BIP32_DERIVATION:d.bip32Derivation===void 0&&(d.bip32Derivation=[]),d.bip32Derivation.push(q.outputs.bip32Derivation.decode(S));break;case H.OutputTypes.TAP_INTERNAL_KEY:pe("output",S.key,H.OutputTypes.TAP_INTERNAL_KEY),d.tapInternalKey=q.outputs.tapInternalKey.decode(S);break;case H.OutputTypes.TAP_TREE:pe("output",S.key,H.OutputTypes.TAP_TREE),d.tapTree=q.outputs.tapTree.decode(S);break;case H.OutputTypes.TAP_BIP32_DERIVATION:d.tapBip32Derivation===void 0&&(d.tapBip32Derivation=[]),d.tapBip32Derivation.push(q.outputs.tapBip32Derivation.decode(S));break;default:d.unknownKeyVals||(d.unknownKeyVals=[]),d.unknownKeyVals.push(S)}w.push(d)}return{globalMap:i,inputs:p,outputs:w}}Sr.psbtFromKeyVals=hs;var un={};Object.defineProperty(un,"__esModule",{value:!0});const Bn=St,Ji=De;function Tf({globalMap:e,inputs:t,outputs:r}){const{globalKeyVals:n,inputKeyVals:i,outputKeyVals:c}=ps({globalMap:e,inputs:t,outputs:r}),s=Ji.keyValsToBuffer(n),a=d=>d.length===0?[E.from([0])]:d.map(Ji.keyValsToBuffer),p=a(i),w=a(c),f=E.allocUnsafe(5);return f.writeUIntBE(482972169471,0,5),E.concat([f,s].concat(p,w))}un.psbtToBuffer=Tf;const If=(e,t)=>e.key.compare(t.key);function xn(e,t){const r=new Set,n=Object.entries(e).reduce((c,[s,a])=>{if(s==="unknownKeyVals")return c;const p=t[s];if(p===void 0)return c;const w=(Array.isArray(a)?a:[a]).map(p.encode);return w.map(d=>d.key.toString("hex")).forEach(d=>{if(r.has(d))throw new Error("Serialize Error: Duplicate key: "+d);r.add(d)}),c.concat(w)},[]),i=e.unknownKeyVals?e.unknownKeyVals.filter(c=>!r.has(c.key.toString("hex"))):[];return n.concat(i).sort(If)}function ps({globalMap:e,inputs:t,outputs:r}){return{globalKeyVals:xn(e,Bn.globals),inputKeyVals:t.map(n=>xn(n,Bn.inputs)),outputKeyVals:r.map(n=>xn(n,Bn.outputs))}}un.psbtToKeyVals=ps;(function(e){function t(r){for(var n in r)e.hasOwnProperty(n)||(e[n]=r[n])}Object.defineProperty(e,"__esModule",{value:!0}),t(Sr),t(un)})(oi);Object.defineProperty(ii,"__esModule",{value:!0});const Un=oi;function kf(e){const t=e[0],r=Un.psbtToKeyVals(t),n=e.slice(1);if(n.length===0)throw new Error("Combine: Nothing to combine");const i=Qi(t);if(i===void 0)throw new Error("Combine: Self missing transaction");const c=Mt(r.globalKeyVals),s=r.inputKeyVals.map(Mt),a=r.outputKeyVals.map(Mt);for(const p of n){const w=Qi(p);if(w===void 0||!w.toBuffer().equals(i.toBuffer()))throw new Error("Combine: One of the Psbts does not have the same transaction.");const f=Un.psbtToKeyVals(p);Mt(f.globalKeyVals).forEach(Nn(c,r.globalKeyVals,f.globalKeyVals)),f.inputKeyVals.map(Mt).forEach((_,T)=>_.forEach(Nn(s[T],r.inputKeyVals[T],f.inputKeyVals[T]))),f.outputKeyVals.map(Mt).forEach((_,T)=>_.forEach(Nn(a[T],r.outputKeyVals[T],f.outputKeyVals[T])))}return Un.psbtFromKeyVals(i,{globalMapKeyVals:r.globalKeyVals,inputKeyVals:r.inputKeyVals,outputKeyVals:r.outputKeyVals})}ii.combine=kf;function Nn(e,t,r){return n=>{if(e.has(n))return;const i=r.filter(c=>c.key.toString("hex")===n)[0];t.push(i),e.add(n)}}function Qi(e){return e.globalMap.unsignedTx}function Mt(e){const t=new Set;return e.forEach(r=>{const n=r.key.toString("hex");if(t.has(n))throw new Error("Combine: KeyValue Map keys should be unique");t.add(n)}),t}var di={};(function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=St;function r(y,_){const T=y[_];if(T===void 0)throw new Error(`No input #${_}`);return T}e.checkForInput=r;function n(y,_){const T=y[_];if(T===void 0)throw new Error(`No output #${_}`);return T}e.checkForOutput=n;function i(y,_,T){if(y.key[0]P.key.equals(y.key)).length!==0)throw new Error(`Duplicate Key: ${y.key.toString("hex")}`)}e.checkHasKey=i;function c(y){let _=0;return Object.keys(y).forEach(T=>{Number(isNaN(Number(T)))&&_++}),_}e.getEnumLength=c;function s(y,_){let T=!1;if(_.nonWitnessUtxo||_.witnessUtxo){const P=!!_.redeemScript,x=!!_.witnessScript,N=!P||!!_.finalScriptSig,k=!x||!!_.finalScriptWitness,m=!!_.finalScriptSig||!!_.finalScriptWitness;T=N&&k&&m}if(T===!1)throw new Error(`Input #${y} has too much or too little data to clean`)}e.inputCheckUncleanFinalized=s;function a(y,_,T,P){throw new Error(`Data for ${y} key ${_} is incorrect: Expected ${T} and got ${JSON.stringify(P)}`)}function p(y){return(_,T)=>{for(const P of Object.keys(_)){const x=_[P],{canAdd:N,canAddToArray:k,check:m,expected:v}=t[y+"s"][P]||{},I=!!k;if(m)if(I){if(!Array.isArray(x)||T[P]&&!Array.isArray(T[P]))throw new Error(`Key type ${P} must be an array`);x.every(m)||a(y,P,v,x);const C=T[P]||[],M=new Set;if(!x.every(B=>k(C,B,M)))throw new Error("Can not add duplicate data to array");T[P]=C.concat(x)}else{if(m(x)||a(y,P,v,x),!N(T,x))throw new Error(`Can not add duplicate data to ${y}`);T[P]=x}}}}e.updateGlobal=p("global"),e.updateInput=p("input"),e.updateOutput=p("output");function w(y,_){const T=y.length-1,P=r(y,T);e.updateInput(_,P)}e.addInputAttributes=w;function f(y,_){const T=y.length-1,P=n(y,T);e.updateOutput(_,P)}e.addOutputAttributes=f;function d(y,_){if(!E.isBuffer(_)||_.length<4)throw new Error("Set Version: Invalid Transaction");return _.writeUInt32LE(y,0),_}e.defaultVersionSetter=d;function S(y,_){if(!E.isBuffer(_)||_.length<4)throw new Error("Set Locktime: Invalid Transaction");return _.writeUInt32LE(y,_.length-4),_}e.defaultLocktimeSetter=S})(di);Object.defineProperty(ni,"__esModule",{value:!0});const Af=ii,Zi=oi,Cn=fe,he=di;let Of=class{constructor(t){this.inputs=[],this.outputs=[],this.globalMap={unsignedTx:t}}static fromBase64(t,r){const n=E.from(t,"base64");return this.fromBuffer(n,r)}static fromHex(t,r){const n=E.from(t,"hex");return this.fromBuffer(n,r)}static fromBuffer(t,r){const n=Zi.psbtFromBuffer(t,r),i=new this(n.globalMap.unsignedTx);return Object.assign(i,n),i}toBase64(){return this.toBuffer().toString("base64")}toHex(){return this.toBuffer().toString("hex")}toBuffer(){return Zi.psbtToBuffer(this)}updateGlobal(t){return he.updateGlobal(t,this.globalMap),this}updateInput(t,r){const n=he.checkForInput(this.inputs,t);return he.updateInput(r,n),this}updateOutput(t,r){const n=he.checkForOutput(this.outputs,t);return he.updateOutput(r,n),this}addUnknownKeyValToGlobal(t){return he.checkHasKey(t,this.globalMap.unknownKeyVals,he.getEnumLength(Cn.GlobalTypes)),this.globalMap.unknownKeyVals||(this.globalMap.unknownKeyVals=[]),this.globalMap.unknownKeyVals.push(t),this}addUnknownKeyValToInput(t,r){const n=he.checkForInput(this.inputs,t);return he.checkHasKey(r,n.unknownKeyVals,he.getEnumLength(Cn.InputTypes)),n.unknownKeyVals||(n.unknownKeyVals=[]),n.unknownKeyVals.push(r),this}addUnknownKeyValToOutput(t,r){const n=he.checkForOutput(this.outputs,t);return he.checkHasKey(r,n.unknownKeyVals,he.getEnumLength(Cn.OutputTypes)),n.unknownKeyVals||(n.unknownKeyVals=[]),n.unknownKeyVals.push(r),this}addInput(t){this.globalMap.unsignedTx.addInput(t),this.inputs.push({unknownKeyVals:[]});const r=t.unknownKeyVals||[],n=this.inputs.length-1;if(!Array.isArray(r))throw new Error("unknownKeyVals must be an Array");return r.forEach(i=>this.addUnknownKeyValToInput(n,i)),he.addInputAttributes(this.inputs,t),this}addOutput(t){this.globalMap.unsignedTx.addOutput(t),this.outputs.push({unknownKeyVals:[]});const r=t.unknownKeyVals||[],n=this.outputs.length-1;if(!Array.isArray(r))throw new Error("unknownKeyVals must be an Array");return r.forEach(i=>this.addUnknownKeyValToOutput(n,i)),he.addOutputAttributes(this.outputs,t),this}clearFinalizedInput(t){const r=he.checkForInput(this.inputs,t);he.inputCheckUncleanFinalized(t,r);for(const n of Object.keys(r))["witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknownKeyVals"].includes(n)||delete r[n];return this}combine(...t){const r=Af.combine([this].concat(t));return Object.assign(this,r),this}getTransaction(){return this.globalMap.unsignedTx.toBuffer()}};ni.Psbt=Of;var Y={},W={};Object.defineProperty(W,"__esModule",{value:!0});W.signatureBlocksAction=W.checkInputForSig=W.pubkeyInScript=W.pubkeyPositionInScript=W.witnessStackToScriptWitness=W.isP2TR=W.isP2SHScript=W.isP2WSHScript=W.isP2WPKH=W.isP2PKH=W.isP2PK=W.isP2MS=void 0;const eo=xe,lr=_e(),Br=lt,Pf=Ke,Ct=mr();function Ht(e){return t=>{try{return e({output:t}),!0}catch{return!1}}}W.isP2MS=Ht(Ct.p2ms);W.isP2PK=Ht(Ct.p2pk);W.isP2PKH=Ht(Ct.p2pkh);W.isP2WPKH=Ht(Ct.p2wpkh);W.isP2WSHScript=Ht(Ct.p2wsh);W.isP2SHScript=Ht(Ct.p2sh);W.isP2TR=Ht(Ct.p2tr);function vf(e){let t=E.allocUnsafe(0);function r(s){t=E.concat([t,E.from(s)])}function n(s){const a=t.length,p=eo.encodingLength(s);t=E.concat([t,E.allocUnsafe(p)]),eo.encode(s,t,a)}function i(s){n(s.length),r(s)}function c(s){n(s.length),s.forEach(i)}return c(e),t}W.witnessStackToScriptWitness=vf;function ls(e,t){const r=(0,Pf.hash160)(e),n=e.slice(1,33),i=lr.decompile(t);if(i===null)throw new Error("Unknown script error");return i.findIndex(c=>typeof c=="number"?!1:c.equals(e)||c.equals(r)||c.equals(n))}W.pubkeyPositionInScript=ls;function Bf(e,t){return ls(e,t)!==-1}W.pubkeyInScript=Bf;function xf(e,t){return Uf(e).some(n=>ds(n,lr.signature.decode,t))}W.checkInputForSig=xf;function ds(e,t,r){const{hashType:n}=t(e),i=[];switch(n&Br.Transaction.SIGHASH_ANYONECANPAY&&i.push("addInput"),n&31){case Br.Transaction.SIGHASH_ALL:break;case Br.Transaction.SIGHASH_SINGLE:case Br.Transaction.SIGHASH_NONE:i.push("addOutput"),i.push("setInputSequence");break}return i.indexOf(r)===-1}W.signatureBlocksAction=ds;function Uf(e){let t=[];if((e.partialSig||[]).length===0){if(!e.finalScriptSig&&!e.finalScriptWitness)return[];t=Nf(e)}else t=e.partialSig;return t.map(r=>r.signature)}function Nf(e){const t=e.finalScriptSig?lr.decompile(e.finalScriptSig)||[]:[],r=e.finalScriptWitness?lr.decompile(e.finalScriptWitness)||[]:[];return t.concat(r).filter(n=>E.isBuffer(n)&&lr.isCanonicalScriptSignature(n)).map(n=>({signature:n}))}Object.defineProperty(Y,"__esModule",{value:!0});Y.checkTaprootInputForSigs=Y.tapTreeFromList=Y.tapTreeToList=Y.tweakInternalPubKey=Y.checkTaprootOutputFields=Y.checkTaprootInputFields=Y.isTaprootOutput=Y.isTaprootInput=Y.serializeTaprootSignature=Y.tapScriptFinalizer=Y.toXOnly=void 0;const yi=de,Cf=lt,an=W,pt=rn,Hf=mr(),Rf=W,Ff=e=>e.length===32?e:e.slice(1,33);Y.toXOnly=Ff;function Lf(e,t,r){const n=rh(t,e,r);try{const c=eh(t,n).concat(n.script).concat(n.controlBlock);return{finalScriptWitness:(0,an.witnessStackToScriptWitness)(c)}}catch(i){throw new Error(`Can not finalize taproot input #${e}: ${i}`)}}Y.tapScriptFinalizer=Lf;function $f(e,t){const r=t?E.from([t]):E.from([]);return E.concat([e,r])}Y.serializeTaprootSignature=$f;function Hr(e){return e&&!!(e.tapInternalKey||e.tapMerkleRoot||e.tapLeafScript&&e.tapLeafScript.length||e.tapBip32Derivation&&e.tapBip32Derivation.length||e.witnessUtxo&&(0,an.isP2TR)(e.witnessUtxo.script))}Y.isTaprootInput=Hr;function Rr(e,t){return e&&!!(e.tapInternalKey||e.tapTree||e.tapBip32Derivation&&e.tapBip32Derivation.length||t&&(0,an.isP2TR)(t))}Y.isTaprootOutput=Rr;function Mf(e,t,r){Jf(e,t,r),Zf(e,t,r)}Y.checkTaprootInputFields=Mf;function Kf(e,t,r){Qf(e,t,r),Df(e,t)}Y.checkTaprootOutputFields=Kf;function Df(e,t){if(!t.tapTree&&!t.tapInternalKey)return;const r=t.tapInternalKey||e.tapInternalKey,n=t.tapTree||e.tapTree;if(r){const{script:i}=e,c=Wf(r,n);if(i&&!i.equals(c))throw new Error("Error adding output. Script or address missmatch.")}}function Wf(e,t){const r=t&&ys(t.leaves),{output:n}=(0,Hf.p2tr)({internalPubkey:e,scriptTree:r});return n}function jf(e,t){const r=t.tapInternalKey,n=r&&(0,pt.tweakKey)(r,t.tapMerkleRoot);if(!n)throw new Error(`Cannot tweak tap internal key for input #${e}. Public key: ${r&&r.toString("hex")}`);return n.x}Y.tweakInternalPubKey=jf;function Vf(e){if(!(0,yi.isTaptree)(e))throw new Error("Cannot convert taptree to tapleaf list. Expecting a tapree structure.");return Kn(e)}Y.tapTreeToList=Vf;function ys(e=[]){return e.length===1&&e[0].depth===0?{output:e[0].script,version:e[0].leafVersion}:Yf(e)}Y.tapTreeFromList=ys;function Gf(e,t){return qf(e).some(n=>(0,Rf.signatureBlocksAction)(n,Xf,t))}Y.checkTaprootInputForSigs=Gf;function Xf(e){return{signature:e.slice(0,64),hashType:e.slice(64)[0]||Cf.Transaction.SIGHASH_DEFAULT}}function qf(e){const t=[];if(e.tapKeySig&&t.push(e.tapKeySig),e.tapScriptSig&&t.push(...e.tapScriptSig.map(r=>r.signature)),!t.length){const r=zf(e.finalScriptWitness);r&&t.push(r)}return t}function zf(e){if(!e)return;const t=e.slice(2);if(t.length===64||t.length===65)return t}function Kn(e,t=[],r=0){if(r>pt.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");return e?(0,yi.isTapleaf)(e)?(t.push({depth:r,leafVersion:e.version||pt.LEAF_VERSION_TAPSCRIPT,script:e.output}),t):(e[0]&&Kn(e[0],t,r+1),e[1]&&Kn(e[1],t,r+1),t):[]}function Yf(e){let t;for(const r of e)if(t=Dn(r,t),!t)throw new Error("No room left to insert tapleaf in tree");return t}function Dn(e,t,r=0){if(r>pt.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");if(e.depth===r)return t?void 0:{output:e.script,version:e.leafVersion};if((0,yi.isTapleaf)(t))return;const n=Dn(e,t&&t[0],r+1);if(n)return[n,t&&t[1]];const i=Dn(e,t&&t[1],r+1);if(i)return[t&&t[0],i]}function Jf(e,t,r){const n=Hr(e)&&qt(t),i=qt(e)&&Hr(t),c=e===t&&Hr(t)&&qt(t);if(n||i||c)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function Qf(e,t,r){const n=Rr(e)&&qt(t),i=qt(e)&&Rr(t),c=e===t&&Rr(t)&&qt(t);if(n||i||c)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function Zf(e,t,r){if(t.tapMerkleRoot){const n=(t.tapLeafScript||[]).every(c=>Hn(c,t.tapMerkleRoot)),i=(e.tapLeafScript||[]).every(c=>Hn(c,t.tapMerkleRoot));if(!n||!i)throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}else if(e.tapMerkleRoot&&!(t.tapLeafScript||[]).every(i=>Hn(i,e.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}function Hn(e,t){if(!t)return!0;const r=(0,pt.tapleafHash)({output:e.script,version:e.leafVersion});return(0,pt.rootHashFromPath)(e.controlBlock,r).equals(t)}function eh(e,t){const r=(0,pt.tapleafHash)({output:t.script,version:t.leafVersion});return(e.tapScriptSig||[]).filter(n=>n.leafHash.equals(r)).map(n=>th(t.script,n)).sort((n,i)=>i.positionInScript-n.positionInScript).map(n=>n.signature)}function th(e,t){return Object.assign({positionInScript:(0,an.pubkeyPositionInScript)(t.pubkey,e)},t)}function rh(e,t,r){if(!e.tapScriptSig||!e.tapScriptSig.length)throw new Error(`Can not finalize taproot input #${t}. No tapleaf script signature provided.`);const n=(e.tapLeafScript||[]).sort((i,c)=>i.controlBlock.length-c.controlBlock.length).find(i=>nh(i,e.tapScriptSig,r));if(!n)throw new Error(`Can not finalize taproot input #${t}. Signature for tapleaf script not found.`);return n}function nh(e,t,r){const n=(0,pt.tapleafHash)({output:e.script,version:e.leafVersion});return(!r||r.equals(n))&&t.find(c=>c.leafHash.equals(n))!==void 0}function qt(e){return e&&!!(e.redeemScript||e.witnessScript||e.bip32Derivation&&e.bip32Derivation.length)}Object.defineProperty(sn,"__esModule",{value:!0});sn.Psbt=void 0;const to=ni,ro=xe,Se=di,no=ri(),Dr=oe,ih=ae,ve=mr(),oh=rn,Ye=_e(),we=lt,J=Y,re=W,sh={network:ih.bitcoin,maximumFeeRate:5e3};class Wr{static fromBase64(t,r={}){const n=E.from(t,"base64");return this.fromBuffer(n,r)}static fromHex(t,r={}){const n=E.from(t,"hex");return this.fromBuffer(n,r)}static fromBuffer(t,r={}){const n=to.Psbt.fromBuffer(t,ch),i=new Wr(r,n);return ph(i.__CACHE.__TX,i.__CACHE),i}constructor(t={},r=new to.Psbt(new ws)){this.data=r,this.opts=Object.assign({},sh,t),this.__CACHE={__NON_WITNESS_UTXO_TX_CACHE:[],__NON_WITNESS_UTXO_BUF_CACHE:[],__TX_IN_CACHE:{},__TX:this.data.globalMap.unsignedTx.tx,__UNSAFE_SIGN_NONSEGWIT:!1},this.data.inputs.length===0&&this.setVersion(2);const n=(i,c,s,a)=>Object.defineProperty(i,c,{enumerable:s,writable:a});n(this,"__CACHE",!1,!0),n(this,"opts",!1,!0)}get inputCount(){return this.data.inputs.length}get version(){return this.__CACHE.__TX.version}set version(t){this.setVersion(t)}get locktime(){return this.__CACHE.__TX.locktime}set locktime(t){this.setLocktime(t)}get txInputs(){return this.__CACHE.__TX.ins.map(t=>({hash:(0,Dr.cloneBuffer)(t.hash),index:t.index,sequence:t.sequence}))}get txOutputs(){return this.__CACHE.__TX.outs.map(t=>{let r;try{r=(0,no.fromOutputScript)(t.script,this.opts.network)}catch{}return{script:(0,Dr.cloneBuffer)(t.script),value:t.value,address:r}})}combine(...t){return this.data.combine(...t.map(r=>r.data)),this}clone(){const t=Wr.fromBuffer(this.data.toBuffer());return t.opts=JSON.parse(JSON.stringify(this.opts)),t}setMaximumFeeRate(t){xr(t),this.opts.maximumFeeRate=t}setVersion(t){xr(t),or(this.data.inputs,"setVersion");const r=this.__CACHE;return r.__TX.version=t,r.__EXTRACTED_TX=void 0,this}setLocktime(t){xr(t),or(this.data.inputs,"setLocktime");const r=this.__CACHE;return r.__TX.locktime=t,r.__EXTRACTED_TX=void 0,this}setInputSequence(t,r){xr(r),or(this.data.inputs,"setInputSequence");const n=this.__CACHE;if(n.__TX.ins.length<=t)throw new Error("Input index too high");return n.__TX.ins[t].sequence=r,n.__EXTRACTED_TX=void 0,this}addInputs(t){return t.forEach(r=>this.addInput(r)),this}addInput(t){if(arguments.length>1||!t||t.hash===void 0||t.index===void 0)throw new Error("Invalid arguments for Psbt.addInput. Requires single object with at least [hash] and [index]");(0,J.checkTaprootInputFields)(t,t,"addInput"),or(this.data.inputs,"addInput"),t.witnessScript&&jr(t.witnessScript);const r=this.__CACHE;this.data.addInput(t);const n=r.__TX.ins[r.__TX.ins.length-1];ms(r,n);const i=this.data.inputs.length-1,c=this.data.inputs[i];return c.nonWitnessUtxo&&jn(this.__CACHE,c,i),r.__FEE=void 0,r.__FEE_RATE=void 0,r.__EXTRACTED_TX=void 0,this}addOutputs(t){return t.forEach(r=>this.addOutput(r)),this}addOutput(t){if(arguments.length>1||!t||t.value===void 0||t.address===void 0&&t.script===void 0)throw new Error("Invalid arguments for Psbt.addOutput. Requires single object with at least [script or address] and [value]");or(this.data.inputs,"addOutput");const{address:r}=t;if(typeof r=="string"){const{network:i}=this.opts,c=(0,no.toOutputScript)(r,i);t=Object.assign({},t,{script:c})}(0,J.checkTaprootOutputFields)(t,t,"addOutput");const n=this.__CACHE;return this.data.addOutput(t),n.__FEE=void 0,n.__FEE_RATE=void 0,n.__EXTRACTED_TX=void 0,this}extractTransaction(t){if(!this.data.inputs.every(gs))throw new Error("Not finalized");const r=this.__CACHE;if(t||ah(this,r,this.opts),r.__EXTRACTED_TX)return r.__EXTRACTED_TX;const n=r.__TX.clone();return ks(this.data.inputs,n,r,!0),n}getFeeRate(){return uo("__FEE_RATE","fee rate",this.data.inputs,this.__CACHE)}getFee(){return uo("__FEE","fee",this.data.inputs,this.__CACHE)}finalizeAllInputs(){return(0,Se.checkForInput)(this.data.inputs,0),sr(this.data.inputs.length).forEach(t=>this.finalizeInput(t)),this}finalizeInput(t,r){const n=(0,Se.checkForInput)(this.data.inputs,t);return(0,J.isTaprootInput)(n)?this._finalizeTaprootInput(t,n,void 0,r):this._finalizeInput(t,n,r)}finalizeTaprootInput(t,r,n=J.tapScriptFinalizer){const i=(0,Se.checkForInput)(this.data.inputs,t);if((0,J.isTaprootInput)(i))return this._finalizeTaprootInput(t,i,r,n);throw new Error(`Cannot finalize input #${t}. Not Taproot.`)}_finalizeInput(t,r,n=lh){const{script:i,isP2SH:c,isP2WSH:s,isSegwit:a}=gh(t,r,this.__CACHE);if(!i)throw new Error(`No script found for input #${t}`);fh(r);const{finalScriptSig:p,finalScriptWitness:w}=n(t,r,i,a,c,s);if(p&&this.data.updateInput(t,{finalScriptSig:p}),w&&this.data.updateInput(t,{finalScriptWitness:w}),!p&&!w)throw new Error(`Unknown error finalizing input #${t}`);return this.data.clearFinalizedInput(t),this}_finalizeTaprootInput(t,r,n,i=J.tapScriptFinalizer){if(!r.witnessUtxo)throw new Error(`Cannot finalize input #${t}. Missing withness utxo.`);if(r.tapKeySig){const c=ve.p2tr({output:r.witnessUtxo.script,signature:r.tapKeySig}),s=(0,re.witnessStackToScriptWitness)(c.witness);this.data.updateInput(t,{finalScriptWitness:s})}else{const{finalScriptWitness:c}=i(t,r,n);this.data.updateInput(t,{finalScriptWitness:c})}return this.data.clearFinalizedInput(t),this}getInputType(t){const r=(0,Se.checkForInput)(this.data.inputs,t),n=As(t,r,this.__CACHE),i=hn(n,t,"input",r.redeemScript||_h(r.finalScriptSig),r.witnessScript||Th(r.finalScriptWitness)),c=i.type==="raw"?"":i.type+"-",s=Ps(i.meaningfulScript);return c+s}inputHasPubkey(t,r){const n=(0,Se.checkForInput)(this.data.inputs,t);return Sh(r,n,t,this.__CACHE)}inputHasHDKey(t,r){const n=(0,Se.checkForInput)(this.data.inputs,t),i=oo(r);return!!n.bip32Derivation&&n.bip32Derivation.some(i)}outputHasPubkey(t,r){const n=(0,Se.checkForOutput)(this.data.outputs,t);return bh(r,n,t,this.__CACHE)}outputHasHDKey(t,r){const n=(0,Se.checkForOutput)(this.data.outputs,t),i=oo(r);return!!n.bip32Derivation&&n.bip32Derivation.some(i)}validateSignaturesOfAllInputs(t){return(0,Se.checkForInput)(this.data.inputs,0),sr(this.data.inputs.length).map(n=>this.validateSignaturesOfInput(n,t)).reduce((n,i)=>i===!0&&n,!0)}validateSignaturesOfInput(t,r,n){const i=this.data.inputs[t];return(0,J.isTaprootInput)(i)?this.validateSignaturesOfTaprootInput(t,r,n):this._validateSignaturesOfInput(t,r,n)}_validateSignaturesOfInput(t,r,n){const i=this.data.inputs[t],c=(i||{}).partialSig;if(!i||!c||c.length<1)throw new Error("No signatures to validate");if(typeof r!="function")throw new Error("Need validator function to validate signatures");const s=n?c.filter(d=>d.pubkey.equals(n)):c;if(s.length<1)throw new Error("No signatures for this pubkey");const a=[];let p,w,f;for(const d of s){const S=Ye.signature.decode(d.signature),{hash:y,script:_}=f!==S.hashType?bs(t,Object.assign({},i,{sighashType:S.hashType}),this.__CACHE,!0):{hash:p,script:w};f=S.hashType,p=y,w=_,Es(d.pubkey,_,"verify"),a.push(r(d.pubkey,y,S.signature))}return a.every(d=>d===!0)}validateSignaturesOfTaprootInput(t,r,n){const i=this.data.inputs[t],c=(i||{}).tapKeySig,s=(i||{}).tapScriptSig;if(!i&&!c&&!(s&&!s.length))throw new Error("No signatures to validate");if(typeof r!="function")throw new Error("Need validator function to validate signatures");n=n&&(0,J.toXOnly)(n);const a=n?Wn(t,i,this.data.inputs,n,this.__CACHE):yh(t,i,this.data.inputs,this.__CACHE);if(!a.length)throw new Error("No signatures for this pubkey");const p=a.find(f=>!f.leafHash);let w=0;if(c&&p){if(!r(p.pubkey,p.hash,fo(c)))return!1;w++}if(s)for(const f of s){const d=a.find(S=>f.pubkey.equals(S.pubkey));if(d){if(!r(f.pubkey,d.hash,fo(f.signature)))return!1;w++}}return w>0}signAllInputsHD(t,r=[we.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey||!t.fingerprint)throw new Error("Need HDSigner to sign input");const n=[];for(const i of sr(this.data.inputs.length))try{this.signInputHD(i,t,r),n.push(!0)}catch{n.push(!1)}if(n.every(i=>i===!1))throw new Error("No inputs were signed");return this}signAllInputsHDAsync(t,r=[we.Transaction.SIGHASH_ALL]){return new Promise((n,i)=>{if(!t||!t.publicKey||!t.fingerprint)return i(new Error("Need HDSigner to sign input"));const c=[],s=[];for(const a of sr(this.data.inputs.length))s.push(this.signInputHDAsync(a,t,r).then(()=>{c.push(!0)},()=>{c.push(!1)}));return Promise.all(s).then(()=>{if(c.every(a=>a===!1))return i(new Error("No inputs were signed"));n()})})}signInputHD(t,r,n=[we.Transaction.SIGHASH_ALL]){if(!r||!r.publicKey||!r.fingerprint)throw new Error("Need HDSigner to sign input");return ho(t,this.data.inputs,r).forEach(c=>this.signInput(t,c,n)),this}signInputHDAsync(t,r,n=[we.Transaction.SIGHASH_ALL]){return new Promise((i,c)=>{if(!r||!r.publicKey||!r.fingerprint)return c(new Error("Need HDSigner to sign input"));const a=ho(t,this.data.inputs,r).map(p=>this.signInputAsync(t,p,n));return Promise.all(a).then(()=>{i()}).catch(c)})}signAllInputs(t,r){if(!t||!t.publicKey)throw new Error("Need Signer to sign input");const n=[];for(const i of sr(this.data.inputs.length))try{this.signInput(i,t,r),n.push(!0)}catch{n.push(!1)}if(n.every(i=>i===!1))throw new Error("No inputs were signed");return this}signAllInputsAsync(t,r){return new Promise((n,i)=>{if(!t||!t.publicKey)return i(new Error("Need Signer to sign input"));const c=[],s=[];for(const[a]of this.data.inputs.entries())s.push(this.signInputAsync(a,t,r).then(()=>{c.push(!0)},()=>{c.push(!1)}));return Promise.all(s).then(()=>{if(c.every(a=>a===!1))return i(new Error("No inputs were signed"));n()})})}signInput(t,r,n){if(!r||!r.publicKey)throw new Error("Need Signer to sign input");const i=(0,Se.checkForInput)(this.data.inputs,t);return(0,J.isTaprootInput)(i)?this._signTaprootInput(t,i,r,void 0,n):this._signInput(t,r,n)}signTaprootInput(t,r,n,i){if(!r||!r.publicKey)throw new Error("Need Signer to sign input");const c=(0,Se.checkForInput)(this.data.inputs,t);if((0,J.isTaprootInput)(c))return this._signTaprootInput(t,c,r,n,i);throw new Error(`Input #${t} is not of type Taproot.`)}_signInput(t,r,n=[we.Transaction.SIGHASH_ALL]){const{hash:i,sighashType:c}=ao(this.data.inputs,t,r.publicKey,this.__CACHE,n),s=[{pubkey:r.publicKey,signature:Ye.signature.encode(r.sign(i),c)}];return this.data.updateInput(t,{partialSig:s}),this}_signTaprootInput(t,r,n,i,c=[we.Transaction.SIGHASH_DEFAULT]){const s=this.checkTaprootHashesForSig(t,r,n,i,c),a=s.filter(w=>!w.leafHash).map(w=>(0,J.serializeTaprootSignature)(n.signSchnorr(w.hash),r.sighashType))[0],p=s.filter(w=>!!w.leafHash).map(w=>({pubkey:(0,J.toXOnly)(n.publicKey),signature:(0,J.serializeTaprootSignature)(n.signSchnorr(w.hash),r.sighashType),leafHash:w.leafHash}));return a&&this.data.updateInput(t,{tapKeySig:a}),p.length&&this.data.updateInput(t,{tapScriptSig:p}),this}signInputAsync(t,r,n){return Promise.resolve().then(()=>{if(!r||!r.publicKey)throw new Error("Need Signer to sign input");const i=(0,Se.checkForInput)(this.data.inputs,t);return(0,J.isTaprootInput)(i)?this._signTaprootInputAsync(t,i,r,void 0,n):this._signInputAsync(t,r,n)})}signTaprootInputAsync(t,r,n,i){return Promise.resolve().then(()=>{if(!r||!r.publicKey)throw new Error("Need Signer to sign input");const c=(0,Se.checkForInput)(this.data.inputs,t);if((0,J.isTaprootInput)(c))return this._signTaprootInputAsync(t,c,r,n,i);throw new Error(`Input #${t} is not of type Taproot.`)})}_signInputAsync(t,r,n=[we.Transaction.SIGHASH_ALL]){const{hash:i,sighashType:c}=ao(this.data.inputs,t,r.publicKey,this.__CACHE,n);return Promise.resolve(r.sign(i)).then(s=>{const a=[{pubkey:r.publicKey,signature:Ye.signature.encode(s,c)}];this.data.updateInput(t,{partialSig:a})})}async _signTaprootInputAsync(t,r,n,i,c=[we.Transaction.SIGHASH_DEFAULT]){const s=this.checkTaprootHashesForSig(t,r,n,i,c),a=[],p=s.filter(f=>!f.leafHash)[0];if(p){const f=Promise.resolve(n.signSchnorr(p.hash)).then(d=>({tapKeySig:(0,J.serializeTaprootSignature)(d,r.sighashType)}));a.push(f)}const w=s.filter(f=>!!f.leafHash);if(w.length){const f=w.map(d=>Promise.resolve(n.signSchnorr(d.hash)).then(S=>({tapScriptSig:[{pubkey:(0,J.toXOnly)(n.publicKey),signature:(0,J.serializeTaprootSignature)(S,r.sighashType),leafHash:d.leafHash}]})));a.push(...f)}return Promise.all(a).then(f=>{f.forEach(d=>this.data.updateInput(t,d))})}checkTaprootHashesForSig(t,r,n,i,c){if(typeof n.signSchnorr!="function")throw new Error(`Need Schnorr Signer to sign taproot input #${t}.`);const s=Wn(t,r,this.data.inputs,n.publicKey,this.__CACHE,i,c);if(!s||!s.length)throw new Error(`Can not sign for input #${t} with the key ${n.publicKey.toString("hex")}`);return s}toBuffer(){return Rn(this.__CACHE),this.data.toBuffer()}toHex(){return Rn(this.__CACHE),this.data.toHex()}toBase64(){return Rn(this.__CACHE),this.data.toBase64()}updateGlobal(t){return this.data.updateGlobal(t),this}updateInput(t,r){return r.witnessScript&&jr(r.witnessScript),(0,J.checkTaprootInputFields)(this.data.inputs[t],r,"updateInput"),this.data.updateInput(t,r),r.nonWitnessUtxo&&jn(this.__CACHE,this.data.inputs[t],t),this}updateOutput(t,r){const n=this.data.outputs[t];return(0,J.checkTaprootOutputFields)(n,r,"updateOutput"),this.data.updateOutput(t,r),this}addUnknownKeyValToGlobal(t){return this.data.addUnknownKeyValToGlobal(t),this}addUnknownKeyValToInput(t,r){return this.data.addUnknownKeyValToInput(t,r),this}addUnknownKeyValToOutput(t,r){return this.data.addUnknownKeyValToOutput(t,r),this}clearFinalizedInput(t){return this.data.clearFinalizedInput(t),this}}sn.Psbt=Wr;const ch=e=>new ws(e);class ws{constructor(t=E.from([2,0,0,0,0,0,0,0,0,0])){this.tx=we.Transaction.fromBuffer(t),hh(this.tx),Object.defineProperty(this,"tx",{enumerable:!1,writable:!0})}getInputOutputCounts(){return{inputCount:this.tx.ins.length,outputCount:this.tx.outs.length}}addInput(t){if(t.hash===void 0||t.index===void 0||!E.isBuffer(t.hash)&&typeof t.hash!="string"||typeof t.index!="number")throw new Error("Error adding input.");const r=typeof t.hash=="string"?(0,Dr.reverseBuffer)(E.from(t.hash,"hex")):t.hash;this.tx.addInput(r,t.index,t.sequence)}addOutput(t){if(t.script===void 0||t.value===void 0||!E.isBuffer(t.script)||typeof t.value!="number")throw new Error("Error adding output.");this.tx.addOutput(t.script,t.value)}toBuffer(){return this.tx.toBuffer()}}function uh(e,t,r){switch(r){case"pubkey":case"pubkeyhash":case"witnesspubkeyhash":return io(1,e.partialSig);case"multisig":const n=ve.p2ms({output:t});return io(n.m,e.partialSig,n.pubkeys);default:return!1}}function Rn(e){if(e.__UNSAFE_SIGN_NONSEGWIT!==!1)throw new Error("Not BIP174 compliant, can not export")}function io(e,t,r){if(!t)return!1;let n;if(r?n=r.map(i=>{const c=Ih(i);return t.find(s=>s.pubkey.equals(c))}).filter(i=>!!i):n=t,n.length>e)throw new Error("Too many signatures");return n.length===e}function gs(e){return!!e.finalScriptSig||!!e.finalScriptWitness}function oo(e){return t=>!(!t.masterFingerprint.equals(e.fingerprint)||!e.derivePath(t.path).publicKey.equals(t.pubkey))}function xr(e){if(typeof e!="number"||e!==Math.floor(e)||e>4294967295||e<0)throw new Error("Invalid 32 bit integer")}function ah(e,t,r){const n=t.__FEE_RATE||e.getFeeRate(),i=t.__EXTRACTED_TX.virtualSize(),c=n*i;if(n>=r.maximumFeeRate)throw new Error(`Warning: You are paying around ${(c/1e8).toFixed(8)} in fees, which is ${n} satoshi per byte for a transaction with a VSize of ${i} bytes (segwit counted as 0.25 byte per byte). Use setMaximumFeeRate method to raise your threshold, or pass true to the first arg of extractTransaction.`)}function or(e,t){e.forEach(r=>{if((0,J.isTaprootInput)(r)?(0,J.checkTaprootInputForSigs)(r,t):(0,re.checkInputForSig)(r,t))throw new Error("Can not modify transaction, signatures exist.")})}function fh(e){if(!e.sighashType||!e.partialSig)return;const{partialSig:t,sighashType:r}=e;t.forEach(n=>{const{hashType:i}=Ye.signature.decode(n.signature);if(r!==i)throw new Error("Signature sighash does not match input sighash type")})}function Es(e,t,r){if(!(0,re.pubkeyInScript)(e,t))throw new Error(`Can not ${r} for this input with the key ${e.toString("hex")}`)}function hh(e){if(!e.ins.every(r=>r.script&&r.script.length===0&&r.witness&&r.witness.length===0))throw new Error("Format Error: Transaction ScriptSigs are not empty")}function ph(e,t){e.ins.forEach(r=>{ms(t,r)})}function ms(e,t){const r=(0,Dr.reverseBuffer)(E.from(t.hash)).toString("hex")+":"+t.index;if(e.__TX_IN_CACHE[r])throw new Error("Duplicate input detected.");e.__TX_IN_CACHE[r]=1}function Ss(e,t){return(r,n,i,c)=>{const s=e({redeem:{output:i}}).output;if(!n.equals(s))throw new Error(`${t} for ${c} #${r} doesn't match the scriptPubKey in the prevout`)}}const so=Ss(ve.p2sh,"Redeem script"),co=Ss(ve.p2wsh,"Witness script");function uo(e,t,r,n){if(!r.every(gs))throw new Error(`PSBT must be finalized to calculate ${t}`);if(e==="__FEE_RATE"&&n.__FEE_RATE)return n.__FEE_RATE;if(e==="__FEE"&&n.__FEE)return n.__FEE;let i,c=!0;if(n.__EXTRACTED_TX?(i=n.__EXTRACTED_TX,c=!1):i=n.__TX.clone(),ks(r,i,n,c),e==="__FEE_RATE")return n.__FEE_RATE;if(e==="__FEE")return n.__FEE}function lh(e,t,r,n,i,c){const s=Ps(r);if(!uh(t,r,s))throw new Error(`Can not finalize input #${e}`);return dh(r,s,t.partialSig,n,i,c)}function dh(e,t,r,n,i,c){let s,a;const p=wh(e,t,r),w=c?ve.p2wsh({redeem:p}):null,f=i?ve.p2sh({redeem:w||p}):null;return n?(w?a=(0,re.witnessStackToScriptWitness)(w.witness):a=(0,re.witnessStackToScriptWitness)(p.witness),f&&(s=f.input)):f?s=f.input:s=p.input,{finalScriptSig:s,finalScriptWitness:a}}function ao(e,t,r,n,i){const c=(0,Se.checkForInput)(e,t),{hash:s,sighashType:a,script:p}=bs(t,c,n,!1,i);return Es(r,p,"sign"),{hash:s,sighashType:a}}function bs(e,t,r,n,i){const c=r.__TX,s=t.sighashType||we.Transaction.SIGHASH_ALL;Ts(s,i);let a,p;if(t.nonWitnessUtxo){const d=fn(r,t,e),S=c.ins[e].hash,y=d.getHash();if(!S.equals(y))throw new Error(`Non-witness UTXO hash for input #${e} doesn't match the hash specified in the prevout`);const _=c.ins[e].index;p=d.outs[_]}else if(t.witnessUtxo)p=t.witnessUtxo;else throw new Error("Need a Utxo input item for signing");const{meaningfulScript:w,type:f}=hn(p.script,e,"input",t.redeemScript,t.witnessScript);if(["p2sh-p2wsh","p2wsh"].indexOf(f)>=0)a=c.hashForWitnessV0(e,w,p.value,s);else if((0,re.isP2WPKH)(w)){const d=ve.p2pkh({hash:w.slice(2)}).output;a=c.hashForWitnessV0(e,d,p.value,s)}else{if(t.nonWitnessUtxo===void 0&&r.__UNSAFE_SIGN_NONSEGWIT===!1)throw new Error(`Input #${e} has witnessUtxo but non-segwit script: ${w.toString("hex")}`);!n&&r.__UNSAFE_SIGN_NONSEGWIT!==!1&&console.warn(`Warning: Signing non-segwit inputs without the full parent transaction means there is a chance that a miner could feed you incorrect information to trick you into paying large fees. This behavior is the same as Psbt's predecessor (TransactionBuilder - now removed) when signing non-segwit scripts. You are not able to export this Psbt with toBuffer|toBase64|toHex since it is not BIP174 compliant. +`,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var mn={},Xr={},En={},ze={};Object.defineProperty(ze,"__esModule",{value:!0});ze.encode=ze.decode=ze.check=void 0;function Sc(e){if(e.length<8||e.length>72||e[0]!==48||e[1]!==e.length-2||e[2]!==2)return!1;const t=e[3];if(t===0||5+t>=e.length||e[4+t]!==2)return!1;const r=e[5+t];return!(r===0||6+t+r!==e.length||e[4]&128||t>1&&e[4]===0&&!(e[5]&128)||e[t+6]&128||r>1&&e[t+6]===0&&!(e[t+7]&128))}ze.check=Sc;function bc(e){if(e.length<8)throw new Error("DER sequence length is too short");if(e.length>72)throw new Error("DER sequence length is too long");if(e[0]!==48)throw new Error("Expected DER sequence");if(e[1]!==e.length-2)throw new Error("DER sequence length is invalid");if(e[2]!==2)throw new Error("Expected DER integer");const t=e[3];if(t===0)throw new Error("R length is zero");if(5+t>=e.length)throw new Error("R length is too long");if(e[4+t]!==2)throw new Error("Expected DER integer (2)");const r=e[5+t];if(r===0)throw new Error("S length is zero");if(6+t+r!==e.length)throw new Error("S length is invalid");if(e[4]&128)throw new Error("R value is negative");if(t>1&&e[4]===0&&!(e[5]&128))throw new Error("R value excessively padded");if(e[t+6]&128)throw new Error("S value is negative");if(r>1&&e[t+6]===0&&!(e[t+7]&128))throw new Error("S value excessively padded");return{r:e.slice(4,4+t),s:e.slice(6+t)}}ze.decode=bc;function _c(e,t){const r=e.length,n=t.length;if(r===0)throw new Error("R length is zero");if(n===0)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(n>33)throw new Error("S length is too long");if(e[0]&128)throw new Error("R value is negative");if(t[0]&128)throw new Error("S value is negative");if(r>1&&e[0]===0&&!(e[1]&128))throw new Error("R value excessively padded");if(n>1&&t[0]===0&&!(t[1]&128))throw new Error("S value excessively padded");const i=m.allocUnsafe(6+r+n);return i[0]=48,i[1]=i.length-2,i[2]=2,i[3]=e.length,e.copy(i,4),i[4+r]=2,i[5+r]=t.length,t.copy(i,6+r),i}ze.encode=_c;var ft={};Object.defineProperty(ft,"__esModule",{value:!0});ft.REVERSE_OPS=ft.OPS=void 0;const Ln={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_LEFT:128,OP_RIGHT:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_CHECKLOCKTIMEVERIFY:177,OP_NOP3:178,OP_CHECKSEQUENCEVERIFY:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_CHECKSIGADD:186,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255};ft.OPS=Ln;const Eo={};ft.REVERSE_OPS=Eo;for(const e of Object.keys(Ln)){const t=Ln[e];Eo[t]=e}var ut={};Object.defineProperty(ut,"__esModule",{value:!0});ut.decode=ut.encode=ut.encodingLength=void 0;const ct=ft;function So(e){return ee.length)return null;n=e.readUInt8(t+1),i=2}else if(r===ct.OPS.OP_PUSHDATA2){if(t+3>e.length)return null;n=e.readUInt16LE(t+1),i=3}else{if(t+5>e.length)return null;if(r!==ct.OPS.OP_PUSHDATA4)throw new Error("Unexpected opcode");n=e.readUInt32LE(t+1),i=5}return{opcode:r,number:n,size:i}}ut.decode=Ic;var zt={};Object.defineProperty(zt,"__esModule",{value:!0});zt.encode=zt.decode=void 0;function kc(e,t,r){t=t||4,r=r===void 0?!0:r;const n=e.length;if(n===0)return 0;if(n>t)throw new TypeError("Script number overflow");if(r&&!(e[n-1]&127)&&(n<=1||!(e[n-2]&128)))throw new Error("Non-minimally encoded script number");if(n===5){const c=e.readUInt32LE(0),s=e.readUInt8(4);return s&128?-((s&-129)*4294967296+c):s*4294967296+c}let i=0;for(let c=0;c2147483647?5:e>8388607?4:e>32767?3:e>127?2:e>0?1:0}function Pc(e){let t=Math.abs(e);const r=Ac(t),n=m.allocUnsafe(r),i=e<0;for(let c=0;c>=8;return n[r-1]&128?n.writeUInt8(i?128:0,r-1):i&&(n[r-1]|=128),n}zt.encode=Pc;var dt={},de={};const qr=qs(Ec);var dr={Array:function(e){return e!=null&&e.constructor===Array},Boolean:function(e){return typeof e=="boolean"},Function:function(e){return typeof e=="function"},Nil:function(e){return e==null},Number:function(e){return typeof e=="number"},Object:function(e){return typeof e=="object"},String:function(e){return typeof e=="string"},"":function(){return!0}};dr.Null=dr.Nil;for(var Ai in dr)dr[Ai].toJSON=(function(e){return e}).bind(null,Ai);var Xn=dr,gt=Xn;function bo(e){return e.name||e.toString().match(/function (.*?)\s*\(/)[1]}function qn(e){return gt.Nil(e)?"":bo(e.constructor)}function Oc(e){return gt.Function(e)?"":gt.String(e)?JSON.stringify(e):e&>.Object(e)?"":e}function zn(e,t){Error.captureStackTrace&&Error.captureStackTrace(e,t)}function Lr(e){return gt.Function(e)?e.toJSON?e.toJSON():bo(e):gt.Array(e)?"Array":e&>.Object(e)?"Object":e!==void 0?e:""}function _o(e,t,r){var n=Oc(t);return"Expected "+Lr(e)+", got"+(r!==""?" "+r:"")+(n!==""?" "+n:"")}function Je(e,t,r){r=r||qn(t),this.message=_o(e,t,r),zn(this,Je),this.__type=e,this.__value=t,this.__valueTypeName=r}Je.prototype=Object.create(Error.prototype);Je.prototype.constructor=Je;function vc(e,t,r,n,i){var c='" of type ';return t==="key"&&(c='" with key type '),_o('property "'+Lr(r)+c+Lr(e),n,i)}function Gt(e,t,r,n,i){e?(i=i||qn(n),this.message=vc(e,r,t,n,i)):this.message='Unexpected property "'+t+'"',zn(this,Je),this.__label=r,this.__property=t,this.__type=e,this.__value=n,this.__valueTypeName=i}Gt.prototype=Object.create(Error.prototype);Gt.prototype.constructor=Je;function Bc(e,t){return new Je(e,{},t)}function xc(e,t,r){return e instanceof Gt?(t=t+"."+e.__property,e=new Gt(e.__type,t,e.__label,e.__value,e.__valueTypeName)):e instanceof Je&&(e=new Gt(e.__type,t,r,e.__value,e.__valueTypeName)),zn(e),e}var To={TfTypeError:Je,TfPropertyTypeError:Gt,tfCustomError:Bc,tfSubError:xc,tfJSON:Lr,getValueTypeName:qn},Sn,Pi;function Uc(){if(Pi)return Sn;Pi=1;var e=Xn,t=To;function r(k){return m.isBuffer(k)}function n(k){return typeof k=="string"&&/^([0-9a-f]{2})+$/i.test(k)}function i(k,N){var $=k.toJSON();function B(R){if(!k(R))return!1;if(R.length===N)return!0;throw t.tfCustomError($+"(Length: "+N+")",$+"(Length: "+R.length+")")}return B.toJSON=function(){return $},B}var c=i.bind(null,e.Array),s=i.bind(null,r),a=i.bind(null,n),p=i.bind(null,e.String);function w(k,N,$){$=$||e.Number;function B(R,j){return $(R,j)&&R>k&&R>24===k}function y(k){return k<<16>>16===k}function _(k){return(k|0)===k}function T(k){return typeof k=="number"&&k>=-f&&k<=f&&Math.floor(k)===k}function A(k){return(k&255)===k}function x(k){return(k&65535)===k}function U(k){return k>>>0===k}function I(k){return typeof k=="number"&&k>=0&&k<=f&&Math.floor(k)===k}var S={ArrayN:c,Buffer:r,BufferN:s,Finite:d,Hex:n,HexN:a,Int8:E,Int16:y,Int32:_,Int53:T,Range:w,StringN:p,UInt8:A,UInt16:x,UInt32:U,UInt53:I};for(var v in S)S[v].toJSON=(function(k){return k}).bind(null,v);return Sn=S,Sn}var wr=To,le=Xn,We=wr.tfJSON,Io=wr.TfTypeError,ko=wr.TfPropertyTypeError,Zt=wr.tfSubError,Cc=wr.getValueTypeName,qe={arrayOf:function(t,r){t=Le(t),r=r||{};function n(i,c){return!le.Array(i)||le.Nil(i)||r.minLength!==void 0&&i.lengthr.maxLength||r.length!==void 0&&i.length!==r.length?!1:i.every(function(s,a){try{return be(t,s,c)}catch(p){throw Zt(p,a)}})}return n.toJSON=function(){var i="["+We(t)+"]";return r.length!==void 0?i+="{"+r.length+"}":(r.minLength!==void 0||r.maxLength!==void 0)&&(i+="{"+(r.minLength===void 0?0:r.minLength)+","+(r.maxLength===void 0?1/0:r.maxLength)+"}"),i},n},maybe:function e(t){t=Le(t);function r(n,i){return le.Nil(n)||t(n,i,e)}return r.toJSON=function(){return"?"+We(t)},r},map:function(t,r){t=Le(t),r&&(r=Le(r));function n(i,c){if(!le.Object(i)||le.Nil(i))return!1;for(var s in i){try{r&&be(r,s,c)}catch(p){throw Zt(p,s,"key")}try{var a=i[s];be(t,a,c)}catch(p){throw Zt(p,s)}}return!0}return r?n.toJSON=function(){return"{"+We(r)+": "+We(t)+"}"}:n.toJSON=function(){return"{"+We(t)+"}"},n},object:function(t){var r={};for(var n in t)r[n]=Le(t[n]);function i(c,s){if(!le.Object(c)||le.Nil(c))return!1;var a;try{for(a in r){var p=r[a],w=c[a];be(p,w,s)}}catch(f){throw Zt(f,a)}if(s){for(a in c)if(!r[a])throw new ko(void 0,a)}return!0}return i.toJSON=function(){return We(r)},i},anyOf:function(){var t=[].slice.call(arguments).map(Le);function r(n,i){return t.some(function(c){try{return be(c,n,i)}catch{return!1}})}return r.toJSON=function(){return t.map(We).join("|")},r},allOf:function(){var t=[].slice.call(arguments).map(Le);function r(n,i){return t.every(function(c){try{return be(c,n,i)}catch{return!1}})}return r.toJSON=function(){return t.map(We).join(" & ")},r},quacksLike:function(t){function r(n){return t===Cc(n)}return r.toJSON=function(){return t},r},tuple:function(){var t=[].slice.call(arguments).map(Le);function r(n,i){return le.Nil(n)||le.Nil(n.length)||i&&n.length!==t.length?!1:t.every(function(c,s){try{return be(c,n[s],i)}catch(a){throw Zt(a,s)}})}return r.toJSON=function(){return"("+t.map(We).join(", ")+")"},r},value:function(t){function r(n){return n===t}return r.toJSON=function(){return t},r}};qe.oneOf=qe.anyOf;function Le(e){if(le.String(e))return e[0]==="?"?qe.maybe(e.slice(1)):le[e]||qe.quacksLike(e);if(e&&le.Object(e)){if(le.Array(e)){if(e.length!==1)throw new TypeError("Expected compile() parameter of type Array of length 1");return qe.arrayOf(e[0])}return qe.object(e)}else if(le.Function(e))return e;return qe.value(e)}function be(e,t,r,n){if(le.Function(e)){if(e(t,r))return!0;throw new Io(n||e,t)}return be(Le(e),t,r)}for(var at in le)be[at]=le[at];for(at in qe)be[at]=qe[at];var Oi=Uc();for(at in Oi)be[at]=Oi[at];be.compile=Le;be.TfTypeError=Io;be.TfPropertyTypeError=ko;var Nc=be;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.oneOf=e.Null=e.BufferN=e.Function=e.UInt32=e.UInt8=e.tuple=e.maybe=e.Hex=e.Buffer=e.String=e.Boolean=e.Array=e.Number=e.Hash256bit=e.Hash160bit=e.Buffer256bit=e.isTaptree=e.isTapleaf=e.TAPLEAF_VERSION_MASK=e.Satoshi=e.isPoint=e.stacksEqual=e.typeforce=void 0;const t=qr;e.typeforce=Nc;const r=t.Buffer.alloc(32,0),n=t.Buffer.from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f","hex");function i(f,d){return f.length!==d.length?!1:f.every((E,y)=>E.equals(d[y]))}e.stacksEqual=i;function c(f){if(!t.Buffer.isBuffer(f)||f.length<33)return!1;const d=f[0],E=f.slice(1,33);if(E.compare(r)===0||E.compare(n)>=0)return!1;if((d===2||d===3)&&f.length===33)return!0;const y=f.slice(33);return y.compare(r)===0||y.compare(n)>=0?!1:d===4&&f.length===65}e.isPoint=c;const s=21*1e14;function a(f){return e.typeforce.UInt53(f)&&f<=s}e.Satoshi=a,e.TAPLEAF_VERSION_MASK=254;function p(f){return!f||!("output"in f)||!t.Buffer.isBuffer(f.output)?!1:f.version!==void 0?(f.version&e.TAPLEAF_VERSION_MASK)===f.version:!0}e.isTapleaf=p;function w(f){return(0,e.Array)(f)?f.length!==2?!1:f.every(d=>w(d)):p(f)}e.isTaptree=w,e.Buffer256bit=e.typeforce.BufferN(32),e.Hash160bit=e.typeforce.BufferN(20),e.Hash256bit=e.typeforce.BufferN(32),e.Number=e.typeforce.Number,e.Array=e.typeforce.Array,e.Boolean=e.typeforce.Boolean,e.String=e.typeforce.String,e.Buffer=e.typeforce.Buffer,e.Hex=e.typeforce.Hex,e.maybe=e.typeforce.maybe,e.tuple=e.typeforce.tuple,e.UInt8=e.typeforce.UInt8,e.UInt32=e.typeforce.UInt32,e.Function=e.typeforce.Function,e.BufferN=e.typeforce.BufferN,e.Null=e.typeforce.Null,e.oneOf=e.typeforce.oneOf})(de);var vi;function Hc(){if(vi)return dt;vi=1,Object.defineProperty(dt,"__esModule",{value:!0}),dt.encode=dt.decode=void 0;const e=ze,t=_e(),r=de,{typeforce:n}=r,i=m.alloc(1,0);function c(w){let f=0;for(;w[f]===0;)++f;return f===w.length?i:(w=w.slice(f),w[0]&128?m.concat([i,w],1+w.length):w)}function s(w){w[0]===0&&(w=w.slice(1));const f=m.alloc(32,0),d=Math.max(0,32-w.length);return w.copy(f,d),f}function a(w){const f=w.readUInt8(w.length-1);if(!(0,t.isDefinedHashType)(f))throw new Error("Invalid hashType "+f);const d=e.decode(w.slice(0,-1)),E=s(d.r),y=s(d.s);return{signature:m.concat([E,y],64),hashType:f}}dt.decode=a;function p(w,f){if(n({signature:r.BufferN(64),hashType:r.UInt8},{signature:w,hashType:f}),!(0,t.isDefinedHashType)(f))throw new Error("Invalid hashType "+f);const d=m.allocUnsafe(1);d.writeUInt8(f,0);const E=c(w.slice(0,32)),y=c(w.slice(32,64));return m.concat([e.encode(E,y),d])}return dt.encode=p,dt}var Bi;function _e(){return Bi||(Bi=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.signature=e.number=e.isCanonicalScriptSignature=e.isDefinedHashType=e.isCanonicalPubKey=e.toStack=e.fromASM=e.toASM=e.decompile=e.compile=e.countNonPushOnlyOPs=e.isPushOnly=e.OPS=void 0;const t=ze,r=ft;Object.defineProperty(e,"OPS",{enumerable:!0,get:function(){return r.OPS}});const n=ut,i=zt,c=Hc(),s=de,{typeforce:a}=s,p=r.OPS.OP_RESERVED;function w(B){return s.Number(B)&&(B===r.OPS.OP_0||B>=r.OPS.OP_1&&B<=r.OPS.OP_16||B===r.OPS.OP_1NEGATE)}function f(B){return s.Buffer(B)||w(B)}function d(B){return s.Array(B)&&B.every(f)}e.isPushOnly=d;function E(B){return B.length-B.filter(f).length}e.countNonPushOnlyOPs=E;function y(B){if(B.length===0)return r.OPS.OP_0;if(B.length===1){if(B[0]>=1&&B[0]<=16)return p+B[0];if(B[0]===129)return r.OPS.OP_1NEGATE}}function _(B){return m.isBuffer(B)}function T(B){return s.Array(B)}function A(B){return m.isBuffer(B)}function x(B){if(_(B))return B;a(s.Array,B);const R=B.reduce((C,F)=>A(F)?F.length===1&&y(F)!==void 0?C+1:C+n.encodingLength(F.length)+F.length:C+1,0),j=m.allocUnsafe(R);let O=0;if(B.forEach(C=>{if(A(C)){const F=y(C);if(F!==void 0){j.writeUInt8(F,O),O+=1;return}O+=n.encode(j,C.length,O),C.copy(j,O),O+=C.length}else j.writeUInt8(C,O),O+=1}),O!==j.length)throw new Error("Could not decode chunks");return j}e.compile=x;function U(B){if(T(B))return B;a(s.Buffer,B);const R=[];let j=0;for(;jr.OPS.OP_0&&O<=r.OPS.OP_PUSHDATA4){const C=n.decode(B,j);if(C===null||(j+=C.size,j+C.number>B.length))return null;const F=B.slice(j,j+C.number);j+=C.number;const D=y(F);D!==void 0?R.push(D):R.push(F)}else R.push(O),j+=1}return R}e.decompile=U;function I(B){if(_(B)&&(B=U(B)),!B)throw new Error("Could not convert invalid chunks to ASM");return B.map(R=>{if(A(R)){const j=y(R);if(j===void 0)return R.toString("hex");R=j}return r.REVERSE_OPS[R]}).join(" ")}e.toASM=I;function S(B){return a(s.String,B),x(B.split(" ").map(R=>r.OPS[R]!==void 0?r.OPS[R]:(a(s.Hex,R),m.from(R,"hex"))))}e.fromASM=S;function v(B){return B=U(B),a(d,B),B.map(R=>A(R)?R:R===r.OPS.OP_0?m.allocUnsafe(0):i.encode(R-p))}e.toStack=v;function k(B){return s.isPoint(B)}e.isCanonicalPubKey=k;function N(B){const R=B&-129;return R>0&&R<4}e.isDefinedHashType=N;function $(B){return!m.isBuffer(B)||!N(B[B.length-1])?!1:t.check(B.slice(0,-1))}e.isCanonicalScriptSignature=$,e.number=i,e.signature=c}(En)),En}var ke={};Object.defineProperty(ke,"__esModule",{value:!0});ke.value=ke.prop=void 0;function Rc(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){const n=r.call(this);return this[t]=n,n},set(n){Object.defineProperty(this,t,{configurable:!0,enumerable:!0,value:n,writable:!0})}})}ke.prop=Rc;function Fc(e){let t;return()=>(t!==void 0||(t=e()),t)}ke.value=Fc;Object.defineProperty(Xr,"__esModule",{value:!0});Xr.p2data=void 0;const Lc=ae,Ur=_e(),Ce=de,xi=ke,Ui=Ur.OPS;function Mc(e,t){if(!e.data&&!e.output)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,Ce.typeforce)({network:Ce.typeforce.maybe(Ce.typeforce.Object),output:Ce.typeforce.maybe(Ce.typeforce.Buffer),data:Ce.typeforce.maybe(Ce.typeforce.arrayOf(Ce.typeforce.Buffer))},e);const n={name:"embed",network:e.network||Lc.bitcoin};if(xi.prop(n,"output",()=>{if(e.data)return Ur.compile([Ui.OP_RETURN].concat(e.data))}),xi.prop(n,"data",()=>{if(e.output)return Ur.decompile(e.output).slice(1)}),t.validate&&e.output){const i=Ur.decompile(e.output);if(i[0]!==Ui.OP_RETURN)throw new TypeError("Output is invalid");if(!i.slice(1).every(Ce.typeforce.Buffer))throw new TypeError("Output is invalid");if(e.data&&!(0,Ce.stacksEqual)(e.data,n.data))throw new TypeError("Data mismatch")}return Object.assign(n,e)}Xr.p2data=Mc;var zr={};Object.defineProperty(zr,"__esModule",{value:!0});zr.p2ms=void 0;const $c=ae,Dt=_e(),ee=de,et=ke,Wt=Dt.OPS,_r=Wt.OP_RESERVED;function Kc(e,t){if(!e.input&&!e.output&&!(e.pubkeys&&e.m!==void 0)&&!e.signatures)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{});function r(p){return Dt.isCanonicalScriptSignature(p)||(t.allowIncomplete&&p===Wt.OP_0)!==void 0}(0,ee.typeforce)({network:ee.typeforce.maybe(ee.typeforce.Object),m:ee.typeforce.maybe(ee.typeforce.Number),n:ee.typeforce.maybe(ee.typeforce.Number),output:ee.typeforce.maybe(ee.typeforce.Buffer),pubkeys:ee.typeforce.maybe(ee.typeforce.arrayOf(ee.isPoint)),signatures:ee.typeforce.maybe(ee.typeforce.arrayOf(r)),input:ee.typeforce.maybe(ee.typeforce.Buffer)},e);const i={network:e.network||$c.bitcoin};let c=[],s=!1;function a(p){s||(s=!0,c=Dt.decompile(p),i.m=c[0]-_r,i.n=c[c.length-2]-_r,i.pubkeys=c.slice(1,-2))}if(et.prop(i,"output",()=>{if(e.m&&i.n&&e.pubkeys)return Dt.compile([].concat(_r+e.m,e.pubkeys,_r+i.n,Wt.OP_CHECKMULTISIG))}),et.prop(i,"m",()=>{if(i.output)return a(i.output),i.m}),et.prop(i,"n",()=>{if(i.pubkeys)return i.pubkeys.length}),et.prop(i,"pubkeys",()=>{if(e.output)return a(e.output),i.pubkeys}),et.prop(i,"signatures",()=>{if(e.input)return Dt.decompile(e.input).slice(1)}),et.prop(i,"input",()=>{if(e.signatures)return Dt.compile([Wt.OP_0].concat(e.signatures))}),et.prop(i,"witness",()=>{if(i.input)return[]}),et.prop(i,"name",()=>{if(!(!i.m||!i.n))return`p2ms(${i.m} of ${i.n})`}),t.validate){if(e.output){if(a(e.output),!ee.typeforce.Number(c[0]))throw new TypeError("Output is invalid");if(!ee.typeforce.Number(c[c.length-2]))throw new TypeError("Output is invalid");if(c[c.length-1]!==Wt.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(i.m<=0||i.n>16||i.m>i.n||i.n!==c.length-3)throw new TypeError("Output is invalid");if(!i.pubkeys.every(p=>(0,ee.isPoint)(p)))throw new TypeError("Output is invalid");if(e.m!==void 0&&e.m!==i.m)throw new TypeError("m mismatch");if(e.n!==void 0&&e.n!==i.n)throw new TypeError("n mismatch");if(e.pubkeys&&!(0,ee.stacksEqual)(e.pubkeys,i.pubkeys))throw new TypeError("Pubkeys mismatch")}if(e.pubkeys){if(e.n!==void 0&&e.n!==e.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(i.n=e.pubkeys.length,i.ni.m)throw new TypeError("Too many signatures provided")}if(e.input){if(e.input[0]!==Wt.OP_0)throw new TypeError("Input is invalid");if(i.signatures.length===0||!i.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(e.signatures&&!(0,ee.stacksEqual)(e.signatures,i.signatures))throw new TypeError("Signature mismatch");if(e.m!==void 0&&e.m!==e.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(i,e)}zr.p2ms=Kc;var Yr={};Object.defineProperty(Yr,"__esModule",{value:!0});Yr.p2pk=void 0;const Dc=ae,jt=_e(),Be=de,$t=ke,Ci=jt.OPS;function Wc(e,t){if(!e.input&&!e.output&&!e.pubkey&&!e.input&&!e.signature)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,Be.typeforce)({network:Be.typeforce.maybe(Be.typeforce.Object),output:Be.typeforce.maybe(Be.typeforce.Buffer),pubkey:Be.typeforce.maybe(Be.isPoint),signature:Be.typeforce.maybe(jt.isCanonicalScriptSignature),input:Be.typeforce.maybe(Be.typeforce.Buffer)},e);const r=$t.value(()=>jt.decompile(e.input)),i={name:"p2pk",network:e.network||Dc.bitcoin};if($t.prop(i,"output",()=>{if(e.pubkey)return jt.compile([e.pubkey,Ci.OP_CHECKSIG])}),$t.prop(i,"pubkey",()=>{if(e.output)return e.output.slice(1,-1)}),$t.prop(i,"signature",()=>{if(e.input)return r()[0]}),$t.prop(i,"input",()=>{if(e.signature)return jt.compile([e.signature])}),$t.prop(i,"witness",()=>{if(i.input)return[]}),t.validate){if(e.output){if(e.output[e.output.length-1]!==Ci.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!(0,Be.isPoint)(i.pubkey))throw new TypeError("Output pubkey is invalid");if(e.pubkey&&!e.pubkey.equals(i.pubkey))throw new TypeError("Pubkey mismatch")}if(e.signature&&e.input&&!e.input.equals(i.input))throw new TypeError("Signature mismatch");if(e.input){if(r().length!==1)throw new TypeError("Input is invalid");if(!jt.isCanonicalScriptSignature(i.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(i,e)}Yr.p2pk=Wc;var Jr={},Ke={},Yt={},$e={},ue={};Object.defineProperty(ue,"__esModule",{value:!0});ue.output=ue.exists=ue.hash=ue.bytes=ue.bool=ue.number=ue.isBytes=void 0;function Mr(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}ue.number=Mr;function Ao(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}ue.bool=Ao;function Po(e){return e instanceof Uint8Array||e!=null&&typeof e=="object"&&e.constructor.name==="Uint8Array"}ue.isBytes=Po;function Yn(e,...t){if(!Po(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}`)}ue.bytes=Yn;function Oo(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Mr(e.outputLen),Mr(e.blockLen)}ue.hash=Oo;function vo(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")}ue.exists=vo;function Bo(e,t){Yn(e);const r=t.outputLen;if(e.lengthnew Uint8Array(O.buffer,O.byteOffset,O.byteLength);e.u8=i;const c=O=>new Uint32Array(O.buffer,O.byteOffset,Math.floor(O.byteLength/4));e.u32=c;const s=O=>new DataView(O.buffer,O.byteOffset,O.byteLength);e.createView=s;const a=(O,C)=>O<<32-C|O>>>C;e.rotr=a;const p=(O,C)=>O<>>32-C>>>0;e.rotl=p,e.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;const w=O=>O<<24&4278190080|O<<8&16711680|O>>>8&65280|O>>>24&255;e.byteSwap=w,e.byteSwapIfBE=e.isLE?O=>O:O=>(0,e.byteSwap)(O);function f(O){for(let C=0;CC.toString(16).padStart(2,"0"));function E(O){(0,r.bytes)(O);let C="";for(let F=0;F=y._0&&O<=y._9)return O-y._0;if(O>=y._A&&O<=y._F)return O-(y._A-10);if(O>=y._a&&O<=y._f)return O-(y._a-10)}function T(O){if(typeof O!="string")throw new Error("hex string expected, got "+typeof O);const C=O.length,F=C/2;if(C%2)throw new Error("padded hex string expected, got unpadded hex of length "+C);const D=new Uint8Array(F);for(let ne=0,ye=0;ne{};e.nextTick=A;async function x(O,C,F){let D=Date.now();for(let ne=0;ne=0&&yeO().update(I(D)).digest(),F=O();return C.outputLen=F.outputLen,C.blockLen=F.blockLen,C.create=()=>O(),C}e.wrapConstructor=$;function B(O){const C=(D,ne)=>O(ne).update(I(D)).digest(),F=O({});return C.outputLen=F.outputLen,C.blockLen=F.blockLen,C.create=D=>O(D),C}e.wrapConstructorWithOpts=B;function R(O){const C=(D,ne)=>O(ne).update(I(D)).digest(),F=O({});return C.outputLen=F.outputLen,C.blockLen=F.blockLen,C.create=D=>O(D),C}e.wrapXOFConstructorWithOpts=R;function j(O=32){if(t.crypto&&typeof t.crypto.getRandomValues=="function")return t.crypto.getRandomValues(new Uint8Array(O));throw new Error("crypto.getRandomValues must be defined")}e.randomBytes=j})(gr);Object.defineProperty($e,"__esModule",{value:!0});$e.HashMD=$e.Maj=$e.Chi=void 0;const bn=ue,er=gr;function Vc(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);const i=BigInt(32),c=BigInt(4294967295),s=Number(r>>i&c),a=Number(r&c),p=n?4:0,w=n?0:4;e.setUint32(t+p,s,n),e.setUint32(t+w,a,n)}const Gc=(e,t,r)=>e&t^~e&r;$e.Chi=Gc;const Xc=(e,t,r)=>e&t^e&r^t&r;$e.Maj=Xc;class qc extends er.Hash{constructor(t,r,n,i){super(),this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=(0,er.createView)(this.buffer)}update(t){(0,bn.exists)(this);const{view:r,buffer:n,blockLen:i}=this;t=(0,er.toBytes)(t);const c=t.length;for(let s=0;si-s&&(this.process(n,0),s=0);for(let d=s;df.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;dt)),Jc=xo.map(e=>(9*e+5)%16);let Jn=[xo],Qn=[Jc];for(let e=0;e<4;e++)for(let t of[Jn,Qn])t.push(t[e].map(r=>Yc[r]));const Uo=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(e=>new Uint8Array(e)),Qc=Jn.map((e,t)=>e.map(r=>Uo[t][r])),Zc=Qn.map((e,t)=>e.map(r=>Uo[t][r])),eu=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),tu=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]);function Ni(e,t,r,n){return e===0?t^r^n:e===1?t&r|~t&n:e===2?(t|~r)^n:e===3?t&n|r&~n:t^(r|~n)}const Tr=new Uint32Array(16);class Co extends zc.HashMD{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:t,h1:r,h2:n,h3:i,h4:c}=this;return[t,r,n,i,c]}set(t,r,n,i,c){this.h0=t|0,this.h1=r|0,this.h2=n|0,this.h3=i|0,this.h4=c|0}process(t,r){for(let y=0;y<16;y++,r+=4)Tr[y]=t.getUint32(r,!0);let n=this.h0|0,i=n,c=this.h1|0,s=c,a=this.h2|0,p=a,w=this.h3|0,f=w,d=this.h4|0,E=d;for(let y=0;y<5;y++){const _=4-y,T=eu[y],A=tu[y],x=Jn[y],U=Qn[y],I=Qc[y],S=Zc[y];for(let v=0;v<16;v++){const k=(0,sr.rotl)(n+Ni(y,c,a,w)+Tr[x[v]]+T,I[v])+d|0;n=d,d=w,w=(0,sr.rotl)(a,10)|0,a=c,c=k}for(let v=0;v<16;v++){const k=(0,sr.rotl)(i+Ni(_,s,p,f)+Tr[U[v]]+A,S[v])+E|0;i=E,E=f,f=(0,sr.rotl)(p,10)|0,p=s,s=k}}this.set(this.h1+a+f|0,this.h2+w+E|0,this.h3+d+i|0,this.h4+n+s|0,this.h0+c+p|0)}roundClean(){Tr.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}}Yt.RIPEMD160=Co;Yt.ripemd160=(0,sr.wrapConstructor)(()=>new Co);var Zr={};Object.defineProperty(Zr,"__esModule",{value:!0});Zr.sha1=void 0;const _n=$e,Cr=gr,tr=new Uint32Array([1732584193,4023233417,2562383102,271733878,3285377520]),tt=new Uint32Array(80);class ru extends _n.HashMD{constructor(){super(64,20,8,!1),this.A=tr[0]|0,this.B=tr[1]|0,this.C=tr[2]|0,this.D=tr[3]|0,this.E=tr[4]|0}get(){const{A:t,B:r,C:n,D:i,E:c}=this;return[t,r,n,i,c]}set(t,r,n,i,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=c|0}process(t,r){for(let p=0;p<16;p++,r+=4)tt[p]=t.getUint32(r,!1);for(let p=16;p<80;p++)tt[p]=(0,Cr.rotl)(tt[p-3]^tt[p-8]^tt[p-14]^tt[p-16],1);let{A:n,B:i,C:c,D:s,E:a}=this;for(let p=0;p<80;p++){let w,f;p<20?(w=(0,_n.Chi)(i,c,s),f=1518500249):p<40?(w=i^c^s,f=1859775393):p<60?(w=(0,_n.Maj)(i,c,s),f=2400959708):(w=i^c^s,f=3395469782);const d=(0,Cr.rotl)(n,5)+w+a+f+tt[p]|0;a=s,s=c,c=(0,Cr.rotl)(i,30),i=n,n=d}n=n+this.A|0,i=i+this.B|0,c=c+this.C|0,s=s+this.D|0,a=a+this.E|0,this.set(n,i,c,s,a)}roundClean(){tt.fill(0)}destroy(){this.set(0,0,0,0,0),this.buffer.fill(0)}}Zr.sha1=(0,Cr.wrapConstructor)(()=>new ru);var Et={};Object.defineProperty(Et,"__esModule",{value:!0});Et.sha224=Et.sha256=void 0;const Tn=$e,Pe=gr,nu=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]),rt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),nt=new Uint32Array(64);class No extends Tn.HashMD{constructor(){super(64,32,8,!1),this.A=rt[0]|0,this.B=rt[1]|0,this.C=rt[2]|0,this.D=rt[3]|0,this.E=rt[4]|0,this.F=rt[5]|0,this.G=rt[6]|0,this.H=rt[7]|0}get(){const{A:t,B:r,C:n,D:i,E:c,F:s,G:a,H:p}=this;return[t,r,n,i,c,s,a,p]}set(t,r,n,i,c,s,a,p){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=c|0,this.F=s|0,this.G=a|0,this.H=p|0}process(t,r){for(let d=0;d<16;d++,r+=4)nt[d]=t.getUint32(r,!1);for(let d=16;d<64;d++){const E=nt[d-15],y=nt[d-2],_=(0,Pe.rotr)(E,7)^(0,Pe.rotr)(E,18)^E>>>3,T=(0,Pe.rotr)(y,17)^(0,Pe.rotr)(y,19)^y>>>10;nt[d]=T+nt[d-7]+_+nt[d-16]|0}let{A:n,B:i,C:c,D:s,E:a,F:p,G:w,H:f}=this;for(let d=0;d<64;d++){const E=(0,Pe.rotr)(a,6)^(0,Pe.rotr)(a,11)^(0,Pe.rotr)(a,25),y=f+E+(0,Tn.Chi)(a,p,w)+nu[d]+nt[d]|0,T=((0,Pe.rotr)(n,2)^(0,Pe.rotr)(n,13)^(0,Pe.rotr)(n,22))+(0,Tn.Maj)(n,i,c)|0;f=w,w=p,p=a,a=s+y|0,s=c,c=i,i=n,n=y+T|0}n=n+this.A|0,i=i+this.B|0,c=c+this.C|0,s=s+this.D|0,a=a+this.E|0,p=p+this.F|0,w=w+this.G|0,f=f+this.H|0,this.set(n,i,c,s,a,p,w,f)}roundClean(){nt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}class iu extends No{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}}Et.sha256=(0,Pe.wrapConstructor)(()=>new No);Et.sha224=(0,Pe.wrapConstructor)(()=>new iu);(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.taggedHash=e.TAGGED_HASH_PREFIXES=e.TAGS=e.hash256=e.hash160=e.sha256=e.sha1=e.ripemd160=void 0;const t=Yt,r=Zr,n=Et;function i(f){return m.from((0,t.ripemd160)(Uint8Array.from(f)))}e.ripemd160=i;function c(f){return m.from((0,r.sha1)(Uint8Array.from(f)))}e.sha1=c;function s(f){return m.from((0,n.sha256)(Uint8Array.from(f)))}e.sha256=s;function a(f){return m.from((0,t.ripemd160)((0,n.sha256)(Uint8Array.from(f))))}e.hash160=a;function p(f){return m.from((0,n.sha256)((0,n.sha256)(Uint8Array.from(f))))}e.hash256=p,e.TAGS=["BIP0340/challenge","BIP0340/aux","BIP0340/nonce","TapLeaf","TapBranch","TapSighash","TapTweak","KeyAgg list","KeyAgg coefficient"],e.TAGGED_HASH_PREFIXES={"BIP0340/challenge":m.from([123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124,123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124]),"BIP0340/aux":m.from([241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144,241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144]),"BIP0340/nonce":m.from([7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47,7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47]),TapLeaf:m.from([174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238,174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238]),TapBranch:m.from([25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21,25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21]),TapSighash:m.from([244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49,244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49]),TapTweak:m.from([232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233,232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233]),"KeyAgg list":m.from([72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240,72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240]),"KeyAgg coefficient":m.from([191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129,191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129])};function w(f,d){return s(m.concat([e.TAGGED_HASH_PREFIXES[f],d]))}e.taggedHash=w})(Ke);function ou(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r>>0,I=new Uint8Array(U);A!==x;){for(var S=y[A],v=0,k=U-1;(S!==0||v>>0,I[k]=S%s>>>0,S=S/s>>>0;if(S!==0)throw new Error("Non-zero carry");T=v,A++}for(var N=U-T;N!==U&&I[N]===0;)N++;for(var $=a.repeat(_);N>>0,U=new Uint8Array(x);y[_];){var I=t[y.charCodeAt(_)];if(I===255)return;for(var S=0,v=x-1;(I!==0||S>>0,U[v]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");A=S,_++}for(var k=x-A;k!==x&&U[k]===0;)k++;for(var N=new Uint8Array(T+(x-k)),$=T;k!==x;)N[$++]=U[k++];return N}function E(y){var _=d(y);if(_)return _;throw new Error("Non-base"+s+" character")}return{encode:f,decodeUnsafe:d,decode:E}}var su=ou;const cu=su,uu="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";var au=cu(uu),In=au,fu=function(e){function t(c){var s=Uint8Array.from(c),a=e(s),p=s.length+4,w=new Uint8Array(p);return w.set(s,0),w.set(a.subarray(0,4),s.length),In.encode(w,p)}function r(c){var s=c.slice(0,-4),a=c.slice(-4),p=e(s);if(!(a[0]^p[0]|a[1]^p[1]|a[2]^p[2]|a[3]^p[3]))return s}function n(c){var s=In.decodeUnsafe(c);if(s)return r(s)}function i(c){var s=In.decode(c),a=r(s);if(!a)throw new Error("Invalid checksum");return a}return{encode:t,decode:i,decodeUnsafe:n}},{sha256:Hi}=Et,hu=fu;function pu(e){return Hi(Hi(e))}var Zn=hu(pu);Object.defineProperty(Jr,"__esModule",{value:!0});Jr.p2pkh=void 0;const kn=Ke,lu=ae,Vt=_e(),me=de,je=ke,Ri=Zn,it=Vt.OPS;function du(e,t){if(!e.address&&!e.hash&&!e.output&&!e.pubkey&&!e.input)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,me.typeforce)({network:me.typeforce.maybe(me.typeforce.Object),address:me.typeforce.maybe(me.typeforce.String),hash:me.typeforce.maybe(me.typeforce.BufferN(20)),output:me.typeforce.maybe(me.typeforce.BufferN(25)),pubkey:me.typeforce.maybe(me.isPoint),signature:me.typeforce.maybe(Vt.isCanonicalScriptSignature),input:me.typeforce.maybe(me.typeforce.Buffer)},e);const r=je.value(()=>{const s=m.from(Ri.decode(e.address)),a=s.readUInt8(0),p=s.slice(1);return{version:a,hash:p}}),n=je.value(()=>Vt.decompile(e.input)),i=e.network||lu.bitcoin,c={name:"p2pkh",network:i};if(je.prop(c,"address",()=>{if(!c.hash)return;const s=m.allocUnsafe(21);return s.writeUInt8(i.pubKeyHash,0),c.hash.copy(s,1),Ri.encode(s)}),je.prop(c,"hash",()=>{if(e.output)return e.output.slice(3,23);if(e.address)return r().hash;if(e.pubkey||c.pubkey)return kn.hash160(e.pubkey||c.pubkey)}),je.prop(c,"output",()=>{if(c.hash)return Vt.compile([it.OP_DUP,it.OP_HASH160,c.hash,it.OP_EQUALVERIFY,it.OP_CHECKSIG])}),je.prop(c,"pubkey",()=>{if(e.input)return n()[1]}),je.prop(c,"signature",()=>{if(e.input)return n()[0]}),je.prop(c,"input",()=>{if(e.pubkey&&e.signature)return Vt.compile([e.signature,e.pubkey])}),je.prop(c,"witness",()=>{if(c.input)return[]}),t.validate){let s=m.from([]);if(e.address){if(r().version!==i.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(r().hash.length!==20)throw new TypeError("Invalid address");s=r().hash}if(e.hash){if(s.length>0&&!s.equals(e.hash))throw new TypeError("Hash mismatch");s=e.hash}if(e.output){if(e.output.length!==25||e.output[0]!==it.OP_DUP||e.output[1]!==it.OP_HASH160||e.output[2]!==20||e.output[23]!==it.OP_EQUALVERIFY||e.output[24]!==it.OP_CHECKSIG)throw new TypeError("Output is invalid");const a=e.output.slice(3,23);if(s.length>0&&!s.equals(a))throw new TypeError("Hash mismatch");s=a}if(e.pubkey){const a=kn.hash160(e.pubkey);if(s.length>0&&!s.equals(a))throw new TypeError("Hash mismatch");s=a}if(e.input){const a=n();if(a.length!==2)throw new TypeError("Input is invalid");if(!Vt.isCanonicalScriptSignature(a[0]))throw new TypeError("Input has invalid signature");if(!(0,me.isPoint)(a[1]))throw new TypeError("Input has invalid pubkey");if(e.signature&&!e.signature.equals(a[0]))throw new TypeError("Signature mismatch");if(e.pubkey&&!e.pubkey.equals(a[1]))throw new TypeError("Pubkey mismatch");const p=kn.hash160(a[1]);if(s.length>0&&!s.equals(p))throw new TypeError("Hash mismatch")}}return Object.assign(c,e)}Jr.p2pkh=du;var en={};Object.defineProperty(en,"__esModule",{value:!0});en.p2sh=void 0;const Fi=Ke,yu=ae,Re=_e(),X=de,Ne=ke,Li=Zn,rr=Re.OPS;function wu(e,t){if(!e.address&&!e.hash&&!e.output&&!e.redeem&&!e.input)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,X.typeforce)({network:X.typeforce.maybe(X.typeforce.Object),address:X.typeforce.maybe(X.typeforce.String),hash:X.typeforce.maybe(X.typeforce.BufferN(20)),output:X.typeforce.maybe(X.typeforce.BufferN(23)),redeem:X.typeforce.maybe({network:X.typeforce.maybe(X.typeforce.Object),output:X.typeforce.maybe(X.typeforce.Buffer),input:X.typeforce.maybe(X.typeforce.Buffer),witness:X.typeforce.maybe(X.typeforce.arrayOf(X.typeforce.Buffer))}),input:X.typeforce.maybe(X.typeforce.Buffer),witness:X.typeforce.maybe(X.typeforce.arrayOf(X.typeforce.Buffer))},e);let r=e.network;r||(r=e.redeem&&e.redeem.network||yu.bitcoin);const n={network:r},i=Ne.value(()=>{const a=m.from(Li.decode(e.address)),p=a.readUInt8(0),w=a.slice(1);return{version:p,hash:w}}),c=Ne.value(()=>Re.decompile(e.input)),s=Ne.value(()=>{const a=c(),p=a[a.length-1];return{network:r,output:p===rr.OP_FALSE?m.from([]):p,input:Re.compile(a.slice(0,-1)),witness:e.witness||[]}});if(Ne.prop(n,"address",()=>{if(!n.hash)return;const a=m.allocUnsafe(21);return a.writeUInt8(n.network.scriptHash,0),n.hash.copy(a,1),Li.encode(a)}),Ne.prop(n,"hash",()=>{if(e.output)return e.output.slice(2,22);if(e.address)return i().hash;if(n.redeem&&n.redeem.output)return Fi.hash160(n.redeem.output)}),Ne.prop(n,"output",()=>{if(n.hash)return Re.compile([rr.OP_HASH160,n.hash,rr.OP_EQUAL])}),Ne.prop(n,"redeem",()=>{if(e.input)return s()}),Ne.prop(n,"input",()=>{if(!(!e.redeem||!e.redeem.input||!e.redeem.output))return Re.compile([].concat(Re.decompile(e.redeem.input),e.redeem.output))}),Ne.prop(n,"witness",()=>{if(n.redeem&&n.redeem.witness)return n.redeem.witness;if(n.input)return[]}),Ne.prop(n,"name",()=>{const a=["p2sh"];return n.redeem!==void 0&&n.redeem.name!==void 0&&a.push(n.redeem.name),a.join("-")}),t.validate){let a=m.from([]);if(e.address){if(i().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(i().hash.length!==20)throw new TypeError("Invalid address");a=i().hash}if(e.hash){if(a.length>0&&!a.equals(e.hash))throw new TypeError("Hash mismatch");a=e.hash}if(e.output){if(e.output.length!==23||e.output[0]!==rr.OP_HASH160||e.output[1]!==20||e.output[22]!==rr.OP_EQUAL)throw new TypeError("Output is invalid");const w=e.output.slice(2,22);if(a.length>0&&!a.equals(w))throw new TypeError("Hash mismatch");a=w}const p=w=>{if(w.output){const f=Re.decompile(w.output);if(!f||f.length<1)throw new TypeError("Redeem.output too short");if(w.output.byteLength>520)throw new TypeError("Redeem.output unspendable if larger than 520 bytes");if(Re.countNonPushOnlyOPs(f)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const d=Fi.hash160(w.output);if(a.length>0&&!a.equals(d))throw new TypeError("Hash mismatch");a=d}if(w.input){const f=w.input.length>0,d=w.witness&&w.witness.length>0;if(!f&&!d)throw new TypeError("Empty input");if(f&&d)throw new TypeError("Input and witness provided");if(f){const E=Re.decompile(w.input);if(!Re.isPushOnly(E))throw new TypeError("Non push-only scriptSig")}}};if(e.input){const w=c();if(!w||w.length<1)throw new TypeError("Input too short");if(!m.isBuffer(s().output))throw new TypeError("Input is invalid");p(s())}if(e.redeem){if(e.redeem.network&&e.redeem.network!==r)throw new TypeError("Network mismatch");if(e.input){const w=s();if(e.redeem.output&&!e.redeem.output.equals(w.output))throw new TypeError("Redeem.output mismatch");if(e.redeem.input&&!e.redeem.input.equals(w.input))throw new TypeError("Redeem.input mismatch")}p(e.redeem)}if(e.witness&&e.redeem&&e.redeem.witness&&!(0,X.stacksEqual)(e.redeem.witness,e.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,e)}en.p2sh=wu;var tn={},Qe={};Object.defineProperty(Qe,"__esModule",{value:!0});Qe.bech32m=Qe.bech32=void 0;const $r="qpzry9x8gf2tvdw0s3jn54khce6mua7l",Ho={};for(let e=0;e<$r.length;e++){const t=$r.charAt(e);Ho[t]=e}function Xt(e){const t=e>>25;return(e&33554431)<<5^-(t>>0&1)&996825010^-(t>>1&1)&642813549^-(t>>2&1)&513874426^-(t>>3&1)&1027748829^-(t>>4&1)&705979059}function Mi(e){let t=1;for(let r=0;r126)return"Invalid prefix ("+e+")";t=Xt(t)^n>>5}t=Xt(t);for(let r=0;r=r;)c-=r,a.push(i>>c&s);if(n)c>0&&a.push(i<=t)return"Excess padding";if(i<p)throw new TypeError("Exceeds length limit");s=s.toLowerCase();let w=Mi(s);if(typeof w=="string")throw new Error(w);let f=s+"1";for(let d=0;d>5)throw new Error("Non 5-bit word");w=Xt(w)^E,f+=$r.charAt(E)}for(let d=0;d<6;++d)w=Xt(w);w^=t;for(let d=0;d<6;++d){const E=w>>(5-d)*5&31;f+=$r.charAt(E)}return f}function n(s,a){if(a=a||90,s.length<8)return s+" too short";if(s.length>a)return"Exceeds length limit";const p=s.toLowerCase(),w=s.toUpperCase();if(s!==p&&s!==w)return"Mixed-case string "+s;s=p;const f=s.lastIndexOf("1");if(f===-1)return"No separator character for "+s;if(f===0)return"Missing prefix for "+s;const d=s.slice(0,f),E=s.slice(f+1);if(E.length<6)return"Data too short";let y=Mi(d);if(typeof y=="string")return y;const _=[];for(let T=0;T=E.length)&&_.push(x)}return y!==t?"Invalid checksum for "+s:{prefix:d,words:_}}function i(s,a){const p=n(s,a);if(typeof p=="object")return p}function c(s,a){const p=n(s,a);if(typeof p=="object")return p;throw new Error(p)}return{decodeUnsafe:i,decode:c,encode:r,toWords:gu,fromWordsUnsafe:mu,fromWords:Eu}}Qe.bech32=Ro("bech32");Qe.bech32m=Ro("bech32m");Object.defineProperty(tn,"__esModule",{value:!0});tn.p2wpkh=void 0;const An=Ke,Su=ae,Nr=_e(),ie=de,ot=ke,Ir=Qe,$i=Nr.OPS,bu=m.alloc(0);function _u(e,t){if(!e.address&&!e.hash&&!e.output&&!e.pubkey&&!e.witness)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,ie.typeforce)({address:ie.typeforce.maybe(ie.typeforce.String),hash:ie.typeforce.maybe(ie.typeforce.BufferN(20)),input:ie.typeforce.maybe(ie.typeforce.BufferN(0)),network:ie.typeforce.maybe(ie.typeforce.Object),output:ie.typeforce.maybe(ie.typeforce.BufferN(22)),pubkey:ie.typeforce.maybe(ie.isPoint),signature:ie.typeforce.maybe(Nr.isCanonicalScriptSignature),witness:ie.typeforce.maybe(ie.typeforce.arrayOf(ie.typeforce.Buffer))},e);const r=ot.value(()=>{const c=Ir.bech32.decode(e.address),s=c.words.shift(),a=Ir.bech32.fromWords(c.words);return{version:s,prefix:c.prefix,data:m.from(a)}}),n=e.network||Su.bitcoin,i={name:"p2wpkh",network:n};if(ot.prop(i,"address",()=>{if(!i.hash)return;const c=Ir.bech32.toWords(i.hash);return c.unshift(0),Ir.bech32.encode(n.bech32,c)}),ot.prop(i,"hash",()=>{if(e.output)return e.output.slice(2,22);if(e.address)return r().data;if(e.pubkey||i.pubkey)return An.hash160(e.pubkey||i.pubkey)}),ot.prop(i,"output",()=>{if(i.hash)return Nr.compile([$i.OP_0,i.hash])}),ot.prop(i,"pubkey",()=>{if(e.pubkey)return e.pubkey;if(e.witness)return e.witness[1]}),ot.prop(i,"signature",()=>{if(e.witness)return e.witness[0]}),ot.prop(i,"input",()=>{if(i.witness)return bu}),ot.prop(i,"witness",()=>{if(e.pubkey&&e.signature)return[e.signature,e.pubkey]}),t.validate){let c=m.from([]);if(e.address){if(n&&n.bech32!==r().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(r().version!==0)throw new TypeError("Invalid address version");if(r().data.length!==20)throw new TypeError("Invalid address data");c=r().data}if(e.hash){if(c.length>0&&!c.equals(e.hash))throw new TypeError("Hash mismatch");c=e.hash}if(e.output){if(e.output.length!==22||e.output[0]!==$i.OP_0||e.output[1]!==20)throw new TypeError("Output is invalid");if(c.length>0&&!c.equals(e.output.slice(2)))throw new TypeError("Hash mismatch");c=e.output.slice(2)}if(e.pubkey){const s=An.hash160(e.pubkey);if(c.length>0&&!c.equals(s))throw new TypeError("Hash mismatch");if(c=s,!(0,ie.isPoint)(e.pubkey)||e.pubkey.length!==33)throw new TypeError("Invalid pubkey for p2wpkh")}if(e.witness){if(e.witness.length!==2)throw new TypeError("Witness is invalid");if(!Nr.isCanonicalScriptSignature(e.witness[0]))throw new TypeError("Witness has invalid signature");if(!(0,ie.isPoint)(e.witness[1])||e.witness[1].length!==33)throw new TypeError("Witness has invalid pubkey");if(e.signature&&!e.signature.equals(e.witness[0]))throw new TypeError("Signature mismatch");if(e.pubkey&&!e.pubkey.equals(e.witness[1]))throw new TypeError("Pubkey mismatch");const s=An.hash160(e.witness[1]);if(c.length>0&&!c.equals(s))throw new TypeError("Hash mismatch")}}return Object.assign(i,e)}tn.p2wpkh=_u;var rn={};Object.defineProperty(rn,"__esModule",{value:!0});rn.p2wsh=void 0;const Ki=Ke,Tu=ae,Xe=_e(),G=de,Ve=ke,kr=Qe,Di=Xe.OPS,Pn=m.alloc(0);function Ar(e){return!!(m.isBuffer(e)&&e.length===65&&e[0]===4&&(0,G.isPoint)(e))}function Iu(e,t){if(!e.address&&!e.hash&&!e.output&&!e.redeem&&!e.witness)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,G.typeforce)({network:G.typeforce.maybe(G.typeforce.Object),address:G.typeforce.maybe(G.typeforce.String),hash:G.typeforce.maybe(G.typeforce.BufferN(32)),output:G.typeforce.maybe(G.typeforce.BufferN(34)),redeem:G.typeforce.maybe({input:G.typeforce.maybe(G.typeforce.Buffer),network:G.typeforce.maybe(G.typeforce.Object),output:G.typeforce.maybe(G.typeforce.Buffer),witness:G.typeforce.maybe(G.typeforce.arrayOf(G.typeforce.Buffer))}),input:G.typeforce.maybe(G.typeforce.BufferN(0)),witness:G.typeforce.maybe(G.typeforce.arrayOf(G.typeforce.Buffer))},e);const r=Ve.value(()=>{const s=kr.bech32.decode(e.address),a=s.words.shift(),p=kr.bech32.fromWords(s.words);return{version:a,prefix:s.prefix,data:m.from(p)}}),n=Ve.value(()=>Xe.decompile(e.redeem.input));let i=e.network;i||(i=e.redeem&&e.redeem.network||Tu.bitcoin);const c={network:i};if(Ve.prop(c,"address",()=>{if(!c.hash)return;const s=kr.bech32.toWords(c.hash);return s.unshift(0),kr.bech32.encode(i.bech32,s)}),Ve.prop(c,"hash",()=>{if(e.output)return e.output.slice(2);if(e.address)return r().data;if(c.redeem&&c.redeem.output)return Ki.sha256(c.redeem.output)}),Ve.prop(c,"output",()=>{if(c.hash)return Xe.compile([Di.OP_0,c.hash])}),Ve.prop(c,"redeem",()=>{if(e.witness)return{output:e.witness[e.witness.length-1],input:Pn,witness:e.witness.slice(0,-1)}}),Ve.prop(c,"input",()=>{if(c.witness)return Pn}),Ve.prop(c,"witness",()=>{if(e.redeem&&e.redeem.input&&e.redeem.input.length>0&&e.redeem.output&&e.redeem.output.length>0){const s=Xe.toStack(n());return c.redeem=Object.assign({witness:s},e.redeem),c.redeem.input=Pn,[].concat(s,e.redeem.output)}if(e.redeem&&e.redeem.output&&e.redeem.witness)return[].concat(e.redeem.witness,e.redeem.output)}),Ve.prop(c,"name",()=>{const s=["p2wsh"];return c.redeem!==void 0&&c.redeem.name!==void 0&&s.push(c.redeem.name),s.join("-")}),t.validate){let s=m.from([]);if(e.address){if(r().prefix!==i.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(r().version!==0)throw new TypeError("Invalid address version");if(r().data.length!==32)throw new TypeError("Invalid address data");s=r().data}if(e.hash){if(s.length>0&&!s.equals(e.hash))throw new TypeError("Hash mismatch");s=e.hash}if(e.output){if(e.output.length!==34||e.output[0]!==Di.OP_0||e.output[1]!==32)throw new TypeError("Output is invalid");const a=e.output.slice(2);if(s.length>0&&!s.equals(a))throw new TypeError("Hash mismatch");s=a}if(e.redeem){if(e.redeem.network&&e.redeem.network!==i)throw new TypeError("Network mismatch");if(e.redeem.input&&e.redeem.input.length>0&&e.redeem.witness&&e.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(e.redeem.output){const a=Xe.decompile(e.redeem.output);if(!a||a.length<1)throw new TypeError("Redeem.output is invalid");if(e.redeem.output.byteLength>3600)throw new TypeError("Redeem.output unspendable if larger than 3600 bytes");if(Xe.countNonPushOnlyOPs(a)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const p=Ki.sha256(e.redeem.output);if(s.length>0&&!s.equals(p))throw new TypeError("Hash mismatch");s=p}if(e.redeem.input&&!Xe.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(e.witness&&e.redeem.witness&&!(0,G.stacksEqual)(e.witness,e.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(e.redeem.input&&n().some(Ar)||e.redeem.output&&(Xe.decompile(e.redeem.output)||[]).some(Ar))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(e.witness&&e.witness.length>0){const a=e.witness[e.witness.length-1];if(e.redeem&&e.redeem.output&&!e.redeem.output.equals(a))throw new TypeError("Witness and redeem.output mismatch");if(e.witness.some(Ar)||(Xe.decompile(a)||[]).some(Ar))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(c,e)}rn.p2wsh=Iu;var nr={},ht={};Object.defineProperty(ht,"__esModule",{value:!0});ht.getEccLib=ht.initEccLib=void 0;const hr={};function ku(e){e?e!==hr.eccLib&&(Pu(e),hr.eccLib=e):hr.eccLib=e}ht.initEccLib=ku;function Au(){if(!hr.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return hr.eccLib}ht.getEccLib=Au;const Ge=e=>m.from(e,"hex");function Pu(e){Ae(typeof e.isXOnlyPoint=="function"),Ae(e.isXOnlyPoint(Ge("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),Ae(e.isXOnlyPoint(Ge("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),Ae(e.isXOnlyPoint(Ge("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),Ae(e.isXOnlyPoint(Ge("0000000000000000000000000000000000000000000000000000000000000001"))),Ae(!e.isXOnlyPoint(Ge("0000000000000000000000000000000000000000000000000000000000000000"))),Ae(!e.isXOnlyPoint(Ge("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),Ae(typeof e.xOnlyPointAddTweak=="function"),Ou.forEach(t=>{const r=e.xOnlyPointAddTweak(Ge(t.pubkey),Ge(t.tweak));t.result===null?Ae(r===null):(Ae(r!==null),Ae(r.parity===t.parity),Ae(m.from(r.xOnlyPubkey).equals(Ge(t.result))))})}function Ae(e){if(!e)throw new Error("ecc library invalid")}const Ou=[{pubkey:"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",tweak:"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140",parity:-1,result:null},{pubkey:"1617d38ed8d8657da4d4761e8057bc396ea9e4b9d29776d4be096016dbd2509b",tweak:"a8397a935f0dfceba6ba9618f6451ef4d80637abf4e6af2669fbc9de6a8fd2ac",parity:1,result:"e478f99dab91052ab39a33ea35fd5e6e4933f4d28023cd597c9a1f6760346adf"},{pubkey:"2c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991",tweak:"823c3cd2142744b075a87eade7e1b8678ba308d566226a0056ca2b7a76f86b47",parity:0,result:"9534f8dc8c6deda2dc007655981c78b49c5d96c778fbf363462a11ec9dfd948c"}];var nn={},oe={},Mn={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh */(function(e,t){var r=qr,n=r.Buffer;function i(s,a){for(var p in s)a[p]=s[p]}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=c);function c(s,a,p){return n(s,a,p)}c.prototype=Object.create(n.prototype),i(n,c),c.from=function(s,a,p){if(typeof s=="number")throw new TypeError("Argument must not be a number");return n(s,a,p)},c.alloc=function(s,a,p){if(typeof s!="number")throw new TypeError("Argument must be a number");var w=n(s);return a!==void 0?typeof p=="string"?w.fill(a,p):w.fill(a):w.fill(0),w},c.allocUnsafe=function(s){if(typeof s!="number")throw new TypeError("Argument must be a number");return n(s)},c.allocUnsafeSlow=function(s){if(typeof s!="number")throw new TypeError("Argument must be a number");return r.SlowBuffer(s)}})(Mn,Mn.exports);var vu=Mn.exports,$n=vu.Buffer,Bu=9007199254740991;function ti(e){if(e<0||e>Bu||e%1!==0)throw new RangeError("value out of range")}function cr(e,t,r){if(ti(e),t||(t=$n.allocUnsafe(Fo(e))),!$n.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");return r||(r=0),e<253?(t.writeUInt8(e,r),cr.bytes=1):e<=65535?(t.writeUInt8(253,r),t.writeUInt16LE(e,r+1),cr.bytes=3):e<=4294967295?(t.writeUInt8(254,r),t.writeUInt32LE(e,r+1),cr.bytes=5):(t.writeUInt8(255,r),t.writeUInt32LE(e>>>0,r+1),t.writeUInt32LE(e/4294967296|0,r+5),cr.bytes=9),t}function ur(e,t){if(!$n.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");t||(t=0);var r=e.readUInt8(t);if(r<253)return ur.bytes=1,r;if(r===253)return ur.bytes=3,e.readUInt16LE(t+1);if(r===254)return ur.bytes=5,e.readUInt32LE(t+1);ur.bytes=9;var n=e.readUInt32LE(t+1),i=e.readUInt32LE(t+5),c=i*4294967296+n;return ti(c),c}function Fo(e){return ti(e),e<253?1:e<=65535?3:e<=4294967295?5:9}var xu={encode:cr,decode:ur,encodingLength:Fo};Object.defineProperty(oe,"__esModule",{value:!0});oe.BufferReader=oe.BufferWriter=oe.cloneBuffer=oe.reverseBuffer=oe.writeUInt64LE=oe.readUInt64LE=oe.varuint=void 0;const mt=de,{typeforce:Lo}=mt,yr=xu;oe.varuint=yr;function Mo(e,t){if(typeof e!="number")throw new Error("cannot write a non-number as a number");if(e<0)throw new Error("specified a negative value for writing an unsigned value");if(e>t)throw new Error("RangeError: value out of range");if(Math.floor(e)!==e)throw new Error("value has a fractional component")}function $o(e,t){const r=e.readUInt32LE(t);let n=e.readUInt32LE(t+4);return n*=4294967296,Mo(n+r,9007199254740991),n+r}oe.readUInt64LE=$o;function Ko(e,t,r){return Mo(t,9007199254740991),e.writeInt32LE(t&-1,r),e.writeUInt32LE(Math.floor(t/4294967296),r+4),r+8}oe.writeUInt64LE=Ko;function Uu(e){if(e.length<1)return e;let t=e.length-1,r=0;for(let n=0;nthis.writeVarSlice(r))}end(){if(this.buffer.length===this.offset)return this.buffer;throw new Error(`buffer size ${this.buffer.length}, offset ${this.offset}`)}}oe.BufferWriter=ri;class Nu{constructor(t,r=0){this.buffer=t,this.offset=r,Lo(mt.tuple(mt.Buffer,mt.UInt32),[t,r])}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=$o(this.buffer,this.offset);return this.offset+=8,t}readVarInt(){const t=yr.decode(this.buffer,this.offset);return this.offset+=yr.decode.bytes,t}readSlice(t){if(this.buffer.length"left"in T&&"right"in T;function a(T,A){if(T.length<33)throw new TypeError(`The control-block length is too small. Got ${T.length}, expected min 33.`);const x=(T.length-33)/32;let U=A;for(let I=0;II.hash.compare(S.hash));const[x,U]=A;return{hash:y(x.hash,U.hash),left:x,right:U}}e.toHashTree=p;function w(T,A){if(s(T)){const x=w(T.left,A);if(x!==void 0)return[...x,T.right.hash];const U=w(T.right,A);if(U!==void 0)return[...U,T.left.hash]}else if(T.hash.equals(A))return[]}e.findScriptPath=w;function f(T){const A=T.version||e.LEAF_VERSION_TAPSCRIPT;return n.taggedHash("TapLeaf",t.Buffer.concat([t.Buffer.from([A]),_(T.output)]))}e.tapleafHash=f;function d(T,A){return n.taggedHash("TapTweak",t.Buffer.concat(A?[T,A]:[T]))}e.tapTweakHash=d;function E(T,A){if(!t.Buffer.isBuffer(T)||T.length!==32||A&&A.length!==32)return null;const x=d(T,A),U=(0,r.getEccLib)().xOnlyPointAddTweak(T,x);return!U||U.xOnlyPubkey===null?null:{parity:U.parity,x:t.Buffer.from(U.xOnlyPubkey)}}e.tweakKey=E;function y(T,A){return n.taggedHash("TapBranch",t.Buffer.concat([T,A]))}function _(T){const A=i.varuint.encodingLength(T.length),x=t.Buffer.allocUnsafe(A);return i.varuint.encode(T.length,x),t.Buffer.concat([x,T])}})(nn);var Wi;function Hu(){if(Wi)return nr;Wi=1,Object.defineProperty(nr,"__esModule",{value:!0}),nr.p2tr=void 0;const e=qr,t=ae,r=_e(),n=de,i=ht,c=nn,s=ke,a=Qe,p=ni(),w=r.OPS,f=1,d=80;function E(y,_){if(!y.address&&!y.output&&!y.pubkey&&!y.internalPubkey&&!(y.witness&&y.witness.length>1))throw new TypeError("Not enough data");_=Object.assign({validate:!0},_||{}),(0,n.typeforce)({address:n.typeforce.maybe(n.typeforce.String),input:n.typeforce.maybe(n.typeforce.BufferN(0)),network:n.typeforce.maybe(n.typeforce.Object),output:n.typeforce.maybe(n.typeforce.BufferN(34)),internalPubkey:n.typeforce.maybe(n.typeforce.BufferN(32)),hash:n.typeforce.maybe(n.typeforce.BufferN(32)),pubkey:n.typeforce.maybe(n.typeforce.BufferN(32)),signature:n.typeforce.maybe(n.typeforce.anyOf(n.typeforce.BufferN(64),n.typeforce.BufferN(65))),witness:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer)),scriptTree:n.typeforce.maybe(n.isTaptree),redeem:n.typeforce.maybe({output:n.typeforce.maybe(n.typeforce.Buffer),redeemVersion:n.typeforce.maybe(n.typeforce.Number),witness:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer))}),redeemVersion:n.typeforce.maybe(n.typeforce.Number)},y);const T=s.value(()=>(0,p.fromBech32)(y.address)),A=s.value(()=>{if(!(!y.witness||!y.witness.length))return y.witness.length>=2&&y.witness[y.witness.length-1][0]===d?y.witness.slice(0,-1):y.witness.slice()}),x=s.value(()=>{if(y.scriptTree)return(0,c.toHashTree)(y.scriptTree);if(y.hash)return{hash:y.hash}}),U=y.network||t.bitcoin,I={name:"p2tr",network:U};if(s.prop(I,"address",()=>{if(!I.pubkey)return;const S=a.bech32m.toWords(I.pubkey);return S.unshift(f),a.bech32m.encode(U.bech32,S)}),s.prop(I,"hash",()=>{const S=x();if(S)return S.hash;const v=A();if(v&&v.length>1){const k=v[v.length-1],N=k[0]&n.TAPLEAF_VERSION_MASK,$=v[v.length-2],B=(0,c.tapleafHash)({output:$,version:N});return(0,c.rootHashFromPath)(k,B)}return null}),s.prop(I,"output",()=>{if(I.pubkey)return r.compile([w.OP_1,I.pubkey])}),s.prop(I,"redeemVersion",()=>y.redeemVersion?y.redeemVersion:y.redeem&&y.redeem.redeemVersion!==void 0&&y.redeem.redeemVersion!==null?y.redeem.redeemVersion:c.LEAF_VERSION_TAPSCRIPT),s.prop(I,"redeem",()=>{const S=A();if(!(!S||S.length<2))return{output:S[S.length-2],witness:S.slice(0,-2),redeemVersion:S[S.length-1][0]&n.TAPLEAF_VERSION_MASK}}),s.prop(I,"pubkey",()=>{if(y.pubkey)return y.pubkey;if(y.output)return y.output.slice(2);if(y.address)return T().data;if(I.internalPubkey){const S=(0,c.tweakKey)(I.internalPubkey,I.hash);if(S)return S.x}}),s.prop(I,"internalPubkey",()=>{if(y.internalPubkey)return y.internalPubkey;const S=A();if(S&&S.length>1)return S[S.length-1].slice(1,33)}),s.prop(I,"signature",()=>{if(y.signature)return y.signature;const S=A();if(!(!S||S.length!==1))return S[0]}),s.prop(I,"witness",()=>{if(y.witness)return y.witness;const S=x();if(S&&y.redeem&&y.redeem.output&&y.internalPubkey){const v=(0,c.tapleafHash)({output:y.redeem.output,version:I.redeemVersion}),k=(0,c.findScriptPath)(S,v);if(!k)return;const N=(0,c.tweakKey)(y.internalPubkey,S.hash);if(!N)return;const $=e.Buffer.concat([e.Buffer.from([I.redeemVersion|N.parity]),y.internalPubkey].concat(k));return[y.redeem.output,$]}if(y.signature)return[y.signature]}),_.validate){let S=e.Buffer.from([]);if(y.address){if(U&&U.bech32!==T().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(T().version!==f)throw new TypeError("Invalid address version");if(T().data.length!==32)throw new TypeError("Invalid address data");S=T().data}if(y.pubkey){if(S.length>0&&!S.equals(y.pubkey))throw new TypeError("Pubkey mismatch");S=y.pubkey}if(y.output){if(y.output.length!==34||y.output[0]!==w.OP_1||y.output[1]!==32)throw new TypeError("Output is invalid");if(S.length>0&&!S.equals(y.output.slice(2)))throw new TypeError("Pubkey mismatch");S=y.output.slice(2)}if(y.internalPubkey){const N=(0,c.tweakKey)(y.internalPubkey,I.hash);if(S.length>0&&!S.equals(N.x))throw new TypeError("Pubkey mismatch");S=N.x}if(S&&S.length&&!(0,i.getEccLib)().isXOnlyPoint(S))throw new TypeError("Invalid pubkey for p2tr");const v=x();if(y.hash&&v&&!y.hash.equals(v.hash))throw new TypeError("Hash mismatch");if(y.redeem&&y.redeem.output&&v){const N=(0,c.tapleafHash)({output:y.redeem.output,version:I.redeemVersion});if(!(0,c.findScriptPath)(v,N))throw new TypeError("Redeem script not in tree")}const k=A();if(y.redeem&&I.redeem){if(y.redeem.redeemVersion&&y.redeem.redeemVersion!==I.redeem.redeemVersion)throw new TypeError("Redeem.redeemVersion and witness mismatch");if(y.redeem.output){if(r.decompile(y.redeem.output).length===0)throw new TypeError("Redeem.output is invalid");if(I.redeem.output&&!y.redeem.output.equals(I.redeem.output))throw new TypeError("Redeem.output and witness mismatch")}if(y.redeem.witness&&I.redeem.witness&&!(0,n.stacksEqual)(y.redeem.witness,I.redeem.witness))throw new TypeError("Redeem.witness and witness mismatch")}if(k&&k.length)if(k.length===1){if(y.signature&&!y.signature.equals(k[0]))throw new TypeError("Signature mismatch")}else{const N=k[k.length-1];if(N.length<33)throw new TypeError(`The control-block length is too small. Got ${N.length}, expected min 33.`);if((N.length-33)%32!==0)throw new TypeError(`The control-block length of ${N.length} is incorrect!`);const $=(N.length-33)/32;if($>128)throw new TypeError(`The script path is too long. Got ${$}, expected max 128.`);const B=N.slice(1,33);if(y.internalPubkey&&!y.internalPubkey.equals(B))throw new TypeError("Internal pubkey mismatch");if(!(0,i.getEccLib)().isXOnlyPoint(B))throw new TypeError("Invalid internalPubkey for p2tr witness");const R=N[0]&n.TAPLEAF_VERSION_MASK,j=k[k.length-2],O=(0,c.tapleafHash)({output:j,version:R}),C=(0,c.rootHashFromPath)(N,O),F=(0,c.tweakKey)(B,C);if(!F)throw new TypeError("Invalid outputKey for p2tr witness");if(S.length&&!S.equals(F.x))throw new TypeError("Pubkey mismatch for p2tr witness");if(F.parity!==(N[0]&1))throw new Error("Incorrect parity")}}return Object.assign(I,y)}return nr.p2tr=E,nr}var ji;function mr(){return ji||(ji=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.p2tr=e.p2wsh=e.p2wpkh=e.p2sh=e.p2pkh=e.p2pk=e.p2ms=e.embed=void 0;const t=Xr;Object.defineProperty(e,"embed",{enumerable:!0,get:function(){return t.p2data}});const r=zr;Object.defineProperty(e,"p2ms",{enumerable:!0,get:function(){return r.p2ms}});const n=Yr;Object.defineProperty(e,"p2pk",{enumerable:!0,get:function(){return n.p2pk}});const i=Jr;Object.defineProperty(e,"p2pkh",{enumerable:!0,get:function(){return i.p2pkh}});const c=en;Object.defineProperty(e,"p2sh",{enumerable:!0,get:function(){return c.p2sh}});const s=tn;Object.defineProperty(e,"p2wpkh",{enumerable:!0,get:function(){return s.p2wpkh}});const a=rn;Object.defineProperty(e,"p2wsh",{enumerable:!0,get:function(){return a.p2wsh}});const p=Hu();Object.defineProperty(e,"p2tr",{enumerable:!0,get:function(){return p.p2tr}})}(mn)),mn}var Vi;function ni(){if(Vi)return ge;Vi=1,Object.defineProperty(ge,"__esModule",{value:!0}),ge.toOutputScript=ge.fromOutputScript=ge.toBech32=ge.toBase58Check=ge.fromBech32=ge.fromBase58Check=void 0;const e=ae,t=mr(),r=_e(),n=de,i=Qe,c=Zn,s=40,a=2,p=16,w=2,f=80,d="WARNING: Sending to a future segwit version address can lead to loss of funds. End users MUST be warned carefully in the GUI and asked if they wish to proceed with caution. Wallets should verify the segwit version from the output of fromBech32, then decide when it is safe to use which version of segwit.";function E(I,S){const v=I.slice(2);if(v.lengths)throw new TypeError("Invalid program length for segwit address");const k=I[0]-f;if(kp)throw new TypeError("Invalid version for segwit address");if(I[1]!==v.length)throw new TypeError("Invalid script for segwit address");return console.warn(d),A(v,k,S.bech32)}function y(I){const S=m.from(c.decode(I));if(S.length<21)throw new TypeError(I+" is too short");if(S.length>21)throw new TypeError(I+" is too long");const v=S.readUInt8(0),k=S.slice(1);return{version:v,hash:k}}ge.fromBase58Check=y;function _(I){let S,v;try{S=i.bech32.decode(I)}catch{}if(S){if(v=S.words[0],v!==0)throw new TypeError(I+" uses wrong encoding")}else if(S=i.bech32m.decode(I),v=S.words[0],v===0)throw new TypeError(I+" uses wrong encoding");const k=i.bech32.fromWords(S.words.slice(1));return{version:v,prefix:S.prefix,data:m.from(k)}}ge.fromBech32=_;function T(I,S){(0,n.typeforce)((0,n.tuple)(n.Hash160bit,n.UInt8),arguments);const v=m.allocUnsafe(21);return v.writeUInt8(S,0),I.copy(v,1),c.encode(v)}ge.toBase58Check=T;function A(I,S,v){const k=i.bech32.toWords(I);return k.unshift(S),S===0?i.bech32.encode(v,k):i.bech32m.encode(v,k)}ge.toBech32=A;function x(I,S){S=S||e.bitcoin;try{return t.p2pkh({output:I,network:S}).address}catch{}try{return t.p2sh({output:I,network:S}).address}catch{}try{return t.p2wpkh({output:I,network:S}).address}catch{}try{return t.p2wsh({output:I,network:S}).address}catch{}try{return t.p2tr({output:I,network:S}).address}catch{}try{return E(I,S)}catch{}throw new Error(r.toASM(I)+" has no matching Address")}ge.fromOutputScript=x;function U(I,S){S=S||e.bitcoin;let v,k;try{v=y(I)}catch{}if(v){if(v.version===S.pubKeyHash)return t.p2pkh({hash:v.hash}).output;if(v.version===S.scriptHash)return t.p2sh({hash:v.hash}).output}else{try{k=_(I)}catch{}if(k){if(k.prefix!==S.bech32)throw new Error(I+" has an invalid prefix");if(k.version===0){if(k.data.length===20)return t.p2wpkh({hash:k.data}).output;if(k.data.length===32)return t.p2wsh({hash:k.data}).output}else if(k.version===1){if(k.data.length===32)return t.p2tr({pubkey:k.data}).output}else if(k.version>=w&&k.version<=p&&k.data.length>=a&&k.data.length<=s)return console.warn(d),r.compile([k.version+f,k.data])}}throw new Error(I+" has no matching Script")}return ge.toOutputScript=U,ge}var on={},sn={};Object.defineProperty(sn,"__esModule",{value:!0});sn.fastMerkleRoot=void 0;function Ru(e,t){if(!Array.isArray(e))throw TypeError("Expected values Array");if(typeof t!="function")throw TypeError("Expected digest Function");let r=e.length;const n=e.concat();for(;r>1;){let i=0;for(let c=0;cr+Fe(n),0)}const st=m.allocUnsafe(0),Xi=[],On=m.from("0000000000000000000000000000000000000000000000000000000000000000","hex"),qi=m.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),Mu=m.from("ffffffffffffffff","hex"),$u={script:st,valueBuffer:Mu};function Ku(e){return e.value!==void 0}class L{constructor(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}static fromBuffer(t,r){const n=new te.BufferReader(t),i=new L;i.version=n.readInt32();const c=n.readUInt8(),s=n.readUInt8();let a=!1;c===L.ADVANCED_TRANSACTION_MARKER&&s===L.ADVANCED_TRANSACTION_FLAG?a=!0:n.offset-=2;const p=n.readVarInt();for(let f=0;ft.witness.length!==0)}weight(){const t=this.byteLength(!1),r=this.byteLength(!0);return t*3+r}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(t=!0){const r=t&&this.hasWitnesses();return(r?10:8)+te.varuint.encodingLength(this.ins.length)+te.varuint.encodingLength(this.outs.length)+this.ins.reduce((n,i)=>n+40+Fe(i.script),0)+this.outs.reduce((n,i)=>n+8+Fe(i.script),0)+(r?this.ins.reduce((n,i)=>n+Lu(i.witness),0):0)}clone(){const t=new L;return t.version=this.version,t.locktime=this.locktime,t.ins=this.ins.map(r=>({hash:r.hash,index:r.index,script:r.script,sequence:r.sequence,witness:r.witness})),t.outs=this.outs.map(r=>({script:r.script,value:r.value})),t}hashForSignature(t,r,n){if(He(K.tuple(K.UInt32,K.Buffer,K.Number),arguments),t>=this.ins.length)return qi;const i=Gi.compile(Gi.decompile(r).filter(a=>a!==Fu.OPS.OP_CODESEPARATOR)),c=this.clone();if((n&31)===L.SIGHASH_NONE)c.outs=[],c.ins.forEach((a,p)=>{p!==t&&(a.sequence=0)});else if((n&31)===L.SIGHASH_SINGLE){if(t>=this.outs.length)return qi;c.outs.length=t+1;for(let a=0;a{p!==t&&(a.sequence=0)})}n&L.SIGHASH_ANYONECANPAY?(c.ins=[c.ins[t]],c.ins[0].script=i):(c.ins.forEach(a=>{a.script=st}),c.ins[t].script=i);const s=m.allocUnsafe(c.byteLength(!1)+4);return s.writeInt32LE(n,s.length-4),c.__toBuffer(s,0,!1),Ee.hash256(s)}hashForWitnessV1(t,r,n,i,c,s){if(He(K.tuple(K.UInt32,He.arrayOf(K.Buffer),He.arrayOf(K.Satoshi),K.UInt32),arguments),n.length!==this.ins.length||r.length!==this.ins.length)throw new Error("Must supply prevout script and value for all inputs");const a=i===L.SIGHASH_DEFAULT?L.SIGHASH_ALL:i&L.SIGHASH_OUTPUT_MASK,w=(i&L.SIGHASH_INPUT_MASK)===L.SIGHASH_ANYONECANPAY,f=a===L.SIGHASH_NONE,d=a===L.SIGHASH_SINGLE;let E=st,y=st,_=st,T=st,A=st;if(!w){let S=te.BufferWriter.withCapacity(36*this.ins.length);this.ins.forEach(v=>{S.writeSlice(v.hash),S.writeUInt32(v.index)}),E=Ee.sha256(S.end()),S=te.BufferWriter.withCapacity(8*this.ins.length),n.forEach(v=>S.writeUInt64(v)),y=Ee.sha256(S.end()),S=te.BufferWriter.withCapacity(r.map(Fe).reduce((v,k)=>v+k)),r.forEach(v=>S.writeVarSlice(v)),_=Ee.sha256(S.end()),S=te.BufferWriter.withCapacity(4*this.ins.length),this.ins.forEach(v=>S.writeUInt32(v.sequence)),T=Ee.sha256(S.end())}if(f||d){if(d&&t8+Fe(k.script)).reduce((k,N)=>k+N),v=te.BufferWriter.withCapacity(S);this.outs.forEach(k=>{v.writeUInt64(k.value),v.writeVarSlice(k.script)}),A=Ee.sha256(v.end())}const x=(c?2:0)+(s?1:0),U=174-(w?49:0)-(f?32:0)+(s?32:0)+(c?37:0),I=te.BufferWriter.withCapacity(U);if(I.writeUInt8(i),I.writeInt32(this.version),I.writeUInt32(this.locktime),I.writeSlice(E),I.writeSlice(y),I.writeSlice(_),I.writeSlice(T),f||d||I.writeSlice(A),I.writeUInt8(x),w){const S=this.ins[t];I.writeSlice(S.hash),I.writeUInt32(S.index),I.writeUInt64(n[t]),I.writeVarSlice(r[t]),I.writeUInt32(S.sequence)}else I.writeUInt32(t);if(s){const S=te.BufferWriter.withCapacity(Fe(s));S.writeVarSlice(s),I.writeSlice(Ee.sha256(S.end()))}return d&&I.writeSlice(A),c&&(I.writeSlice(c),I.writeUInt8(0),I.writeUInt32(4294967295)),Ee.taggedHash("TapSighash",m.concat([m.from([0]),I.end()]))}hashForWitnessV0(t,r,n,i){He(K.tuple(K.UInt32,K.Buffer,K.Satoshi,K.UInt32),arguments);let c=m.from([]),s,a=On,p=On,w=On;if(i&L.SIGHASH_ANYONECANPAY||(c=m.allocUnsafe(36*this.ins.length),s=new te.BufferWriter(c,0),this.ins.forEach(d=>{s.writeSlice(d.hash),s.writeUInt32(d.index)}),p=Ee.hash256(c)),!(i&L.SIGHASH_ANYONECANPAY)&&(i&31)!==L.SIGHASH_SINGLE&&(i&31)!==L.SIGHASH_NONE&&(c=m.allocUnsafe(4*this.ins.length),s=new te.BufferWriter(c,0),this.ins.forEach(d=>{s.writeUInt32(d.sequence)}),w=Ee.hash256(c)),(i&31)!==L.SIGHASH_SINGLE&&(i&31)!==L.SIGHASH_NONE){const d=this.outs.reduce((E,y)=>E+8+Fe(y.script),0);c=m.allocUnsafe(d),s=new te.BufferWriter(c,0),this.outs.forEach(E=>{s.writeUInt64(E.value),s.writeVarSlice(E.script)}),a=Ee.hash256(c)}else if((i&31)===L.SIGHASH_SINGLE&&t{i.writeSlice(s.hash),i.writeUInt32(s.index),i.writeVarSlice(s.script),i.writeUInt32(s.sequence)}),i.writeVarInt(this.outs.length),this.outs.forEach(s=>{Ku(s)?i.writeUInt64(s.value):i.writeSlice(s.valueBuffer),i.writeVarSlice(s.script)}),c&&this.ins.forEach(s=>{i.writeVector(s.witness)}),i.writeUInt32(this.locktime),r!==void 0?t.slice(r,i.offset):t}}lt.Transaction=L;L.DEFAULT_SEQUENCE=4294967295;L.SIGHASH_DEFAULT=0;L.SIGHASH_ALL=1;L.SIGHASH_NONE=2;L.SIGHASH_SINGLE=3;L.SIGHASH_ANYONECANPAY=128;L.SIGHASH_OUTPUT_MASK=3;L.SIGHASH_INPUT_MASK=128;L.ADVANCED_TRANSACTION_MARKER=0;L.ADVANCED_TRANSACTION_FLAG=1;Object.defineProperty(on,"__esModule",{value:!0});on.Block=void 0;const yt=oe,vn=Ke,Du=sn,Wu=lt,Do=de,{typeforce:ju}=Do,Bn=new TypeError("Cannot compute merkle root for zero transactions"),zi=new TypeError("Cannot compute witness commit for non-segwit block");class wt{constructor(){this.version=1,this.prevHash=void 0,this.merkleRoot=void 0,this.timestamp=0,this.witnessCommit=void 0,this.bits=0,this.nonce=0,this.transactions=void 0}static fromBuffer(t){if(t.length<80)throw new Error("Buffer too small (< 80 bytes)");const r=new yt.BufferReader(t),n=new wt;if(n.version=r.readInt32(),n.prevHash=r.readSlice(32),n.merkleRoot=r.readSlice(32),n.timestamp=r.readUInt32(),n.bits=r.readUInt32(),n.nonce=r.readUInt32(),t.length===80)return n;const i=()=>{const a=Wu.Transaction.fromBuffer(r.buffer.slice(r.offset),!0);return r.offset+=a.byteLength(),a},c=r.readVarInt();n.transactions=[];for(let a=0;a>24)-3,n=t&8388607,i=m.alloc(32,0);return i.writeUIntBE(n,29-r,3),i}static calculateMerkleRoot(t,r){if(ju([{getHash:Do.Function}],t),t.length===0)throw Bn;if(r&&!Yi(t))throw zi;const n=t.map(c=>c.getHash(r)),i=(0,Du.fastMerkleRoot)(n,vn.hash256);return r?vn.hash256(m.concat([i,t[0].ins[0].witness[0]])):i}getWitnessCommit(){if(!Yi(this.transactions))return null;const t=this.transactions[0].outs.filter(n=>n.script.slice(0,6).equals(m.from("6a24aa21a9ed","hex"))).map(n=>n.script.slice(6,38));if(t.length===0)return null;const r=t[t.length-1];return r instanceof m&&r.length===32?r:null}hasWitnessCommit(){return this.witnessCommit instanceof m&&this.witnessCommit.length===32||this.getWitnessCommit()!==null}hasWitness(){return Vu(this.transactions)}weight(){const t=this.byteLength(!1,!1),r=this.byteLength(!1,!0);return t*3+r}byteLength(t,r=!0){return t||!this.transactions?80:80+yt.varuint.encodingLength(this.transactions.length)+this.transactions.reduce((n,i)=>n+i.byteLength(r),0)}getHash(){return vn.hash256(this.toBuffer(!0))}getId(){return(0,yt.reverseBuffer)(this.getHash()).toString("hex")}getUTCDate(){const t=new Date(0);return t.setUTCSeconds(this.timestamp),t}toBuffer(t){const r=m.allocUnsafe(this.byteLength(t)),n=new yt.BufferWriter(r);return n.writeInt32(this.version),n.writeSlice(this.prevHash),n.writeSlice(this.merkleRoot),n.writeUInt32(this.timestamp),n.writeUInt32(this.bits),n.writeUInt32(this.nonce),t||!this.transactions||(yt.varuint.encode(this.transactions.length,r,n.offset),n.offset+=yt.varuint.encode.bytes,this.transactions.forEach(i=>{const c=i.byteLength();i.toBuffer(r,n.offset),n.offset+=c})),r}toHex(t){return this.toBuffer(t).toString("hex")}checkTxRoots(){const t=this.hasWitnessCommit();return!t&&this.hasWitness()?!1:this.__checkMerkleRoot()&&(t?this.__checkWitnessCommit():!0)}checkProofOfWork(){const t=(0,yt.reverseBuffer)(this.getHash()),r=wt.calculateTarget(this.bits);return t.compare(r)<=0}__checkMerkleRoot(){if(!this.transactions)throw Bn;const t=wt.calculateMerkleRoot(this.transactions);return this.merkleRoot.compare(t)===0}__checkWitnessCommit(){if(!this.transactions)throw Bn;if(!this.hasWitnessCommit())throw zi;const t=wt.calculateMerkleRoot(this.transactions,!0);return this.witnessCommit.compare(t)===0}}on.Block=wt;function Yi(e){return e instanceof Array&&e[0]&&e[0].ins&&e[0].ins instanceof Array&&e[0].ins[0]&&e[0].ins[0].witness&&e[0].ins[0].witness instanceof Array&&e[0].ins[0].witness.length>0}function Vu(e){return e instanceof Array&&e.some(t=>typeof t=="object"&&t.ins instanceof Array&&t.ins.some(r=>typeof r=="object"&&r.witness instanceof Array&&r.witness.length>0))}var cn={},ii={},oi={},si={},Er={},St={},fe={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),function(t){t[t.UNSIGNED_TX=0]="UNSIGNED_TX",t[t.GLOBAL_XPUB=1]="GLOBAL_XPUB"}(e.GlobalTypes||(e.GlobalTypes={})),e.GLOBAL_TYPE_NAMES=["unsignedTx","globalXpub"],function(t){t[t.NON_WITNESS_UTXO=0]="NON_WITNESS_UTXO",t[t.WITNESS_UTXO=1]="WITNESS_UTXO",t[t.PARTIAL_SIG=2]="PARTIAL_SIG",t[t.SIGHASH_TYPE=3]="SIGHASH_TYPE",t[t.REDEEM_SCRIPT=4]="REDEEM_SCRIPT",t[t.WITNESS_SCRIPT=5]="WITNESS_SCRIPT",t[t.BIP32_DERIVATION=6]="BIP32_DERIVATION",t[t.FINAL_SCRIPTSIG=7]="FINAL_SCRIPTSIG",t[t.FINAL_SCRIPTWITNESS=8]="FINAL_SCRIPTWITNESS",t[t.POR_COMMITMENT=9]="POR_COMMITMENT",t[t.TAP_KEY_SIG=19]="TAP_KEY_SIG",t[t.TAP_SCRIPT_SIG=20]="TAP_SCRIPT_SIG",t[t.TAP_LEAF_SCRIPT=21]="TAP_LEAF_SCRIPT",t[t.TAP_BIP32_DERIVATION=22]="TAP_BIP32_DERIVATION",t[t.TAP_INTERNAL_KEY=23]="TAP_INTERNAL_KEY",t[t.TAP_MERKLE_ROOT=24]="TAP_MERKLE_ROOT"}(e.InputTypes||(e.InputTypes={})),e.INPUT_TYPE_NAMES=["nonWitnessUtxo","witnessUtxo","partialSig","sighashType","redeemScript","witnessScript","bip32Derivation","finalScriptSig","finalScriptWitness","porCommitment","tapKeySig","tapScriptSig","tapLeafScript","tapBip32Derivation","tapInternalKey","tapMerkleRoot"],function(t){t[t.REDEEM_SCRIPT=0]="REDEEM_SCRIPT",t[t.WITNESS_SCRIPT=1]="WITNESS_SCRIPT",t[t.BIP32_DERIVATION=2]="BIP32_DERIVATION",t[t.TAP_INTERNAL_KEY=5]="TAP_INTERNAL_KEY",t[t.TAP_TREE=6]="TAP_TREE",t[t.TAP_BIP32_DERIVATION=7]="TAP_BIP32_DERIVATION"}(e.OutputTypes||(e.OutputTypes={})),e.OUTPUT_TYPE_NAMES=["redeemScript","witnessScript","bip32Derivation","tapInternalKey","tapTree","tapBip32Derivation"]})(fe);var bt={};Object.defineProperty(bt,"__esModule",{value:!0});const Wo=fe,Gu=e=>[...Array(e).keys()];function Xu(e){if(e.key[0]!==Wo.GlobalTypes.GLOBAL_XPUB)throw new Error("Decode Error: could not decode globalXpub with key 0x"+e.key.toString("hex"));if(e.key.length!==79||![2,3].includes(e.key[46]))throw new Error("Decode Error: globalXpub has invalid extended pubkey in key 0x"+e.key.toString("hex"));if(e.value.length/4%1!==0)throw new Error("Decode Error: Global GLOBAL_XPUB value length should be multiple of 4");const t=e.key.slice(1),r={masterFingerprint:e.value.slice(0,4),extendedPubkey:t,path:"m"};for(const n of Gu(e.value.length/4-1)){const i=e.value.readUInt32LE(n*4+4),c=!!(i&2147483648),s=i&2147483647;r.path+="/"+s.toString(10)+(c?"'":"")}return r}bt.decode=Xu;function qu(e){const t=m.from([Wo.GlobalTypes.GLOBAL_XPUB]),r=m.concat([t,e.extendedPubkey]),n=e.path.split("/"),i=m.allocUnsafe(n.length*4);e.masterFingerprint.copy(i,0);let c=4;return n.slice(1).forEach(s=>{const a=s.slice(-1)==="'";let p=2147483647&parseInt(a?s.slice(0,-1):s,10);a&&(p+=2147483648),i.writeUInt32LE(p,c),c+=4}),{key:r,value:i}}bt.encode=qu;bt.expected="{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }";function zu(e){const t=e.extendedPubkey,r=e.masterFingerprint,n=e.path;return m.isBuffer(t)&&t.length===78&&[2,3].indexOf(t[45])>-1&&m.isBuffer(r)&&r.length===4&&typeof n=="string"&&!!n.match(/^m(\/\d+'?)*$/)}bt.check=zu;function Yu(e,t,r){const n=t.extendedPubkey.toString("hex");return r.has(n)?!1:(r.add(n),e.filter(i=>i.extendedPubkey.equals(t.extendedPubkey)).length===0)}bt.canAddToArray=Yu;var ci={};Object.defineProperty(ci,"__esModule",{value:!0});const Ju=fe;function Qu(e){return{key:m.from([Ju.GlobalTypes.UNSIGNED_TX]),value:e.toBuffer()}}ci.encode=Qu;var _t={};Object.defineProperty(_t,"__esModule",{value:!0});const jo=fe;function Zu(e){if(e.key[0]!==jo.InputTypes.FINAL_SCRIPTSIG)throw new Error("Decode Error: could not decode finalScriptSig with key 0x"+e.key.toString("hex"));return e.value}_t.decode=Zu;function ea(e){return{key:m.from([jo.InputTypes.FINAL_SCRIPTSIG]),value:e}}_t.encode=ea;_t.expected="Buffer";function ta(e){return m.isBuffer(e)}_t.check=ta;function ra(e,t){return!!e&&!!t&&e.finalScriptSig===void 0}_t.canAdd=ra;var Tt={};Object.defineProperty(Tt,"__esModule",{value:!0});const Vo=fe;function na(e){if(e.key[0]!==Vo.InputTypes.FINAL_SCRIPTWITNESS)throw new Error("Decode Error: could not decode finalScriptWitness with key 0x"+e.key.toString("hex"));return e.value}Tt.decode=na;function ia(e){return{key:m.from([Vo.InputTypes.FINAL_SCRIPTWITNESS]),value:e}}Tt.encode=ia;Tt.expected="Buffer";function oa(e){return m.isBuffer(e)}Tt.check=oa;function sa(e,t){return!!e&&!!t&&e.finalScriptWitness===void 0}Tt.canAdd=sa;var It={};Object.defineProperty(It,"__esModule",{value:!0});const Go=fe;function ca(e){if(e.key[0]!==Go.InputTypes.NON_WITNESS_UTXO)throw new Error("Decode Error: could not decode nonWitnessUtxo with key 0x"+e.key.toString("hex"));return e.value}It.decode=ca;function ua(e){return{key:m.from([Go.InputTypes.NON_WITNESS_UTXO]),value:e}}It.encode=ua;It.expected="Buffer";function aa(e){return m.isBuffer(e)}It.check=aa;function fa(e,t){return!!e&&!!t&&e.nonWitnessUtxo===void 0}It.canAdd=fa;var kt={};Object.defineProperty(kt,"__esModule",{value:!0});const Xo=fe;function ha(e){if(e.key[0]!==Xo.InputTypes.PARTIAL_SIG)throw new Error("Decode Error: could not decode partialSig with key 0x"+e.key.toString("hex"));if(!(e.key.length===34||e.key.length===66)||![2,3,4].includes(e.key[1]))throw new Error("Decode Error: partialSig has invalid pubkey in key 0x"+e.key.toString("hex"));return{pubkey:e.key.slice(1),signature:e.value}}kt.decode=ha;function pa(e){const t=m.from([Xo.InputTypes.PARTIAL_SIG]);return{key:m.concat([t,e.pubkey]),value:e.signature}}kt.encode=pa;kt.expected="{ pubkey: Buffer; signature: Buffer; }";function la(e){return m.isBuffer(e.pubkey)&&m.isBuffer(e.signature)&&[33,65].includes(e.pubkey.length)&&[2,3,4].includes(e.pubkey[0])&&da(e.signature)}kt.check=la;function da(e){if(!m.isBuffer(e)||e.length<9||e[0]!==48||e.length!==e[1]+3||e[2]!==2)return!1;const t=e[3];if(t>33||t<1||e[3+t+1]!==2)return!1;const r=e[3+t+2];return!(r>33||r<1||e.length!==3+t+2+r+2)}function ya(e,t,r){const n=t.pubkey.toString("hex");return r.has(n)?!1:(r.add(n),e.filter(i=>i.pubkey.equals(t.pubkey)).length===0)}kt.canAddToArray=ya;var At={};Object.defineProperty(At,"__esModule",{value:!0});const qo=fe;function wa(e){if(e.key[0]!==qo.InputTypes.POR_COMMITMENT)throw new Error("Decode Error: could not decode porCommitment with key 0x"+e.key.toString("hex"));return e.value.toString("utf8")}At.decode=wa;function ga(e){return{key:m.from([qo.InputTypes.POR_COMMITMENT]),value:m.from(e,"utf8")}}At.encode=ga;At.expected="string";function ma(e){return typeof e=="string"}At.check=ma;function Ea(e,t){return!!e&&!!t&&e.porCommitment===void 0}At.canAdd=Ea;var Pt={};Object.defineProperty(Pt,"__esModule",{value:!0});const zo=fe;function Sa(e){if(e.key[0]!==zo.InputTypes.SIGHASH_TYPE)throw new Error("Decode Error: could not decode sighashType with key 0x"+e.key.toString("hex"));return e.value.readUInt32LE(0)}Pt.decode=Sa;function ba(e){const t=m.from([zo.InputTypes.SIGHASH_TYPE]),r=m.allocUnsafe(4);return r.writeUInt32LE(e,0),{key:t,value:r}}Pt.encode=ba;Pt.expected="number";function _a(e){return typeof e=="number"}Pt.check=_a;function Ta(e,t){return!!e&&!!t&&e.sighashType===void 0}Pt.canAdd=Ta;var Ot={};Object.defineProperty(Ot,"__esModule",{value:!0});const Yo=fe;function Ia(e){if(e.key[0]!==Yo.InputTypes.TAP_KEY_SIG||e.key.length!==1)throw new Error("Decode Error: could not decode tapKeySig with key 0x"+e.key.toString("hex"));if(!Jo(e.value))throw new Error("Decode Error: tapKeySig not a valid 64-65-byte BIP340 signature");return e.value}Ot.decode=Ia;function ka(e){return{key:m.from([Yo.InputTypes.TAP_KEY_SIG]),value:e}}Ot.encode=ka;Ot.expected="Buffer";function Jo(e){return m.isBuffer(e)&&(e.length===64||e.length===65)}Ot.check=Jo;function Aa(e,t){return!!e&&!!t&&e.tapKeySig===void 0}Ot.canAdd=Aa;var vt={};Object.defineProperty(vt,"__esModule",{value:!0});const Qo=fe;function Pa(e){if(e.key[0]!==Qo.InputTypes.TAP_LEAF_SCRIPT)throw new Error("Decode Error: could not decode tapLeafScript with key 0x"+e.key.toString("hex"));if((e.key.length-2)%32!==0)throw new Error("Decode Error: tapLeafScript has invalid control block in key 0x"+e.key.toString("hex"));const t=e.value[e.value.length-1];if((e.key[1]&254)!==t)throw new Error("Decode Error: tapLeafScript bad leaf version in key 0x"+e.key.toString("hex"));const r=e.value.slice(0,-1);return{controlBlock:e.key.slice(1),script:r,leafVersion:t}}vt.decode=Pa;function Oa(e){const t=m.from([Qo.InputTypes.TAP_LEAF_SCRIPT]),r=m.from([e.leafVersion]);return{key:m.concat([t,e.controlBlock]),value:m.concat([e.script,r])}}vt.encode=Oa;vt.expected="{ controlBlock: Buffer; leafVersion: number, script: Buffer; }";function va(e){return m.isBuffer(e.controlBlock)&&(e.controlBlock.length-1)%32===0&&(e.controlBlock[0]&254)===e.leafVersion&&m.isBuffer(e.script)}vt.check=va;function Ba(e,t,r){const n=t.controlBlock.toString("hex");return r.has(n)?!1:(r.add(n),e.filter(i=>i.controlBlock.equals(t.controlBlock)).length===0)}vt.canAddToArray=Ba;var Bt={};Object.defineProperty(Bt,"__esModule",{value:!0});const Zo=fe;function xa(e){if(e.key[0]!==Zo.InputTypes.TAP_MERKLE_ROOT||e.key.length!==1)throw new Error("Decode Error: could not decode tapMerkleRoot with key 0x"+e.key.toString("hex"));if(!es(e.value))throw new Error("Decode Error: tapMerkleRoot not a 32-byte hash");return e.value}Bt.decode=xa;function Ua(e){return{key:m.from([Zo.InputTypes.TAP_MERKLE_ROOT]),value:e}}Bt.encode=Ua;Bt.expected="Buffer";function es(e){return m.isBuffer(e)&&e.length===32}Bt.check=es;function Ca(e,t){return!!e&&!!t&&e.tapMerkleRoot===void 0}Bt.canAdd=Ca;var xt={};Object.defineProperty(xt,"__esModule",{value:!0});const ts=fe;function Na(e){if(e.key[0]!==ts.InputTypes.TAP_SCRIPT_SIG)throw new Error("Decode Error: could not decode tapScriptSig with key 0x"+e.key.toString("hex"));if(e.key.length!==65)throw new Error("Decode Error: tapScriptSig has invalid key 0x"+e.key.toString("hex"));if(e.value.length!==64&&e.value.length!==65)throw new Error("Decode Error: tapScriptSig has invalid signature in key 0x"+e.key.toString("hex"));const t=e.key.slice(1,33),r=e.key.slice(33);return{pubkey:t,leafHash:r,signature:e.value}}xt.decode=Na;function Ha(e){const t=m.from([ts.InputTypes.TAP_SCRIPT_SIG]);return{key:m.concat([t,e.pubkey,e.leafHash]),value:e.signature}}xt.encode=Ha;xt.expected="{ pubkey: Buffer; leafHash: Buffer; signature: Buffer; }";function Ra(e){return m.isBuffer(e.pubkey)&&m.isBuffer(e.leafHash)&&m.isBuffer(e.signature)&&e.pubkey.length===32&&e.leafHash.length===32&&(e.signature.length===64||e.signature.length===65)}xt.check=Ra;function Fa(e,t,r){const n=t.pubkey.toString("hex")+t.leafHash.toString("hex");return r.has(n)?!1:(r.add(n),e.filter(i=>i.pubkey.equals(t.pubkey)&&i.leafHash.equals(t.leafHash)).length===0)}xt.canAddToArray=Fa;var Ut={},De={},xe={};Object.defineProperty(xe,"__esModule",{value:!0});const La=9007199254740991;function ui(e){if(e<0||e>La||e%1!==0)throw new RangeError("value out of range")}function ar(e,t,r){if(ui(e),t||(t=m.allocUnsafe(rs(e))),!m.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");return r||(r=0),e<253?(t.writeUInt8(e,r),Object.assign(ar,{bytes:1})):e<=65535?(t.writeUInt8(253,r),t.writeUInt16LE(e,r+1),Object.assign(ar,{bytes:3})):e<=4294967295?(t.writeUInt8(254,r),t.writeUInt32LE(e,r+1),Object.assign(ar,{bytes:5})):(t.writeUInt8(255,r),t.writeUInt32LE(e>>>0,r+1),t.writeUInt32LE(e/4294967296|0,r+5),Object.assign(ar,{bytes:9})),t}xe.encode=ar;function fr(e,t){if(!m.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");t||(t=0);const r=e.readUInt8(t);if(r<253)return Object.assign(fr,{bytes:1}),r;if(r===253)return Object.assign(fr,{bytes:3}),e.readUInt16LE(t+1);if(r===254)return Object.assign(fr,{bytes:5}),e.readUInt32LE(t+1);{Object.assign(fr,{bytes:9});const n=e.readUInt32LE(t+1),c=e.readUInt32LE(t+5)*4294967296+n;return ui(c),c}}xe.decode=fr;function rs(e){return ui(e),e<253?1:e<=65535?3:e<=4294967295?5:9}xe.encodingLength=rs;Object.defineProperty(De,"__esModule",{value:!0});const Pr=xe;De.range=e=>[...Array(e).keys()];function Ma(e){if(e.length<1)return e;let t=e.length-1,r=0;for(let n=0;nt)throw new Error("RangeError: value out of range");if(Math.floor(e)!==e)throw new Error("value has a fractional component")}function Ka(e,t){const r=e.readUInt32LE(t);let n=e.readUInt32LE(t+4);return n*=4294967296,is(n+r,9007199254740991),n+r}De.readUInt64LE=Ka;function Da(e,t,r){return is(t,9007199254740991),e.writeInt32LE(t&-1,r),e.writeUInt32LE(Math.floor(t/4294967296),r+4),r+8}De.writeUInt64LE=Da;Object.defineProperty(Ut,"__esModule",{value:!0});const os=fe,ss=De,Kr=xe;function Wa(e){if(e.key[0]!==os.InputTypes.WITNESS_UTXO)throw new Error("Decode Error: could not decode witnessUtxo with key 0x"+e.key.toString("hex"));const t=ss.readUInt64LE(e.value,0);let r=8;const n=Kr.decode(e.value,r);r+=Kr.encodingLength(n);const i=e.value.slice(r);if(i.length!==n)throw new Error("Decode Error: WITNESS_UTXO script is not proper length");return{script:i,value:t}}Ut.decode=Wa;function ja(e){const{script:t,value:r}=e,n=Kr.encodingLength(t.length),i=m.allocUnsafe(8+n+t.length);return ss.writeUInt64LE(i,r,0),Kr.encode(t.length,i,8),t.copy(i,8+n),{key:m.from([os.InputTypes.WITNESS_UTXO]),value:i}}Ut.encode=ja;Ut.expected="{ script: Buffer; value: number; }";function Va(e){return m.isBuffer(e.script)&&typeof e.value=="number"}Ut.check=Va;function Ga(e,t){return!!e&&!!t&&e.witnessUtxo===void 0}Ut.canAdd=Ga;var Ct={};Object.defineProperty(Ct,"__esModule",{value:!0});const cs=fe,Kn=xe;function Xa(e){if(e.key[0]!==cs.OutputTypes.TAP_TREE||e.key.length!==1)throw new Error("Decode Error: could not decode tapTree with key 0x"+e.key.toString("hex"));let t=0;const r=[];for(;t[m.of(n.depth,n.leafVersion),Kn.encode(n.script.length),n.script]));return{key:t,value:m.concat(r)}}Ct.encode=qa;Ct.expected="{ leaves: [{ depth: number; leafVersion: number, script: Buffer; }] }";function za(e){return Array.isArray(e.leaves)&&e.leaves.every(t=>t.depth>=0&&t.depth<=128&&(t.leafVersion&254)===t.leafVersion&&m.isBuffer(t.script))}Ct.check=za;function Ya(e,t){return!!e&&!!t&&e.tapTree===void 0}Ct.canAdd=Ya;var un={};Object.defineProperty(un,"__esModule",{value:!0});const Ja=e=>[...Array(e).keys()],Qa=e=>e.length===33&&[2,3].includes(e[0])||e.length===65&&e[0]===4;function Za(e,t=Qa){function r(a){if(a.key[0]!==e)throw new Error("Decode Error: could not decode bip32Derivation with key 0x"+a.key.toString("hex"));const p=a.key.slice(1);if(!t(p))throw new Error("Decode Error: bip32Derivation has invalid pubkey in key 0x"+a.key.toString("hex"));if(a.value.length/4%1!==0)throw new Error("Decode Error: Input BIP32_DERIVATION value length should be multiple of 4");const w={masterFingerprint:a.value.slice(0,4),pubkey:p,path:"m"};for(const f of Ja(a.value.length/4-1)){const d=a.value.readUInt32LE(f*4+4),E=!!(d&2147483648),y=d&2147483647;w.path+="/"+y.toString(10)+(E?"'":"")}return w}function n(a){const p=m.from([e]),w=m.concat([p,a.pubkey]),f=a.path.split("/"),d=m.allocUnsafe(f.length*4);a.masterFingerprint.copy(d,0);let E=4;return f.slice(1).forEach(y=>{const _=y.slice(-1)==="'";let T=2147483647&parseInt(_?y.slice(0,-1):y,10);_&&(T+=2147483648),d.writeUInt32LE(T,E),E+=4}),{key:w,value:d}}const i="{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }";function c(a){return m.isBuffer(a.pubkey)&&m.isBuffer(a.masterFingerprint)&&typeof a.path=="string"&&t(a.pubkey)&&a.masterFingerprint.length===4}function s(a,p,w){const f=p.pubkey.toString("hex");return w.has(f)?!1:(w.add(f),a.filter(d=>d.pubkey.equals(p.pubkey)).length===0)}return{decode:r,encode:n,check:c,expected:i,canAddToArray:s}}un.makeConverter=Za;var ai={};Object.defineProperty(ai,"__esModule",{value:!0});function ef(e){return t;function t(r){let n;if(e.includes(r.key[0])&&(n=r.key.slice(1),!(n.length===33||n.length===65)||![2,3,4].includes(n[0])))throw new Error("Format Error: invalid pubkey in key 0x"+r.key.toString("hex"));return n}}ai.makeChecker=ef;var fi={};Object.defineProperty(fi,"__esModule",{value:!0});function tf(e){function t(s){if(s.key[0]!==e)throw new Error("Decode Error: could not decode redeemScript with key 0x"+s.key.toString("hex"));return s.value}function r(s){return{key:m.from([e]),value:s}}const n="Buffer";function i(s){return m.isBuffer(s)}function c(s,a){return!!s&&!!a&&s.redeemScript===void 0}return{decode:t,encode:r,check:i,expected:n,canAdd:c}}fi.makeConverter=tf;var hi={};Object.defineProperty(hi,"__esModule",{value:!0});const Or=xe,rf=un,nf=e=>e.length===32;function of(e){const t=rf.makeConverter(e,nf);function r(s){const a=Or.decode(s.value),p=Or.encodingLength(a),w=t.decode({key:s.key,value:s.value.slice(p+a*32)}),f=new Array(a);for(let d=0,E=p;dm.isBuffer(a)&&a.length===32)&&t.check(s)}return{decode:r,encode:n,check:c,expected:i,canAddToArray:t.canAddToArray}}hi.makeConverter=of;var pi={};Object.defineProperty(pi,"__esModule",{value:!0});function sf(e){function t(s){if(s.key[0]!==e||s.key.length!==1)throw new Error("Decode Error: could not decode tapInternalKey with key 0x"+s.key.toString("hex"));if(s.value.length!==32)throw new Error("Decode Error: tapInternalKey not a 32-byte x-only pubkey");return s.value}function r(s){return{key:m.from([e]),value:s}}const n="Buffer";function i(s){return m.isBuffer(s)&&s.length===32}function c(s,a){return!!s&&!!a&&s.tapInternalKey===void 0}return{decode:t,encode:r,check:i,expected:n,canAdd:c}}pi.makeConverter=sf;var li={};Object.defineProperty(li,"__esModule",{value:!0});function cf(e){function t(s){if(s.key[0]!==e)throw new Error("Decode Error: could not decode witnessScript with key 0x"+s.key.toString("hex"));return s.value}function r(s){return{key:m.from([e]),value:s}}const n="Buffer";function i(s){return m.isBuffer(s)}function c(s,a){return!!s&&!!a&&s.witnessScript===void 0}return{decode:t,encode:r,check:i,expected:n,canAdd:c}}li.makeConverter=cf;Object.defineProperty(St,"__esModule",{value:!0});const Ie=fe,uf=bt,af=ci,ff=_t,hf=Tt,pf=It,lf=kt,df=At,yf=Pt,wf=Ot,gf=vt,mf=Bt,Ef=xt,Sf=Ut,bf=Ct,us=un,di=ai,as=fi,fs=hi,hs=pi,ps=li,_f={unsignedTx:af,globalXpub:uf,checkPubkey:di.makeChecker([])};St.globals=_f;const Tf={nonWitnessUtxo:pf,partialSig:lf,sighashType:yf,finalScriptSig:ff,finalScriptWitness:hf,porCommitment:df,witnessUtxo:Sf,bip32Derivation:us.makeConverter(Ie.InputTypes.BIP32_DERIVATION),redeemScript:as.makeConverter(Ie.InputTypes.REDEEM_SCRIPT),witnessScript:ps.makeConverter(Ie.InputTypes.WITNESS_SCRIPT),checkPubkey:di.makeChecker([Ie.InputTypes.PARTIAL_SIG,Ie.InputTypes.BIP32_DERIVATION]),tapKeySig:wf,tapScriptSig:Ef,tapLeafScript:gf,tapBip32Derivation:fs.makeConverter(Ie.InputTypes.TAP_BIP32_DERIVATION),tapInternalKey:hs.makeConverter(Ie.InputTypes.TAP_INTERNAL_KEY),tapMerkleRoot:mf};St.inputs=Tf;const If={bip32Derivation:us.makeConverter(Ie.OutputTypes.BIP32_DERIVATION),redeemScript:as.makeConverter(Ie.OutputTypes.REDEEM_SCRIPT),witnessScript:ps.makeConverter(Ie.OutputTypes.WITNESS_SCRIPT),checkPubkey:di.makeChecker([Ie.OutputTypes.BIP32_DERIVATION]),tapBip32Derivation:fs.makeConverter(Ie.OutputTypes.TAP_BIP32_DERIVATION),tapTree:bf,tapInternalKey:hs.makeConverter(Ie.OutputTypes.TAP_INTERNAL_KEY)};St.outputs=If;Object.defineProperty(Er,"__esModule",{value:!0});const q=St,Dr=De,Ji=xe,H=fe;function kf(e,t){let r=0;function n(){const A=Ji.decode(e,r);r+=Ji.encodingLength(A);const x=e.slice(r,r+A);return r+=A,x}function i(){const A=e.readUInt32BE(r);return r+=4,A}function c(){const A=e.readUInt8(r);return r+=1,A}function s(){const A=n(),x=n();return{key:A,value:x}}function a(){if(r>=e.length)throw new Error("Format Error: Unexpected End of PSBT");const A=e.readUInt8(r)===0;return A&&r++,A}if(i()!==1886610036)throw new Error("Format Error: Invalid Magic Number");if(c()!==255)throw new Error("Format Error: Magic Number must be followed by 0xff separator");const p=[],w={};for(;!a();){const A=s(),x=A.key.toString("hex");if(w[x])throw new Error("Format Error: Keys must be unique for global keymap: key "+x);w[x]=1,p.push(A)}const f=p.filter(A=>A.key[0]===H.GlobalTypes.UNSIGNED_TX);if(f.length!==1)throw new Error("Format Error: Only one UNSIGNED_TX allowed");const d=t(f[0].value),{inputCount:E,outputCount:y}=d.getInputOutputCounts(),_=[],T=[];for(const A of Dr.range(E)){const x={},U=[];for(;!a();){const I=s(),S=I.key.toString("hex");if(x[S])throw new Error("Format Error: Keys must be unique for each input: input index "+A+" key "+S);x[S]=1,U.push(I)}_.push(U)}for(const A of Dr.range(y)){const x={},U=[];for(;!a();){const I=s(),S=I.key.toString("hex");if(x[S])throw new Error("Format Error: Keys must be unique for each output: output index "+A+" key "+S);x[S]=1,U.push(I)}T.push(U)}return ls(d,{globalMapKeyVals:p,inputKeyVals:_,outputKeyVals:T})}Er.psbtFromBuffer=kf;function pe(e,t,r){if(!t.equals(m.from([r])))throw new Error(`Format Error: Invalid ${e} key: ${t.toString("hex")}`)}Er.checkKeyBuffer=pe;function ls(e,{globalMapKeyVals:t,inputKeyVals:r,outputKeyVals:n}){const i={unsignedTx:e};let c=0;for(const f of t)switch(f.key[0]){case H.GlobalTypes.UNSIGNED_TX:if(pe("global",f.key,H.GlobalTypes.UNSIGNED_TX),c>0)throw new Error("Format Error: GlobalMap has multiple UNSIGNED_TX");c++;break;case H.GlobalTypes.GLOBAL_XPUB:i.globalXpub===void 0&&(i.globalXpub=[]),i.globalXpub.push(q.globals.globalXpub.decode(f));break;default:i.unknownKeyVals||(i.unknownKeyVals=[]),i.unknownKeyVals.push(f)}const s=r.length,a=n.length,p=[],w=[];for(const f of Dr.range(s)){const d={};for(const E of r[f])switch(q.inputs.checkPubkey(E),E.key[0]){case H.InputTypes.NON_WITNESS_UTXO:if(pe("input",E.key,H.InputTypes.NON_WITNESS_UTXO),d.nonWitnessUtxo!==void 0)throw new Error("Format Error: Input has multiple NON_WITNESS_UTXO");d.nonWitnessUtxo=q.inputs.nonWitnessUtxo.decode(E);break;case H.InputTypes.WITNESS_UTXO:if(pe("input",E.key,H.InputTypes.WITNESS_UTXO),d.witnessUtxo!==void 0)throw new Error("Format Error: Input has multiple WITNESS_UTXO");d.witnessUtxo=q.inputs.witnessUtxo.decode(E);break;case H.InputTypes.PARTIAL_SIG:d.partialSig===void 0&&(d.partialSig=[]),d.partialSig.push(q.inputs.partialSig.decode(E));break;case H.InputTypes.SIGHASH_TYPE:if(pe("input",E.key,H.InputTypes.SIGHASH_TYPE),d.sighashType!==void 0)throw new Error("Format Error: Input has multiple SIGHASH_TYPE");d.sighashType=q.inputs.sighashType.decode(E);break;case H.InputTypes.REDEEM_SCRIPT:if(pe("input",E.key,H.InputTypes.REDEEM_SCRIPT),d.redeemScript!==void 0)throw new Error("Format Error: Input has multiple REDEEM_SCRIPT");d.redeemScript=q.inputs.redeemScript.decode(E);break;case H.InputTypes.WITNESS_SCRIPT:if(pe("input",E.key,H.InputTypes.WITNESS_SCRIPT),d.witnessScript!==void 0)throw new Error("Format Error: Input has multiple WITNESS_SCRIPT");d.witnessScript=q.inputs.witnessScript.decode(E);break;case H.InputTypes.BIP32_DERIVATION:d.bip32Derivation===void 0&&(d.bip32Derivation=[]),d.bip32Derivation.push(q.inputs.bip32Derivation.decode(E));break;case H.InputTypes.FINAL_SCRIPTSIG:pe("input",E.key,H.InputTypes.FINAL_SCRIPTSIG),d.finalScriptSig=q.inputs.finalScriptSig.decode(E);break;case H.InputTypes.FINAL_SCRIPTWITNESS:pe("input",E.key,H.InputTypes.FINAL_SCRIPTWITNESS),d.finalScriptWitness=q.inputs.finalScriptWitness.decode(E);break;case H.InputTypes.POR_COMMITMENT:pe("input",E.key,H.InputTypes.POR_COMMITMENT),d.porCommitment=q.inputs.porCommitment.decode(E);break;case H.InputTypes.TAP_KEY_SIG:pe("input",E.key,H.InputTypes.TAP_KEY_SIG),d.tapKeySig=q.inputs.tapKeySig.decode(E);break;case H.InputTypes.TAP_SCRIPT_SIG:d.tapScriptSig===void 0&&(d.tapScriptSig=[]),d.tapScriptSig.push(q.inputs.tapScriptSig.decode(E));break;case H.InputTypes.TAP_LEAF_SCRIPT:d.tapLeafScript===void 0&&(d.tapLeafScript=[]),d.tapLeafScript.push(q.inputs.tapLeafScript.decode(E));break;case H.InputTypes.TAP_BIP32_DERIVATION:d.tapBip32Derivation===void 0&&(d.tapBip32Derivation=[]),d.tapBip32Derivation.push(q.inputs.tapBip32Derivation.decode(E));break;case H.InputTypes.TAP_INTERNAL_KEY:pe("input",E.key,H.InputTypes.TAP_INTERNAL_KEY),d.tapInternalKey=q.inputs.tapInternalKey.decode(E);break;case H.InputTypes.TAP_MERKLE_ROOT:pe("input",E.key,H.InputTypes.TAP_MERKLE_ROOT),d.tapMerkleRoot=q.inputs.tapMerkleRoot.decode(E);break;default:d.unknownKeyVals||(d.unknownKeyVals=[]),d.unknownKeyVals.push(E)}p.push(d)}for(const f of Dr.range(a)){const d={};for(const E of n[f])switch(q.outputs.checkPubkey(E),E.key[0]){case H.OutputTypes.REDEEM_SCRIPT:if(pe("output",E.key,H.OutputTypes.REDEEM_SCRIPT),d.redeemScript!==void 0)throw new Error("Format Error: Output has multiple REDEEM_SCRIPT");d.redeemScript=q.outputs.redeemScript.decode(E);break;case H.OutputTypes.WITNESS_SCRIPT:if(pe("output",E.key,H.OutputTypes.WITNESS_SCRIPT),d.witnessScript!==void 0)throw new Error("Format Error: Output has multiple WITNESS_SCRIPT");d.witnessScript=q.outputs.witnessScript.decode(E);break;case H.OutputTypes.BIP32_DERIVATION:d.bip32Derivation===void 0&&(d.bip32Derivation=[]),d.bip32Derivation.push(q.outputs.bip32Derivation.decode(E));break;case H.OutputTypes.TAP_INTERNAL_KEY:pe("output",E.key,H.OutputTypes.TAP_INTERNAL_KEY),d.tapInternalKey=q.outputs.tapInternalKey.decode(E);break;case H.OutputTypes.TAP_TREE:pe("output",E.key,H.OutputTypes.TAP_TREE),d.tapTree=q.outputs.tapTree.decode(E);break;case H.OutputTypes.TAP_BIP32_DERIVATION:d.tapBip32Derivation===void 0&&(d.tapBip32Derivation=[]),d.tapBip32Derivation.push(q.outputs.tapBip32Derivation.decode(E));break;default:d.unknownKeyVals||(d.unknownKeyVals=[]),d.unknownKeyVals.push(E)}w.push(d)}return{globalMap:i,inputs:p,outputs:w}}Er.psbtFromKeyVals=ls;var an={};Object.defineProperty(an,"__esModule",{value:!0});const xn=St,Qi=De;function Af({globalMap:e,inputs:t,outputs:r}){const{globalKeyVals:n,inputKeyVals:i,outputKeyVals:c}=ds({globalMap:e,inputs:t,outputs:r}),s=Qi.keyValsToBuffer(n),a=d=>d.length===0?[m.from([0])]:d.map(Qi.keyValsToBuffer),p=a(i),w=a(c),f=m.allocUnsafe(5);return f.writeUIntBE(482972169471,0,5),m.concat([f,s].concat(p,w))}an.psbtToBuffer=Af;const Pf=(e,t)=>e.key.compare(t.key);function Un(e,t){const r=new Set,n=Object.entries(e).reduce((c,[s,a])=>{if(s==="unknownKeyVals")return c;const p=t[s];if(p===void 0)return c;const w=(Array.isArray(a)?a:[a]).map(p.encode);return w.map(d=>d.key.toString("hex")).forEach(d=>{if(r.has(d))throw new Error("Serialize Error: Duplicate key: "+d);r.add(d)}),c.concat(w)},[]),i=e.unknownKeyVals?e.unknownKeyVals.filter(c=>!r.has(c.key.toString("hex"))):[];return n.concat(i).sort(Pf)}function ds({globalMap:e,inputs:t,outputs:r}){return{globalKeyVals:Un(e,xn.globals),inputKeyVals:t.map(n=>Un(n,xn.inputs)),outputKeyVals:r.map(n=>Un(n,xn.outputs))}}an.psbtToKeyVals=ds;(function(e){function t(r){for(var n in r)e.hasOwnProperty(n)||(e[n]=r[n])}Object.defineProperty(e,"__esModule",{value:!0}),t(Er),t(an)})(si);Object.defineProperty(oi,"__esModule",{value:!0});const Cn=si;function Of(e){const t=e[0],r=Cn.psbtToKeyVals(t),n=e.slice(1);if(n.length===0)throw new Error("Combine: Nothing to combine");const i=Zi(t);if(i===void 0)throw new Error("Combine: Self missing transaction");const c=Kt(r.globalKeyVals),s=r.inputKeyVals.map(Kt),a=r.outputKeyVals.map(Kt);for(const p of n){const w=Zi(p);if(w===void 0||!w.toBuffer().equals(i.toBuffer()))throw new Error("Combine: One of the Psbts does not have the same transaction.");const f=Cn.psbtToKeyVals(p);Kt(f.globalKeyVals).forEach(Nn(c,r.globalKeyVals,f.globalKeyVals)),f.inputKeyVals.map(Kt).forEach((_,T)=>_.forEach(Nn(s[T],r.inputKeyVals[T],f.inputKeyVals[T]))),f.outputKeyVals.map(Kt).forEach((_,T)=>_.forEach(Nn(a[T],r.outputKeyVals[T],f.outputKeyVals[T])))}return Cn.psbtFromKeyVals(i,{globalMapKeyVals:r.globalKeyVals,inputKeyVals:r.inputKeyVals,outputKeyVals:r.outputKeyVals})}oi.combine=Of;function Nn(e,t,r){return n=>{if(e.has(n))return;const i=r.filter(c=>c.key.toString("hex")===n)[0];t.push(i),e.add(n)}}function Zi(e){return e.globalMap.unsignedTx}function Kt(e){const t=new Set;return e.forEach(r=>{const n=r.key.toString("hex");if(t.has(n))throw new Error("Combine: KeyValue Map keys should be unique");t.add(n)}),t}var yi={};(function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=St;function r(y,_){const T=y[_];if(T===void 0)throw new Error(`No input #${_}`);return T}e.checkForInput=r;function n(y,_){const T=y[_];if(T===void 0)throw new Error(`No output #${_}`);return T}e.checkForOutput=n;function i(y,_,T){if(y.key[0]A.key.equals(y.key)).length!==0)throw new Error(`Duplicate Key: ${y.key.toString("hex")}`)}e.checkHasKey=i;function c(y){let _=0;return Object.keys(y).forEach(T=>{Number(isNaN(Number(T)))&&_++}),_}e.getEnumLength=c;function s(y,_){let T=!1;if(_.nonWitnessUtxo||_.witnessUtxo){const A=!!_.redeemScript,x=!!_.witnessScript,U=!A||!!_.finalScriptSig,I=!x||!!_.finalScriptWitness,S=!!_.finalScriptSig||!!_.finalScriptWitness;T=U&&I&&S}if(T===!1)throw new Error(`Input #${y} has too much or too little data to clean`)}e.inputCheckUncleanFinalized=s;function a(y,_,T,A){throw new Error(`Data for ${y} key ${_} is incorrect: Expected ${T} and got ${JSON.stringify(A)}`)}function p(y){return(_,T)=>{for(const A of Object.keys(_)){const x=_[A],{canAdd:U,canAddToArray:I,check:S,expected:v}=t[y+"s"][A]||{},k=!!I;if(S)if(k){if(!Array.isArray(x)||T[A]&&!Array.isArray(T[A]))throw new Error(`Key type ${A} must be an array`);x.every(S)||a(y,A,v,x);const N=T[A]||[],$=new Set;if(!x.every(B=>I(N,B,$)))throw new Error("Can not add duplicate data to array");T[A]=N.concat(x)}else{if(S(x)||a(y,A,v,x),!U(T,x))throw new Error(`Can not add duplicate data to ${y}`);T[A]=x}}}}e.updateGlobal=p("global"),e.updateInput=p("input"),e.updateOutput=p("output");function w(y,_){const T=y.length-1,A=r(y,T);e.updateInput(_,A)}e.addInputAttributes=w;function f(y,_){const T=y.length-1,A=n(y,T);e.updateOutput(_,A)}e.addOutputAttributes=f;function d(y,_){if(!m.isBuffer(_)||_.length<4)throw new Error("Set Version: Invalid Transaction");return _.writeUInt32LE(y,0),_}e.defaultVersionSetter=d;function E(y,_){if(!m.isBuffer(_)||_.length<4)throw new Error("Set Locktime: Invalid Transaction");return _.writeUInt32LE(y,_.length-4),_}e.defaultLocktimeSetter=E})(yi);Object.defineProperty(ii,"__esModule",{value:!0});const vf=oi,eo=si,Hn=fe,he=yi;let Bf=class{constructor(t){this.inputs=[],this.outputs=[],this.globalMap={unsignedTx:t}}static fromBase64(t,r){const n=m.from(t,"base64");return this.fromBuffer(n,r)}static fromHex(t,r){const n=m.from(t,"hex");return this.fromBuffer(n,r)}static fromBuffer(t,r){const n=eo.psbtFromBuffer(t,r),i=new this(n.globalMap.unsignedTx);return Object.assign(i,n),i}toBase64(){return this.toBuffer().toString("base64")}toHex(){return this.toBuffer().toString("hex")}toBuffer(){return eo.psbtToBuffer(this)}updateGlobal(t){return he.updateGlobal(t,this.globalMap),this}updateInput(t,r){const n=he.checkForInput(this.inputs,t);return he.updateInput(r,n),this}updateOutput(t,r){const n=he.checkForOutput(this.outputs,t);return he.updateOutput(r,n),this}addUnknownKeyValToGlobal(t){return he.checkHasKey(t,this.globalMap.unknownKeyVals,he.getEnumLength(Hn.GlobalTypes)),this.globalMap.unknownKeyVals||(this.globalMap.unknownKeyVals=[]),this.globalMap.unknownKeyVals.push(t),this}addUnknownKeyValToInput(t,r){const n=he.checkForInput(this.inputs,t);return he.checkHasKey(r,n.unknownKeyVals,he.getEnumLength(Hn.InputTypes)),n.unknownKeyVals||(n.unknownKeyVals=[]),n.unknownKeyVals.push(r),this}addUnknownKeyValToOutput(t,r){const n=he.checkForOutput(this.outputs,t);return he.checkHasKey(r,n.unknownKeyVals,he.getEnumLength(Hn.OutputTypes)),n.unknownKeyVals||(n.unknownKeyVals=[]),n.unknownKeyVals.push(r),this}addInput(t){this.globalMap.unsignedTx.addInput(t),this.inputs.push({unknownKeyVals:[]});const r=t.unknownKeyVals||[],n=this.inputs.length-1;if(!Array.isArray(r))throw new Error("unknownKeyVals must be an Array");return r.forEach(i=>this.addUnknownKeyValToInput(n,i)),he.addInputAttributes(this.inputs,t),this}addOutput(t){this.globalMap.unsignedTx.addOutput(t),this.outputs.push({unknownKeyVals:[]});const r=t.unknownKeyVals||[],n=this.outputs.length-1;if(!Array.isArray(r))throw new Error("unknownKeyVals must be an Array");return r.forEach(i=>this.addUnknownKeyValToOutput(n,i)),he.addOutputAttributes(this.outputs,t),this}clearFinalizedInput(t){const r=he.checkForInput(this.inputs,t);he.inputCheckUncleanFinalized(t,r);for(const n of Object.keys(r))["witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknownKeyVals"].includes(n)||delete r[n];return this}combine(...t){const r=vf.combine([this].concat(t));return Object.assign(this,r),this}getTransaction(){return this.globalMap.unsignedTx.toBuffer()}};ii.Psbt=Bf;var Y={},W={};Object.defineProperty(W,"__esModule",{value:!0});W.signatureBlocksAction=W.checkInputForSig=W.pubkeyInScript=W.pubkeyPositionInScript=W.witnessStackToScriptWitness=W.isP2TR=W.isP2SHScript=W.isP2WSHScript=W.isP2WPKH=W.isP2PKH=W.isP2PK=W.isP2MS=void 0;const to=xe,pr=_e(),vr=lt,xf=Ke,Nt=mr();function Ht(e){return t=>{try{return e({output:t}),!0}catch{return!1}}}W.isP2MS=Ht(Nt.p2ms);W.isP2PK=Ht(Nt.p2pk);W.isP2PKH=Ht(Nt.p2pkh);W.isP2WPKH=Ht(Nt.p2wpkh);W.isP2WSHScript=Ht(Nt.p2wsh);W.isP2SHScript=Ht(Nt.p2sh);W.isP2TR=Ht(Nt.p2tr);function Uf(e){let t=m.allocUnsafe(0);function r(s){t=m.concat([t,m.from(s)])}function n(s){const a=t.length,p=to.encodingLength(s);t=m.concat([t,m.allocUnsafe(p)]),to.encode(s,t,a)}function i(s){n(s.length),r(s)}function c(s){n(s.length),s.forEach(i)}return c(e),t}W.witnessStackToScriptWitness=Uf;function ys(e,t){const r=(0,xf.hash160)(e),n=e.slice(1,33),i=pr.decompile(t);if(i===null)throw new Error("Unknown script error");return i.findIndex(c=>typeof c=="number"?!1:c.equals(e)||c.equals(r)||c.equals(n))}W.pubkeyPositionInScript=ys;function Cf(e,t){return ys(e,t)!==-1}W.pubkeyInScript=Cf;function Nf(e,t){return Hf(e).some(n=>ws(n,pr.signature.decode,t))}W.checkInputForSig=Nf;function ws(e,t,r){const{hashType:n}=t(e),i=[];switch(n&vr.Transaction.SIGHASH_ANYONECANPAY&&i.push("addInput"),n&31){case vr.Transaction.SIGHASH_ALL:break;case vr.Transaction.SIGHASH_SINGLE:case vr.Transaction.SIGHASH_NONE:i.push("addOutput"),i.push("setInputSequence");break}return i.indexOf(r)===-1}W.signatureBlocksAction=ws;function Hf(e){let t=[];if((e.partialSig||[]).length===0){if(!e.finalScriptSig&&!e.finalScriptWitness)return[];t=Rf(e)}else t=e.partialSig;return t.map(r=>r.signature)}function Rf(e){const t=e.finalScriptSig?pr.decompile(e.finalScriptSig)||[]:[],r=e.finalScriptWitness?pr.decompile(e.finalScriptWitness)||[]:[];return t.concat(r).filter(n=>m.isBuffer(n)&&pr.isCanonicalScriptSignature(n)).map(n=>({signature:n}))}Object.defineProperty(Y,"__esModule",{value:!0});Y.checkTaprootInputForSigs=Y.tapTreeFromList=Y.tapTreeToList=Y.tweakInternalPubKey=Y.checkTaprootOutputFields=Y.checkTaprootInputFields=Y.isTaprootOutput=Y.isTaprootInput=Y.serializeTaprootSignature=Y.tapScriptFinalizer=Y.toXOnly=void 0;const wi=de,Ff=lt,fn=W,pt=nn,Lf=mr(),Mf=W,$f=e=>e.length===32?e:e.slice(1,33);Y.toXOnly=$f;function Kf(e,t,r){const n=oh(t,e,r);try{const c=nh(t,n).concat(n.script).concat(n.controlBlock);return{finalScriptWitness:(0,fn.witnessStackToScriptWitness)(c)}}catch(i){throw new Error(`Can not finalize taproot input #${e}: ${i}`)}}Y.tapScriptFinalizer=Kf;function Df(e,t){const r=t?m.from([t]):m.from([]);return m.concat([e,r])}Y.serializeTaprootSignature=Df;function Hr(e){return e&&!!(e.tapInternalKey||e.tapMerkleRoot||e.tapLeafScript&&e.tapLeafScript.length||e.tapBip32Derivation&&e.tapBip32Derivation.length||e.witnessUtxo&&(0,fn.isP2TR)(e.witnessUtxo.script))}Y.isTaprootInput=Hr;function Rr(e,t){return e&&!!(e.tapInternalKey||e.tapTree||e.tapBip32Derivation&&e.tapBip32Derivation.length||t&&(0,fn.isP2TR)(t))}Y.isTaprootOutput=Rr;function Wf(e,t,r){eh(e,t,r),rh(e,t,r)}Y.checkTaprootInputFields=Wf;function jf(e,t,r){th(e,t,r),Vf(e,t)}Y.checkTaprootOutputFields=jf;function Vf(e,t){if(!t.tapTree&&!t.tapInternalKey)return;const r=t.tapInternalKey||e.tapInternalKey,n=t.tapTree||e.tapTree;if(r){const{script:i}=e,c=Gf(r,n);if(i&&!i.equals(c))throw new Error("Error adding output. Script or address missmatch.")}}function Gf(e,t){const r=t&&gs(t.leaves),{output:n}=(0,Lf.p2tr)({internalPubkey:e,scriptTree:r});return n}function Xf(e,t){const r=t.tapInternalKey,n=r&&(0,pt.tweakKey)(r,t.tapMerkleRoot);if(!n)throw new Error(`Cannot tweak tap internal key for input #${e}. Public key: ${r&&r.toString("hex")}`);return n.x}Y.tweakInternalPubKey=Xf;function qf(e){if(!(0,wi.isTaptree)(e))throw new Error("Cannot convert taptree to tapleaf list. Expecting a tapree structure.");return Dn(e)}Y.tapTreeToList=qf;function gs(e=[]){return e.length===1&&e[0].depth===0?{output:e[0].script,version:e[0].leafVersion}:Zf(e)}Y.tapTreeFromList=gs;function zf(e,t){return Jf(e).some(n=>(0,Mf.signatureBlocksAction)(n,Yf,t))}Y.checkTaprootInputForSigs=zf;function Yf(e){return{signature:e.slice(0,64),hashType:e.slice(64)[0]||Ff.Transaction.SIGHASH_DEFAULT}}function Jf(e){const t=[];if(e.tapKeySig&&t.push(e.tapKeySig),e.tapScriptSig&&t.push(...e.tapScriptSig.map(r=>r.signature)),!t.length){const r=Qf(e.finalScriptWitness);r&&t.push(r)}return t}function Qf(e){if(!e)return;const t=e.slice(2);if(t.length===64||t.length===65)return t}function Dn(e,t=[],r=0){if(r>pt.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");return e?(0,wi.isTapleaf)(e)?(t.push({depth:r,leafVersion:e.version||pt.LEAF_VERSION_TAPSCRIPT,script:e.output}),t):(e[0]&&Dn(e[0],t,r+1),e[1]&&Dn(e[1],t,r+1),t):[]}function Zf(e){let t;for(const r of e)if(t=Wn(r,t),!t)throw new Error("No room left to insert tapleaf in tree");return t}function Wn(e,t,r=0){if(r>pt.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");if(e.depth===r)return t?void 0:{output:e.script,version:e.leafVersion};if((0,wi.isTapleaf)(t))return;const n=Wn(e,t&&t[0],r+1);if(n)return[n,t&&t[1]];const i=Wn(e,t&&t[1],r+1);if(i)return[t&&t[0],i]}function eh(e,t,r){const n=Hr(e)&&qt(t),i=qt(e)&&Hr(t),c=e===t&&Hr(t)&&qt(t);if(n||i||c)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function th(e,t,r){const n=Rr(e)&&qt(t),i=qt(e)&&Rr(t),c=e===t&&Rr(t)&&qt(t);if(n||i||c)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function rh(e,t,r){if(t.tapMerkleRoot){const n=(t.tapLeafScript||[]).every(c=>Rn(c,t.tapMerkleRoot)),i=(e.tapLeafScript||[]).every(c=>Rn(c,t.tapMerkleRoot));if(!n||!i)throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}else if(e.tapMerkleRoot&&!(t.tapLeafScript||[]).every(i=>Rn(i,e.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}function Rn(e,t){if(!t)return!0;const r=(0,pt.tapleafHash)({output:e.script,version:e.leafVersion});return(0,pt.rootHashFromPath)(e.controlBlock,r).equals(t)}function nh(e,t){const r=(0,pt.tapleafHash)({output:t.script,version:t.leafVersion});return(e.tapScriptSig||[]).filter(n=>n.leafHash.equals(r)).map(n=>ih(t.script,n)).sort((n,i)=>i.positionInScript-n.positionInScript).map(n=>n.signature)}function ih(e,t){return Object.assign({positionInScript:(0,fn.pubkeyPositionInScript)(t.pubkey,e)},t)}function oh(e,t,r){if(!e.tapScriptSig||!e.tapScriptSig.length)throw new Error(`Can not finalize taproot input #${t}. No tapleaf script signature provided.`);const n=(e.tapLeafScript||[]).sort((i,c)=>i.controlBlock.length-c.controlBlock.length).find(i=>sh(i,e.tapScriptSig,r));if(!n)throw new Error(`Can not finalize taproot input #${t}. Signature for tapleaf script not found.`);return n}function sh(e,t,r){const n=(0,pt.tapleafHash)({output:e.script,version:e.leafVersion});return(!r||r.equals(n))&&t.find(c=>c.leafHash.equals(n))!==void 0}function qt(e){return e&&!!(e.redeemScript||e.witnessScript||e.bip32Derivation&&e.bip32Derivation.length)}Object.defineProperty(cn,"__esModule",{value:!0});cn.Psbt=void 0;const ro=ii,no=xe,Se=yi,io=ni(),Wr=oe,ch=ae,ve=mr(),uh=nn,Ye=_e(),we=lt,J=Y,re=W,ah={network:ch.bitcoin,maximumFeeRate:5e3};class jr{static fromBase64(t,r={}){const n=m.from(t,"base64");return this.fromBuffer(n,r)}static fromHex(t,r={}){const n=m.from(t,"hex");return this.fromBuffer(n,r)}static fromBuffer(t,r={}){const n=ro.Psbt.fromBuffer(t,fh),i=new jr(r,n);return yh(i.__CACHE.__TX,i.__CACHE),i}constructor(t={},r=new ro.Psbt(new ms)){this.data=r,this.opts=Object.assign({},ah,t),this.__CACHE={__NON_WITNESS_UTXO_TX_CACHE:[],__NON_WITNESS_UTXO_BUF_CACHE:[],__TX_IN_CACHE:{},__TX:this.data.globalMap.unsignedTx.tx,__UNSAFE_SIGN_NONSEGWIT:!1},this.data.inputs.length===0&&this.setVersion(2);const n=(i,c,s,a)=>Object.defineProperty(i,c,{enumerable:s,writable:a});n(this,"__CACHE",!1,!0),n(this,"opts",!1,!0)}get inputCount(){return this.data.inputs.length}get version(){return this.__CACHE.__TX.version}set version(t){this.setVersion(t)}get locktime(){return this.__CACHE.__TX.locktime}set locktime(t){this.setLocktime(t)}get txInputs(){return this.__CACHE.__TX.ins.map(t=>({hash:(0,Wr.cloneBuffer)(t.hash),index:t.index,sequence:t.sequence}))}get txOutputs(){return this.__CACHE.__TX.outs.map(t=>{let r;try{r=(0,io.fromOutputScript)(t.script,this.opts.network)}catch{}return{script:(0,Wr.cloneBuffer)(t.script),value:t.value,address:r}})}combine(...t){return this.data.combine(...t.map(r=>r.data)),this}clone(){const t=jr.fromBuffer(this.data.toBuffer());return t.opts=JSON.parse(JSON.stringify(this.opts)),t}setMaximumFeeRate(t){Br(t),this.opts.maximumFeeRate=t}setVersion(t){Br(t),ir(this.data.inputs,"setVersion");const r=this.__CACHE;return r.__TX.version=t,r.__EXTRACTED_TX=void 0,this}setLocktime(t){Br(t),ir(this.data.inputs,"setLocktime");const r=this.__CACHE;return r.__TX.locktime=t,r.__EXTRACTED_TX=void 0,this}setInputSequence(t,r){Br(r),ir(this.data.inputs,"setInputSequence");const n=this.__CACHE;if(n.__TX.ins.length<=t)throw new Error("Input index too high");return n.__TX.ins[t].sequence=r,n.__EXTRACTED_TX=void 0,this}addInputs(t){return t.forEach(r=>this.addInput(r)),this}addInput(t){if(arguments.length>1||!t||t.hash===void 0||t.index===void 0)throw new Error("Invalid arguments for Psbt.addInput. Requires single object with at least [hash] and [index]");(0,J.checkTaprootInputFields)(t,t,"addInput"),ir(this.data.inputs,"addInput"),t.witnessScript&&Vr(t.witnessScript);const r=this.__CACHE;this.data.addInput(t);const n=r.__TX.ins[r.__TX.ins.length-1];bs(r,n);const i=this.data.inputs.length-1,c=this.data.inputs[i];return c.nonWitnessUtxo&&Vn(this.__CACHE,c,i),r.__FEE=void 0,r.__FEE_RATE=void 0,r.__EXTRACTED_TX=void 0,this}addOutputs(t){return t.forEach(r=>this.addOutput(r)),this}addOutput(t){if(arguments.length>1||!t||t.value===void 0||t.address===void 0&&t.script===void 0)throw new Error("Invalid arguments for Psbt.addOutput. Requires single object with at least [script or address] and [value]");ir(this.data.inputs,"addOutput");const{address:r}=t;if(typeof r=="string"){const{network:i}=this.opts,c=(0,io.toOutputScript)(r,i);t=Object.assign({},t,{script:c})}(0,J.checkTaprootOutputFields)(t,t,"addOutput");const n=this.__CACHE;return this.data.addOutput(t),n.__FEE=void 0,n.__FEE_RATE=void 0,n.__EXTRACTED_TX=void 0,this}extractTransaction(t){if(!this.data.inputs.every(Es))throw new Error("Not finalized");const r=this.__CACHE;if(t||ph(this,r,this.opts),r.__EXTRACTED_TX)return r.__EXTRACTED_TX;const n=r.__TX.clone();return Ps(this.data.inputs,n,r,!0),n}getFeeRate(){return ao("__FEE_RATE","fee rate",this.data.inputs,this.__CACHE)}getFee(){return ao("__FEE","fee",this.data.inputs,this.__CACHE)}finalizeAllInputs(){return(0,Se.checkForInput)(this.data.inputs,0),or(this.data.inputs.length).forEach(t=>this.finalizeInput(t)),this}finalizeInput(t,r){const n=(0,Se.checkForInput)(this.data.inputs,t);return(0,J.isTaprootInput)(n)?this._finalizeTaprootInput(t,n,void 0,r):this._finalizeInput(t,n,r)}finalizeTaprootInput(t,r,n=J.tapScriptFinalizer){const i=(0,Se.checkForInput)(this.data.inputs,t);if((0,J.isTaprootInput)(i))return this._finalizeTaprootInput(t,i,r,n);throw new Error(`Cannot finalize input #${t}. Not Taproot.`)}_finalizeInput(t,r,n=wh){const{script:i,isP2SH:c,isP2WSH:s,isSegwit:a}=Sh(t,r,this.__CACHE);if(!i)throw new Error(`No script found for input #${t}`);lh(r);const{finalScriptSig:p,finalScriptWitness:w}=n(t,r,i,a,c,s);if(p&&this.data.updateInput(t,{finalScriptSig:p}),w&&this.data.updateInput(t,{finalScriptWitness:w}),!p&&!w)throw new Error(`Unknown error finalizing input #${t}`);return this.data.clearFinalizedInput(t),this}_finalizeTaprootInput(t,r,n,i=J.tapScriptFinalizer){if(!r.witnessUtxo)throw new Error(`Cannot finalize input #${t}. Missing withness utxo.`);if(r.tapKeySig){const c=ve.p2tr({output:r.witnessUtxo.script,signature:r.tapKeySig}),s=(0,re.witnessStackToScriptWitness)(c.witness);this.data.updateInput(t,{finalScriptWitness:s})}else{const{finalScriptWitness:c}=i(t,r,n);this.data.updateInput(t,{finalScriptWitness:c})}return this.data.clearFinalizedInput(t),this}getInputType(t){const r=(0,Se.checkForInput)(this.data.inputs,t),n=Os(t,r,this.__CACHE),i=pn(n,t,"input",r.redeemScript||kh(r.finalScriptSig),r.witnessScript||Ah(r.finalScriptWitness)),c=i.type==="raw"?"":i.type+"-",s=Bs(i.meaningfulScript);return c+s}inputHasPubkey(t,r){const n=(0,Se.checkForInput)(this.data.inputs,t);return Th(r,n,t,this.__CACHE)}inputHasHDKey(t,r){const n=(0,Se.checkForInput)(this.data.inputs,t),i=so(r);return!!n.bip32Derivation&&n.bip32Derivation.some(i)}outputHasPubkey(t,r){const n=(0,Se.checkForOutput)(this.data.outputs,t);return Ih(r,n,t,this.__CACHE)}outputHasHDKey(t,r){const n=(0,Se.checkForOutput)(this.data.outputs,t),i=so(r);return!!n.bip32Derivation&&n.bip32Derivation.some(i)}validateSignaturesOfAllInputs(t){return(0,Se.checkForInput)(this.data.inputs,0),or(this.data.inputs.length).map(n=>this.validateSignaturesOfInput(n,t)).reduce((n,i)=>i===!0&&n,!0)}validateSignaturesOfInput(t,r,n){const i=this.data.inputs[t];return(0,J.isTaprootInput)(i)?this.validateSignaturesOfTaprootInput(t,r,n):this._validateSignaturesOfInput(t,r,n)}_validateSignaturesOfInput(t,r,n){const i=this.data.inputs[t],c=(i||{}).partialSig;if(!i||!c||c.length<1)throw new Error("No signatures to validate");if(typeof r!="function")throw new Error("Need validator function to validate signatures");const s=n?c.filter(d=>d.pubkey.equals(n)):c;if(s.length<1)throw new Error("No signatures for this pubkey");const a=[];let p,w,f;for(const d of s){const E=Ye.signature.decode(d.signature),{hash:y,script:_}=f!==E.hashType?Ts(t,Object.assign({},i,{sighashType:E.hashType}),this.__CACHE,!0):{hash:p,script:w};f=E.hashType,p=y,w=_,Ss(d.pubkey,_,"verify"),a.push(r(d.pubkey,y,E.signature))}return a.every(d=>d===!0)}validateSignaturesOfTaprootInput(t,r,n){const i=this.data.inputs[t],c=(i||{}).tapKeySig,s=(i||{}).tapScriptSig;if(!i&&!c&&!(s&&!s.length))throw new Error("No signatures to validate");if(typeof r!="function")throw new Error("Need validator function to validate signatures");n=n&&(0,J.toXOnly)(n);const a=n?jn(t,i,this.data.inputs,n,this.__CACHE):mh(t,i,this.data.inputs,this.__CACHE);if(!a.length)throw new Error("No signatures for this pubkey");const p=a.find(f=>!f.leafHash);let w=0;if(c&&p){if(!r(p.pubkey,p.hash,ho(c)))return!1;w++}if(s)for(const f of s){const d=a.find(E=>f.pubkey.equals(E.pubkey));if(d){if(!r(f.pubkey,d.hash,ho(f.signature)))return!1;w++}}return w>0}signAllInputsHD(t,r=[we.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey||!t.fingerprint)throw new Error("Need HDSigner to sign input");const n=[];for(const i of or(this.data.inputs.length))try{this.signInputHD(i,t,r),n.push(!0)}catch{n.push(!1)}if(n.every(i=>i===!1))throw new Error("No inputs were signed");return this}signAllInputsHDAsync(t,r=[we.Transaction.SIGHASH_ALL]){return new Promise((n,i)=>{if(!t||!t.publicKey||!t.fingerprint)return i(new Error("Need HDSigner to sign input"));const c=[],s=[];for(const a of or(this.data.inputs.length))s.push(this.signInputHDAsync(a,t,r).then(()=>{c.push(!0)},()=>{c.push(!1)}));return Promise.all(s).then(()=>{if(c.every(a=>a===!1))return i(new Error("No inputs were signed"));n()})})}signInputHD(t,r,n=[we.Transaction.SIGHASH_ALL]){if(!r||!r.publicKey||!r.fingerprint)throw new Error("Need HDSigner to sign input");return po(t,this.data.inputs,r).forEach(c=>this.signInput(t,c,n)),this}signInputHDAsync(t,r,n=[we.Transaction.SIGHASH_ALL]){return new Promise((i,c)=>{if(!r||!r.publicKey||!r.fingerprint)return c(new Error("Need HDSigner to sign input"));const a=po(t,this.data.inputs,r).map(p=>this.signInputAsync(t,p,n));return Promise.all(a).then(()=>{i()}).catch(c)})}signAllInputs(t,r){if(!t||!t.publicKey)throw new Error("Need Signer to sign input");const n=[];for(const i of or(this.data.inputs.length))try{this.signInput(i,t,r),n.push(!0)}catch{n.push(!1)}if(n.every(i=>i===!1))throw new Error("No inputs were signed");return this}signAllInputsAsync(t,r){return new Promise((n,i)=>{if(!t||!t.publicKey)return i(new Error("Need Signer to sign input"));const c=[],s=[];for(const[a]of this.data.inputs.entries())s.push(this.signInputAsync(a,t,r).then(()=>{c.push(!0)},()=>{c.push(!1)}));return Promise.all(s).then(()=>{if(c.every(a=>a===!1))return i(new Error("No inputs were signed"));n()})})}signInput(t,r,n){if(!r||!r.publicKey)throw new Error("Need Signer to sign input");const i=(0,Se.checkForInput)(this.data.inputs,t);return(0,J.isTaprootInput)(i)?this._signTaprootInput(t,i,r,void 0,n):this._signInput(t,r,n)}signTaprootInput(t,r,n,i){if(!r||!r.publicKey)throw new Error("Need Signer to sign input");const c=(0,Se.checkForInput)(this.data.inputs,t);if((0,J.isTaprootInput)(c))return this._signTaprootInput(t,c,r,n,i);throw new Error(`Input #${t} is not of type Taproot.`)}_signInput(t,r,n=[we.Transaction.SIGHASH_ALL]){const{hash:i,sighashType:c}=fo(this.data.inputs,t,r.publicKey,this.__CACHE,n),s=[{pubkey:r.publicKey,signature:Ye.signature.encode(r.sign(i),c)}];return this.data.updateInput(t,{partialSig:s}),this}_signTaprootInput(t,r,n,i,c=[we.Transaction.SIGHASH_DEFAULT]){const s=this.checkTaprootHashesForSig(t,r,n,i,c),a=s.filter(w=>!w.leafHash).map(w=>(0,J.serializeTaprootSignature)(n.signSchnorr(w.hash),r.sighashType))[0],p=s.filter(w=>!!w.leafHash).map(w=>({pubkey:(0,J.toXOnly)(n.publicKey),signature:(0,J.serializeTaprootSignature)(n.signSchnorr(w.hash),r.sighashType),leafHash:w.leafHash}));return a&&this.data.updateInput(t,{tapKeySig:a}),p.length&&this.data.updateInput(t,{tapScriptSig:p}),this}signInputAsync(t,r,n){return Promise.resolve().then(()=>{if(!r||!r.publicKey)throw new Error("Need Signer to sign input");const i=(0,Se.checkForInput)(this.data.inputs,t);return(0,J.isTaprootInput)(i)?this._signTaprootInputAsync(t,i,r,void 0,n):this._signInputAsync(t,r,n)})}signTaprootInputAsync(t,r,n,i){return Promise.resolve().then(()=>{if(!r||!r.publicKey)throw new Error("Need Signer to sign input");const c=(0,Se.checkForInput)(this.data.inputs,t);if((0,J.isTaprootInput)(c))return this._signTaprootInputAsync(t,c,r,n,i);throw new Error(`Input #${t} is not of type Taproot.`)})}_signInputAsync(t,r,n=[we.Transaction.SIGHASH_ALL]){const{hash:i,sighashType:c}=fo(this.data.inputs,t,r.publicKey,this.__CACHE,n);return Promise.resolve(r.sign(i)).then(s=>{const a=[{pubkey:r.publicKey,signature:Ye.signature.encode(s,c)}];this.data.updateInput(t,{partialSig:a})})}async _signTaprootInputAsync(t,r,n,i,c=[we.Transaction.SIGHASH_DEFAULT]){const s=this.checkTaprootHashesForSig(t,r,n,i,c),a=[],p=s.filter(f=>!f.leafHash)[0];if(p){const f=Promise.resolve(n.signSchnorr(p.hash)).then(d=>({tapKeySig:(0,J.serializeTaprootSignature)(d,r.sighashType)}));a.push(f)}const w=s.filter(f=>!!f.leafHash);if(w.length){const f=w.map(d=>Promise.resolve(n.signSchnorr(d.hash)).then(E=>({tapScriptSig:[{pubkey:(0,J.toXOnly)(n.publicKey),signature:(0,J.serializeTaprootSignature)(E,r.sighashType),leafHash:d.leafHash}]})));a.push(...f)}return Promise.all(a).then(f=>{f.forEach(d=>this.data.updateInput(t,d))})}checkTaprootHashesForSig(t,r,n,i,c){if(typeof n.signSchnorr!="function")throw new Error(`Need Schnorr Signer to sign taproot input #${t}.`);const s=jn(t,r,this.data.inputs,n.publicKey,this.__CACHE,i,c);if(!s||!s.length)throw new Error(`Can not sign for input #${t} with the key ${n.publicKey.toString("hex")}`);return s}toBuffer(){return Fn(this.__CACHE),this.data.toBuffer()}toHex(){return Fn(this.__CACHE),this.data.toHex()}toBase64(){return Fn(this.__CACHE),this.data.toBase64()}updateGlobal(t){return this.data.updateGlobal(t),this}updateInput(t,r){return r.witnessScript&&Vr(r.witnessScript),(0,J.checkTaprootInputFields)(this.data.inputs[t],r,"updateInput"),this.data.updateInput(t,r),r.nonWitnessUtxo&&Vn(this.__CACHE,this.data.inputs[t],t),this}updateOutput(t,r){const n=this.data.outputs[t];return(0,J.checkTaprootOutputFields)(n,r,"updateOutput"),this.data.updateOutput(t,r),this}addUnknownKeyValToGlobal(t){return this.data.addUnknownKeyValToGlobal(t),this}addUnknownKeyValToInput(t,r){return this.data.addUnknownKeyValToInput(t,r),this}addUnknownKeyValToOutput(t,r){return this.data.addUnknownKeyValToOutput(t,r),this}clearFinalizedInput(t){return this.data.clearFinalizedInput(t),this}}cn.Psbt=jr;const fh=e=>new ms(e);class ms{constructor(t=m.from([2,0,0,0,0,0,0,0,0,0])){this.tx=we.Transaction.fromBuffer(t),dh(this.tx),Object.defineProperty(this,"tx",{enumerable:!1,writable:!0})}getInputOutputCounts(){return{inputCount:this.tx.ins.length,outputCount:this.tx.outs.length}}addInput(t){if(t.hash===void 0||t.index===void 0||!m.isBuffer(t.hash)&&typeof t.hash!="string"||typeof t.index!="number")throw new Error("Error adding input.");const r=typeof t.hash=="string"?(0,Wr.reverseBuffer)(m.from(t.hash,"hex")):t.hash;this.tx.addInput(r,t.index,t.sequence)}addOutput(t){if(t.script===void 0||t.value===void 0||!m.isBuffer(t.script)||typeof t.value!="number")throw new Error("Error adding output.");this.tx.addOutput(t.script,t.value)}toBuffer(){return this.tx.toBuffer()}}function hh(e,t,r){switch(r){case"pubkey":case"pubkeyhash":case"witnesspubkeyhash":return oo(1,e.partialSig);case"multisig":const n=ve.p2ms({output:t});return oo(n.m,e.partialSig,n.pubkeys);default:return!1}}function Fn(e){if(e.__UNSAFE_SIGN_NONSEGWIT!==!1)throw new Error("Not BIP174 compliant, can not export")}function oo(e,t,r){if(!t)return!1;let n;if(r?n=r.map(i=>{const c=Ph(i);return t.find(s=>s.pubkey.equals(c))}).filter(i=>!!i):n=t,n.length>e)throw new Error("Too many signatures");return n.length===e}function Es(e){return!!e.finalScriptSig||!!e.finalScriptWitness}function so(e){return t=>!(!t.masterFingerprint.equals(e.fingerprint)||!e.derivePath(t.path).publicKey.equals(t.pubkey))}function Br(e){if(typeof e!="number"||e!==Math.floor(e)||e>4294967295||e<0)throw new Error("Invalid 32 bit integer")}function ph(e,t,r){const n=t.__FEE_RATE||e.getFeeRate(),i=t.__EXTRACTED_TX.virtualSize(),c=n*i;if(n>=r.maximumFeeRate)throw new Error(`Warning: You are paying around ${(c/1e8).toFixed(8)} in fees, which is ${n} satoshi per byte for a transaction with a VSize of ${i} bytes (segwit counted as 0.25 byte per byte). Use setMaximumFeeRate method to raise your threshold, or pass true to the first arg of extractTransaction.`)}function ir(e,t){e.forEach(r=>{if((0,J.isTaprootInput)(r)?(0,J.checkTaprootInputForSigs)(r,t):(0,re.checkInputForSig)(r,t))throw new Error("Can not modify transaction, signatures exist.")})}function lh(e){if(!e.sighashType||!e.partialSig)return;const{partialSig:t,sighashType:r}=e;t.forEach(n=>{const{hashType:i}=Ye.signature.decode(n.signature);if(r!==i)throw new Error("Signature sighash does not match input sighash type")})}function Ss(e,t,r){if(!(0,re.pubkeyInScript)(e,t))throw new Error(`Can not ${r} for this input with the key ${e.toString("hex")}`)}function dh(e){if(!e.ins.every(r=>r.script&&r.script.length===0&&r.witness&&r.witness.length===0))throw new Error("Format Error: Transaction ScriptSigs are not empty")}function yh(e,t){e.ins.forEach(r=>{bs(t,r)})}function bs(e,t){const r=(0,Wr.reverseBuffer)(m.from(t.hash)).toString("hex")+":"+t.index;if(e.__TX_IN_CACHE[r])throw new Error("Duplicate input detected.");e.__TX_IN_CACHE[r]=1}function _s(e,t){return(r,n,i,c)=>{const s=e({redeem:{output:i}}).output;if(!n.equals(s))throw new Error(`${t} for ${c} #${r} doesn't match the scriptPubKey in the prevout`)}}const co=_s(ve.p2sh,"Redeem script"),uo=_s(ve.p2wsh,"Witness script");function ao(e,t,r,n){if(!r.every(Es))throw new Error(`PSBT must be finalized to calculate ${t}`);if(e==="__FEE_RATE"&&n.__FEE_RATE)return n.__FEE_RATE;if(e==="__FEE"&&n.__FEE)return n.__FEE;let i,c=!0;if(n.__EXTRACTED_TX?(i=n.__EXTRACTED_TX,c=!1):i=n.__TX.clone(),Ps(r,i,n,c),e==="__FEE_RATE")return n.__FEE_RATE;if(e==="__FEE")return n.__FEE}function wh(e,t,r,n,i,c){const s=Bs(r);if(!hh(t,r,s))throw new Error(`Can not finalize input #${e}`);return gh(r,s,t.partialSig,n,i,c)}function gh(e,t,r,n,i,c){let s,a;const p=Eh(e,t,r),w=c?ve.p2wsh({redeem:p}):null,f=i?ve.p2sh({redeem:w||p}):null;return n?(w?a=(0,re.witnessStackToScriptWitness)(w.witness):a=(0,re.witnessStackToScriptWitness)(p.witness),f&&(s=f.input)):f?s=f.input:s=p.input,{finalScriptSig:s,finalScriptWitness:a}}function fo(e,t,r,n,i){const c=(0,Se.checkForInput)(e,t),{hash:s,sighashType:a,script:p}=Ts(t,c,n,!1,i);return Ss(r,p,"sign"),{hash:s,sighashType:a}}function Ts(e,t,r,n,i){const c=r.__TX,s=t.sighashType||we.Transaction.SIGHASH_ALL;ks(s,i);let a,p;if(t.nonWitnessUtxo){const d=hn(r,t,e),E=c.ins[e].hash,y=d.getHash();if(!E.equals(y))throw new Error(`Non-witness UTXO hash for input #${e} doesn't match the hash specified in the prevout`);const _=c.ins[e].index;p=d.outs[_]}else if(t.witnessUtxo)p=t.witnessUtxo;else throw new Error("Need a Utxo input item for signing");const{meaningfulScript:w,type:f}=pn(p.script,e,"input",t.redeemScript,t.witnessScript);if(["p2sh-p2wsh","p2wsh"].indexOf(f)>=0)a=c.hashForWitnessV0(e,w,p.value,s);else if((0,re.isP2WPKH)(w)){const d=ve.p2pkh({hash:w.slice(2)}).output;a=c.hashForWitnessV0(e,d,p.value,s)}else{if(t.nonWitnessUtxo===void 0&&r.__UNSAFE_SIGN_NONSEGWIT===!1)throw new Error(`Input #${e} has witnessUtxo but non-segwit script: ${w.toString("hex")}`);!n&&r.__UNSAFE_SIGN_NONSEGWIT!==!1&&console.warn(`Warning: Signing non-segwit inputs without the full parent transaction means there is a chance that a miner could feed you incorrect information to trick you into paying large fees. This behavior is the same as Psbt's predecessor (TransactionBuilder - now removed) when signing non-segwit scripts. You are not able to export this Psbt with toBuffer|toBase64|toHex since it is not BIP174 compliant. ********************* PROCEED WITH CAUTION! -*********************`),a=c.hashForSignature(e,w,s)}return{script:w,sighashType:s,hash:a}}function yh(e,t,r,n){const i=[];if(t.tapInternalKey){const s=_s(e,t,n);s&&i.push(s)}if(t.tapScriptSig){const s=t.tapScriptSig.map(a=>a.pubkey);i.push(...s)}return i.map(s=>Wn(e,t,r,s,n)).flat()}function _s(e,t,r){const{script:n}=wi(e,t,r);return(0,re.isP2TR)(n)?n.subarray(2,34):null}function fo(e){return e.length===64?e:e.subarray(0,64)}function Wn(e,t,r,n,i,c,s){const a=i.__TX,p=t.sighashType||we.Transaction.SIGHASH_DEFAULT;Ts(p,s);const w=r.map((_,T)=>wi(T,_,i)),f=w.map(_=>_.script),d=w.map(_=>_.value),S=[];if(t.tapInternalKey&&!c){const _=_s(e,t,i)||E.from([]);if((0,J.toXOnly)(n).equals(_)){const T=a.hashForWitnessV1(e,f,d,p);S.push({pubkey:n,hash:T})}}const y=(t.tapLeafScript||[]).filter(_=>(0,re.pubkeyInScript)(n,_.script)).map(_=>{const T=(0,oh.tapleafHash)({output:_.script,version:_.leafVersion});return Object.assign({hash:T},_)}).filter(_=>!c||c.equals(_.hash)).map(_=>{const T=a.hashForWitnessV1(e,f,d,p,_.hash);return{pubkey:n,hash:T,leafHash:_.hash}});return S.concat(y)}function Ts(e,t){if(t&&t.indexOf(e)<0){const r=mh(e);throw new Error(`Sighash type is not allowed. Retry the sign method passing the sighashTypes array of whitelisted types. Sighash type: ${r}`)}}function wh(e,t,r){let n;switch(t){case"multisig":const i=Eh(e,r);n=ve.p2ms({output:e,signatures:i});break;case"pubkey":n=ve.p2pk({output:e,signature:r[0].signature});break;case"pubkeyhash":n=ve.p2pkh({output:e,pubkey:r[0].pubkey,signature:r[0].signature});break;case"witnesspubkeyhash":n=ve.p2wpkh({output:e,pubkey:r[0].pubkey,signature:r[0].signature});break}return n}function gh(e,t,r){const n=r.__TX,i={script:null,isSegwit:!1,isP2SH:!1,isP2WSH:!1};if(i.isP2SH=!!t.redeemScript,i.isP2WSH=!!t.witnessScript,t.witnessScript)i.script=t.witnessScript;else if(t.redeemScript)i.script=t.redeemScript;else if(t.nonWitnessUtxo){const c=fn(r,t,e),s=n.ins[e].index;i.script=c.outs[s].script}else t.witnessUtxo&&(i.script=t.witnessUtxo.script);return(t.witnessScript||(0,re.isP2WPKH)(i.script))&&(i.isSegwit=!0),i}function ho(e,t,r){const n=(0,Se.checkForInput)(t,e);if(!n.bip32Derivation||n.bip32Derivation.length===0)throw new Error("Need bip32Derivation to sign with HD");const i=n.bip32Derivation.map(s=>{if(s.masterFingerprint.equals(r.fingerprint))return s}).filter(s=>!!s);if(i.length===0)throw new Error("Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint");return i.map(s=>{const a=r.derivePath(s.path);if(!s.pubkey.equals(a.publicKey))throw new Error("pubkey did not match bip32Derivation");return a})}function Eh(e,t){return ve.p2ms({output:e}).pubkeys.map(n=>(t.filter(i=>i.pubkey.equals(n))[0]||{}).signature).filter(n=>!!n)}function Is(e){let t=0;function r(s){return t+=s,e.slice(t-s,t)}function n(){const s=ro.decode(e,t);return t+=ro.decode.bytes,s}function i(){return r(n())}function c(){const s=n(),a=[];for(let p=0;p{if(n&&p.finalScriptSig&&(t.ins[w].script=p.finalScriptSig),n&&p.finalScriptWitness&&(t.ins[w].witness=Is(p.finalScriptWitness)),p.witnessUtxo)i+=p.witnessUtxo.value;else if(p.nonWitnessUtxo){const f=fn(r,p,w),d=t.ins[w].index,S=f.outs[d];i+=S.value}});const c=t.outs.reduce((p,w)=>p+w.value,0),s=i-c;if(s<0)throw new Error("Outputs are spending more than Inputs");const a=t.virtualSize();r.__FEE=s,r.__EXTRACTED_TX=t,r.__FEE_RATE=Math.floor(s/a)}function fn(e,t,r){const n=e.__NON_WITNESS_UTXO_TX_CACHE;return n[r]||jn(e,t,r),n[r]}function As(e,t,r){const{script:n}=wi(e,t,r);return n}function wi(e,t,r){if(t.witnessUtxo!==void 0)return{script:t.witnessUtxo.script,value:t.witnessUtxo.value};if(t.nonWitnessUtxo!==void 0){const i=fn(r,t,e).outs[r.__TX.ins[e].index];return{script:i.script,value:i.value}}else throw new Error("Can't find pubkey in input without Utxo data")}function Sh(e,t,r,n){const i=As(r,t,n),{meaningfulScript:c}=hn(i,r,"input",t.redeemScript,t.witnessScript);return(0,re.pubkeyInScript)(e,c)}function bh(e,t,r,n){const i=n.__TX.outs[r].script,{meaningfulScript:c}=hn(i,r,"output",t.redeemScript,t.witnessScript);return(0,re.pubkeyInScript)(e,c)}function _h(e){if(!e)return;const t=Ye.decompile(e);if(!t)return;const r=t[t.length-1];if(!(!E.isBuffer(r)||Os(r)||kh(r)||!Ye.decompile(r)))return r}function Th(e){if(!e)return;const t=Is(e),r=t[t.length-1];if(!(Os(r)||!Ye.decompile(r)))return r}function Ih(e){if(e.length===65){const t=e[64]&1,r=e.slice(0,33);return r[0]=2|t,r}return e.slice()}function Os(e){return e.length===33&&Ye.isCanonicalPubKey(e)}function kh(e){return Ye.isCanonicalScriptSignature(e)}function hn(e,t,r,n,i){const c=(0,re.isP2SHScript)(e),s=c&&n&&(0,re.isP2WSHScript)(n),a=(0,re.isP2WSHScript)(e);if(c&&n===void 0)throw new Error("scriptPubkey is P2SH but redeemScript missing");if((a||s)&&i===void 0)throw new Error("scriptPubkey or redeemScript is P2WSH but witnessScript missing");let p;return s?(p=i,so(t,e,n,r),co(t,n,i,r),jr(p)):a?(p=i,co(t,e,i,r),jr(p)):c?(p=n,so(t,e,n,r)):p=e,{meaningfulScript:p,type:s?"p2sh-p2wsh":c?"p2sh":a?"p2wsh":"raw"}}function jr(e){if((0,re.isP2WPKH)(e)||(0,re.isP2SHScript)(e))throw new Error("P2WPKH or P2SH can not be contained within P2WSH")}function Ps(e){return(0,re.isP2WPKH)(e)?"witnesspubkeyhash":(0,re.isP2PKH)(e)?"pubkeyhash":(0,re.isP2MS)(e)?"multisig":(0,re.isP2PK)(e)?"pubkey":"nonstandard"}function sr(e){return[...Array(e).keys()]}(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.initEccLib=e.Transaction=e.opcodes=e.Psbt=e.Block=e.script=e.payments=e.networks=e.crypto=e.address=void 0;const t=ri();e.address=t;const r=Ke;e.crypto=r;const n=ae;e.networks=n;const i=mr();e.payments=i;const c=_e();e.script=c;var s=nn;Object.defineProperty(e,"Block",{enumerable:!0,get:function(){return s.Block}});var a=sn;Object.defineProperty(e,"Psbt",{enumerable:!0,get:function(){return a.Psbt}});var p=ft;Object.defineProperty(e,"opcodes",{enumerable:!0,get:function(){return p.OPS}});var w=lt;Object.defineProperty(e,"Transaction",{enumerable:!0,get:function(){return w.Transaction}});var f=ht;Object.defineProperty(e,"initEccLib",{enumerable:!0,get:function(){return f.initEccLib}})})(lo);const vs={BTC:["https://mempool.space/api/tx","https://blockstream.info/api/tx"],XTN:["https://mempool.space/testnet/api/tx","https://blockstream.info/testnet/api/tx"]},Ah={BTC:[["mempool.space","https://mempool.space/tx/"],["blockstream.info","https://blockstream.info/tx/"],["btcscan.org","https://btcscan.org/tx/"],["btc.com","https://explorer.btc.com/btc/transaction/"]],XTN:[["mempool.space","https://mempool.space/testnet/tx/"],["blockstream.info","https://blockstream.info/testnet/tx/"],["blockcypher.com","https://live.blockcypher.com/btc-testnet/tx/"]]},Oh={success:` +*********************`),a=c.hashForSignature(e,w,s)}return{script:w,sighashType:s,hash:a}}function mh(e,t,r,n){const i=[];if(t.tapInternalKey){const s=Is(e,t,n);s&&i.push(s)}if(t.tapScriptSig){const s=t.tapScriptSig.map(a=>a.pubkey);i.push(...s)}return i.map(s=>jn(e,t,r,s,n)).flat()}function Is(e,t,r){const{script:n}=gi(e,t,r);return(0,re.isP2TR)(n)?n.subarray(2,34):null}function ho(e){return e.length===64?e:e.subarray(0,64)}function jn(e,t,r,n,i,c,s){const a=i.__TX,p=t.sighashType||we.Transaction.SIGHASH_DEFAULT;ks(p,s);const w=r.map((_,T)=>gi(T,_,i)),f=w.map(_=>_.script),d=w.map(_=>_.value),E=[];if(t.tapInternalKey&&!c){const _=Is(e,t,i)||m.from([]);if((0,J.toXOnly)(n).equals(_)){const T=a.hashForWitnessV1(e,f,d,p);E.push({pubkey:n,hash:T})}}const y=(t.tapLeafScript||[]).filter(_=>(0,re.pubkeyInScript)(n,_.script)).map(_=>{const T=(0,uh.tapleafHash)({output:_.script,version:_.leafVersion});return Object.assign({hash:T},_)}).filter(_=>!c||c.equals(_.hash)).map(_=>{const T=a.hashForWitnessV1(e,f,d,p,_.hash);return{pubkey:n,hash:T,leafHash:_.hash}});return E.concat(y)}function ks(e,t){if(t&&t.indexOf(e)<0){const r=_h(e);throw new Error(`Sighash type is not allowed. Retry the sign method passing the sighashTypes array of whitelisted types. Sighash type: ${r}`)}}function Eh(e,t,r){let n;switch(t){case"multisig":const i=bh(e,r);n=ve.p2ms({output:e,signatures:i});break;case"pubkey":n=ve.p2pk({output:e,signature:r[0].signature});break;case"pubkeyhash":n=ve.p2pkh({output:e,pubkey:r[0].pubkey,signature:r[0].signature});break;case"witnesspubkeyhash":n=ve.p2wpkh({output:e,pubkey:r[0].pubkey,signature:r[0].signature});break}return n}function Sh(e,t,r){const n=r.__TX,i={script:null,isSegwit:!1,isP2SH:!1,isP2WSH:!1};if(i.isP2SH=!!t.redeemScript,i.isP2WSH=!!t.witnessScript,t.witnessScript)i.script=t.witnessScript;else if(t.redeemScript)i.script=t.redeemScript;else if(t.nonWitnessUtxo){const c=hn(r,t,e),s=n.ins[e].index;i.script=c.outs[s].script}else t.witnessUtxo&&(i.script=t.witnessUtxo.script);return(t.witnessScript||(0,re.isP2WPKH)(i.script))&&(i.isSegwit=!0),i}function po(e,t,r){const n=(0,Se.checkForInput)(t,e);if(!n.bip32Derivation||n.bip32Derivation.length===0)throw new Error("Need bip32Derivation to sign with HD");const i=n.bip32Derivation.map(s=>{if(s.masterFingerprint.equals(r.fingerprint))return s}).filter(s=>!!s);if(i.length===0)throw new Error("Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint");return i.map(s=>{const a=r.derivePath(s.path);if(!s.pubkey.equals(a.publicKey))throw new Error("pubkey did not match bip32Derivation");return a})}function bh(e,t){return ve.p2ms({output:e}).pubkeys.map(n=>(t.filter(i=>i.pubkey.equals(n))[0]||{}).signature).filter(n=>!!n)}function As(e){let t=0;function r(s){return t+=s,e.slice(t-s,t)}function n(){const s=no.decode(e,t);return t+=no.decode.bytes,s}function i(){return r(n())}function c(){const s=n(),a=[];for(let p=0;p{if(n&&p.finalScriptSig&&(t.ins[w].script=p.finalScriptSig),n&&p.finalScriptWitness&&(t.ins[w].witness=As(p.finalScriptWitness)),p.witnessUtxo)i+=p.witnessUtxo.value;else if(p.nonWitnessUtxo){const f=hn(r,p,w),d=t.ins[w].index,E=f.outs[d];i+=E.value}});const c=t.outs.reduce((p,w)=>p+w.value,0),s=i-c;if(s<0)throw new Error("Outputs are spending more than Inputs");const a=t.virtualSize();r.__FEE=s,r.__EXTRACTED_TX=t,r.__FEE_RATE=Math.floor(s/a)}function hn(e,t,r){const n=e.__NON_WITNESS_UTXO_TX_CACHE;return n[r]||Vn(e,t,r),n[r]}function Os(e,t,r){const{script:n}=gi(e,t,r);return n}function gi(e,t,r){if(t.witnessUtxo!==void 0)return{script:t.witnessUtxo.script,value:t.witnessUtxo.value};if(t.nonWitnessUtxo!==void 0){const i=hn(r,t,e).outs[r.__TX.ins[e].index];return{script:i.script,value:i.value}}else throw new Error("Can't find pubkey in input without Utxo data")}function Th(e,t,r,n){const i=Os(r,t,n),{meaningfulScript:c}=pn(i,r,"input",t.redeemScript,t.witnessScript);return(0,re.pubkeyInScript)(e,c)}function Ih(e,t,r,n){const i=n.__TX.outs[r].script,{meaningfulScript:c}=pn(i,r,"output",t.redeemScript,t.witnessScript);return(0,re.pubkeyInScript)(e,c)}function kh(e){if(!e)return;const t=Ye.decompile(e);if(!t)return;const r=t[t.length-1];if(!(!m.isBuffer(r)||vs(r)||Oh(r)||!Ye.decompile(r)))return r}function Ah(e){if(!e)return;const t=As(e),r=t[t.length-1];if(!(vs(r)||!Ye.decompile(r)))return r}function Ph(e){if(e.length===65){const t=e[64]&1,r=e.slice(0,33);return r[0]=2|t,r}return e.slice()}function vs(e){return e.length===33&&Ye.isCanonicalPubKey(e)}function Oh(e){return Ye.isCanonicalScriptSignature(e)}function pn(e,t,r,n,i){const c=(0,re.isP2SHScript)(e),s=c&&n&&(0,re.isP2WSHScript)(n),a=(0,re.isP2WSHScript)(e);if(c&&n===void 0)throw new Error("scriptPubkey is P2SH but redeemScript missing");if((a||s)&&i===void 0)throw new Error("scriptPubkey or redeemScript is P2WSH but witnessScript missing");let p;return s?(p=i,co(t,e,n,r),uo(t,n,i,r),Vr(p)):a?(p=i,uo(t,e,i,r),Vr(p)):c?(p=n,co(t,e,n,r)):p=e,{meaningfulScript:p,type:s?"p2sh-p2wsh":c?"p2sh":a?"p2wsh":"raw"}}function Vr(e){if((0,re.isP2WPKH)(e)||(0,re.isP2SHScript)(e))throw new Error("P2WPKH or P2SH can not be contained within P2WSH")}function Bs(e){return(0,re.isP2WPKH)(e)?"witnesspubkeyhash":(0,re.isP2PKH)(e)?"pubkeyhash":(0,re.isP2MS)(e)?"multisig":(0,re.isP2PK)(e)?"pubkey":"nonstandard"}function or(e){return[...Array(e).keys()]}(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.initEccLib=e.Transaction=e.opcodes=e.Psbt=e.Block=e.script=e.payments=e.networks=e.crypto=e.address=void 0;const t=ni();e.address=t;const r=Ke;e.crypto=r;const n=ae;e.networks=n;const i=mr();e.payments=i;const c=_e();e.script=c;var s=on;Object.defineProperty(e,"Block",{enumerable:!0,get:function(){return s.Block}});var a=cn;Object.defineProperty(e,"Psbt",{enumerable:!0,get:function(){return a.Psbt}});var p=ft;Object.defineProperty(e,"opcodes",{enumerable:!0,get:function(){return p.OPS}});var w=lt;Object.defineProperty(e,"Transaction",{enumerable:!0,get:function(){return w.Transaction}});var f=ht;Object.defineProperty(e,"initEccLib",{enumerable:!0,get:function(){return f.initEccLib}})})(wo);const xs={BTC:["https://mempool.space/api/tx","https://blockstream.info/api/tx"],XTN:["https://mempool.space/testnet/api/tx","https://blockstream.info/testnet/api/tx"]},vh={BTC:[["mempool.space","https://mempool.space/tx/"],["blockstream.info","https://blockstream.info/tx/"],["btcscan.org","https://btcscan.org/tx/"],["btc.com","https://explorer.btc.com/btc/transaction/"]],XTN:[["mempool.space","https://mempool.space/testnet/tx/"],["blockstream.info","https://blockstream.info/testnet/tx/"],["blockcypher.com","https://live.blockcypher.com/btc-testnet/tx/"]]},Bh={success:` @@ -25,87 +25,4 @@ PROCEED WITH CAUTION! - `};async function dr(e){try{return[null,await e]}catch(t){return t instanceof Error?[t,null]:typeof t=="string"?[new Error(t),null]:[new Error,null]}}function po(e){const t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(e.length+(4-e.length%4)%4,"="),r=atob(t);return new Uint8Array([...r].map(n=>n.charCodeAt(0)))}class Bs extends Error{constructor(r,n,i,c){super();Zt(this,"url");Zt(this,"status");Zt(this,"statusText");Zt(this,"body");this.url=r,this.name="FetchStatusError",this.status=n,this.statusText=i,this.body=c}}const xs=async(e,t)=>{const r=await fetch(e,t);if(!r.ok){const[n,i]=await dr(r.text());throw new Bs(e.toString(),r.status,r.statusText,i)}return r};async function Ph(e,t){if(t!=="BTC"&&t!=="XTN")throw new Error("Unsupported network: "+t);const n=vs[t].map(s=>xs(s,{method:"POST",body:e.toHex()})),[i,c]=await dr(Promise.any(n).then(s=>s.text()));if(c)return c;if(i instanceof AggregateError){const s=i.errors.filter(a=>a instanceof Bs);if(s.length>0){let a=` -

The transaction was rejected by all providers:

- -
    - `;throw s.forEach(p=>{a+=`
  • ${p.url}: ${p.body}
  • `}),a+="
",new Error(a)}}throw new Error("

Could not connect to any push servers. Make sure you are connected to the Internet and try again.

")}async function vh(e){e[0]==="#"&&(e=e.slice(1));const t=new URLSearchParams(e),r=t.get("t"),n=t.get("c"),i=t.get("n")||"BTC";if(!r)throw new Error("Invalid URL - missing transaction.");if(!n||n.length!==11)throw new Error("Invalid URL - missing or incomplete checksum. The URL is probably truncated");let c;if(i==="BTC"||i==="XTN")c=i;else throw i==="XRT"?new Error("Regtest transactions are not supported."):new Error(`Invalid URL. The network "${i}" is not recognized.`);let s,a;try{s=po(r),a=po(n)}catch{throw new Error("Invalid URL encoding. The URL is probably corrupted.")}const p=new Uint8Array(await crypto.subtle.digest("SHA-256",s));if(!a.every((f,d)=>f===p[d+24]))throw new Error("Checksum mismatch in URL. Some bytes corrupted in transit. Try again.");return{tx:lo.Transaction.fromBuffer(wo.from(s)),network:c}}async function Bh(e,t){if(t!=="BTC"&&t!=="XTN")throw new Error("Unsupported network: "+t);const n=vs[t].map(i=>xs(i+"/"+e).then(c=>c.json()));return await Promise.any(n)}function xh(e){const t=e.vin.map(n=>` - - - - ${n.prevout.scriptpubkey_address.slice(0,-8)} - ${n.prevout.scriptpubkey_address.slice(-8)} - - - - ${(n.prevout.value/1e8).toFixed(8)} - - - `).join(""),r=e.vout.map(n=>` - - - - ${n.scriptpubkey_address.slice(0,-8)} - ${n.scriptpubkey_address.slice(-8)} - - - - ${(n.value/1e8).toFixed(8)} - - - `).join("");return` -
-
- - - - - - - - - ${t} - -
Inputs
-
- -
- - - - - - - - - - ${r} - -
Outputs
-
- -
- Fee: ${(e.fee/1e8).toFixed(8)} -
-
- `}function Kt(e,t){const r=Oh[e];return` - - `}async function Us(){const e=document.querySelector(".pushtx-message-area"),t=document.querySelector(".pushtx-details-area");if(!e||!t)throw new Error("Need message and details areas in HTML.");if(e.innerHTML="",t.innerHTML="",!window.location.hash){const S=` -

Did you get here by accident?

-

- This page is meant to be loaded together with transaction data using the - COLDCARD NFC Push TX feature. The complete URL should look something like this (but longer): -

- -

${window.location.origin+window.location.pathname}#t=AgAAAAMNCxXtp2GVYVhkRXHLMmdZFs4p3kbFK ⋯ ABf&c=uiSVRda-1tw

- `;e.innerHTML=Kt("info",S);return}e.innerHTML=Kt("progress","Sending transaction, please wait...");const[r,n]=await dr(vh(window.location.hash));if(r){e.innerHTML=Kt("error",r.message);return}const{tx:i,network:c}=n,s=i.getId(),[a,p]=await dr(Ph(i,c)),[w,f]=await dr(Bh(s,c));if(p||f){const d=f!=null&&f.status.confirmed?"This transaction has already been confirmed.":"The transaction has been sent and is waiting to be confirmed.",S=Ah[c].map(([y,_])=>`
  • ${y}
  • `).join("");e.innerHTML=Kt("success",`

    ${d} Transaction ID:

    - -

    ${s}

    - -

    Verify on a block explorer:

    - -
      ${S}
    - `),f&&(t.innerHTML=xh(f));return}if(a&&w)e.innerHTML=Kt("error",a.message);else if(w){e.innerHTML=Kt("error",w.message);return}}Us();window.addEventListener("hashchange",Us); + `};async function lr(e){try{return[null,await e]}catch(t){return t instanceof Error?[t,null]:typeof t=="string"?[new Error(t),null]:[new Error,null]}}function lo(e){const t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(e.length+(4-e.length%4)%4,"="),r=atob(t);return new Uint8Array([...r].map(n=>n.charCodeAt(0)))}class Us extends Error{constructor(r,n,i,c){super();Lt(this,"url");Lt(this,"status");Lt(this,"statusText");Lt(this,"body");this.url=r,this.name="FetchStatusError",this.status=n,this.statusText=i,this.body=c}}class Cs extends Error{constructor(r){super("The transaction was rejected by all providers.");Lt(this,"details");this.details=r}}const Ns=async(e,t)=>{const r=await fetch(e,t);if(!r.ok){const[n,i]=await lr(r.text());throw new Us(e.toString(),r.status,r.statusText,i)}return r};async function xh(e,t){if(t!=="BTC"&&t!=="XTN")throw new Error("Unsupported network: "+t);const n=xs[t].map(s=>Ns(s,{method:"POST",body:e.toHex()})),[i,c]=await lr(Promise.any(n).then(s=>s.text()));if(c)return c;if(i instanceof AggregateError){const s=i.errors.filter(a=>a instanceof Us);if(s.length>0)throw new Cs(s.map(a=>({url:a.url,body:a.body})))}throw new Error("Could not connect to any push servers. Make sure you are connected to the Internet and try again.")}async function Uh(e){e[0]==="#"&&(e=e.slice(1));const t=new URLSearchParams(e),r=t.get("t"),n=t.get("c"),i=t.get("n")||"BTC";if(!r)throw new Error("Invalid URL - missing transaction.");if(!n||n.length!==11)throw new Error("Invalid URL - missing or incomplete checksum. The URL is probably truncated");let c;if(i==="BTC"||i==="XTN")c=i;else throw i==="XRT"?new Error("Regtest transactions are not supported."):new Error("Invalid URL. The network parameter is not recognized.");let s,a;try{s=lo(r),a=lo(n)}catch{throw new Error("Invalid URL encoding. The URL is probably corrupted.")}const p=new Uint8Array(await crypto.subtle.digest("SHA-256",s));if(!a.every((f,d)=>f===p[d+24]))throw new Error("Checksum mismatch in URL. Some bytes corrupted in transit. Try again.");return{tx:wo.Transaction.fromBuffer(mo.from(s)),network:c}}async function Ch(e,t){if(t!=="BTC"&&t!=="XTN")throw new Error("Unsupported network: "+t);const n=xs[t].map(i=>Ns(i+"/"+e).then(c=>c.json()));return await Promise.any(n)}function yo(e,t){const r=document.createElement("tr"),n=document.createElement("td"),i=document.createElement("span");i.className="address";const c=document.createElement("span");c.textContent=e.slice(0,-8);const s=document.createElement("span");s.textContent=e.slice(-8),i.appendChild(c),i.appendChild(s),n.appendChild(i),r.appendChild(n);const a=document.createElement("td"),p=document.createElement("span");return p.className="value",p.textContent=(t/1e8).toFixed(8),a.appendChild(p),r.appendChild(a),r}function Nh(e){const t=document.createElement("div");t.className="pushtx-details";const r=(p,w)=>{const f=document.createElement("div"),d=document.createElement("table"),E=document.createElement("thead"),y=document.createElement("tr"),_=document.createElement("th");_.textContent=p;const T=document.createElement("th");y.appendChild(_),y.appendChild(T),E.appendChild(y),d.appendChild(E);const A=document.createElement("tbody");return w.forEach(x=>A.appendChild(x)),d.appendChild(A),f.appendChild(d),f},n=e.vin.map(p=>yo(p.prevout.scriptpubkey_address,p.prevout.value));t.appendChild(r("Inputs",n));const i=e.vout.map(p=>yo(p.scriptpubkey_address,p.value));t.appendChild(r("Outputs",i));const c=document.createElement("div");c.className="fee";const s=document.createElement("strong");s.textContent="Fee:";const a=document.createElement("span");return a.className="value",a.textContent=(e.fee/1e8).toFixed(8),c.appendChild(s),c.appendChild(document.createTextNode(" ")),c.appendChild(a),t.appendChild(c),t}function Fr(e,t){const r=document.createElement("div");r.className=`pushtx-message pushtx-message--${e}`,r.setAttribute("role","alert");const n=document.createElement("div");n.innerHTML=Bh[e],r.appendChild(n);const i=document.createElement("div");return i.appendChild(t),r.appendChild(i),r}function xr(e,t){const r=document.createDocumentFragment();return r.appendChild(document.createTextNode(t)),Fr(e,r)}async function Hs(){const e=document.querySelector(".pushtx-message-area"),t=document.querySelector(".pushtx-details-area");if(!e||!t)throw new Error("Need message and details areas in HTML.");if(e.replaceChildren(),t.replaceChildren(),!window.location.hash){const d=window.location.origin+window.location.pathname,E=document.createDocumentFragment(),y=document.createElement("p"),_=document.createElement("strong");_.textContent="Did you get here by accident?",y.appendChild(_),E.appendChild(y);const T=document.createElement("p");T.textContent="This page is meant to be loaded together with transaction data using the ";const A=document.createElement("strong");A.textContent="COLDCARD NFC Push TX feature",T.appendChild(A),T.appendChild(document.createTextNode(". The complete URL should look something like this (but longer):")),E.appendChild(T);const x=document.createElement("p"),U=document.createElement("code");U.textContent=`${d}#t=AgAAAAMNCxXtp2GVYVhkRXHLMmdZFs4p3kbFK ⋯ ABf&c=uiSVRda-1tw`,x.appendChild(U),E.appendChild(x),e.replaceChildren(Fr("info",E));return}e.replaceChildren(xr("progress","Sending transaction, please wait..."));const[r,n]=await lr(Uh(window.location.hash));if(r){e.replaceChildren(xr("error",r.message));return}const{tx:i,network:c}=n,s=i.getId(),[a,p]=await lr(xh(i,c)),[w,f]=await lr(Ch(s,c));if(p||f){const d=f!=null&&f.status.confirmed?"This transaction has already been confirmed.":"The transaction has been sent and is waiting to be confirmed.",E=document.createDocumentFragment(),y=document.createElement("p");y.textContent=`${d} Transaction ID:`,E.appendChild(y);const _=document.createElement("p");_.className="txid",_.textContent=s,E.appendChild(_);const T=document.createElement("p");T.textContent="Verify on a block explorer:",E.appendChild(T);const A=document.createElement("ul");vh[c].forEach(([x,U])=>{const I=document.createElement("li"),S=document.createElement("a");S.href=`${U}${s}`,S.target="_blank",S.rel="noopener",S.textContent=x,I.appendChild(S),A.appendChild(I)}),E.appendChild(A),e.replaceChildren(Fr("success",E)),f&&t.replaceChildren(Nh(f));return}if(a&&w)if(a instanceof Cs){const d=document.createDocumentFragment(),E=document.createElement("p");E.textContent=a.message,d.appendChild(E);const y=document.createElement("ul");a.details.forEach(_=>{const T=document.createElement("li");T.textContent=`${_.url}: ${_.body??""}`,y.appendChild(T)}),d.appendChild(y),e.replaceChildren(Fr("error",d))}else e.replaceChildren(xr("error",a.message));else if(w){e.replaceChildren(xr("error",w.message));return}}Hs();window.addEventListener("hashchange",Hs); diff --git a/cc-implementation/index.html b/cc-implementation/index.html index e6e0b13..5d065a6 100644 --- a/cc-implementation/index.html +++ b/cc-implementation/index.html @@ -4,6 +4,10 @@ + COLDCARD NFC Push TX diff --git a/cc-implementation/src/main.ts b/cc-implementation/src/main.ts index 8f98f02..32623d8 100644 --- a/cc-implementation/src/main.ts +++ b/cc-implementation/src/main.ts @@ -53,6 +53,19 @@ class FetchStatusError extends Error { } } +/** + * Carries provider-specific rejection details so the UI can render them + * as plain text instead of embedding them in an HTML string. + */ +class ProviderErrorsError extends Error { + details: { url: string; body: string | null }[]; + + constructor(details: { url: string; body: string | null }[]) { + super('The transaction was rejected by all providers.'); + this.details = details; + } +} + /** * Wrapper around fetch that throws an error if the response is not 2xx. */ @@ -93,24 +106,14 @@ async function pushTx(tx: Transaction, network: Network): Promise { ); if (fetchStatusErrors.length > 0) { - let errMsg = ` -

    The transaction was rejected by all providers:

    - -
      - `; - - fetchStatusErrors.forEach((e) => { - errMsg += `
    • ${e.url}: ${e.body}
    • `; - }); - - errMsg += `
    `; - - throw new Error(errMsg); + throw new ProviderErrorsError( + fetchStatusErrors.map((e) => ({ url: e.url, body: e.body })) + ); } } throw new Error( - `

    Could not connect to any push servers. Make sure you are connected to the Internet and try again.

    ` + 'Could not connect to any push servers. Make sure you are connected to the Internet and try again.' ); } @@ -144,7 +147,7 @@ async function parseFragment(fragment: string) { } else if (n === 'XRT') { throw new Error('Regtest transactions are not supported.'); } else { - throw new Error(`Invalid URL. The network "${n}" is not recognized.`); + throw new Error('Invalid URL. The network parameter is not recognized.'); } let txBytes: Uint8Array; @@ -189,97 +192,121 @@ async function fetchTxData(txid: string, network: Network): Promise { - return ` - - - - ${input.prevout.scriptpubkey_address.slice(0, -8)} - ${input.prevout.scriptpubkey_address.slice(-8)} - - - - ${(input.prevout.value / 1e8).toFixed(8)} - - - `; - }) - .join(''); +function createTxRow(address: string, value: number): HTMLTableRowElement { + const row = document.createElement('tr'); - const outputRows = txData.vout - .map((output) => { - return ` - - - - ${output.scriptpubkey_address.slice(0, -8)} - ${output.scriptpubkey_address.slice(-8)} - - - - ${(output.value / 1e8).toFixed(8)} - - - `; - }) - .join(''); + const addressCell = document.createElement('td'); + const addressSpan = document.createElement('span'); + addressSpan.className = 'address'; + const addressStart = document.createElement('span'); + addressStart.textContent = address.slice(0, -8); + const addressEnd = document.createElement('span'); + addressEnd.textContent = address.slice(-8); + addressSpan.appendChild(addressStart); + addressSpan.appendChild(addressEnd); + addressCell.appendChild(addressSpan); + row.appendChild(addressCell); - return ` -
    -
    - - - - - - - - - ${inputRows} - -
    Inputs
    -
    + const valueCell = document.createElement('td'); + const valueSpan = document.createElement('span'); + valueSpan.className = 'value'; + valueSpan.textContent = (value / 1e8).toFixed(8); + valueCell.appendChild(valueSpan); + row.appendChild(valueCell); -
    - - - - - - - - - - ${outputRows} - -
    Outputs
    -
    - -
    - Fee: ${(txData.fee / 1e8).toFixed(8)} -
    -
    - `; + return row; } /** - * Get the HTML for a message box that can be rendered on the page. - * @param type - The type of message, e.g. 'success', 'error', 'info' - * @param message - The message to display - can be HTML + * Get the DOM element for the transaction details that can be rendered on the page. */ -function renderMessage(type: 'success' | 'error' | 'info' | 'progress', message: string): string { - const icon = MESSAGE_ICONS[type]; +function renderTxDetails(txData: MempoolTxData): HTMLElement { + const container = document.createElement('div'); + container.className = 'pushtx-details'; - return ` - - `; + const createTable = (title: string, rows: HTMLTableRowElement[]) => { + const wrapper = document.createElement('div'); + const table = document.createElement('table'); + const thead = document.createElement('thead'); + const headerRow = document.createElement('tr'); + const titleHeader = document.createElement('th'); + titleHeader.textContent = title; + const emptyHeader = document.createElement('th'); + headerRow.appendChild(titleHeader); + headerRow.appendChild(emptyHeader); + thead.appendChild(headerRow); + table.appendChild(thead); + const tbody = document.createElement('tbody'); + rows.forEach((row) => tbody.appendChild(row)); + table.appendChild(tbody); + wrapper.appendChild(table); + return wrapper; + }; + + const inputRows = txData.vin.map((input) => + createTxRow(input.prevout.scriptpubkey_address, input.prevout.value) + ); + container.appendChild(createTable('Inputs', inputRows)); + + const outputRows = txData.vout.map((output) => + createTxRow(output.scriptpubkey_address, output.value) + ); + container.appendChild(createTable('Outputs', outputRows)); + + const feeDiv = document.createElement('div'); + feeDiv.className = 'fee'; + const strong = document.createElement('strong'); + strong.textContent = 'Fee:'; + const feeSpan = document.createElement('span'); + feeSpan.className = 'value'; + feeSpan.textContent = (txData.fee / 1e8).toFixed(8); + feeDiv.appendChild(strong); + feeDiv.appendChild(document.createTextNode(' ')); + feeDiv.appendChild(feeSpan); + container.appendChild(feeDiv); + + return container; +} + +/** + * Get a message box element that can be rendered on the page. + * The caller supplies the content as a DOM Node/DocumentFragment; dynamic text + * must be set via textContent before calling this helper. + * @param type - The type of message, e.g. 'success', 'error', 'info' + * @param content - The content to display inside the message box + */ +function renderMessage( + type: 'success' | 'error' | 'info' | 'progress', + content: Node +): HTMLElement { + const wrapper = document.createElement('div'); + wrapper.className = `pushtx-message pushtx-message--${type}`; + wrapper.setAttribute('role', 'alert'); + + const iconContainer = document.createElement('div'); + iconContainer.innerHTML = MESSAGE_ICONS[type]; + wrapper.appendChild(iconContainer); + + const contentContainer = document.createElement('div'); + contentContainer.appendChild(content); + wrapper.appendChild(contentContainer); + + return wrapper; +} + +/** + * Convenience helper for messages that are plain text only. + */ +function textMessage( + type: 'success' | 'error' | 'info' | 'progress', + text: string +): HTMLElement { + const fragment = document.createDocumentFragment(); + fragment.appendChild(document.createTextNode(text)); + return renderMessage(type, fragment); } /** @@ -313,32 +340,51 @@ async function run() { throw new Error('Need message and details areas in HTML.'); } - messageArea.innerHTML = ''; - detailsArea.innerHTML = ''; + messageArea.replaceChildren(); + detailsArea.replaceChildren(); if (!window.location.hash) { const path = window.location.origin + window.location.pathname; - const msg = ` -

    Did you get here by accident?

    -

    - This page is meant to be loaded together with transaction data using the - COLDCARD NFC Push TX feature. The complete URL should look something like this (but longer): -

    + const fragment = document.createDocumentFragment(); -

    ${path}#t=AgAAAAMNCxXtp2GVYVhkRXHLMmdZFs4p3kbFK ⋯ ABf&c=uiSVRda-1tw

    - `; + const p1 = document.createElement('p'); + const strong1 = document.createElement('strong'); + strong1.textContent = 'Did you get here by accident?'; + p1.appendChild(strong1); + fragment.appendChild(p1); - messageArea.innerHTML = renderMessage('info', msg); + const p2 = document.createElement('p'); + p2.textContent = + 'This page is meant to be loaded together with transaction data using the '; + const strong2 = document.createElement('strong'); + strong2.textContent = 'COLDCARD NFC Push TX feature'; + p2.appendChild(strong2); + p2.appendChild( + document.createTextNode( + '. The complete URL should look something like this (but longer):' + ) + ); + fragment.appendChild(p2); + + const p3 = document.createElement('p'); + const code = document.createElement('code'); + code.textContent = `${path}#t=AgAAAAMNCxXtp2GVYVhkRXHLMmdZFs4p3kbFK ⋯ ABf&c=uiSVRda-1tw`; + p3.appendChild(code); + fragment.appendChild(p3); + + messageArea.replaceChildren(renderMessage('info', fragment)); return; } - messageArea.innerHTML = renderMessage('progress', 'Sending transaction, please wait...'); + messageArea.replaceChildren( + textMessage('progress', 'Sending transaction, please wait...') + ); const [parseErr, parseResult] = await collect(parseFragment(window.location.hash)); if (parseErr) { - messageArea.innerHTML = renderMessage('error', parseErr.message); + messageArea.replaceChildren(textMessage('error', parseErr.message)); return; } @@ -360,27 +406,38 @@ async function run() { ? 'This transaction has already been confirmed.' : 'The transaction has been sent and is waiting to be confirmed.'; - const listHtml = BLOCK_EXPLORER_CONFIG[network] - .map( - ([name, url]) => - `
  • ${name}
  • ` - ) - .join(''); + const fragment = document.createDocumentFragment(); - messageArea.innerHTML = renderMessage( - 'success', - `

    ${msg} Transaction ID:

    - -

    ${txid}

    - -

    Verify on a block explorer:

    - -
      ${listHtml}
    - ` - ); + const p1 = document.createElement('p'); + p1.textContent = `${msg} Transaction ID:`; + fragment.appendChild(p1); + + const txidP = document.createElement('p'); + txidP.className = 'txid'; + txidP.textContent = txid; + fragment.appendChild(txidP); + + const p2 = document.createElement('p'); + p2.textContent = 'Verify on a block explorer:'; + fragment.appendChild(p2); + + const ul = document.createElement('ul'); + BLOCK_EXPLORER_CONFIG[network].forEach(([name, url]) => { + const li = document.createElement('li'); + const a = document.createElement('a'); + a.href = `${url}${txid}`; + a.target = '_blank'; + a.rel = 'noopener'; + a.textContent = name; + li.appendChild(a); + ul.appendChild(li); + }); + fragment.appendChild(ul); + + messageArea.replaceChildren(renderMessage('success', fragment)); if (mempoolTxData) { - detailsArea.innerHTML = renderTxDetails(mempoolTxData); + detailsArea.replaceChildren(renderTxDetails(mempoolTxData)); } return; @@ -388,9 +445,27 @@ async function run() { if (pushErr && mempoolErr) { // pushing failed and we also couldn't fetch the TX details - messageArea.innerHTML = renderMessage('error', pushErr.message); + if (pushErr instanceof ProviderErrorsError) { + const fragment = document.createDocumentFragment(); + + const p = document.createElement('p'); + p.textContent = pushErr.message; + fragment.appendChild(p); + + const ul = document.createElement('ul'); + pushErr.details.forEach((detail) => { + const li = document.createElement('li'); + li.textContent = `${detail.url}: ${detail.body ?? ''}`; + ul.appendChild(li); + }); + fragment.appendChild(ul); + + messageArea.replaceChildren(renderMessage('error', fragment)); + } else { + messageArea.replaceChildren(textMessage('error', pushErr.message)); + } } else if (mempoolErr) { - messageArea.innerHTML = renderMessage('error', mempoolErr.message); + messageArea.replaceChildren(textMessage('error', mempoolErr.message)); return; } }