@smartledger/bsv 9.3.0 → 9.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +66 -0
- package/README.md +19 -19
- package/bsv-gdaf.min.js +52 -52
- package/bsv-ltp.min.js +1 -1
- package/bsv-smartcontract.min.js +18 -18
- package/bsv.bundle.js +52 -52
- package/bsv.d.ts +8 -0
- package/bsv.min.js +52 -52
- package/docs/AUDIT_SCOPE.md +135 -34
- package/docs/MODULE_REFERENCE_COMPLETE.md +27 -27
- package/docs/advanced/UTXO_MANAGER_GUIDE.md +1 -1
- package/docs/getting-started/INSTALLATION.md +23 -23
- package/docs/getting-started/QUICK_START.md +7 -7
- package/docs/migration/FROM_BSV_1_5_6.md +5 -5
- package/lib/script/interpreter.js +7 -2
- package/lib/smart_contract/dsl.js +55 -3
- package/package.json +3 -3
- package/version.js +1 -1
package/bsv-smartcontract.min.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
var bsvSmartContract=(()=>{var Yn=Object.create;var mr=Object.defineProperty;var Xn=Object.getOwnPropertyDescriptor;var jn=Object.getOwnPropertyNames;var Wn=Object.getPrototypeOf,Qn=Object.prototype.hasOwnProperty;var C=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Zn=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var x=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Jn=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of jn(t))!Qn.call(e,n)&&n!==r&&mr(e,n,{get:()=>t[n],enumerable:!(i=Xn(t,n))||i.enumerable});return e};var yr=(e,t,r)=>(r=e!=null?Yn(Wn(e)):{},Jn(t||!e||!e.__esModule?mr(r,"default",{value:e,enumerable:!0}):r,e));var Pr=x((Ba,Or)=>{f();var I=Or.exports={},j,W;function ft(){throw new Error("setTimeout has not been defined")}function gt(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?j=setTimeout:j=ft}catch{j=ft}try{typeof clearTimeout=="function"?W=clearTimeout:W=gt}catch{W=gt}})();function Sr(e){if(j===setTimeout)return setTimeout(e,0);if((j===ft||!j)&&setTimeout)return j=setTimeout,setTimeout(e,0);try{return j(e,0)}catch{try{return j.call(null,e,0)}catch{return j.call(this,e,0)}}}function eo(e){if(W===clearTimeout)return clearTimeout(e);if((W===gt||!W)&&clearTimeout)return W=clearTimeout,clearTimeout(e);try{return W(e)}catch{try{return W.call(null,e)}catch{return W.call(this,e)}}}var ie=[],Ie=!1,xe,Qe=-1;function to(){!Ie||!xe||(Ie=!1,xe.length?ie=xe.concat(ie):Qe=-1,ie.length&&vr())}function vr(){if(!Ie){var e=Sr(to);Ie=!0;for(var t=ie.length;t;){for(xe=ie,ie=[];++Qe<t;)xe&&xe[Qe].run();Qe=-1,t=ie.length}xe=null,Ie=!1,eo(e)}}I.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];ie.push(new xr(e,t)),ie.length===1&&!Ie&&Sr(vr)};function xr(e,t){this.fun=e,this.array=t}xr.prototype.run=function(){this.fun.apply(null,this.array)};I.title="browser";I.browser=!0;I.env={};I.argv=[];I.version="";I.versions={};function ne(){}I.on=ne;I.addListener=ne;I.once=ne;I.off=ne;I.removeListener=ne;I.removeAllListeners=ne;I.emit=ne;I.prependListener=ne;I.prependOnceListener=ne;I.listeners=function(e){return[]};I.binding=function(e){throw new Error("process.binding is not supported")};I.cwd=function(){return"/"};I.chdir=function(e){throw new Error("process.chdir is not supported")};I.umask=function(){return 0}});var wr=x(Ze=>{"use strict";f();Ze.byteLength=io;Ze.toByteArray=oo;Ze.fromByteArray=co;var Q=[],V=[],ro=typeof Uint8Array<"u"?Uint8Array:Array,mt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Oe=0,_r=mt.length;Oe<_r;++Oe)Q[Oe]=mt[Oe],V[mt.charCodeAt(Oe)]=Oe;var Oe,_r;V[45]=62;V[95]=63;function Er(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");r===-1&&(r=t);var i=r===t?0:4-r%4;return[r,i]}function io(e){var t=Er(e),r=t[0],i=t[1];return(r+i)*3/4-i}function no(e,t,r){return(t+r)*3/4-r}function oo(e){var t,r=Er(e),i=r[0],n=r[1],o=new ro(no(e,i,n)),s=0,a=n>0?i-4:i,c;for(c=0;c<a;c+=4)t=V[e.charCodeAt(c)]<<18|V[e.charCodeAt(c+1)]<<12|V[e.charCodeAt(c+2)]<<6|V[e.charCodeAt(c+3)],o[s++]=t>>16&255,o[s++]=t>>8&255,o[s++]=t&255;return n===2&&(t=V[e.charCodeAt(c)]<<2|V[e.charCodeAt(c+1)]>>4,o[s++]=t&255),n===1&&(t=V[e.charCodeAt(c)]<<10|V[e.charCodeAt(c+1)]<<4|V[e.charCodeAt(c+2)]>>2,o[s++]=t>>8&255,o[s++]=t&255),o}function so(e){return Q[e>>18&63]+Q[e>>12&63]+Q[e>>6&63]+Q[e&63]}function ao(e,t,r){for(var i,n=[],o=t;o<r;o+=3)i=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(e[o+2]&255),n.push(so(i));return n.join("")}function co(e){for(var t,r=e.length,i=r%3,n=[],o=16383,s=0,a=r-i;s<a;s+=o)n.push(ao(e,s,s+o>a?a:s+o));return i===1?(t=e[r-1],n.push(Q[t>>2]+Q[t<<4&63]+"==")):i===2&&(t=(e[r-2]<<8)+e[r-1],n.push(Q[t>>10]+Q[t>>4&63]+Q[t<<2&63]+"=")),n.join("")}});var Ir=x(yt=>{f();yt.read=function(e,t,r,i,n){var o,s,a=n*8-i-1,c=(1<<a)-1,d=c>>1,g=-7,y=r?n-1:0,P=r?-1:1,O=e[t+y];for(y+=P,o=O&(1<<-g)-1,O>>=-g,g+=a;g>0;o=o*256+e[t+y],y+=P,g-=8);for(s=o&(1<<-g)-1,o>>=-g,g+=i;g>0;s=s*256+e[t+y],y+=P,g-=8);if(o===0)o=1-d;else{if(o===c)return s?NaN:(O?-1:1)*(1/0);s=s+Math.pow(2,i),o=o-d}return(O?-1:1)*s*Math.pow(2,o-i)};yt.write=function(e,t,r,i,n,o){var s,a,c,d=o*8-n-1,g=(1<<d)-1,y=g>>1,P=n===23?Math.pow(2,-24)-Math.pow(2,-77):0,O=i?0:o-1,re=i?1:-1,$n=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=g):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),s+y>=1?t+=P/c:t+=P*Math.pow(2,1-y),t*c>=2&&(s++,c/=2),s+y>=g?(a=0,s=g):s+y>=1?(a=(t*c-1)*Math.pow(2,n),s=s+y):(a=t*Math.pow(2,y-1)*Math.pow(2,n),s=0));n>=8;e[r+O]=a&255,O+=re,a/=256,n-=8);for(s=s<<n|a,d+=n;d>0;e[r+O]=s&255,O+=re,s/=256,d-=8);e[r+O-re]|=$n*128}});var Vr=x(ke=>{"use strict";f();var St=wr(),Ae=Ir(),Tr=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;ke.Buffer=h;ke.SlowBuffer=go;ke.INSPECT_MAX_BYTES=50;var Je=2147483647;ke.kMaxLength=Je;h.TYPED_ARRAY_SUPPORT=uo();!h.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 uo(){try{let e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),e.foo()===42}catch{return!1}}Object.defineProperty(h.prototype,"parent",{enumerable:!0,get:function(){if(h.isBuffer(this))return this.buffer}});Object.defineProperty(h.prototype,"offset",{enumerable:!0,get:function(){if(h.isBuffer(this))return this.byteOffset}});function oe(e){if(e>Je)throw new RangeError('The value "'+e+'" is invalid for option "size"');let t=new Uint8Array(e);return Object.setPrototypeOf(t,h.prototype),t}function h(e,t,r){if(typeof e=="number"){if(typeof t=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return Pt(e)}return Hr(e,t,r)}h.poolSize=8192;function Hr(e,t,r){if(typeof e=="string")return po(e,t);if(ArrayBuffer.isView(e))return lo(e);if(e==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(Z(e,ArrayBuffer)||e&&Z(e.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Z(e,SharedArrayBuffer)||e&&Z(e.buffer,SharedArrayBuffer)))return xt(e,t,r);if(typeof e=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let i=e.valueOf&&e.valueOf();if(i!=null&&i!==e)return h.from(i,t,r);let n=fo(e);if(n)return n;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof e[Symbol.toPrimitive]=="function")return h.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}h.from=function(e,t,r){return Hr(e,t,r)};Object.setPrototypeOf(h.prototype,Uint8Array.prototype);Object.setPrototypeOf(h,Uint8Array);function Fr(e){if(typeof e!="number")throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function ho(e,t,r){return Fr(e),e<=0?oe(e):t!==void 0?typeof r=="string"?oe(e).fill(t,r):oe(e).fill(t):oe(e)}h.alloc=function(e,t,r){return ho(e,t,r)};function Pt(e){return Fr(e),oe(e<0?0:_t(e)|0)}h.allocUnsafe=function(e){return Pt(e)};h.allocUnsafeSlow=function(e){return Pt(e)};function po(e,t){if((typeof t!="string"||t==="")&&(t="utf8"),!h.isEncoding(t))throw new TypeError("Unknown encoding: "+t);let r=Cr(e,t)|0,i=oe(r),n=i.write(e,t);return n!==r&&(i=i.slice(0,n)),i}function vt(e){let t=e.length<0?0:_t(e.length)|0,r=oe(t);for(let i=0;i<t;i+=1)r[i]=e[i]&255;return r}function lo(e){if(Z(e,Uint8Array)){let t=new Uint8Array(e);return xt(t.buffer,t.byteOffset,t.byteLength)}return vt(e)}function xt(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');let i;return t===void 0&&r===void 0?i=new Uint8Array(e):r===void 0?i=new Uint8Array(e,t):i=new Uint8Array(e,t,r),Object.setPrototypeOf(i,h.prototype),i}function fo(e){if(h.isBuffer(e)){let t=_t(e.length)|0,r=oe(t);return r.length===0||e.copy(r,0,0,t),r}if(e.length!==void 0)return typeof e.length!="number"||wt(e.length)?oe(0):vt(e);if(e.type==="Buffer"&&Array.isArray(e.data))return vt(e.data)}function _t(e){if(e>=Je)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Je.toString(16)+" bytes");return e|0}function go(e){return+e!=e&&(e=0),h.alloc(+e)}h.isBuffer=function(t){return t!=null&&t._isBuffer===!0&&t!==h.prototype};h.compare=function(t,r){if(Z(t,Uint8Array)&&(t=h.from(t,t.offset,t.byteLength)),Z(r,Uint8Array)&&(r=h.from(r,r.offset,r.byteLength)),!h.isBuffer(t)||!h.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(t===r)return 0;let i=t.length,n=r.length;for(let o=0,s=Math.min(i,n);o<s;++o)if(t[o]!==r[o]){i=t[o],n=r[o];break}return i<n?-1:n<i?1:0};h.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};h.concat=function(t,r){if(!Array.isArray(t))throw new TypeError('"list" argument must be an Array of Buffers');if(t.length===0)return h.alloc(0);let i;if(r===void 0)for(r=0,i=0;i<t.length;++i)r+=t[i].length;let n=h.allocUnsafe(r),o=0;for(i=0;i<t.length;++i){let s=t[i];if(Z(s,Uint8Array))o+s.length>n.length?(h.isBuffer(s)||(s=h.from(s)),s.copy(n,o)):Uint8Array.prototype.set.call(n,s,o);else if(h.isBuffer(s))s.copy(n,o);else throw new TypeError('"list" argument must be an Array of Buffers');o+=s.length}return n};function Cr(e,t){if(h.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||Z(e,ArrayBuffer))return e.byteLength;if(typeof e!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);let r=e.length,i=arguments.length>2&&arguments[2]===!0;if(!i&&r===0)return 0;let n=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return Ot(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return Gr(e).length;default:if(n)return i?-1:Ot(e).length;t=(""+t).toLowerCase(),n=!0}}h.byteLength=Cr;function mo(e,t,r){let i=!1;if((t===void 0||t<0)&&(t=0),t>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,t>>>=0,r<=t))return"";for(e||(e="utf8");;)switch(e){case"hex":return Io(this,t,r);case"utf8":case"utf-8":return Rr(this,t,r);case"ascii":return Eo(this,t,r);case"latin1":case"binary":return wo(this,t,r);case"base64":return Po(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return To(this,t,r);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}h.prototype._isBuffer=!0;function Pe(e,t,r){let i=e[t];e[t]=e[r],e[r]=i}h.prototype.swap16=function(){let t=this.length;if(t%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let r=0;r<t;r+=2)Pe(this,r,r+1);return this};h.prototype.swap32=function(){let t=this.length;if(t%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let r=0;r<t;r+=4)Pe(this,r,r+3),Pe(this,r+1,r+2);return this};h.prototype.swap64=function(){let t=this.length;if(t%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let r=0;r<t;r+=8)Pe(this,r,r+7),Pe(this,r+1,r+6),Pe(this,r+2,r+5),Pe(this,r+3,r+4);return this};h.prototype.toString=function(){let t=this.length;return t===0?"":arguments.length===0?Rr(this,0,t):mo.apply(this,arguments)};h.prototype.toLocaleString=h.prototype.toString;h.prototype.equals=function(t){if(!h.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t?!0:h.compare(this,t)===0};h.prototype.inspect=function(){let t="",r=ke.INSPECT_MAX_BYTES;return t=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(t+=" ... "),"<Buffer "+t+">"};Tr&&(h.prototype[Tr]=h.prototype.inspect);h.prototype.compare=function(t,r,i,n,o){if(Z(t,Uint8Array)&&(t=h.from(t,t.offset,t.byteLength)),!h.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(r===void 0&&(r=0),i===void 0&&(i=t?t.length:0),n===void 0&&(n=0),o===void 0&&(o=this.length),r<0||i>t.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&r>=i)return 0;if(n>=o)return-1;if(r>=i)return 1;if(r>>>=0,i>>>=0,n>>>=0,o>>>=0,this===t)return 0;let s=o-n,a=i-r,c=Math.min(s,a),d=this.slice(n,o),g=t.slice(r,i);for(let y=0;y<c;++y)if(d[y]!==g[y]){s=d[y],a=g[y];break}return s<a?-1:a<s?1:0};function Lr(e,t,r,i,n){if(e.length===0)return-1;if(typeof r=="string"?(i=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,wt(r)&&(r=n?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(n)return-1;r=e.length-1}else if(r<0)if(n)r=0;else return-1;if(typeof t=="string"&&(t=h.from(t,i)),h.isBuffer(t))return t.length===0?-1:Ar(e,t,r,i,n);if(typeof t=="number")return t=t&255,typeof Uint8Array.prototype.indexOf=="function"?n?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):Ar(e,[t],r,i,n);throw new TypeError("val must be string, number or Buffer")}function Ar(e,t,r,i,n){let o=1,s=e.length,a=t.length;if(i!==void 0&&(i=String(i).toLowerCase(),i==="ucs2"||i==="ucs-2"||i==="utf16le"||i==="utf-16le")){if(e.length<2||t.length<2)return-1;o=2,s/=2,a/=2,r/=2}function c(g,y){return o===1?g[y]:g.readUInt16BE(y*o)}let d;if(n){let g=-1;for(d=r;d<s;d++)if(c(e,d)===c(t,g===-1?0:d-g)){if(g===-1&&(g=d),d-g+1===a)return g*o}else g!==-1&&(d-=d-g),g=-1}else for(r+a>s&&(r=s-a),d=r;d>=0;d--){let g=!0;for(let y=0;y<a;y++)if(c(e,d+y)!==c(t,y)){g=!1;break}if(g)return d}return-1}h.prototype.includes=function(t,r,i){return this.indexOf(t,r,i)!==-1};h.prototype.indexOf=function(t,r,i){return Lr(this,t,r,i,!0)};h.prototype.lastIndexOf=function(t,r,i){return Lr(this,t,r,i,!1)};function yo(e,t,r,i){r=Number(r)||0;let n=e.length-r;i?(i=Number(i),i>n&&(i=n)):i=n;let o=t.length;i>o/2&&(i=o/2);let s;for(s=0;s<i;++s){let a=parseInt(t.substr(s*2,2),16);if(wt(a))return s;e[r+s]=a}return s}function So(e,t,r,i){return et(Ot(t,e.length-r),e,r,i)}function vo(e,t,r,i){return et(Ho(t),e,r,i)}function xo(e,t,r,i){return et(Gr(t),e,r,i)}function Oo(e,t,r,i){return et(Fo(t,e.length-r),e,r,i)}h.prototype.write=function(t,r,i,n){if(r===void 0)n="utf8",i=this.length,r=0;else if(i===void 0&&typeof r=="string")n=r,i=this.length,r=0;else if(isFinite(r))r=r>>>0,isFinite(i)?(i=i>>>0,n===void 0&&(n="utf8")):(n=i,i=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let o=this.length-r;if((i===void 0||i>o)&&(i=o),t.length>0&&(i<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let s=!1;for(;;)switch(n){case"hex":return yo(this,t,r,i);case"utf8":case"utf-8":return So(this,t,r,i);case"ascii":case"latin1":case"binary":return vo(this,t,r,i);case"base64":return xo(this,t,r,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Oo(this,t,r,i);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),s=!0}};h.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Po(e,t,r){return t===0&&r===e.length?St.fromByteArray(e):St.fromByteArray(e.slice(t,r))}function Rr(e,t,r){r=Math.min(e.length,r);let i=[],n=t;for(;n<r;){let o=e[n],s=null,a=o>239?4:o>223?3:o>191?2:1;if(n+a<=r){let c,d,g,y;switch(a){case 1:o<128&&(s=o);break;case 2:c=e[n+1],(c&192)===128&&(y=(o&31)<<6|c&63,y>127&&(s=y));break;case 3:c=e[n+1],d=e[n+2],(c&192)===128&&(d&192)===128&&(y=(o&15)<<12|(c&63)<<6|d&63,y>2047&&(y<55296||y>57343)&&(s=y));break;case 4:c=e[n+1],d=e[n+2],g=e[n+3],(c&192)===128&&(d&192)===128&&(g&192)===128&&(y=(o&15)<<18|(c&63)<<12|(d&63)<<6|g&63,y>65535&&y<1114112&&(s=y))}}s===null?(s=65533,a=1):s>65535&&(s-=65536,i.push(s>>>10&1023|55296),s=56320|s&1023),i.push(s),n+=a}return _o(i)}var br=4096;function _o(e){let t=e.length;if(t<=br)return String.fromCharCode.apply(String,e);let r="",i=0;for(;i<t;)r+=String.fromCharCode.apply(String,e.slice(i,i+=br));return r}function Eo(e,t,r){let i="";r=Math.min(e.length,r);for(let n=t;n<r;++n)i+=String.fromCharCode(e[n]&127);return i}function wo(e,t,r){let i="";r=Math.min(e.length,r);for(let n=t;n<r;++n)i+=String.fromCharCode(e[n]);return i}function Io(e,t,r){let i=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>i)&&(r=i);let n="";for(let o=t;o<r;++o)n+=Co[e[o]];return n}function To(e,t,r){let i=e.slice(t,r),n="";for(let o=0;o<i.length-1;o+=2)n+=String.fromCharCode(i[o]+i[o+1]*256);return n}h.prototype.slice=function(t,r){let i=this.length;t=~~t,r=r===void 0?i:~~r,t<0?(t+=i,t<0&&(t=0)):t>i&&(t=i),r<0?(r+=i,r<0&&(r=0)):r>i&&(r=i),r<t&&(r=t);let n=this.subarray(t,r);return Object.setPrototypeOf(n,h.prototype),n};function H(e,t,r){if(e%1!==0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}h.prototype.readUintLE=h.prototype.readUIntLE=function(t,r,i){t=t>>>0,r=r>>>0,i||H(t,r,this.length);let n=this[t],o=1,s=0;for(;++s<r&&(o*=256);)n+=this[t+s]*o;return n};h.prototype.readUintBE=h.prototype.readUIntBE=function(t,r,i){t=t>>>0,r=r>>>0,i||H(t,r,this.length);let n=this[t+--r],o=1;for(;r>0&&(o*=256);)n+=this[t+--r]*o;return n};h.prototype.readUint8=h.prototype.readUInt8=function(t,r){return t=t>>>0,r||H(t,1,this.length),this[t]};h.prototype.readUint16LE=h.prototype.readUInt16LE=function(t,r){return t=t>>>0,r||H(t,2,this.length),this[t]|this[t+1]<<8};h.prototype.readUint16BE=h.prototype.readUInt16BE=function(t,r){return t=t>>>0,r||H(t,2,this.length),this[t]<<8|this[t+1]};h.prototype.readUint32LE=h.prototype.readUInt32LE=function(t,r){return t=t>>>0,r||H(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+this[t+3]*16777216};h.prototype.readUint32BE=h.prototype.readUInt32BE=function(t,r){return t=t>>>0,r||H(t,4,this.length),this[t]*16777216+(this[t+1]<<16|this[t+2]<<8|this[t+3])};h.prototype.readBigUInt64LE=de(function(t){t=t>>>0,be(t,"offset");let r=this[t],i=this[t+7];(r===void 0||i===void 0)&&Ve(t,this.length-8);let n=r+this[++t]*2**8+this[++t]*2**16+this[++t]*2**24,o=this[++t]+this[++t]*2**8+this[++t]*2**16+i*2**24;return BigInt(n)+(BigInt(o)<<BigInt(32))});h.prototype.readBigUInt64BE=de(function(t){t=t>>>0,be(t,"offset");let r=this[t],i=this[t+7];(r===void 0||i===void 0)&&Ve(t,this.length-8);let n=r*2**24+this[++t]*2**16+this[++t]*2**8+this[++t],o=this[++t]*2**24+this[++t]*2**16+this[++t]*2**8+i;return(BigInt(n)<<BigInt(32))+BigInt(o)});h.prototype.readIntLE=function(t,r,i){t=t>>>0,r=r>>>0,i||H(t,r,this.length);let n=this[t],o=1,s=0;for(;++s<r&&(o*=256);)n+=this[t+s]*o;return o*=128,n>=o&&(n-=Math.pow(2,8*r)),n};h.prototype.readIntBE=function(t,r,i){t=t>>>0,r=r>>>0,i||H(t,r,this.length);let n=r,o=1,s=this[t+--n];for(;n>0&&(o*=256);)s+=this[t+--n]*o;return o*=128,s>=o&&(s-=Math.pow(2,8*r)),s};h.prototype.readInt8=function(t,r){return t=t>>>0,r||H(t,1,this.length),this[t]&128?(255-this[t]+1)*-1:this[t]};h.prototype.readInt16LE=function(t,r){t=t>>>0,r||H(t,2,this.length);let i=this[t]|this[t+1]<<8;return i&32768?i|4294901760:i};h.prototype.readInt16BE=function(t,r){t=t>>>0,r||H(t,2,this.length);let i=this[t+1]|this[t]<<8;return i&32768?i|4294901760:i};h.prototype.readInt32LE=function(t,r){return t=t>>>0,r||H(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24};h.prototype.readInt32BE=function(t,r){return t=t>>>0,r||H(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]};h.prototype.readBigInt64LE=de(function(t){t=t>>>0,be(t,"offset");let r=this[t],i=this[t+7];(r===void 0||i===void 0)&&Ve(t,this.length-8);let n=this[t+4]+this[t+5]*2**8+this[t+6]*2**16+(i<<24);return(BigInt(n)<<BigInt(32))+BigInt(r+this[++t]*2**8+this[++t]*2**16+this[++t]*2**24)});h.prototype.readBigInt64BE=de(function(t){t=t>>>0,be(t,"offset");let r=this[t],i=this[t+7];(r===void 0||i===void 0)&&Ve(t,this.length-8);let n=(r<<24)+this[++t]*2**16+this[++t]*2**8+this[++t];return(BigInt(n)<<BigInt(32))+BigInt(this[++t]*2**24+this[++t]*2**16+this[++t]*2**8+i)});h.prototype.readFloatLE=function(t,r){return t=t>>>0,r||H(t,4,this.length),Ae.read(this,t,!0,23,4)};h.prototype.readFloatBE=function(t,r){return t=t>>>0,r||H(t,4,this.length),Ae.read(this,t,!1,23,4)};h.prototype.readDoubleLE=function(t,r){return t=t>>>0,r||H(t,8,this.length),Ae.read(this,t,!0,52,8)};h.prototype.readDoubleBE=function(t,r){return t=t>>>0,r||H(t,8,this.length),Ae.read(this,t,!1,52,8)};function L(e,t,r,i,n,o){if(!h.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>n||t<o)throw new RangeError('"value" argument is out of bounds');if(r+i>e.length)throw new RangeError("Index out of range")}h.prototype.writeUintLE=h.prototype.writeUIntLE=function(t,r,i,n){if(t=+t,r=r>>>0,i=i>>>0,!n){let a=Math.pow(2,8*i)-1;L(this,t,r,i,a,0)}let o=1,s=0;for(this[r]=t&255;++s<i&&(o*=256);)this[r+s]=t/o&255;return r+i};h.prototype.writeUintBE=h.prototype.writeUIntBE=function(t,r,i,n){if(t=+t,r=r>>>0,i=i>>>0,!n){let a=Math.pow(2,8*i)-1;L(this,t,r,i,a,0)}let o=i-1,s=1;for(this[r+o]=t&255;--o>=0&&(s*=256);)this[r+o]=t/s&255;return r+i};h.prototype.writeUint8=h.prototype.writeUInt8=function(t,r,i){return t=+t,r=r>>>0,i||L(this,t,r,1,255,0),this[r]=t&255,r+1};h.prototype.writeUint16LE=h.prototype.writeUInt16LE=function(t,r,i){return t=+t,r=r>>>0,i||L(this,t,r,2,65535,0),this[r]=t&255,this[r+1]=t>>>8,r+2};h.prototype.writeUint16BE=h.prototype.writeUInt16BE=function(t,r,i){return t=+t,r=r>>>0,i||L(this,t,r,2,65535,0),this[r]=t>>>8,this[r+1]=t&255,r+2};h.prototype.writeUint32LE=h.prototype.writeUInt32LE=function(t,r,i){return t=+t,r=r>>>0,i||L(this,t,r,4,4294967295,0),this[r+3]=t>>>24,this[r+2]=t>>>16,this[r+1]=t>>>8,this[r]=t&255,r+4};h.prototype.writeUint32BE=h.prototype.writeUInt32BE=function(t,r,i){return t=+t,r=r>>>0,i||L(this,t,r,4,4294967295,0),this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=t&255,r+4};function Br(e,t,r,i,n){Mr(t,i,n,e,r,7);let o=Number(t&BigInt(4294967295));e[r++]=o,o=o>>8,e[r++]=o,o=o>>8,e[r++]=o,o=o>>8,e[r++]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=s,s=s>>8,e[r++]=s,s=s>>8,e[r++]=s,s=s>>8,e[r++]=s,r}function Nr(e,t,r,i,n){Mr(t,i,n,e,r,7);let o=Number(t&BigInt(4294967295));e[r+7]=o,o=o>>8,e[r+6]=o,o=o>>8,e[r+5]=o,o=o>>8,e[r+4]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=s,s=s>>8,e[r+2]=s,s=s>>8,e[r+1]=s,s=s>>8,e[r]=s,r+8}h.prototype.writeBigUInt64LE=de(function(t,r=0){return Br(this,t,r,BigInt(0),BigInt("0xffffffffffffffff"))});h.prototype.writeBigUInt64BE=de(function(t,r=0){return Nr(this,t,r,BigInt(0),BigInt("0xffffffffffffffff"))});h.prototype.writeIntLE=function(t,r,i,n){if(t=+t,r=r>>>0,!n){let c=Math.pow(2,8*i-1);L(this,t,r,i,c-1,-c)}let o=0,s=1,a=0;for(this[r]=t&255;++o<i&&(s*=256);)t<0&&a===0&&this[r+o-1]!==0&&(a=1),this[r+o]=(t/s>>0)-a&255;return r+i};h.prototype.writeIntBE=function(t,r,i,n){if(t=+t,r=r>>>0,!n){let c=Math.pow(2,8*i-1);L(this,t,r,i,c-1,-c)}let o=i-1,s=1,a=0;for(this[r+o]=t&255;--o>=0&&(s*=256);)t<0&&a===0&&this[r+o+1]!==0&&(a=1),this[r+o]=(t/s>>0)-a&255;return r+i};h.prototype.writeInt8=function(t,r,i){return t=+t,r=r>>>0,i||L(this,t,r,1,127,-128),t<0&&(t=255+t+1),this[r]=t&255,r+1};h.prototype.writeInt16LE=function(t,r,i){return t=+t,r=r>>>0,i||L(this,t,r,2,32767,-32768),this[r]=t&255,this[r+1]=t>>>8,r+2};h.prototype.writeInt16BE=function(t,r,i){return t=+t,r=r>>>0,i||L(this,t,r,2,32767,-32768),this[r]=t>>>8,this[r+1]=t&255,r+2};h.prototype.writeInt32LE=function(t,r,i){return t=+t,r=r>>>0,i||L(this,t,r,4,2147483647,-2147483648),this[r]=t&255,this[r+1]=t>>>8,this[r+2]=t>>>16,this[r+3]=t>>>24,r+4};h.prototype.writeInt32BE=function(t,r,i){return t=+t,r=r>>>0,i||L(this,t,r,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=t&255,r+4};h.prototype.writeBigInt64LE=de(function(t,r=0){return Br(this,t,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});h.prototype.writeBigInt64BE=de(function(t,r=0){return Nr(this,t,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Ur(e,t,r,i,n,o){if(r+i>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function qr(e,t,r,i,n){return t=+t,r=r>>>0,n||Ur(e,t,r,4,34028234663852886e22,-34028234663852886e22),Ae.write(e,t,r,i,23,4),r+4}h.prototype.writeFloatLE=function(t,r,i){return qr(this,t,r,!0,i)};h.prototype.writeFloatBE=function(t,r,i){return qr(this,t,r,!1,i)};function Dr(e,t,r,i,n){return t=+t,r=r>>>0,n||Ur(e,t,r,8,17976931348623157e292,-17976931348623157e292),Ae.write(e,t,r,i,52,8),r+8}h.prototype.writeDoubleLE=function(t,r,i){return Dr(this,t,r,!0,i)};h.prototype.writeDoubleBE=function(t,r,i){return Dr(this,t,r,!1,i)};h.prototype.copy=function(t,r,i,n){if(!h.isBuffer(t))throw new TypeError("argument should be a Buffer");if(i||(i=0),!n&&n!==0&&(n=this.length),r>=t.length&&(r=t.length),r||(r=0),n>0&&n<i&&(n=i),n===i||t.length===0||this.length===0)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-r<n-i&&(n=t.length-r+i);let o=n-i;return this===t&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(r,i,n):Uint8Array.prototype.set.call(t,this.subarray(i,n),r),o};h.prototype.fill=function(t,r,i,n){if(typeof t=="string"){if(typeof r=="string"?(n=r,r=0,i=this.length):typeof i=="string"&&(n=i,i=this.length),n!==void 0&&typeof n!="string")throw new TypeError("encoding must be a string");if(typeof n=="string"&&!h.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(t.length===1){let s=t.charCodeAt(0);(n==="utf8"&&s<128||n==="latin1")&&(t=s)}}else typeof t=="number"?t=t&255:typeof t=="boolean"&&(t=Number(t));if(r<0||this.length<r||this.length<i)throw new RangeError("Out of range index");if(i<=r)return this;r=r>>>0,i=i===void 0?this.length:i>>>0,t||(t=0);let o;if(typeof t=="number")for(o=r;o<i;++o)this[o]=t;else{let s=h.isBuffer(t)?t:h.from(t,n),a=s.length;if(a===0)throw new TypeError('The value "'+t+'" is invalid for argument "value"');for(o=0;o<i-r;++o)this[o+r]=s[o%a]}return this};var Te={};function Et(e,t,r){Te[e]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(n){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:n,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}Et("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError);Et("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError);Et("ERR_OUT_OF_RANGE",function(e,t,r){let i=`The value of "${e}" is out of range.`,n=r;return Number.isInteger(r)&&Math.abs(r)>2**32?n=kr(String(r)):typeof r=="bigint"&&(n=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(n=kr(n)),n+="n"),i+=` It must be ${t}. Received ${n}`,i},RangeError);function kr(e){let t="",r=e.length,i=e[0]==="-"?1:0;for(;r>=i+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function Ao(e,t,r){be(t,"offset"),(e[t]===void 0||e[t+r]===void 0)&&Ve(t,e.length-(r+1))}function Mr(e,t,r,i,n,o){if(e>r||e<t){let s=typeof t=="bigint"?"n":"",a;throw o>3?t===0||t===BigInt(0)?a=`>= 0${s} and < 2${s} ** ${(o+1)*8}${s}`:a=`>= -(2${s} ** ${(o+1)*8-1}${s}) and < 2 ** ${(o+1)*8-1}${s}`:a=`>= ${t}${s} and <= ${r}${s}`,new Te.ERR_OUT_OF_RANGE("value",a,e)}Ao(i,n,o)}function be(e,t){if(typeof e!="number")throw new Te.ERR_INVALID_ARG_TYPE(t,"number",e)}function Ve(e,t,r){throw Math.floor(e)!==e?(be(e,r),new Te.ERR_OUT_OF_RANGE(r||"offset","an integer",e)):t<0?new Te.ERR_BUFFER_OUT_OF_BOUNDS:new Te.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}var bo=/[^+/0-9A-Za-z-_]/g;function ko(e){if(e=e.split("=")[0],e=e.trim().replace(bo,""),e.length<2)return"";for(;e.length%4!==0;)e=e+"=";return e}function Ot(e,t){t=t||1/0;let r,i=e.length,n=null,o=[];for(let s=0;s<i;++s){if(r=e.charCodeAt(s),r>55295&&r<57344){if(!n){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}else if(s+1===i){(t-=3)>-1&&o.push(239,191,189);continue}n=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),n=r;continue}r=(n-55296<<10|r-56320)+65536}else n&&(t-=3)>-1&&o.push(239,191,189);if(n=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,r&63|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return o}function Ho(e){let t=[];for(let r=0;r<e.length;++r)t.push(e.charCodeAt(r)&255);return t}function Fo(e,t){let r,i,n,o=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)r=e.charCodeAt(s),i=r>>8,n=r%256,o.push(n),o.push(i);return o}function Gr(e){return St.toByteArray(ko(e))}function et(e,t,r,i){let n;for(n=0;n<i&&!(n+r>=t.length||n>=e.length);++n)t[n+r]=e[n];return n}function Z(e,t){return e instanceof t||e!=null&&e.constructor!=null&&e.constructor.name!=null&&e.constructor.name===t.name}function wt(e){return e!==e}var Co=(function(){let e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){let i=r*16;for(let n=0;n<16;++n)t[i+n]=e[r]+e[n]}return t})();function de(e){return typeof BigInt>"u"?Lo:e}function Lo(){throw new Error("BigInt not supported")}});var m,u,f=Zn(()=>{m=yr(Pr()),u=yr(Vr())});var fe=x(($a,zr)=>{f();zr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.crypto.Hash});var q=x((Xa,Kr)=>{f();Kr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Transaction});var It=x((Wa,$r)=>{f();$r.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Address});var A=x((Za,Yr)=>{f();Yr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Script});var _e=x((ec,Xr)=>{f();Xr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Transaction.sighash});var He=x((rc,jr)=>{f();jr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Transaction.Input});var ge=x((nc,Wr)=>{f();Wr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Script.Interpreter});var Ee=x((sc,Qr)=>{f();Qr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.crypto.Signature});var D=x((cc,Zr)=>{f();Zr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.crypto.BN});var F=x((hc,Jr)=>{"use strict";f();Jr.exports={}});var oi=x((lc,ni)=>{"use strict";f();var ri=_e(),Ro=He(),Fe=ge(),ei=Ee(),Bo=fe(),Tt=D(),ii=q(),me=A(),ti=F(),se;try{se=F()}catch{se=null}var No=function(){var e=typeof m.default<"u"&&m.default.env&&m.default.env.BSV_DEBUG||typeof window<"u"&&window.BSV_DEBUG;e&&console.log.apply(console,arguments)};function R(e,t){if(!(this instanceof R))return new R(e,t);this.privateKey=e,this.publicKey=e.publicKey,this.address=e.toAddress(),t=t||{},this.storageDir=t.storageDir||(typeof m.default<"u"?ti.join(m.default.cwd(),".bsv-covenants"):".bsv-covenants"),this.covenantUtxoPath=ti.join(this.storageDir,"covenant_utxos.json"),this.sighashType=ei.SIGHASH_ALL|ei.SIGHASH_FORKID,this.allowNonEnforcing=t.allowNonEnforcing===!0,se&&this._ensureStorageDir()}R.prototype.createFromP2PKH=function(e){if(!this.allowNonEnforcing)throw new Error("SmartContract.Covenant builds a NON-ENFORCING script that reduces to plain P2PK \u2014 it does not constrain the spend. Use SmartContract.PushTx.valueCovenant (output binding) or SmartContract.Token / perpetualCovenant (stateful covenants) for real covenants. To use this demo anyway, construct with { allowNonEnforcing: true }.");e.script||(e.script=R.reconstructP2pkhScript(this.address));var t=new ii().from({txId:e.txid,outputIndex:e.vout,script:e.script,satoshis:e.satoshis}).to(this.address,e.satoshis-1e3),r=me.fromHex(e.script),i=ri.sighashPreimage(t,this.sighashType,0,r,new Tt(e.satoshis)),n=Bo.sha256sha256(i),o=new me().add("OP_DUP").add("OP_HASH256").add(n).add("OP_EQUALVERIFY").add("OP_DROP").add(this.publicKey.toBuffer()).add("OP_CHECKSIG");t.outputs[0].setScript(o),t.sign(this.privateKey);var s={txid:t.id,vout:0,satoshis:e.satoshis-1e3,script:o.toHex(),scriptPubKey:o.toHex(),preimageHash:n.toString("hex"),originalPreimage:i.toString("hex"),status:"local",createdAt:new Date().toISOString(),type:"preimage_covenant"};return{transaction:t,covenantUtxo:s}};R.prototype.createSpendingTx=function(e,t,r){var i=t||this.address,n=r||e.satoshis-500,o=new ii;o.addInput(new Ro({prevTxId:e.txid,outputIndex:e.vout,script:me.empty()}),me.fromHex(e.script),e.satoshis),o.to(i,n);var s=me.fromHex(e.script),a=ri.sign(o,this.privateKey,this.sighashType,0,s,new Tt(e.satoshis)),c=u.Buffer.concat([a.toDER(),u.Buffer.from([this.sighashType])]),d=u.Buffer.from(e.originalPreimage,"hex"),g=new me().add(c).add(d);return o.inputs[0].setScript(g),o};R.prototype.validate=function(e,t){var r=new Fe,i=Fe.SCRIPT_VERIFY_P2SH|Fe.SCRIPT_VERIFY_STRICTENC|Fe.SCRIPT_VERIFY_DERSIG|Fe.SCRIPT_VERIFY_LOW_S|Fe.SCRIPT_ENABLE_SIGHASH_FORKID,n=e.inputs[0].script,o=me.fromHex(t.script),s=r.verify(n,o,e,0,i,new Tt(t.satoshis));return{valid:s,error:s?null:r.errstr}};R.prototype.save=function(e){if(!se)return No("File system operations not available in browser environment"),e;var t=this.list();return t.push(e),se.writeFileSync(this.covenantUtxoPath,JSON.stringify(t,null,2)),e};R.prototype.load=function(e){var t=this.list();if(e){var r=t.find(function(i){return i.txid===e});if(!r)throw new Error("Covenant UTXO with TXID "+e+" not found");return r}else{var r=t.find(function(n){return n.type==="preimage_covenant"});if(!r)throw new Error("No preimage covenant UTXO found");return r}};R.prototype.list=function(){return se.existsSync(this.covenantUtxoPath)?JSON.parse(se.readFileSync(this.covenantUtxoPath,"utf8")):[]};R.prototype.getPortfolio=function(){var e=this.list(),t={total:e.length,totalValue:e.reduce(function(r,i){return r+i.satoshis},0),byStatus:{},recent:e.slice(-5)};return e.forEach(function(r){var i=r.status||"local";t.byStatus[i]||(t.byStatus[i]={count:0,value:0}),t.byStatus[i].count++,t.byStatus[i].value+=r.satoshis}),t};R.prototype.completeFlow=function(e,t){var r=this.createFromP2PKH(e),i=this.save(r.covenantUtxo);t&&t(r.transaction,"creation");var n=this.createSpendingTx(i),o=this.validate(n,i);return t&&o.valid&&t(n,"spending"),{creationTx:r.transaction,spendingTx:n,covenantUtxo:i,validation:o,success:o.valid}};R.prototype._ensureStorageDir=function(){se.existsSync(this.storageDir)||se.mkdirSync(this.storageDir,{recursive:!0})};R.reconstructP2pkhScript=function(e){return me.buildPublicKeyHashOut(e).toHex()};ni.exports=R});var ze=x((fc,si)=>{f();si.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.PrivateKey});var J=x((yc,ci)=>{"use strict";f();var Uo=_e(),qo=D(),Do=q(),Mo=ze(),ai=A(),mc=F();function S(e,t){if(!(this instanceof S))return new S(e,t);this.preimage=u.Buffer.isBuffer(e)?e:u.Buffer.from(e,"hex"),this.options=t||{},this.strategy=this.options.strategy||"DYNAMIC",this.fields=null,this.sighashInfo=null,this.options.deferExtraction||this._extractFields()}S.LEFT_FIXED_LENGTH=104;S.RIGHT_FIXED_LENGTH=52;S.MIN_PREIMAGE_LENGTH=S.LEFT_FIXED_LENGTH+1+S.RIGHT_FIXED_LENGTH;S.prototype.extract=function(e){return this.strategy=e||this.strategy,this._extractFields(),this.fields};S.prototype.getSighashInfo=function(){return this.fields||this._extractFields(),this.sighashInfo};S.prototype.getField=function(e){return this.fields||this._extractFields(),this.fields[e]};S.prototype.extractField=function(e,t){t=t||{},this.fields||this._extractFields();var r=this._parsePreimageStructure(),i=this._generateBidirectionalASM(e,r,t.includeComments),n=this._extractSpecificField(e,r),o=this._interpretField(e,n,r);return{field:e,value:n?n.toString("hex"):null,buffer:n,asm:i,interpretation:o,strategy:this._getExtractionStrategy(e),structure:r._structure}};S.prototype.generateASM=function(e,t){var r=this._parsePreimageStructure();return this._generateBidirectionalASM(e,r,t)};S.prototype.extractFields=function(e){var t={};return e.forEach(function(r){t[r]=this.extractField(r)}.bind(this)),t};S.prototype.validate=function(){var e=[],t=[];if(this.preimage.length<S.MIN_PREIMAGE_LENGTH)return e.push("Preimage too short: "+this.preimage.length+" bytes (BIP-143 preimage requires at least "+S.MIN_PREIMAGE_LENGTH+")"),{valid:!1,errors:e,warnings:t,sighashInfo:this.sighashInfo};this.fields||this._extractFields();var r=["version","hashPrevouts","hashSequence","outpoint","scriptCode","amount","sequence","hashOutputs","locktime","sighash"];return r.forEach(function(i){this.fields[i]||e.push("Missing required field: "+i)}.bind(this)),this.sighashInfo.hasZeroHashes&&t.push("Zero hashes detected - check SIGHASH flags: "+this.sighashInfo.zeroFields.join(", ")),{valid:e.length===0,errors:e,warnings:t,sighashInfo:this.sighashInfo}};S.prototype.toObject=function(){return this.fields||this._extractFields(),{preimage:this.preimage.toString("hex"),length:this.preimage.length,strategy:this.strategy,fields:{version:this.fields.version?this.fields.version.toString("hex"):null,hashPrevouts:this.fields.hashPrevouts?this.fields.hashPrevouts.toString("hex"):null,hashSequence:this.fields.hashSequence?this.fields.hashSequence.toString("hex"):null,outpoint:this.fields.outpoint?this.fields.outpoint.toString("hex"):null,scriptCode:this.fields.scriptCode?this.fields.scriptCode.toString("hex"):null,scriptCodeLength:this.fields.scriptCodeLength,amount:this.fields.amount?this.fields.amount.toString("hex"):null,sequence:this.fields.sequence?this.fields.sequence.toString("hex"):null,hashOutputs:this.fields.hashOutputs?this.fields.hashOutputs.toString("hex"):null,locktime:this.fields.locktime?this.fields.locktime.toString("hex"):null,sighash:this.fields.sighash?this.fields.sighash.toString("hex"):null},sighashInfo:this.sighashInfo,validation:this.validate()}};S.prototype._extractFields=function(){if(this.fields={},this.sighashInfo={flag:null,hasZeroHashes:!1,zeroFields:[],warnings:[]},this.preimage.length<S.MIN_PREIMAGE_LENGTH)throw new Error("Preimage too short: "+this.preimage.length+" bytes (BIP-143 preimage requires at least "+S.MIN_PREIMAGE_LENGTH+")");try{this.strategy==="LEFT"||this.strategy==="DYNAMIC"?this._extractFromLeft():this.strategy==="RIGHT"&&this._extractFromRight(),this._analyzeSighash()}catch(e){if(this.strategy==="DYNAMIC")try{this.strategy="RIGHT",this._extractFromRight(),this._analyzeSighash()}catch{throw new Error("Failed to extract preimage fields with any strategy: "+e.message)}else throw e}};S.prototype._extractFromLeft=function(){var e=0;this.fields.version=this.preimage.slice(e,e+4),e+=4,this.fields.hashPrevouts=this.preimage.slice(e,e+32),e+=32,this.fields.hashSequence=this.preimage.slice(e,e+32),e+=32,this.fields.outpoint=this.preimage.slice(e,e+36),e+=36;var t=S.decodeCompactSize(this.preimage,e);this.fields.scriptCodeLength=t.value,e=t.nextOffset,this.fields.scriptCode=this.preimage.slice(e,e+this.fields.scriptCodeLength),e+=this.fields.scriptCodeLength,this.fields.amount=this.preimage.slice(e,e+8),e+=8,this.fields.sequence=this.preimage.slice(e,e+4),e+=4,this.fields.hashOutputs=this.preimage.slice(e,e+32),e+=32,this.fields.locktime=this.preimage.slice(e,e+4),e+=4,this.fields.sighash=this.preimage.slice(e,e+4)};S.prototype._extractFromRight=function(){var e=this.preimage.length,t=e;t-=4,this.fields.sighash=this.preimage.slice(t,t+4),t-=4,this.fields.locktime=this.preimage.slice(t,t+4),t-=32,this.fields.hashOutputs=this.preimage.slice(t,t+32),t-=4,this.fields.sequence=this.preimage.slice(t,t+4),t-=8,this.fields.amount=this.preimage.slice(t,t+8);var r=104,i=S.decodeCompactSize(this.preimage,r);this.fields.scriptCodeLength=i.value,this.fields.scriptCode=this.preimage.slice(i.nextOffset,i.nextOffset+this.fields.scriptCodeLength),this.fields.version=this.preimage.slice(0,4),this.fields.hashPrevouts=this.preimage.slice(4,36),this.fields.hashSequence=this.preimage.slice(36,68),this.fields.outpoint=this.preimage.slice(68,104)};S.prototype._analyzeSighash=function(){if(this.fields.sighash){var e=this.fields.sighash.readUInt32LE(0);this.sighashInfo.flag=e;var t=e&31,r=(e&128)!==0,i=(e&64)!==0,n=u.Buffer.alloc(32);r&&this.fields.hashPrevouts.equals(n)&&(this.sighashInfo.hasZeroHashes=!0,this.sighashInfo.zeroFields.push("hashPrevouts"),this.sighashInfo.warnings.push("ANYONECANPAY flag detected - hashPrevouts is zero")),t===2&&this.fields.hashSequence.equals(n)&&(this.sighashInfo.hasZeroHashes=!0,this.sighashInfo.zeroFields.push("hashSequence"),this.sighashInfo.warnings.push("SIGHASH_NONE flag detected - hashSequence is zero")),(t===2||t===3)&&this.fields.hashOutputs.equals(n)&&(this.sighashInfo.hasZeroHashes=!0,this.sighashInfo.zeroFields.push("hashOutputs"),this.sighashInfo.warnings.push("SIGHASH_NONE/SINGLE flag detected - hashOutputs is zero"));var o=[];t===1?o.push("ALL"):t===2?o.push("NONE"):t===3&&o.push("SINGLE"),r&&o.push("ANYONECANPAY"),i&&o.push("FORKID"),this.sighashInfo.flagName=o.join(" | ")}};S.prototype._parsePreimageStructure=function(){for(var e=this.preimage,t=0,r={},i=[{name:"nVersion",len:4},{name:"hashPrevouts",len:32},{name:"hashSequence",len:32},{name:"outpoint_txid",len:32},{name:"outpoint_vout",len:4}],n=[{name:"value",len:8},{name:"nSequence",len:4},{name:"hashOutputs",len:32},{name:"nLocktime",len:4},{name:"sighashType",len:4}],o=0;o<i.length;o++){var s=i[o];r[s.name]=e.slice(t,t+s.len).toString("hex"),t+=s.len}var a=S.decodeCompactSize(e,t);r.scriptLen=a.value,r.scriptLenSize=a.bytes,r.scriptLenRaw=e.slice(t,t+a.bytes).toString("hex"),t+=a.bytes,r.scriptCode=e.slice(t,t+r.scriptLen).toString("hex"),t+=r.scriptLen;for(var c=0;c<n.length;c++){var d=n[c];r[d.name]=e.slice(t,t+d.len).toString("hex"),t+=d.len}var g=i.reduce(function(P,O){return P+O.len},0),y=n.reduce(function(P,O){return P+O.len},0);return r._structure={leftFixed:g,scriptLenVarint:a.bytes,scriptCode:r.scriptLen,rightFixed:y,totalCalculated:g+a.bytes+r.scriptLen+y,totalActual:e.length},r};S.prototype._generateBidirectionalASM=function(e,t,r){var i=["value","nSequence","hashOutputs","nLocktime","sighashType"],n=["nVersion","hashPrevouts","hashSequence","outpoint_txid","outpoint_vout"];if(i.includes(e))return this._generateRightExtractionASM(e,r);if(n.includes(e))return this._generateLeftExtractionASM(e,r);if(e==="scriptCode")return this._generateDynamicExtractionASM(t,r);if(e==="scriptLen")return this._generateScriptLenExtractionASM(t,r);throw new Error("Unknown field: "+e)};S.prototype._generateRightExtractionASM=function(e,t){for(var r=[{name:"value",len:8},{name:"nSequence",len:4},{name:"hashOutputs",len:32},{name:"nLocktime",len:4},{name:"sighashType",len:4}],i=0,n=0,o=!1,s=0;s<r.length;s++){var a=r[s];if(a.name===e){n=a.len,o=!0;break}i+=a.len}if(!o)throw new Error("Field not found in RIGHT fields: "+e);var c=52,d=c-i,g=[];return t?(g.push("# \u{1F504} Extract "+e+" from RIGHT side (bidirectional strategy)"),g.push("OP_SIZE # Push preimage size: [preimage, size]")):g.push("OP_SIZE"),t?g=g.concat([d+" OP_SUB # Calculate split point: [preimage, split_point]","OP_SPLIT # Split: [left_part, right_part]","OP_NIP # Drop left (OP_SPLIT leaves right on top): [right_part]",n+" OP_SPLIT # Extract field: ["+e+", remaining]","OP_DROP # Clean up: ["+e+"]","# \u2705 Result: "+e+" is now on top of stack"]):g=g.concat([d+" OP_SUB","OP_SPLIT","OP_NIP",n+" OP_SPLIT","OP_DROP"]),g.join(`
|
|
1
|
+
var bsvSmartContract=(()=>{var Xn=Object.create;var yr=Object.defineProperty;var jn=Object.getOwnPropertyDescriptor;var Wn=Object.getOwnPropertyNames;var Qn=Object.getPrototypeOf,Zn=Object.prototype.hasOwnProperty;var L=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Jn=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var O=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var eo=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Wn(t))!Zn.call(e,n)&&n!==r&&yr(e,n,{get:()=>t[n],enumerable:!(i=jn(t,n))||i.enumerable});return e};var Sr=(e,t,r)=>(r=e!=null?Xn(Qn(e)):{},eo(t||!e||!e.__esModule?yr(r,"default",{value:e,enumerable:!0}):r,e));var _r=O((qs,Pr)=>{f();var I=Pr.exports={},j,W;function gt(){throw new Error("setTimeout has not been defined")}function mt(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?j=setTimeout:j=gt}catch{j=gt}try{typeof clearTimeout=="function"?W=clearTimeout:W=mt}catch{W=mt}})();function vr(e){if(j===setTimeout)return setTimeout(e,0);if((j===gt||!j)&&setTimeout)return j=setTimeout,setTimeout(e,0);try{return j(e,0)}catch{try{return j.call(null,e,0)}catch{return j.call(this,e,0)}}}function to(e){if(W===clearTimeout)return clearTimeout(e);if((W===mt||!W)&&clearTimeout)return W=clearTimeout,clearTimeout(e);try{return W(e)}catch{try{return W.call(null,e)}catch{return W.call(this,e)}}}var ie=[],Te=!1,Oe,Ze=-1;function ro(){!Te||!Oe||(Te=!1,Oe.length?ie=Oe.concat(ie):Ze=-1,ie.length&&Or())}function Or(){if(!Te){var e=vr(ro);Te=!0;for(var t=ie.length;t;){for(Oe=ie,ie=[];++Ze<t;)Oe&&Oe[Ze].run();Ze=-1,t=ie.length}Oe=null,Te=!1,to(e)}}I.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];ie.push(new xr(e,t)),ie.length===1&&!Te&&vr(Or)};function xr(e,t){this.fun=e,this.array=t}xr.prototype.run=function(){this.fun.apply(null,this.array)};I.title="browser";I.browser=!0;I.env={};I.argv=[];I.version="";I.versions={};function ne(){}I.on=ne;I.addListener=ne;I.once=ne;I.off=ne;I.removeListener=ne;I.removeAllListeners=ne;I.emit=ne;I.prependListener=ne;I.prependOnceListener=ne;I.listeners=function(e){return[]};I.binding=function(e){throw new Error("process.binding is not supported")};I.cwd=function(){return"/"};I.chdir=function(e){throw new Error("process.chdir is not supported")};I.umask=function(){return 0}});var Tr=O(Je=>{"use strict";f();Je.byteLength=no;Je.toByteArray=ao;Je.fromByteArray=uo;var Q=[],K=[],io=typeof Uint8Array<"u"?Uint8Array:Array,yt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(xe=0,Er=yt.length;xe<Er;++xe)Q[xe]=yt[xe],K[yt.charCodeAt(xe)]=xe;var xe,Er;K[45]=62;K[95]=63;function wr(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");r===-1&&(r=t);var i=r===t?0:4-r%4;return[r,i]}function no(e){var t=wr(e),r=t[0],i=t[1];return(r+i)*3/4-i}function oo(e,t,r){return(t+r)*3/4-r}function ao(e){var t,r=wr(e),i=r[0],n=r[1],o=new io(oo(e,i,n)),a=0,s=n>0?i-4:i,c;for(c=0;c<s;c+=4)t=K[e.charCodeAt(c)]<<18|K[e.charCodeAt(c+1)]<<12|K[e.charCodeAt(c+2)]<<6|K[e.charCodeAt(c+3)],o[a++]=t>>16&255,o[a++]=t>>8&255,o[a++]=t&255;return n===2&&(t=K[e.charCodeAt(c)]<<2|K[e.charCodeAt(c+1)]>>4,o[a++]=t&255),n===1&&(t=K[e.charCodeAt(c)]<<10|K[e.charCodeAt(c+1)]<<4|K[e.charCodeAt(c+2)]>>2,o[a++]=t>>8&255,o[a++]=t&255),o}function so(e){return Q[e>>18&63]+Q[e>>12&63]+Q[e>>6&63]+Q[e&63]}function co(e,t,r){for(var i,n=[],o=t;o<r;o+=3)i=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(e[o+2]&255),n.push(so(i));return n.join("")}function uo(e){for(var t,r=e.length,i=r%3,n=[],o=16383,a=0,s=r-i;a<s;a+=o)n.push(co(e,a,a+o>s?s:a+o));return i===1?(t=e[r-1],n.push(Q[t>>2]+Q[t<<4&63]+"==")):i===2&&(t=(e[r-2]<<8)+e[r-1],n.push(Q[t>>10]+Q[t>>4&63]+Q[t<<2&63]+"=")),n.join("")}});var Ir=O(St=>{f();St.read=function(e,t,r,i,n){var o,a,s=n*8-i-1,c=(1<<s)-1,d=c>>1,g=-7,y=r?n-1:0,P=r?-1:1,x=e[t+y];for(y+=P,o=x&(1<<-g)-1,x>>=-g,g+=s;g>0;o=o*256+e[t+y],y+=P,g-=8);for(a=o&(1<<-g)-1,o>>=-g,g+=i;g>0;a=a*256+e[t+y],y+=P,g-=8);if(o===0)o=1-d;else{if(o===c)return a?NaN:(x?-1:1)*(1/0);a=a+Math.pow(2,i),o=o-d}return(x?-1:1)*a*Math.pow(2,o-i)};St.write=function(e,t,r,i,n,o){var a,s,c,d=o*8-n-1,g=(1<<d)-1,y=g>>1,P=n===23?Math.pow(2,-24)-Math.pow(2,-77):0,x=i?0:o-1,re=i?1:-1,Yn=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=g):(a=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-a))<1&&(a--,c*=2),a+y>=1?t+=P/c:t+=P*Math.pow(2,1-y),t*c>=2&&(a++,c/=2),a+y>=g?(s=0,a=g):a+y>=1?(s=(t*c-1)*Math.pow(2,n),a=a+y):(s=t*Math.pow(2,y-1)*Math.pow(2,n),a=0));n>=8;e[r+x]=s&255,x+=re,s/=256,n-=8);for(a=a<<n|s,d+=n;d>0;e[r+x]=a&255,x+=re,a/=256,d-=8);e[r+x-re]|=Yn*128}});var Kr=O(ke=>{"use strict";f();var vt=Tr(),Ae=Ir(),Ar=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;ke.Buffer=h;ke.SlowBuffer=mo;ke.INSPECT_MAX_BYTES=50;var et=2147483647;ke.kMaxLength=et;h.TYPED_ARRAY_SUPPORT=ho();!h.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 ho(){try{let e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),e.foo()===42}catch{return!1}}Object.defineProperty(h.prototype,"parent",{enumerable:!0,get:function(){if(h.isBuffer(this))return this.buffer}});Object.defineProperty(h.prototype,"offset",{enumerable:!0,get:function(){if(h.isBuffer(this))return this.byteOffset}});function oe(e){if(e>et)throw new RangeError('The value "'+e+'" is invalid for option "size"');let t=new Uint8Array(e);return Object.setPrototypeOf(t,h.prototype),t}function h(e,t,r){if(typeof e=="number"){if(typeof t=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return _t(e)}return Fr(e,t,r)}h.poolSize=8192;function Fr(e,t,r){if(typeof e=="string")return lo(e,t);if(ArrayBuffer.isView(e))return fo(e);if(e==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(Z(e,ArrayBuffer)||e&&Z(e.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Z(e,SharedArrayBuffer)||e&&Z(e.buffer,SharedArrayBuffer)))return xt(e,t,r);if(typeof e=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let i=e.valueOf&&e.valueOf();if(i!=null&&i!==e)return h.from(i,t,r);let n=go(e);if(n)return n;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof e[Symbol.toPrimitive]=="function")return h.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}h.from=function(e,t,r){return Fr(e,t,r)};Object.setPrototypeOf(h.prototype,Uint8Array.prototype);Object.setPrototypeOf(h,Uint8Array);function Cr(e){if(typeof e!="number")throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function po(e,t,r){return Cr(e),e<=0?oe(e):t!==void 0?typeof r=="string"?oe(e).fill(t,r):oe(e).fill(t):oe(e)}h.alloc=function(e,t,r){return po(e,t,r)};function _t(e){return Cr(e),oe(e<0?0:Et(e)|0)}h.allocUnsafe=function(e){return _t(e)};h.allocUnsafeSlow=function(e){return _t(e)};function lo(e,t){if((typeof t!="string"||t==="")&&(t="utf8"),!h.isEncoding(t))throw new TypeError("Unknown encoding: "+t);let r=Lr(e,t)|0,i=oe(r),n=i.write(e,t);return n!==r&&(i=i.slice(0,n)),i}function Ot(e){let t=e.length<0?0:Et(e.length)|0,r=oe(t);for(let i=0;i<t;i+=1)r[i]=e[i]&255;return r}function fo(e){if(Z(e,Uint8Array)){let t=new Uint8Array(e);return xt(t.buffer,t.byteOffset,t.byteLength)}return Ot(e)}function xt(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');let i;return t===void 0&&r===void 0?i=new Uint8Array(e):r===void 0?i=new Uint8Array(e,t):i=new Uint8Array(e,t,r),Object.setPrototypeOf(i,h.prototype),i}function go(e){if(h.isBuffer(e)){let t=Et(e.length)|0,r=oe(t);return r.length===0||e.copy(r,0,0,t),r}if(e.length!==void 0)return typeof e.length!="number"||Tt(e.length)?oe(0):Ot(e);if(e.type==="Buffer"&&Array.isArray(e.data))return Ot(e.data)}function Et(e){if(e>=et)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+et.toString(16)+" bytes");return e|0}function mo(e){return+e!=e&&(e=0),h.alloc(+e)}h.isBuffer=function(t){return t!=null&&t._isBuffer===!0&&t!==h.prototype};h.compare=function(t,r){if(Z(t,Uint8Array)&&(t=h.from(t,t.offset,t.byteLength)),Z(r,Uint8Array)&&(r=h.from(r,r.offset,r.byteLength)),!h.isBuffer(t)||!h.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(t===r)return 0;let i=t.length,n=r.length;for(let o=0,a=Math.min(i,n);o<a;++o)if(t[o]!==r[o]){i=t[o],n=r[o];break}return i<n?-1:n<i?1:0};h.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};h.concat=function(t,r){if(!Array.isArray(t))throw new TypeError('"list" argument must be an Array of Buffers');if(t.length===0)return h.alloc(0);let i;if(r===void 0)for(r=0,i=0;i<t.length;++i)r+=t[i].length;let n=h.allocUnsafe(r),o=0;for(i=0;i<t.length;++i){let a=t[i];if(Z(a,Uint8Array))o+a.length>n.length?(h.isBuffer(a)||(a=h.from(a)),a.copy(n,o)):Uint8Array.prototype.set.call(n,a,o);else if(h.isBuffer(a))a.copy(n,o);else throw new TypeError('"list" argument must be an Array of Buffers');o+=a.length}return n};function Lr(e,t){if(h.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||Z(e,ArrayBuffer))return e.byteLength;if(typeof e!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);let r=e.length,i=arguments.length>2&&arguments[2]===!0;if(!i&&r===0)return 0;let n=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return Pt(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return Vr(e).length;default:if(n)return i?-1:Pt(e).length;t=(""+t).toLowerCase(),n=!0}}h.byteLength=Lr;function yo(e,t,r){let i=!1;if((t===void 0||t<0)&&(t=0),t>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,t>>>=0,r<=t))return"";for(e||(e="utf8");;)switch(e){case"hex":return Io(this,t,r);case"utf8":case"utf-8":return Br(this,t,r);case"ascii":return wo(this,t,r);case"latin1":case"binary":return To(this,t,r);case"base64":return _o(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ao(this,t,r);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}h.prototype._isBuffer=!0;function Pe(e,t,r){let i=e[t];e[t]=e[r],e[r]=i}h.prototype.swap16=function(){let t=this.length;if(t%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let r=0;r<t;r+=2)Pe(this,r,r+1);return this};h.prototype.swap32=function(){let t=this.length;if(t%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let r=0;r<t;r+=4)Pe(this,r,r+3),Pe(this,r+1,r+2);return this};h.prototype.swap64=function(){let t=this.length;if(t%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let r=0;r<t;r+=8)Pe(this,r,r+7),Pe(this,r+1,r+6),Pe(this,r+2,r+5),Pe(this,r+3,r+4);return this};h.prototype.toString=function(){let t=this.length;return t===0?"":arguments.length===0?Br(this,0,t):yo.apply(this,arguments)};h.prototype.toLocaleString=h.prototype.toString;h.prototype.equals=function(t){if(!h.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t?!0:h.compare(this,t)===0};h.prototype.inspect=function(){let t="",r=ke.INSPECT_MAX_BYTES;return t=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(t+=" ... "),"<Buffer "+t+">"};Ar&&(h.prototype[Ar]=h.prototype.inspect);h.prototype.compare=function(t,r,i,n,o){if(Z(t,Uint8Array)&&(t=h.from(t,t.offset,t.byteLength)),!h.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(r===void 0&&(r=0),i===void 0&&(i=t?t.length:0),n===void 0&&(n=0),o===void 0&&(o=this.length),r<0||i>t.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&r>=i)return 0;if(n>=o)return-1;if(r>=i)return 1;if(r>>>=0,i>>>=0,n>>>=0,o>>>=0,this===t)return 0;let a=o-n,s=i-r,c=Math.min(a,s),d=this.slice(n,o),g=t.slice(r,i);for(let y=0;y<c;++y)if(d[y]!==g[y]){a=d[y],s=g[y];break}return a<s?-1:s<a?1:0};function Rr(e,t,r,i,n){if(e.length===0)return-1;if(typeof r=="string"?(i=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,Tt(r)&&(r=n?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(n)return-1;r=e.length-1}else if(r<0)if(n)r=0;else return-1;if(typeof t=="string"&&(t=h.from(t,i)),h.isBuffer(t))return t.length===0?-1:br(e,t,r,i,n);if(typeof t=="number")return t=t&255,typeof Uint8Array.prototype.indexOf=="function"?n?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):br(e,[t],r,i,n);throw new TypeError("val must be string, number or Buffer")}function br(e,t,r,i,n){let o=1,a=e.length,s=t.length;if(i!==void 0&&(i=String(i).toLowerCase(),i==="ucs2"||i==="ucs-2"||i==="utf16le"||i==="utf-16le")){if(e.length<2||t.length<2)return-1;o=2,a/=2,s/=2,r/=2}function c(g,y){return o===1?g[y]:g.readUInt16BE(y*o)}let d;if(n){let g=-1;for(d=r;d<a;d++)if(c(e,d)===c(t,g===-1?0:d-g)){if(g===-1&&(g=d),d-g+1===s)return g*o}else g!==-1&&(d-=d-g),g=-1}else for(r+s>a&&(r=a-s),d=r;d>=0;d--){let g=!0;for(let y=0;y<s;y++)if(c(e,d+y)!==c(t,y)){g=!1;break}if(g)return d}return-1}h.prototype.includes=function(t,r,i){return this.indexOf(t,r,i)!==-1};h.prototype.indexOf=function(t,r,i){return Rr(this,t,r,i,!0)};h.prototype.lastIndexOf=function(t,r,i){return Rr(this,t,r,i,!1)};function So(e,t,r,i){r=Number(r)||0;let n=e.length-r;i?(i=Number(i),i>n&&(i=n)):i=n;let o=t.length;i>o/2&&(i=o/2);let a;for(a=0;a<i;++a){let s=parseInt(t.substr(a*2,2),16);if(Tt(s))return a;e[r+a]=s}return a}function vo(e,t,r,i){return tt(Pt(t,e.length-r),e,r,i)}function Oo(e,t,r,i){return tt(Fo(t),e,r,i)}function xo(e,t,r,i){return tt(Vr(t),e,r,i)}function Po(e,t,r,i){return tt(Co(t,e.length-r),e,r,i)}h.prototype.write=function(t,r,i,n){if(r===void 0)n="utf8",i=this.length,r=0;else if(i===void 0&&typeof r=="string")n=r,i=this.length,r=0;else if(isFinite(r))r=r>>>0,isFinite(i)?(i=i>>>0,n===void 0&&(n="utf8")):(n=i,i=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let o=this.length-r;if((i===void 0||i>o)&&(i=o),t.length>0&&(i<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let a=!1;for(;;)switch(n){case"hex":return So(this,t,r,i);case"utf8":case"utf-8":return vo(this,t,r,i);case"ascii":case"latin1":case"binary":return Oo(this,t,r,i);case"base64":return xo(this,t,r,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Po(this,t,r,i);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}};h.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function _o(e,t,r){return t===0&&r===e.length?vt.fromByteArray(e):vt.fromByteArray(e.slice(t,r))}function Br(e,t,r){r=Math.min(e.length,r);let i=[],n=t;for(;n<r;){let o=e[n],a=null,s=o>239?4:o>223?3:o>191?2:1;if(n+s<=r){let c,d,g,y;switch(s){case 1:o<128&&(a=o);break;case 2:c=e[n+1],(c&192)===128&&(y=(o&31)<<6|c&63,y>127&&(a=y));break;case 3:c=e[n+1],d=e[n+2],(c&192)===128&&(d&192)===128&&(y=(o&15)<<12|(c&63)<<6|d&63,y>2047&&(y<55296||y>57343)&&(a=y));break;case 4:c=e[n+1],d=e[n+2],g=e[n+3],(c&192)===128&&(d&192)===128&&(g&192)===128&&(y=(o&15)<<18|(c&63)<<12|(d&63)<<6|g&63,y>65535&&y<1114112&&(a=y))}}a===null?(a=65533,s=1):a>65535&&(a-=65536,i.push(a>>>10&1023|55296),a=56320|a&1023),i.push(a),n+=s}return Eo(i)}var kr=4096;function Eo(e){let t=e.length;if(t<=kr)return String.fromCharCode.apply(String,e);let r="",i=0;for(;i<t;)r+=String.fromCharCode.apply(String,e.slice(i,i+=kr));return r}function wo(e,t,r){let i="";r=Math.min(e.length,r);for(let n=t;n<r;++n)i+=String.fromCharCode(e[n]&127);return i}function To(e,t,r){let i="";r=Math.min(e.length,r);for(let n=t;n<r;++n)i+=String.fromCharCode(e[n]);return i}function Io(e,t,r){let i=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>i)&&(r=i);let n="";for(let o=t;o<r;++o)n+=Lo[e[o]];return n}function Ao(e,t,r){let i=e.slice(t,r),n="";for(let o=0;o<i.length-1;o+=2)n+=String.fromCharCode(i[o]+i[o+1]*256);return n}h.prototype.slice=function(t,r){let i=this.length;t=~~t,r=r===void 0?i:~~r,t<0?(t+=i,t<0&&(t=0)):t>i&&(t=i),r<0?(r+=i,r<0&&(r=0)):r>i&&(r=i),r<t&&(r=t);let n=this.subarray(t,r);return Object.setPrototypeOf(n,h.prototype),n};function F(e,t,r){if(e%1!==0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}h.prototype.readUintLE=h.prototype.readUIntLE=function(t,r,i){t=t>>>0,r=r>>>0,i||F(t,r,this.length);let n=this[t],o=1,a=0;for(;++a<r&&(o*=256);)n+=this[t+a]*o;return n};h.prototype.readUintBE=h.prototype.readUIntBE=function(t,r,i){t=t>>>0,r=r>>>0,i||F(t,r,this.length);let n=this[t+--r],o=1;for(;r>0&&(o*=256);)n+=this[t+--r]*o;return n};h.prototype.readUint8=h.prototype.readUInt8=function(t,r){return t=t>>>0,r||F(t,1,this.length),this[t]};h.prototype.readUint16LE=h.prototype.readUInt16LE=function(t,r){return t=t>>>0,r||F(t,2,this.length),this[t]|this[t+1]<<8};h.prototype.readUint16BE=h.prototype.readUInt16BE=function(t,r){return t=t>>>0,r||F(t,2,this.length),this[t]<<8|this[t+1]};h.prototype.readUint32LE=h.prototype.readUInt32LE=function(t,r){return t=t>>>0,r||F(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+this[t+3]*16777216};h.prototype.readUint32BE=h.prototype.readUInt32BE=function(t,r){return t=t>>>0,r||F(t,4,this.length),this[t]*16777216+(this[t+1]<<16|this[t+2]<<8|this[t+3])};h.prototype.readBigUInt64LE=de(function(t){t=t>>>0,be(t,"offset");let r=this[t],i=this[t+7];(r===void 0||i===void 0)&&Ke(t,this.length-8);let n=r+this[++t]*2**8+this[++t]*2**16+this[++t]*2**24,o=this[++t]+this[++t]*2**8+this[++t]*2**16+i*2**24;return BigInt(n)+(BigInt(o)<<BigInt(32))});h.prototype.readBigUInt64BE=de(function(t){t=t>>>0,be(t,"offset");let r=this[t],i=this[t+7];(r===void 0||i===void 0)&&Ke(t,this.length-8);let n=r*2**24+this[++t]*2**16+this[++t]*2**8+this[++t],o=this[++t]*2**24+this[++t]*2**16+this[++t]*2**8+i;return(BigInt(n)<<BigInt(32))+BigInt(o)});h.prototype.readIntLE=function(t,r,i){t=t>>>0,r=r>>>0,i||F(t,r,this.length);let n=this[t],o=1,a=0;for(;++a<r&&(o*=256);)n+=this[t+a]*o;return o*=128,n>=o&&(n-=Math.pow(2,8*r)),n};h.prototype.readIntBE=function(t,r,i){t=t>>>0,r=r>>>0,i||F(t,r,this.length);let n=r,o=1,a=this[t+--n];for(;n>0&&(o*=256);)a+=this[t+--n]*o;return o*=128,a>=o&&(a-=Math.pow(2,8*r)),a};h.prototype.readInt8=function(t,r){return t=t>>>0,r||F(t,1,this.length),this[t]&128?(255-this[t]+1)*-1:this[t]};h.prototype.readInt16LE=function(t,r){t=t>>>0,r||F(t,2,this.length);let i=this[t]|this[t+1]<<8;return i&32768?i|4294901760:i};h.prototype.readInt16BE=function(t,r){t=t>>>0,r||F(t,2,this.length);let i=this[t+1]|this[t]<<8;return i&32768?i|4294901760:i};h.prototype.readInt32LE=function(t,r){return t=t>>>0,r||F(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24};h.prototype.readInt32BE=function(t,r){return t=t>>>0,r||F(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]};h.prototype.readBigInt64LE=de(function(t){t=t>>>0,be(t,"offset");let r=this[t],i=this[t+7];(r===void 0||i===void 0)&&Ke(t,this.length-8);let n=this[t+4]+this[t+5]*2**8+this[t+6]*2**16+(i<<24);return(BigInt(n)<<BigInt(32))+BigInt(r+this[++t]*2**8+this[++t]*2**16+this[++t]*2**24)});h.prototype.readBigInt64BE=de(function(t){t=t>>>0,be(t,"offset");let r=this[t],i=this[t+7];(r===void 0||i===void 0)&&Ke(t,this.length-8);let n=(r<<24)+this[++t]*2**16+this[++t]*2**8+this[++t];return(BigInt(n)<<BigInt(32))+BigInt(this[++t]*2**24+this[++t]*2**16+this[++t]*2**8+i)});h.prototype.readFloatLE=function(t,r){return t=t>>>0,r||F(t,4,this.length),Ae.read(this,t,!0,23,4)};h.prototype.readFloatBE=function(t,r){return t=t>>>0,r||F(t,4,this.length),Ae.read(this,t,!1,23,4)};h.prototype.readDoubleLE=function(t,r){return t=t>>>0,r||F(t,8,this.length),Ae.read(this,t,!0,52,8)};h.prototype.readDoubleBE=function(t,r){return t=t>>>0,r||F(t,8,this.length),Ae.read(this,t,!1,52,8)};function R(e,t,r,i,n,o){if(!h.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>n||t<o)throw new RangeError('"value" argument is out of bounds');if(r+i>e.length)throw new RangeError("Index out of range")}h.prototype.writeUintLE=h.prototype.writeUIntLE=function(t,r,i,n){if(t=+t,r=r>>>0,i=i>>>0,!n){let s=Math.pow(2,8*i)-1;R(this,t,r,i,s,0)}let o=1,a=0;for(this[r]=t&255;++a<i&&(o*=256);)this[r+a]=t/o&255;return r+i};h.prototype.writeUintBE=h.prototype.writeUIntBE=function(t,r,i,n){if(t=+t,r=r>>>0,i=i>>>0,!n){let s=Math.pow(2,8*i)-1;R(this,t,r,i,s,0)}let o=i-1,a=1;for(this[r+o]=t&255;--o>=0&&(a*=256);)this[r+o]=t/a&255;return r+i};h.prototype.writeUint8=h.prototype.writeUInt8=function(t,r,i){return t=+t,r=r>>>0,i||R(this,t,r,1,255,0),this[r]=t&255,r+1};h.prototype.writeUint16LE=h.prototype.writeUInt16LE=function(t,r,i){return t=+t,r=r>>>0,i||R(this,t,r,2,65535,0),this[r]=t&255,this[r+1]=t>>>8,r+2};h.prototype.writeUint16BE=h.prototype.writeUInt16BE=function(t,r,i){return t=+t,r=r>>>0,i||R(this,t,r,2,65535,0),this[r]=t>>>8,this[r+1]=t&255,r+2};h.prototype.writeUint32LE=h.prototype.writeUInt32LE=function(t,r,i){return t=+t,r=r>>>0,i||R(this,t,r,4,4294967295,0),this[r+3]=t>>>24,this[r+2]=t>>>16,this[r+1]=t>>>8,this[r]=t&255,r+4};h.prototype.writeUint32BE=h.prototype.writeUInt32BE=function(t,r,i){return t=+t,r=r>>>0,i||R(this,t,r,4,4294967295,0),this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=t&255,r+4};function Nr(e,t,r,i,n){Gr(t,i,n,e,r,7);let o=Number(t&BigInt(4294967295));e[r++]=o,o=o>>8,e[r++]=o,o=o>>8,e[r++]=o,o=o>>8,e[r++]=o;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=a,a=a>>8,e[r++]=a,a=a>>8,e[r++]=a,a=a>>8,e[r++]=a,r}function Ur(e,t,r,i,n){Gr(t,i,n,e,r,7);let o=Number(t&BigInt(4294967295));e[r+7]=o,o=o>>8,e[r+6]=o,o=o>>8,e[r+5]=o,o=o>>8,e[r+4]=o;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=a,a=a>>8,e[r+2]=a,a=a>>8,e[r+1]=a,a=a>>8,e[r]=a,r+8}h.prototype.writeBigUInt64LE=de(function(t,r=0){return Nr(this,t,r,BigInt(0),BigInt("0xffffffffffffffff"))});h.prototype.writeBigUInt64BE=de(function(t,r=0){return Ur(this,t,r,BigInt(0),BigInt("0xffffffffffffffff"))});h.prototype.writeIntLE=function(t,r,i,n){if(t=+t,r=r>>>0,!n){let c=Math.pow(2,8*i-1);R(this,t,r,i,c-1,-c)}let o=0,a=1,s=0;for(this[r]=t&255;++o<i&&(a*=256);)t<0&&s===0&&this[r+o-1]!==0&&(s=1),this[r+o]=(t/a>>0)-s&255;return r+i};h.prototype.writeIntBE=function(t,r,i,n){if(t=+t,r=r>>>0,!n){let c=Math.pow(2,8*i-1);R(this,t,r,i,c-1,-c)}let o=i-1,a=1,s=0;for(this[r+o]=t&255;--o>=0&&(a*=256);)t<0&&s===0&&this[r+o+1]!==0&&(s=1),this[r+o]=(t/a>>0)-s&255;return r+i};h.prototype.writeInt8=function(t,r,i){return t=+t,r=r>>>0,i||R(this,t,r,1,127,-128),t<0&&(t=255+t+1),this[r]=t&255,r+1};h.prototype.writeInt16LE=function(t,r,i){return t=+t,r=r>>>0,i||R(this,t,r,2,32767,-32768),this[r]=t&255,this[r+1]=t>>>8,r+2};h.prototype.writeInt16BE=function(t,r,i){return t=+t,r=r>>>0,i||R(this,t,r,2,32767,-32768),this[r]=t>>>8,this[r+1]=t&255,r+2};h.prototype.writeInt32LE=function(t,r,i){return t=+t,r=r>>>0,i||R(this,t,r,4,2147483647,-2147483648),this[r]=t&255,this[r+1]=t>>>8,this[r+2]=t>>>16,this[r+3]=t>>>24,r+4};h.prototype.writeInt32BE=function(t,r,i){return t=+t,r=r>>>0,i||R(this,t,r,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=t&255,r+4};h.prototype.writeBigInt64LE=de(function(t,r=0){return Nr(this,t,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});h.prototype.writeBigInt64BE=de(function(t,r=0){return Ur(this,t,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function qr(e,t,r,i,n,o){if(r+i>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function Dr(e,t,r,i,n){return t=+t,r=r>>>0,n||qr(e,t,r,4,34028234663852886e22,-34028234663852886e22),Ae.write(e,t,r,i,23,4),r+4}h.prototype.writeFloatLE=function(t,r,i){return Dr(this,t,r,!0,i)};h.prototype.writeFloatBE=function(t,r,i){return Dr(this,t,r,!1,i)};function Mr(e,t,r,i,n){return t=+t,r=r>>>0,n||qr(e,t,r,8,17976931348623157e292,-17976931348623157e292),Ae.write(e,t,r,i,52,8),r+8}h.prototype.writeDoubleLE=function(t,r,i){return Mr(this,t,r,!0,i)};h.prototype.writeDoubleBE=function(t,r,i){return Mr(this,t,r,!1,i)};h.prototype.copy=function(t,r,i,n){if(!h.isBuffer(t))throw new TypeError("argument should be a Buffer");if(i||(i=0),!n&&n!==0&&(n=this.length),r>=t.length&&(r=t.length),r||(r=0),n>0&&n<i&&(n=i),n===i||t.length===0||this.length===0)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-r<n-i&&(n=t.length-r+i);let o=n-i;return this===t&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(r,i,n):Uint8Array.prototype.set.call(t,this.subarray(i,n),r),o};h.prototype.fill=function(t,r,i,n){if(typeof t=="string"){if(typeof r=="string"?(n=r,r=0,i=this.length):typeof i=="string"&&(n=i,i=this.length),n!==void 0&&typeof n!="string")throw new TypeError("encoding must be a string");if(typeof n=="string"&&!h.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(t.length===1){let a=t.charCodeAt(0);(n==="utf8"&&a<128||n==="latin1")&&(t=a)}}else typeof t=="number"?t=t&255:typeof t=="boolean"&&(t=Number(t));if(r<0||this.length<r||this.length<i)throw new RangeError("Out of range index");if(i<=r)return this;r=r>>>0,i=i===void 0?this.length:i>>>0,t||(t=0);let o;if(typeof t=="number")for(o=r;o<i;++o)this[o]=t;else{let a=h.isBuffer(t)?t:h.from(t,n),s=a.length;if(s===0)throw new TypeError('The value "'+t+'" is invalid for argument "value"');for(o=0;o<i-r;++o)this[o+r]=a[o%s]}return this};var Ie={};function wt(e,t,r){Ie[e]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(n){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:n,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}wt("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError);wt("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError);wt("ERR_OUT_OF_RANGE",function(e,t,r){let i=`The value of "${e}" is out of range.`,n=r;return Number.isInteger(r)&&Math.abs(r)>2**32?n=Hr(String(r)):typeof r=="bigint"&&(n=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(n=Hr(n)),n+="n"),i+=` It must be ${t}. Received ${n}`,i},RangeError);function Hr(e){let t="",r=e.length,i=e[0]==="-"?1:0;for(;r>=i+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function bo(e,t,r){be(t,"offset"),(e[t]===void 0||e[t+r]===void 0)&&Ke(t,e.length-(r+1))}function Gr(e,t,r,i,n,o){if(e>r||e<t){let a=typeof t=="bigint"?"n":"",s;throw o>3?t===0||t===BigInt(0)?s=`>= 0${a} and < 2${a} ** ${(o+1)*8}${a}`:s=`>= -(2${a} ** ${(o+1)*8-1}${a}) and < 2 ** ${(o+1)*8-1}${a}`:s=`>= ${t}${a} and <= ${r}${a}`,new Ie.ERR_OUT_OF_RANGE("value",s,e)}bo(i,n,o)}function be(e,t){if(typeof e!="number")throw new Ie.ERR_INVALID_ARG_TYPE(t,"number",e)}function Ke(e,t,r){throw Math.floor(e)!==e?(be(e,r),new Ie.ERR_OUT_OF_RANGE(r||"offset","an integer",e)):t<0?new Ie.ERR_BUFFER_OUT_OF_BOUNDS:new Ie.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}var ko=/[^+/0-9A-Za-z-_]/g;function Ho(e){if(e=e.split("=")[0],e=e.trim().replace(ko,""),e.length<2)return"";for(;e.length%4!==0;)e=e+"=";return e}function Pt(e,t){t=t||1/0;let r,i=e.length,n=null,o=[];for(let a=0;a<i;++a){if(r=e.charCodeAt(a),r>55295&&r<57344){if(!n){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}else if(a+1===i){(t-=3)>-1&&o.push(239,191,189);continue}n=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),n=r;continue}r=(n-55296<<10|r-56320)+65536}else n&&(t-=3)>-1&&o.push(239,191,189);if(n=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,r&63|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return o}function Fo(e){let t=[];for(let r=0;r<e.length;++r)t.push(e.charCodeAt(r)&255);return t}function Co(e,t){let r,i,n,o=[];for(let a=0;a<e.length&&!((t-=2)<0);++a)r=e.charCodeAt(a),i=r>>8,n=r%256,o.push(n),o.push(i);return o}function Vr(e){return vt.toByteArray(Ho(e))}function tt(e,t,r,i){let n;for(n=0;n<i&&!(n+r>=t.length||n>=e.length);++n)t[n+r]=e[n];return n}function Z(e,t){return e instanceof t||e!=null&&e.constructor!=null&&e.constructor.name!=null&&e.constructor.name===t.name}function Tt(e){return e!==e}var Lo=(function(){let e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){let i=r*16;for(let n=0;n<16;++n)t[i+n]=e[r]+e[n]}return t})();function de(e){return typeof BigInt>"u"?Ro:e}function Ro(){throw new Error("BigInt not supported")}});var m,u,f=Jn(()=>{m=Sr(_r()),u=Sr(Kr())});var fe=O((js,zr)=>{f();zr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.crypto.Hash});var D=O((Qs,$r)=>{f();$r.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Transaction});var It=O((Js,Yr)=>{f();Yr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Address});var b=O((tc,Xr)=>{f();Xr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Script});var _e=O((ic,jr)=>{f();jr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Transaction.sighash});var He=O((oc,Wr)=>{f();Wr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Transaction.Input});var ge=O((sc,Qr)=>{f();Qr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Script.Interpreter});var Ee=O((uc,Zr)=>{f();Zr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.crypto.Signature});var M=O((pc,Jr)=>{f();Jr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.crypto.BN});var C=O((dc,ei)=>{"use strict";f();ei.exports={}});var ai=O((gc,oi)=>{"use strict";f();var ii=_e(),Bo=He(),Fe=ge(),ti=Ee(),No=fe(),At=M(),ni=D(),me=b(),ri=C(),ae;try{ae=C()}catch{ae=null}var Uo=function(){var e=typeof m.default<"u"&&m.default.env&&m.default.env.BSV_DEBUG||typeof window<"u"&&window.BSV_DEBUG;e&&console.log.apply(console,arguments)};function B(e,t){if(!(this instanceof B))return new B(e,t);this.privateKey=e,this.publicKey=e.publicKey,this.address=e.toAddress(),t=t||{},this.storageDir=t.storageDir||(typeof m.default<"u"?ri.join(m.default.cwd(),".bsv-covenants"):".bsv-covenants"),this.covenantUtxoPath=ri.join(this.storageDir,"covenant_utxos.json"),this.sighashType=ti.SIGHASH_ALL|ti.SIGHASH_FORKID,this.allowNonEnforcing=t.allowNonEnforcing===!0,ae&&this._ensureStorageDir()}B.prototype.createFromP2PKH=function(e){if(!this.allowNonEnforcing)throw new Error("SmartContract.Covenant builds a NON-ENFORCING script that reduces to plain P2PK \u2014 it does not constrain the spend. Use SmartContract.PushTx.valueCovenant (output binding) or SmartContract.Token / perpetualCovenant (stateful covenants) for real covenants. To use this demo anyway, construct with { allowNonEnforcing: true }.");e.script||(e.script=B.reconstructP2pkhScript(this.address));var t=new ni().from({txId:e.txid,outputIndex:e.vout,script:e.script,satoshis:e.satoshis}).to(this.address,e.satoshis-1e3),r=me.fromHex(e.script),i=ii.sighashPreimage(t,this.sighashType,0,r,new At(e.satoshis)),n=No.sha256sha256(i),o=new me().add("OP_DUP").add("OP_HASH256").add(n).add("OP_EQUALVERIFY").add("OP_DROP").add(this.publicKey.toBuffer()).add("OP_CHECKSIG");t.outputs[0].setScript(o),t.sign(this.privateKey);var a={txid:t.id,vout:0,satoshis:e.satoshis-1e3,script:o.toHex(),scriptPubKey:o.toHex(),preimageHash:n.toString("hex"),originalPreimage:i.toString("hex"),status:"local",createdAt:new Date().toISOString(),type:"preimage_covenant"};return{transaction:t,covenantUtxo:a}};B.prototype.createSpendingTx=function(e,t,r){var i=t||this.address,n=r||e.satoshis-500,o=new ni;o.addInput(new Bo({prevTxId:e.txid,outputIndex:e.vout,script:me.empty()}),me.fromHex(e.script),e.satoshis),o.to(i,n);var a=me.fromHex(e.script),s=ii.sign(o,this.privateKey,this.sighashType,0,a,new At(e.satoshis)),c=u.Buffer.concat([s.toDER(),u.Buffer.from([this.sighashType])]),d=u.Buffer.from(e.originalPreimage,"hex"),g=new me().add(c).add(d);return o.inputs[0].setScript(g),o};B.prototype.validate=function(e,t){var r=new Fe,i=Fe.SCRIPT_VERIFY_P2SH|Fe.SCRIPT_VERIFY_STRICTENC|Fe.SCRIPT_VERIFY_DERSIG|Fe.SCRIPT_VERIFY_LOW_S|Fe.SCRIPT_ENABLE_SIGHASH_FORKID,n=e.inputs[0].script,o=me.fromHex(t.script),a=r.verify(n,o,e,0,i,new At(t.satoshis));return{valid:a,error:a?null:r.errstr}};B.prototype.save=function(e){if(!ae)return Uo("File system operations not available in browser environment"),e;var t=this.list();return t.push(e),ae.writeFileSync(this.covenantUtxoPath,JSON.stringify(t,null,2)),e};B.prototype.load=function(e){var t=this.list();if(e){var r=t.find(function(i){return i.txid===e});if(!r)throw new Error("Covenant UTXO with TXID "+e+" not found");return r}else{var r=t.find(function(n){return n.type==="preimage_covenant"});if(!r)throw new Error("No preimage covenant UTXO found");return r}};B.prototype.list=function(){return ae.existsSync(this.covenantUtxoPath)?JSON.parse(ae.readFileSync(this.covenantUtxoPath,"utf8")):[]};B.prototype.getPortfolio=function(){var e=this.list(),t={total:e.length,totalValue:e.reduce(function(r,i){return r+i.satoshis},0),byStatus:{},recent:e.slice(-5)};return e.forEach(function(r){var i=r.status||"local";t.byStatus[i]||(t.byStatus[i]={count:0,value:0}),t.byStatus[i].count++,t.byStatus[i].value+=r.satoshis}),t};B.prototype.completeFlow=function(e,t){var r=this.createFromP2PKH(e),i=this.save(r.covenantUtxo);t&&t(r.transaction,"creation");var n=this.createSpendingTx(i),o=this.validate(n,i);return t&&o.valid&&t(n,"spending"),{creationTx:r.transaction,spendingTx:n,covenantUtxo:i,validation:o,success:o.valid}};B.prototype._ensureStorageDir=function(){ae.existsSync(this.storageDir)||ae.mkdirSync(this.storageDir,{recursive:!0})};B.reconstructP2pkhScript=function(e){return me.buildPublicKeyHashOut(e).toHex()};oi.exports=B});var ze=O((yc,si)=>{f();si.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.PrivateKey});var J=O((Oc,ui)=>{"use strict";f();var qo=_e(),Do=M(),Mo=D(),Go=ze(),ci=b(),vc=C();function S(e,t){if(!(this instanceof S))return new S(e,t);this.preimage=u.Buffer.isBuffer(e)?e:u.Buffer.from(e,"hex"),this.options=t||{},this.strategy=this.options.strategy||"DYNAMIC",this.fields=null,this.sighashInfo=null,this.options.deferExtraction||this._extractFields()}S.LEFT_FIXED_LENGTH=104;S.RIGHT_FIXED_LENGTH=52;S.MIN_PREIMAGE_LENGTH=S.LEFT_FIXED_LENGTH+1+S.RIGHT_FIXED_LENGTH;S.prototype.extract=function(e){return this.strategy=e||this.strategy,this._extractFields(),this.fields};S.prototype.getSighashInfo=function(){return this.fields||this._extractFields(),this.sighashInfo};S.prototype.getField=function(e){return this.fields||this._extractFields(),this.fields[e]};S.prototype.extractField=function(e,t){t=t||{},this.fields||this._extractFields();var r=this._parsePreimageStructure(),i=this._generateBidirectionalASM(e,r,t.includeComments),n=this._extractSpecificField(e,r),o=this._interpretField(e,n,r);return{field:e,value:n?n.toString("hex"):null,buffer:n,asm:i,interpretation:o,strategy:this._getExtractionStrategy(e),structure:r._structure}};S.prototype.generateASM=function(e,t){var r=this._parsePreimageStructure();return this._generateBidirectionalASM(e,r,t)};S.prototype.extractFields=function(e){var t={};return e.forEach(function(r){t[r]=this.extractField(r)}.bind(this)),t};S.prototype.validate=function(){var e=[],t=[];if(this.preimage.length<S.MIN_PREIMAGE_LENGTH)return e.push("Preimage too short: "+this.preimage.length+" bytes (BIP-143 preimage requires at least "+S.MIN_PREIMAGE_LENGTH+")"),{valid:!1,errors:e,warnings:t,sighashInfo:this.sighashInfo};this.fields||this._extractFields();var r=["version","hashPrevouts","hashSequence","outpoint","scriptCode","amount","sequence","hashOutputs","locktime","sighash"];return r.forEach(function(i){this.fields[i]||e.push("Missing required field: "+i)}.bind(this)),this.sighashInfo.hasZeroHashes&&t.push("Zero hashes detected - check SIGHASH flags: "+this.sighashInfo.zeroFields.join(", ")),{valid:e.length===0,errors:e,warnings:t,sighashInfo:this.sighashInfo}};S.prototype.toObject=function(){return this.fields||this._extractFields(),{preimage:this.preimage.toString("hex"),length:this.preimage.length,strategy:this.strategy,fields:{version:this.fields.version?this.fields.version.toString("hex"):null,hashPrevouts:this.fields.hashPrevouts?this.fields.hashPrevouts.toString("hex"):null,hashSequence:this.fields.hashSequence?this.fields.hashSequence.toString("hex"):null,outpoint:this.fields.outpoint?this.fields.outpoint.toString("hex"):null,scriptCode:this.fields.scriptCode?this.fields.scriptCode.toString("hex"):null,scriptCodeLength:this.fields.scriptCodeLength,amount:this.fields.amount?this.fields.amount.toString("hex"):null,sequence:this.fields.sequence?this.fields.sequence.toString("hex"):null,hashOutputs:this.fields.hashOutputs?this.fields.hashOutputs.toString("hex"):null,locktime:this.fields.locktime?this.fields.locktime.toString("hex"):null,sighash:this.fields.sighash?this.fields.sighash.toString("hex"):null},sighashInfo:this.sighashInfo,validation:this.validate()}};S.prototype._extractFields=function(){if(this.fields={},this.sighashInfo={flag:null,hasZeroHashes:!1,zeroFields:[],warnings:[]},this.preimage.length<S.MIN_PREIMAGE_LENGTH)throw new Error("Preimage too short: "+this.preimage.length+" bytes (BIP-143 preimage requires at least "+S.MIN_PREIMAGE_LENGTH+")");try{this.strategy==="LEFT"||this.strategy==="DYNAMIC"?this._extractFromLeft():this.strategy==="RIGHT"&&this._extractFromRight(),this._analyzeSighash()}catch(e){if(this.strategy==="DYNAMIC")try{this.strategy="RIGHT",this._extractFromRight(),this._analyzeSighash()}catch{throw new Error("Failed to extract preimage fields with any strategy: "+e.message)}else throw e}};S.prototype._extractFromLeft=function(){var e=0;this.fields.version=this.preimage.slice(e,e+4),e+=4,this.fields.hashPrevouts=this.preimage.slice(e,e+32),e+=32,this.fields.hashSequence=this.preimage.slice(e,e+32),e+=32,this.fields.outpoint=this.preimage.slice(e,e+36),e+=36;var t=S.decodeCompactSize(this.preimage,e);this.fields.scriptCodeLength=t.value,e=t.nextOffset,this.fields.scriptCode=this.preimage.slice(e,e+this.fields.scriptCodeLength),e+=this.fields.scriptCodeLength,this.fields.amount=this.preimage.slice(e,e+8),e+=8,this.fields.sequence=this.preimage.slice(e,e+4),e+=4,this.fields.hashOutputs=this.preimage.slice(e,e+32),e+=32,this.fields.locktime=this.preimage.slice(e,e+4),e+=4,this.fields.sighash=this.preimage.slice(e,e+4)};S.prototype._extractFromRight=function(){var e=this.preimage.length,t=e;t-=4,this.fields.sighash=this.preimage.slice(t,t+4),t-=4,this.fields.locktime=this.preimage.slice(t,t+4),t-=32,this.fields.hashOutputs=this.preimage.slice(t,t+32),t-=4,this.fields.sequence=this.preimage.slice(t,t+4),t-=8,this.fields.amount=this.preimage.slice(t,t+8);var r=104,i=S.decodeCompactSize(this.preimage,r);this.fields.scriptCodeLength=i.value,this.fields.scriptCode=this.preimage.slice(i.nextOffset,i.nextOffset+this.fields.scriptCodeLength),this.fields.version=this.preimage.slice(0,4),this.fields.hashPrevouts=this.preimage.slice(4,36),this.fields.hashSequence=this.preimage.slice(36,68),this.fields.outpoint=this.preimage.slice(68,104)};S.prototype._analyzeSighash=function(){if(this.fields.sighash){var e=this.fields.sighash.readUInt32LE(0);this.sighashInfo.flag=e;var t=e&31,r=(e&128)!==0,i=(e&64)!==0,n=u.Buffer.alloc(32);r&&this.fields.hashPrevouts.equals(n)&&(this.sighashInfo.hasZeroHashes=!0,this.sighashInfo.zeroFields.push("hashPrevouts"),this.sighashInfo.warnings.push("ANYONECANPAY flag detected - hashPrevouts is zero")),t===2&&this.fields.hashSequence.equals(n)&&(this.sighashInfo.hasZeroHashes=!0,this.sighashInfo.zeroFields.push("hashSequence"),this.sighashInfo.warnings.push("SIGHASH_NONE flag detected - hashSequence is zero")),(t===2||t===3)&&this.fields.hashOutputs.equals(n)&&(this.sighashInfo.hasZeroHashes=!0,this.sighashInfo.zeroFields.push("hashOutputs"),this.sighashInfo.warnings.push("SIGHASH_NONE/SINGLE flag detected - hashOutputs is zero"));var o=[];t===1?o.push("ALL"):t===2?o.push("NONE"):t===3&&o.push("SINGLE"),r&&o.push("ANYONECANPAY"),i&&o.push("FORKID"),this.sighashInfo.flagName=o.join(" | ")}};S.prototype._parsePreimageStructure=function(){for(var e=this.preimage,t=0,r={},i=[{name:"nVersion",len:4},{name:"hashPrevouts",len:32},{name:"hashSequence",len:32},{name:"outpoint_txid",len:32},{name:"outpoint_vout",len:4}],n=[{name:"value",len:8},{name:"nSequence",len:4},{name:"hashOutputs",len:32},{name:"nLocktime",len:4},{name:"sighashType",len:4}],o=0;o<i.length;o++){var a=i[o];r[a.name]=e.slice(t,t+a.len).toString("hex"),t+=a.len}var s=S.decodeCompactSize(e,t);r.scriptLen=s.value,r.scriptLenSize=s.bytes,r.scriptLenRaw=e.slice(t,t+s.bytes).toString("hex"),t+=s.bytes,r.scriptCode=e.slice(t,t+r.scriptLen).toString("hex"),t+=r.scriptLen;for(var c=0;c<n.length;c++){var d=n[c];r[d.name]=e.slice(t,t+d.len).toString("hex"),t+=d.len}var g=i.reduce(function(P,x){return P+x.len},0),y=n.reduce(function(P,x){return P+x.len},0);return r._structure={leftFixed:g,scriptLenVarint:s.bytes,scriptCode:r.scriptLen,rightFixed:y,totalCalculated:g+s.bytes+r.scriptLen+y,totalActual:e.length},r};S.prototype._generateBidirectionalASM=function(e,t,r){var i=["value","nSequence","hashOutputs","nLocktime","sighashType"],n=["nVersion","hashPrevouts","hashSequence","outpoint_txid","outpoint_vout"];if(i.includes(e))return this._generateRightExtractionASM(e,r);if(n.includes(e))return this._generateLeftExtractionASM(e,r);if(e==="scriptCode")return this._generateDynamicExtractionASM(t,r);if(e==="scriptLen")return this._generateScriptLenExtractionASM(t,r);throw new Error("Unknown field: "+e)};S.prototype._generateRightExtractionASM=function(e,t){for(var r=[{name:"value",len:8},{name:"nSequence",len:4},{name:"hashOutputs",len:32},{name:"nLocktime",len:4},{name:"sighashType",len:4}],i=0,n=0,o=!1,a=0;a<r.length;a++){var s=r[a];if(s.name===e){n=s.len,o=!0;break}i+=s.len}if(!o)throw new Error("Field not found in RIGHT fields: "+e);var c=52,d=c-i,g=[];return t?(g.push("# \u{1F504} Extract "+e+" from RIGHT side (bidirectional strategy)"),g.push("OP_SIZE # Push preimage size: [preimage, size]")):g.push("OP_SIZE"),t?g=g.concat([d+" OP_SUB # Calculate split point: [preimage, split_point]","OP_SPLIT # Split: [left_part, right_part]","OP_NIP # Drop left (OP_SPLIT leaves right on top): [right_part]",n+" OP_SPLIT # Extract field: ["+e+", remaining]","OP_DROP # Clean up: ["+e+"]","# \u2705 Result: "+e+" is now on top of stack"]):g=g.concat([d+" OP_SUB","OP_SPLIT","OP_NIP",n+" OP_SPLIT","OP_DROP"]),g.join(`
|
|
2
2
|
`)};S.prototype._generateLeftExtractionASM=function(e,t){var r=[{name:"nVersion",len:4,offset:0},{name:"hashPrevouts",len:32,offset:4},{name:"hashSequence",len:32,offset:36},{name:"outpoint_txid",len:32,offset:68},{name:"outpoint_vout",len:4,offset:100}],i=r.find(function(o){return o.name===e});if(!i)throw new Error("Field not found in LEFT fields: "+e);var n=[];return t?n=["# \u{1F504} Extract "+e+" from LEFT side (bidirectional strategy)",i.offset+" OP_SPLIT # Skip to field: [prefix, remainder]","OP_NIP # Drop prefix (OP_SPLIT leaves remainder on top): [remainder]",i.len+" OP_SPLIT # Extract field: ["+e+", suffix]","OP_DROP # Clean up: ["+e+"]","# \u2705 Result: "+e+" is now on top of stack"]:n=[i.offset+" OP_SPLIT","OP_NIP",i.len+" OP_SPLIT","OP_DROP"],n.join(`
|
|
3
3
|
`)};S.prototype._generateDynamicExtractionASM=function(e,t){var r=104+e.scriptLenSize;return["# \u{1F3AF} Extract scriptCode DYNAMICALLY with CompactSize varint support",r+" OP_SPLIT # Skip left zone + scriptLen varint: [left_zone, remainder]","OP_NIP # Drop left (OP_SPLIT leaves remainder on top): [remainder]",e.scriptLen+" OP_SPLIT # Extract scriptCode: [scriptCode, right_zone]","OP_DROP # Clean up: [scriptCode]","# \u2705 Result: scriptCode extracted with "+e.scriptLenSize+"-byte varint awareness"].join(`
|
|
4
4
|
`)};S.prototype._generateScriptLenExtractionASM=function(e,t){return["# \u{1F3AF} Extract scriptLen CompactSize varint ("+e.scriptLenSize+" bytes)","104 OP_SPLIT # Skip left fixed fields: [left_zone, remainder]","OP_NIP # Drop left (OP_SPLIT leaves remainder on top): [remainder]",e.scriptLenSize+" OP_SPLIT # Extract varint: [scriptLen_varint, suffix]","OP_DROP # Clean up: [scriptLen_varint]","# \u2705 Result: CompactSize varint (decode off-chain to get "+e.scriptLen+")"].join(`
|
|
5
|
-
`)};S.prototype._extractSpecificField=function(e,t){var r=t[e];return r?u.Buffer.from(r,"hex"):null};S.prototype._interpretField=function(e,t,r){if(!t)return null;var i={raw:t.toString("hex"),bytes:t.length};try{switch(e){case"nVersion":i.value=t.readUInt32LE(0),i.description="Transaction version "+i.value;break;case"value":t.length===8&&(i.satoshis=t.readBigUInt64LE(0).toString(),i.description=i.satoshis+" satoshis");break;case"sighashType":var n=t.readUInt32LE(0),o={1:"SIGHASH_ALL",65:"SIGHASH_ALL | FORKID",2:"SIGHASH_NONE",66:"SIGHASH_NONE | FORKID",3:"SIGHASH_SINGLE",67:"SIGHASH_SINGLE | FORKID"};i.value=n,i.description=o[n]||"Custom ("+n+")";break;case"outpoint_vout":i.value=t.readUInt32LE(0),i.description="Output index "+i.value;break;case"scriptLen":i.varintSize=r.scriptLenSize,i.scriptLength=r.scriptLen,i.description=r.scriptLen+" bytes encoded as "+r.scriptLenSize+"-byte varint";break;case"scriptCode":t.length===25&&t[0]===118&&t[1]===169?(i.description="Standard P2PKH script (25 bytes)",i.type="P2PKH"):t.length>0&&t[0]===106?(i.description="OP_RETURN data script ("+t.length+" bytes)",i.type="OP_RETURN"):(i.description="Custom script ("+t.length+" bytes)",i.type="CUSTOM");break;default:if(["hashPrevouts","hashSequence","hashOutputs"].includes(e)){var s=u.Buffer.alloc(32);t.equals(s)?(i.isZero=!0,i.description="Zero hash (check SIGHASH flags)"):i.description="32-byte hash"}}}catch(a){i.error=a.message}return i};S.prototype._getExtractionStrategy=function(e){var t=["value","nSequence","hashOutputs","nLocktime","sighashType"],r=["nVersion","hashPrevouts","hashSequence","outpoint_txid","outpoint_vout"];return t.includes(e)?"RIGHT":r.includes(e)?"LEFT":e==="scriptCode"?"DYNAMIC":e==="scriptLen"?"VARINT":"UNKNOWN"};S.decodeCompactSize=function(e,t){if(t>=e.length)throw new Error("CompactSize read past end of preimage buffer (offset "+t+", length "+e.length+")");var r=e[t];if(r<253)return{value:r,nextOffset:t+1,bytes:1};if(r===253){if(t+3>e.length)throw new Error("Truncated 2-byte CompactSize in preimage at offset "+t);var i=e.readUInt16LE(t+1);return{value:i,nextOffset:t+3,bytes:3}}else if(r===254){if(t+5>e.length)throw new Error("Truncated 4-byte CompactSize in preimage at offset "+t);var n=e.readUInt32LE(t+1);return{value:n,nextOffset:t+5,bytes:5}}else throw new Error("Invalid CompactSize: 8-byte length prefix (0xff) is not a valid script length")};S.fromTransaction=function(e,t,r,i,n){var o=Uo.sighashPreimage(e,n,t,r,new qo(i));return new S(o,{transaction:e,inputIndex:t,subscript:r,satoshis:i,sighashType:n})};S.createExample=function(e){var t=Mo.fromRandom(),r=t.toAddress(),i={txId:"0".repeat(64),outputIndex:0,script:ai.buildPublicKeyHashOut(r).toHex(),satoshis:1e5},n=new Do().from(i).to(r,99e3),o=ai.fromHex(i.script);return S.fromTransaction(n,0,o,i.satoshis,e)};S.extractFromHex=function(e,t,r){var i=new S(e,{deferExtraction:!0});return i.extractField(t,r)};S.generateASMFromHex=function(e,t,r){var i=new S(e,{deferExtraction:!0});return i.generateASM(t,r)};S.extractMultipleFromHex=function(e,t){var r=new S(e,{deferExtraction:!0});return r.extractFields(t)};S.validateFromHex=function(e){var t=new S(e);return t.validate()};S.analyzeFromHex=function(e){var t=new S(e),r=t._parsePreimageStructure(),i=t.validate();return{hex:e,length:e.length/2,structure:r._structure,fields:r,validation:i,sighashInfo:t.getSighashInfo(),extractField:function(n){return t.extractField(n)},generateASM:function(n){return t.generateASM(n)},getSummary:function(){return{totalBytes:r._structure.totalActual,scriptLength:r.scriptLen,scriptVarintSize:r.scriptLenSize,sighashType:r.sighashType,valid:i.valid,warnings:i.warnings}}}};ci.exports=S});var pi=x((vc,hi)=>{"use strict";f();var z=Ee(),Go=D(),Vo=q(),zo=ze(),ui=A(),Ko=_e();function B(e){if(!(this instanceof B))return new B(e);this.sighashType=e||z.SIGHASH_ALL|z.SIGHASH_FORKID,this.analysis=this._analyzeFlags()}B.prototype.analyze=function(){return this.analysis};B.prototype.getZeroHashBehavior=function(){var e={hashPrevouts:!1,hashSequence:!1,hashOutputs:!1,explanation:[],criticalNote:null};return this.analysis.anyoneCanPay&&(e.hashPrevouts=!0,e.explanation.push("ANYONECANPAY: hashPrevouts becomes zero hash (0x00...00)")),this.analysis.baseType==="NONE"&&(e.hashSequence=!0,e.hashOutputs=!0,e.explanation.push("SIGHASH_NONE: hashSequence and hashOutputs become zero hash")),this.analysis.baseType==="SINGLE"&&(e.hashSequence=!0,e.hashOutputs=!0,e.explanation.push("SIGHASH_SINGLE: hashSequence becomes zero hash, hashOutputs covers only corresponding output")),(e.hashPrevouts||e.hashSequence||e.hashOutputs)&&(e.criticalNote="These zero hashes are NOT bugs - they are correct BIP-143 behavior for the specified SIGHASH flags!"),e};B.prototype.generateExample=function(){var e=zo.fromRandom(),t=e.toAddress(),r={txId:"a".repeat(64),outputIndex:0,script:ui.buildPublicKeyHashOut(t).toHex(),satoshis:1e5},i=new Vo().from(r).to(t,99e3),n=ui.fromHex(r.script),o=Ko.sighashPreimage(i,this.sighashType,0,n,new Go(r.satoshis)),s=J(),a=new s(o);return{transaction:i,preimage:a,sighashType:this.sighashType,analysis:this.analysis,zeroHashBehavior:this.getZeroHashBehavior(),fields:a.extract(),validation:a.validate()}};B.prototype.createDemonstration=function(){var e=this.generateExample(),t=u.Buffer.alloc(32).toString("hex"),r={sighashType:this.sighashType,analysis:this.analysis,zeroHashBehavior:this.getZeroHashBehavior(),preimageFields:{},observations:[],educationalNotes:[]},i=e.preimage.toObject().fields;return r.preimageFields=i,i.hashPrevouts===t&&r.observations.push({field:"hashPrevouts",value:"ZERO HASH (00...00)",reason:"ANYONECANPAY flag - this input can be combined with any other inputs"}),i.hashSequence===t&&r.observations.push({field:"hashSequence",value:"ZERO HASH (00...00)",reason:this.analysis.baseType+" flag - sequence numbers not covered by signature"}),i.hashOutputs===t&&r.observations.push({field:"hashOutputs",value:"ZERO HASH (00...00)",reason:this.analysis.baseType+" flag - outputs not fully covered by signature"}),r.educationalNotes=["Zero hashes in preimages are NOT errors - they indicate specific SIGHASH flag behavior","BIP-143 mandates these zero values when certain flags are used","ANYONECANPAY allows this input to be combined with different sets of inputs","SIGHASH_NONE means the signer doesn't care about any outputs","SIGHASH_SINGLE means the signer only cares about the corresponding output","Always check SIGHASH flags when you see 'mysterious' zero hashes in preimages"],r};B.prototype.checkCompliance=function(e){var t=e.toObject().fields,r=u.Buffer.alloc(32).toString("hex"),i={compliant:!0,issues:[],expectedZeros:[],unexpectedZeros:[]},n=this.getZeroHashBehavior();return n.hashPrevouts&&t.hashPrevouts!==r?(i.compliant=!1,i.issues.push("hashPrevouts should be zero due to ANYONECANPAY flag")):!n.hashPrevouts&&t.hashPrevouts===r&&i.unexpectedZeros.push("hashPrevouts is zero but ANYONECANPAY not set"),n.hashSequence&&t.hashSequence!==r?(i.compliant=!1,i.issues.push("hashSequence should be zero due to "+this.analysis.baseType+" flag")):!n.hashSequence&&t.hashSequence===r&&i.unexpectedZeros.push("hashSequence is zero but "+this.analysis.baseType+" allows sequence coverage"),n.hashOutputs&&t.hashOutputs!==r?(i.compliant=!1,i.issues.push("hashOutputs should be zero due to "+this.analysis.baseType+" flag")):!n.hashOutputs&&t.hashOutputs===r&&i.unexpectedZeros.push("hashOutputs is zero but "+this.analysis.baseType+" should cover outputs"),i};B.prototype._analyzeFlags=function(){var e=this.sighashType&31,t=(this.sighashType&128)!==0,r=(this.sighashType&64)!==0,i="UNKNOWN";e===1?i="ALL":e===2?i="NONE":e===3&&(i="SINGLE");var n=[];return n.push(i),t&&n.push("ANYONECANPAY"),r&&n.push("FORKID"),{sighashType:this.sighashType,baseType:i,anyoneCanPay:t,forkId:r,flagName:n.join(" | "),hex:"0x"+this.sighashType.toString(16).padStart(8,"0"),binary:"0b"+this.sighashType.toString(2).padStart(32,"0")}};B.getAllTypes=function(){var e=z.SIGHASH_FORKID;return[{name:"ALL",value:z.SIGHASH_ALL|e},{name:"NONE",value:z.SIGHASH_NONE|e},{name:"SINGLE",value:z.SIGHASH_SINGLE|e},{name:"ALL | ANYONECANPAY",value:z.SIGHASH_ALL|z.SIGHASH_ANYONECANPAY|e},{name:"NONE | ANYONECANPAY",value:z.SIGHASH_NONE|z.SIGHASH_ANYONECANPAY|e},{name:"SINGLE | ANYONECANPAY",value:z.SIGHASH_SINGLE|z.SIGHASH_ANYONECANPAY|e}]};B.generateAllDemonstrations=function(){return B.getAllTypes().map(function(e){var t=new B(e.value);return{typeName:e.name,demonstration:t.createDemonstration()}})};B.explainZeroMystery=function(){return{title:"The 'Extra Zero' Mystery in Bitcoin Preimages",problem:"Developers often see zero hashes (0x00...00) in preimage fields and think it's a bug",reality:"These zeros are CORRECT behavior mandated by BIP-143 for specific SIGHASH flags",explanation:["ANYONECANPAY sets hashPrevouts to zero - allows input combination flexibility","SIGHASH_NONE sets hashSequence and hashOutputs to zero - signer doesn't care about outputs","SIGHASH_SINGLE sets hashSequence to zero - only corresponding output matters","These are features, not bugs - they enable advanced Bitcoin transaction patterns"],solution:"Always check SIGHASH flags when analyzing preimages with zero hashes",toolTip:"Use SIGHASH.checkCompliance() to verify if zero hashes match expected flag behavior"}};hi.exports=B});var fi=x((Oc,di)=>{"use strict";f();var At=Object.create(null),bt=[],kt=!(typeof m.default<"u"&&m.default.env&&m.default.env.BSV_NO_DEPRECATION_WARNINGS==="1");function li(e,t){if(!e||typeof e.what!="string"||e.what==="")throw new TypeError(t+"() requires { what: string }")}function $o(e){var t="[@smartledger/bsv] "+e.what+" is deprecated";return e.since&&(t+=" since "+e.since),t+=".",e.why&&(t+=" "+e.why.charAt(0).toUpperCase()+e.why.slice(1)+"."),e.use&&(t+=" Use "+e.use+" instead."),t+=e.removeIn?" It will be removed in "+e.removeIn+".":" A removal version has not been set; it will not be removed in a 9.x release.",t}function ae(e){if(!e||!e.what)throw new TypeError("deprecate() requires { what }");if(At[e.what])return!1;At[e.what]=!0;var t=$o(e);return bt.push({what:e.what,since:e.since||null,removeIn:e.removeIn||null,use:e.use||null,message:t}),kt&&console.warn(t),!0}ae.fn=function(e,t){if(typeof e!="function")throw new TypeError("deprecate.fn() requires a function");li(t,"deprecate.fn");var r=function(){return ae(t),e.apply(this,arguments)};return Object.defineProperty(r,"name",{value:e.name,configurable:!0}),Object.defineProperty(r,"length",{value:e.length,configurable:!0}),r.__wrapped=e,r.__deprecation=t,r};ae.property=function(e,t,r,i){li(i,"deprecate.property");var n,o=!1;return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get:function(){return ae(i),o||(n=r(),o=!0),n}}),e};ae.fired=function(){return bt.slice()};ae.setEnabled=function(e){kt=!!e};ae.isEnabled=function(){return kt};ae.reset=function(){At=Object.create(null),bt.length=0};di.exports=ae});var Si=x((_c,yi)=>{"use strict";f();var Ht=_e(),Ce=ge(),gi=Ee(),mi=fe(),tt=D(),Yo=q(),ye=A(),Xo=fi();function b(e,t){if(!(this instanceof b))return new b(e,t);this.privateKey=e,this.publicKey=e?e.publicKey:null,this.options=t||{},this.allowNonEnforcing=this.options.allowNonEnforcing===!0,this.conditions=[],this.preimageFields=[],this.scriptTemplate=null,this.validationRules=[],this.sighashType=this.options.sighashType||gi.SIGHASH_ALL|gi.SIGHASH_FORKID}b.prototype._assertEnforcingAllowed=function(){if(this.allowNonEnforcing){Xo({what:"SmartContract.Builder ({ allowNonEnforcing: true })",since:"9.1.0",removeIn:"10.0.0",use:"SmartContract.policy(), or SmartContract.PushTx / Token / valueCovenant",why:"the scripts it emits reduce to plain P2PK and constrain nothing about the spend"});return}if(!this.allowNonEnforcing)throw new Error("SmartContract.Builder produces a NON-ENFORCING script (constant hash-lock \u2192 plain P2PK; it does not constrain the spend). Use SmartContract.policy() (declarative OP_PUSH_TX), or SmartContract.PushTx / Token / valueCovenant for real covenants. To use this demo anyway, construct with { allowNonEnforcing: true }.")};b.prototype.validateField=function(e,t,r){r=r||{};var i={field:e,expectedValue:t,operator:r.operator||"EQUAL",required:r.required!==!1,description:r.description||"Validate "+e};return this.validationRules.push(i),this};b.prototype.addCondition=function(e,t){t=t||{};var r={type:typeof e=="function"?"CUSTOM":"OPCODE",condition:e,description:t.description||"Custom condition",required:t.required!==!1};return this.conditions.push(r),this};b.prototype.useTemplate=function(e,t){return this.scriptTemplate={name:e,params:t||{},customScript:typeof e=="object"?e:null},this};b.prototype.buildLockingScript=function(e){this._assertEnforcingAllowed();var t=new ye;return this.scriptTemplate?this._buildFromTemplate(e):this._buildMultiFieldCovenant(e)};b.prototype.buildUnlockingScript=function(e,t,r){var i=new ye,n=ye.fromHex(r.script),o=Ht.sign(e,this.privateKey,this.sighashType,t,n,new tt(r.satoshis)),s=u.Buffer.concat([o.toDER(),u.Buffer.from([this.sighashType])]);return i.add(s),r.originalPreimage&&i.add(u.Buffer.from(r.originalPreimage,"hex")),this.conditions.forEach(function(a){a.type==="UNLOCK_DATA"&&i.add(a.data)}),i};b.prototype.createCovenant=function(e,t){this._assertEnforcingAllowed(),t=t||{};var r=new Yo().from({txId:e.txid,outputIndex:e.vout,script:e.script,satoshis:e.satoshis}).to(this.privateKey.toAddress(),e.satoshis-(t.fee||1e3)),i=ye.fromHex(e.script),n=Ht.sighashPreimage(r,this.sighashType,0,i,new tt(e.satoshis)),o=J(),s=new o(n),a=s.extract(),c=this.buildLockingScript({preimage:n,fields:a,transaction:r});r.outputs[0].setScript(c),r.sign(this.privateKey);var d={txid:r.id,vout:0,satoshis:e.satoshis-(t.fee||1e3),script:c.toHex(),originalPreimage:n.toString("hex"),preimageFields:a,validationRules:this.validationRules.slice(),conditions:this.conditions.slice(),template:this.scriptTemplate,createdAt:new Date().toISOString(),type:"builder_covenant"};return{creationTx:r,covenantUtxo:d,lockingScript:c,preimageData:{preimage:n,fields:a}}};b.prototype.validateSpending=function(e,t){var r={valid:!0,errors:[],warnings:[],fieldValidations:[]},i=ye.fromHex(t.script),n=Ht.sighashPreimage(e,this.sighashType,0,i,new tt(t.satoshis)),o=J(),s=new o(n),a=s.extract();t.validationRules&&t.validationRules.forEach(function(O){var re=this._validateFieldRule(O,a,t.preimageFields);r.fieldValidations.push(re),!re.passed&&O.required&&(r.valid=!1,r.errors.push(re.error))}.bind(this));var c=new Ce,d=Ce.SCRIPT_VERIFY_P2SH|Ce.SCRIPT_VERIFY_STRICTENC|Ce.SCRIPT_VERIFY_DERSIG|Ce.SCRIPT_VERIFY_LOW_S|Ce.SCRIPT_ENABLE_SIGHASH_FORKID,g=e.inputs[0].script,y=ye.fromHex(t.script),P=c.verify(g,y,e,0,d,new tt(t.satoshis));return P||(r.valid=!1,r.errors.push("Script interpreter validation failed: "+c.errstr)),r};b.prototype._buildFromTemplate=function(e){var t=this.scriptTemplate;if(t.name==="HASH_LOCK")return this._buildHashLockTemplate(e,t.params);if(t.name==="MULTI_FIELD")return this._buildMultiFieldTemplate(e,t.params);if(t.customScript)return t.customScript;throw new Error("Unknown template: "+t.name)};b.prototype._buildMultiFieldCovenant=function(e){var t=new ye;return t.add("OP_DUP"),this.validationRules.forEach(function(r,i){if(i>0&&t.add("OP_DUP"),t.add("OP_HASH256"),r.expectedValue){var n=mi.sha256sha256(u.Buffer.from(r.expectedValue,"hex"));t.add(n),t.add("OP_EQUALVERIFY")}}),t.add("OP_DROP"),this.publicKey&&(t.add(this.publicKey.toBuffer()),t.add("OP_CHECKSIG")),t};b.prototype._buildHashLockTemplate=function(e,t){var r=new ye;r.add("OP_DUP"),r.add("OP_HASH256");var i=t.hash||mi.sha256sha256(e.preimage);return r.add(i),r.add("OP_EQUALVERIFY"),r.add("OP_DROP"),this.publicKey&&(r.add(this.publicKey.toBuffer()),r.add("OP_CHECKSIG")),r};b.prototype._validateFieldRule=function(e,t,r){var i=t[e.field],n=e.expectedValue;if(typeof n=="string"&&n.startsWith("ORIGINAL_")){var o=n.replace("ORIGINAL_","");n=r[o]}var s=!1,a=null;switch(e.operator){case"EQUAL":s=i&&i.equals?i.equals(n):i===n,s||(a=e.field+" does not equal expected value");break;case"NOT_EQUAL":s=i&&i.equals?!i.equals(n):i!==n,s||(a=e.field+" should not equal specified value");break;case"PRESENT":s=!!i,s||(a=e.field+" is required but not present");break;default:a="Unknown validation operator: "+e.operator}return{field:e.field,operator:e.operator,passed:s,error:a,description:e.description}};b.createHashLock=function(e,t){return new b(e).useTemplate("HASH_LOCK",{hash:t})};b.createMultiField=function(e,t){var r=new b(e);return t.forEach(function(i){r.validateField(i.field,i.expectedValue,i.options)}),r};yi.exports=b});var xi=x((wc,vi)=>{f();vi.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Networks});var Pi=x((Tc,Oi)=>{f();Oi.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.crypto.Random});var Ei=x((bc,_i)=>{f();_i.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv});var bi=x((Hc,Lt)=>{f();var w=function(){(typeof m.default<"u"&&m.default.env&&m.default.env.BSV_DEBUG||typeof window<"u"&&window.BSV_DEBUG)&&console.log.apply(console,arguments)},jo,Se,Ft,Le;if(typeof window>"u"&&typeof C=="function")try{Se=F(),Ft=F(),Le=Ft.join(__dirname,"blockchain-state.json")}catch{w("BlockchainState: Running in browser mode - persistence disabled")}else jo=typeof window<"u"&&window.bsv||Ei();function rt(){return{metadata:{createdAt:new Date().toISOString(),lastUpdated:new Date().toISOString(),totalWallets:0,totalUTXOs:0,totalValue:0,blockHeight:0},wallets:{},globalUTXOSet:{},spentUTXOs:{},transactionHistory:[]}}function Re(){try{if(!Se||!Le)return rt();if(!Se.existsSync(Le)){w("\u{1F195} Creating new blockchain state...");let t=rt();return Be(t),t}let e=JSON.parse(Se.readFileSync(Le,"utf8"));return w("\u{1F4D6} Loaded existing blockchain state"),e}catch(e){return console.error("\u274C Error loading blockchain state:",e.message),rt()}}function Be(e){try{e.metadata.lastUpdated=new Date().toISOString(),Se&&Le&&(Se.writeFileSync(Le,JSON.stringify(e,null,2)),w("\u{1F4BE} Blockchain state saved"))}catch(t){console.error("\u274C Error saving blockchain state:",t.message)}}function wi(e,t){w(`\u{1F4DD} Registering wallet: ${e}`);let r=Re();return r.wallets[e]&&w("\u2139\uFE0F Wallet already exists, updating..."),r.wallets[e]={address:e,registeredAt:t.registeredAt||new Date().toISOString(),utxos:t.utxos||[],totalValue:0},t.utxos&&t.utxos.forEach(i=>{let n=`${i.txid}:${i.vout}`;r.globalUTXOSet[n]={...i,ownerAddress:e}}),r.metadata.totalWallets=Object.keys(r.wallets).length,Ct(r),Be(r),w(`\u2705 Wallet registered: ${e}`),r}function Ii(e,t){let r=Re(),i=`${e}:${t}`;return r.spentUTXOs[i]?{exists:!1,spent:!0,utxo:r.spentUTXOs[i]}:r.globalUTXOSet[i]?{exists:!0,spent:!1,utxo:r.globalUTXOSet[i]}:{exists:!1,spent:!1,utxo:null}}function Wo(e,t){let r=Ii(e,t);return r.exists&&!r.spent}function Qo(e,t,r){let i=Re(),n=`${e}:${t}`;if(!i.globalUTXOSet[n])throw new Error(`UTXO ${n} does not exist`);if(i.spentUTXOs[n])throw new Error(`UTXO ${n} already spent`);let o=i.globalUTXOSet[n];i.spentUTXOs[n]={...o,spentInTx:r,spentAt:new Date().toISOString()},delete i.globalUTXOSet[n];let s=i.wallets[o.ownerAddress];s&&(s.utxos=s.utxos.filter(a=>!(a.txid===e&&a.vout===t))),Ct(i),Be(i),w(`\u274C UTXO spent: ${n} in tx ${r}`)}function Zo(e,t){let r=Re(),i=`${e.txid}:${e.vout}`;if(r.globalUTXOSet[i]){w(`\u26A0\uFE0F UTXO ${i} already exists, skipping`);return}r.globalUTXOSet[i]={...e,ownerAddress:t,createdAt:new Date().toISOString()},r.wallets[t]||(r.wallets[t]={address:t,registeredAt:new Date().toISOString(),utxos:[],totalValue:0}),r.wallets[t].utxos.some(o=>o.txid===e.txid&&o.vout===e.vout)||r.wallets[t].utxos.push(e),Ct(r),Be(r),w(`\u2705 UTXO added: ${i} for ${t}`)}function Ct(e){let t=Object.keys(e.globalUTXOSet).length,r=Object.values(e.globalUTXOSet).reduce((i,n)=>i+n.satoshis,0);e.metadata.totalUTXOs=t,e.metadata.totalValue=r,Object.values(e.wallets).forEach(i=>{i.totalValue=i.utxos.reduce((n,o)=>n+o.satoshis,0)})}function Ti(){let e=Re();return w("\u{1F310} Blockchain State Statistics:"),w("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),w(`\u{1F4CA} Total Wallets: ${e.metadata.totalWallets}`),w(`\u{1F4B0} Total UTXOs: ${e.metadata.totalUTXOs}`),w(`\u{1F48E} Total Value: ${e.metadata.totalValue} satoshis`),w(`\u{1F3D7}\uFE0F Block Height: ${e.metadata.blockHeight}`),w(`\u{1F550} Last Updated: ${e.metadata.lastUpdated}
|
|
6
|
-
`),Object.keys(e.wallets).length>0&&(w("\u{1F45B} Registered Wallets:"),Object.entries(e.wallets).forEach(([t,r])=>{w(` ${t}: ${r.utxos.length} UTXOs, ${r.totalValue} sats`)})),e}function Ai(){let e=Ft.join(__dirname,"wallet.json");if(!Se.existsSync(e))return w("\u274C No wallet.json found to import"),!1;try{let t=JSON.parse(Se.readFileSync(e,"utf8"));w("\u{1F4E5} Importing wallet from wallet.json...");let r={registeredAt:new Date().toISOString(),utxos:t.availableUTXOs||[t.utxo]};return wi(t.wallet.address,r),w("\u2705 Wallet imported successfully"),!0}catch(t){return console.error("\u274C Error importing wallet:",t.message),!1}}if(C.main===Lt){let e=m.default.argv.slice(2);if(e[0]==="import")Ai();else if(e[0]==="init"){let t=rt();Be(t),w("\u{1F195} Initialized new blockchain state")}Ti()}Lt.exports={loadBlockchainState:Re,saveBlockchainState:Be,registerWallet:wi,getUTXO:Ii,isUTXOAvailable:Wo,spendUTXO:Qo,addUTXO:Zo,getBlockchainStats:Ti,importWalletFromFile:Ai}});var Fi=x((Lc,Hi)=>{"use strict";f();var Y=function(){(typeof m.default<"u"&&m.default.env&&m.default.env.BSV_DEBUG||typeof window<"u"&&window.BSV_DEBUG)&&console.log.apply(console,arguments)},Jo=A(),es=It(),ts=Pi(),Rt,ki,rs,ce;if(typeof window>"u"&&typeof C=="function")try{Rt=F(),ki=F(),rs=F(),ce=bi()}catch{Y("SmartUTXO: Running in browser mode - some features may be limited")}var Bt=class{constructor(t={}){this.options=t||{},this.loadState()}loadState(){try{return ce.loadBlockchainState()}catch(t){return Y("\u26A0\uFE0F Could not load blockchain state:",t.message),null}}saveState(){try{let t=ce.loadBlockchainState();ce.saveBlockchainState(t);let r=Object.keys(t.globalUTXOSet||{}).length;Y(`\u{1F4BE} Saved blockchain state with ${r} UTXOs`)}catch(t){Y("\u26A0\uFE0F Could not save blockchain state:",t.message)}}getUTXOsForAddress(t){try{let r=ce.loadBlockchainState();return!r.wallets||!r.wallets[t]?[]:r.wallets[t].utxos||[]}catch(r){return Y("\u26A0\uFE0F Error getting UTXOs:",r.message),[]}}addUTXO(t){try{ce.addUTXO(t,t.address)}catch(r){Y("\u26A0\uFE0F Error adding UTXO:",r.message)}}spendUTXOs(t,r="manual-spend"){try{for(let i of t)ce.spendUTXO(i.txid,i.vout,r)}catch(i){Y("\u26A0\uFE0F Error spending UTXOs:",i.message)}}createMockUTXOs(t,r=5,i=1e5){let n=Jo.buildPublicKeyHashOut(es.fromString(t)).toHex(),o=[];for(let s=0;s<r;s++)o.push({txid:ts.getRandomBuffer(32).toString("hex"),vout:s,address:t,satoshis:i,script:n});return o}getBalance(t){try{let r=ce.loadBlockchainState();return!r.wallets||!r.wallets[t]?0:r.wallets[t].totalValue||0}catch(r){return Y("\u26A0\uFE0F Error getting balance:",r.message),0}}getStats(){try{let t=ce.getBlockchainStats();return{totalUTXOs:t.metadata.totalUTXOs,totalValue:t.metadata.totalValue,totalWallets:t.metadata.totalWallets,blockHeight:t.metadata.blockHeight,lastUpdated:t.metadata.lastUpdated}}catch(t){return Y("\u26A0\uFE0F Error getting stats:",t.message),{totalUTXOs:0,totalValue:0,totalWallets:0,blockHeight:0}}}reset(){try{let t=ki.join(__dirname,"../utilities/blockchain-state.json");Rt.existsSync(t)&&(Rt.unlinkSync(t),Y("\u{1F504} Blockchain state reset"))}catch(t){Y("\u26A0\uFE0F Could not reset blockchain state:",t.message)}}};Hi.exports=Bt});var Ri=x((Nc,Li)=>{"use strict";f();var is=_e(),Ci=Ee(),ns=D(),os=q(),ss=ze(),as=xi(),Ne=A(),cs=F();function M(e){if(!(this instanceof M))return new M(e);this.options=e||{},this.network=this.options.network||as.mainnet,this.keyRing={},this.utxoPool=[];try{var t=Fi();this.smartUTXO=new t(this.options)}catch{}}M.prototype.generateKeypair=function(e){e=e||"key_"+Date.now();var t=ss.fromRandom(this.network),r=t.toPublicKey(),i=t.toAddress(this.network),n={label:e,privateKey:t,publicKey:r,address:i,wif:t.toWIF(),addressString:i.toString()};return this.keyRing[e]=n,n};M.prototype.createRealUTXOs=function(e){e=e||{};for(var t=e.count||3,r=e.satoshis||1e5,i=e.scriptType||"P2PKH",n=e.keypair||this.generateKeypair("utxo_owner"),o=[],s=0;s<t;s++){var a=this._createSingleUTXO({keypair:n,satoshis:r,scriptType:i,vout:s});o.push(a),this.utxoPool.push(a),this.smartUTXO&&this.smartUTXO.addUTXO(a)}return o};M.prototype._createSingleUTXO=function(e){var t=cs.randomBytes(32).toString("hex"),r,i;switch(e.scriptType){case"P2PKH":r=Ne.buildPublicKeyHashOut(e.keypair.address),i=r.toHex();break;case"P2SH":var n=Ne.buildMultisigOut([e.keypair.publicKey],1);r=Ne.buildScriptHashOut(n),i=r.toHex();break;case"CUSTOM":r=e.customScript||Ne.buildPublicKeyHashOut(e.keypair.address),i=r.toHex();break;default:r=Ne.buildPublicKeyHashOut(e.keypair.address),i=r.toHex()}return{txid:t,vout:e.vout,address:e.keypair.addressString,script:i,satoshis:e.satoshis,keypair:e.keypair,scriptType:e.scriptType,scriptObj:r,created:new Date().toISOString()}};M.prototype.createTestTransaction=function(e){e=e||{};var t=e.inputs||this.utxoPool.slice(0,1);if(t.length===0)throw new Error("No UTXOs available for transaction. Call createRealUTXOs() first.");var r=t.reduce(function(a,c){return a+c.satoshis},0),i=new os;t.forEach(function(a){i.from({txId:a.txid,outputIndex:a.vout,address:a.address,script:a.script,satoshis:a.satoshis})});var n=e.outputAddress||t[0].keypair.addressString,o=e.outputAmount||r-1e4,s=e.fee||1e4;return i.to(n,o),i.fee(s),{transaction:i,inputUTXOs:t,unsignedHex:i.toString(),inputTotal:r,outputAmount:o,fee:s,sign:function(){return t.forEach(function(a){i.sign(a.keypair.privateKey)}),{signedTransaction:i,signedHex:i.toString(),txid:i.id}},generatePreimage:function(a,c){c=c||Ci.SIGHASH_ALL|Ci.SIGHASH_FORKID;var d=t[a];return is.sighashPreimage(i,c,a,Ne.fromHex(d.script),new ns(d.satoshis))}}};M.prototype.createCovenantTest=function(e){e=e||{};var t=this.generateKeypair("covenant_test"),r=this.createRealUTXOs({count:e.utxoCount||2,satoshis:e.satoshis||5e4,keypair:t,scriptType:e.scriptType||"P2PKH"}),i={inputs:r.slice(0,1),outputAmount:e.covenantAmount||4e4,fee:1e4},n=this.createTestTransaction(i),o=n.generatePreimage(0),s=o.toString("hex");return{keypair:t,utxos:r,transaction:n,preimage:{buffer:o,hex:s,length:o.length},extractField:function(a){try{var c=J();return c.extractFromHex(s,a)}catch(d){throw new Error("SmartContract.Preimage not available: "+d.message)}},validateCovenant:function(a){return{preimageValid:o.length>=182,covenantLogic:a,testPassed:!0}},getSummary:function(){return{keypair:t.addressString,utxoCount:r.length,totalValue:r.reduce(function(a,c){return a+c.satoshis},0),preimageLength:o.length,transactionId:n.transaction.id}}}};M.prototype.getKeypairs=function(){return this.keyRing};M.prototype.getUTXOs=function(){return this.utxoPool};M.prototype.reset=function(){this.keyRing={},this.utxoPool=[]};M.createTestEnvironment=function(e){var t=new M(e),r=t.createCovenantTest(e);return{generator:t,test:r,getPreimage:function(){return r.preimage.hex},getKeypair:function(){return r.keypair},extractField:function(i){return r.extractField(i)},generateASM:function(i){try{var n=J();return n.generateASMFromHex(r.preimage.hex,i)}catch(o){throw new Error("Cannot generate ASM: "+o.message)}}}};Li.exports=M});var Ke=x((qc,Bi)=>{f();Bi.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Transaction.Output});var G=x((Mc,Ni)=>{f();Ni.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Opcode});var Di=x((Vc,qi)=>{"use strict";f();var Ui=Ke(),us=He(),Nt=ge(),hs=D(),ps=q(),ls=G(),ve=A();function k(e){if(!(this instanceof k))return new k(e);this.options=e||{},this.flags=this.options.flags||Nt.SCRIPT_ENABLE_SIGHASH_FORKID,this.satoshis=this.options.satoshis||1e5}k.prototype.execute=function(e){var t=this._parseScript(e.unlocking),r=this._parseScript(e.locking),i=this._createDummyTransaction(),n=new Nt,o=new hs(this.satoshis);try{var s=n.verify(t,r,i,0,this.flags,o);return{success:s,unlocking:t.toASM(),locking:r.toASM(),finalStack:n.stack.map(function(a){return a.toString("hex")}),altStack:n.altstack.map(function(a){return a.toString("hex")}),error:null}}catch(a){return{success:!1,unlocking:t.toASM(),locking:r.toASM(),finalStack:[],altStack:[],error:a.message}}};k.prototype.debug=function(e){var t=this._createCombinedScript(e),r=this._createDummyTransaction(),i=new Nt;i.script=t,i.tx=r,i.nIn=0,i.flags=this.flags;var n=[],o=t.chunks;try{for(var s=0;s<o.length;s++){var a=o[s],c=ls.reverseMap[a.opcodenum]||"PUSH",d=i.stack.map(function(O){return O.toString("hex")}),g=i.altstack.map(function(O){return O.toString("hex")});try{i.step();var y=i.stack.map(function(O){return O.toString("hex")}),P=i.altstack.map(function(O){return O.toString("hex")});n.push({step:s+1,opcode:c,beforeStack:d,afterStack:y,beforeAltStack:g,afterAltStack:P,success:!0,error:null})}catch(O){n.push({step:s+1,opcode:c,beforeStack:d,afterStack:d,beforeAltStack:g,afterAltStack:g,success:!1,error:O.message});break}}}catch(O){n.push({step:0,opcode:"INITIALIZATION",beforeStack:[],afterStack:[],beforeAltStack:[],afterAltStack:[],success:!1,error:O.message})}return{script:t.toASM(),steps:n,totalSteps:o.length,success:n.length>0&&n[n.length-1].success}};k.prototype.testCovenant=function(e){var t=e.preimage,r=e.constraints||{},i=this._buildCovenantScript(r,t),n=this.execute({unlocking:t,locking:i});return n.covenant={preimageLength:t.length/2,constraints:r,constraintResults:this._analyzeConstraints(t,r)},n};k.prototype.testFieldExtraction=function(e,t){try{var r=J(),i=r.extractFromHex(e,t,{includeComments:!1}),n=this._cleanASM(i.asm),o=this.execute({unlocking:e,locking:n+" OP_DROP OP_TRUE"});return o.fieldExtraction={field:t,strategy:i.strategy,value:i.value,interpretation:i.interpretation,asmGenerated:i.asm,cleanedASM:n},o}catch(s){return{success:!1,error:s.message,fieldExtraction:{field:t,error:s.message}}}};k.prototype._parseScript=function(e){if(!e)return new ve;var t=e.trim(),r=/^[0-9a-fA-F]+$/.test(t.replace(/\s+/g,""));try{if(r){var i=t.length/2;return i>=180&&i<=250?new ve().add(u.Buffer.from(t,"hex")):ve.fromHex(t)}else return ve.fromASM(t)}catch(n){throw new Error("Failed to parse script: "+n.message)}};k.prototype._createCombinedScript=function(e){if(e.combined)return this._parseScript(e.combined);var t=this._parseScript(e.unlocking),r=this._parseScript(e.locking),i=u.Buffer.concat([t.toBuffer(),r.toBuffer()]);return ve.fromBuffer(i)};k.prototype._createDummyTransaction=function(){var e=new ps,t=new us({prevTxId:"0".repeat(64),outputIndex:0,script:ve.empty(),satoshis:this.satoshis,output:new Ui({satoshis:this.satoshis,script:ve.empty()})});return e.addInput(t),e.addOutput(new Ui({satoshis:this.satoshis,script:ve.empty()})),e};k.prototype._buildCovenantScript=function(e,t){var r=[];try{var i=J();if(e.minimumAmount){var n=i.generateASMFromHex(t,"value",!1);r.push(n),r.push("OP_BIN2NUM"),r.push(e.minimumAmount.toString()),r.push("OP_GREATERTHANOREQUAL"),r.push("OP_VERIFY")}if(e.requiredSighash){var o=i.generateASMFromHex(t,"sighashType",!1);r.push(o),r.push("OP_BIN2NUM"),r.push(e.requiredSighash.toString()),r.push("OP_EQUAL"),r.push("OP_VERIFY")}r.push("OP_TRUE");var s=r.join(" ");return this._cleanASM(s)}catch(a){throw new Error("Failed to build covenant script: "+a.message)}};k.prototype._cleanASM=function(e){var t=e.split(`
|
|
7
|
-
`).map(function(r){return r.split("#")[0].trim()}).filter(function(r){return r.length>0}).join(" ").replace(/\s+/g," ").trim();return t=t.replace(/\b(\d+)\b/g,function(r,i){var n=parseInt(i);if(n>=1&&n<=16)return"OP_"+n;if(n===0)return"OP_0";if(n===-1)return"OP_1NEGATE";var o=n,s=o<0;s&&(o=-o);for(var a=[];o>0;)a.push(o&255),o=Math.floor(o/256);return a.length===0&&a.push(0),s?a[a.length-1]>=128?a.push(128):a[a.length-1]|=128:a.length>0&&a[a.length-1]>=128&&a.push(0),u.Buffer.from(a).toString("hex")}),t};k.prototype._analyzeConstraints=function(e,t){var r={};try{var i=J();if(t.minimumAmount){var n=i.extractFromHex(e,"value",{includeComments:!1}),o=parseInt(n.interpretation.satoshis);r.amountCheck={constraint:t.minimumAmount,actual:o,satisfied:o>=t.minimumAmount}}if(t.requiredSighash){var s=i.extractFromHex(e,"sighashType",{includeComments:!1}),a=parseInt(s.value,16);r.sighashCheck={constraint:t.requiredSighash,actual:a,satisfied:(a&255)===t.requiredSighash}}}catch(c){r.error=c.message}return r};k.test=function(e,t,r){var i=new k(r);return i.execute({unlocking:e,locking:t})};k.testCovenant=function(e,t,r){var i=new k(r);return i.testCovenant({preimage:e,constraints:t})};k.testFieldExtraction=function(e,t,r){var i=new k(r);return i.testFieldExtraction(e,t)};qi.exports=k});var qt=x((Kc,Ut)=>{f();var l={encode:e=>{if(e===0)return u.Buffer.alloc(0);let t=e<0,r=Math.abs(e),i=[],n=r;for(;n>0;)i.push(n&255),n>>=8;return i[i.length-1]&128?i.push(t?128:0):t&&(i[i.length-1]|=128),u.Buffer.from(i)},decode:e=>{if(e.length===0)return 0;let t=Array.from(e),r=t[t.length-1]&128;r&&(t[t.length-1]&=127);let i=0;for(let n=t.length-1;n>=0;n--)i=(i<<8)+t[n];return r?-i:i}},X={OP_FALSE:{code:0,category:"constants",description:"Push empty array (false value)",action:e=>e.push(u.Buffer.alloc(0))},OP_0:{code:0,category:"constants",description:"Push empty array (alias for OP_FALSE)",action:e=>e.push(u.Buffer.alloc(0))},OP_PUSHDATA1:{code:76,category:"pushdata",description:"Push next [1 byte] bytes of data",action:"Read next byte as length; push that many bytes"},OP_PUSHDATA2:{code:77,category:"pushdata",description:"Push next [2 bytes LE] bytes of data",action:"Read next 2 bytes as length; push that many bytes"},OP_PUSHDATA4:{code:78,category:"pushdata",description:"Push next [4 bytes LE] bytes of data",action:"Read next 4 bytes as length; push that many bytes"},OP_1NEGATE:{code:79,category:"constants",description:"Push number -1",action:e=>e.push(l.encode(-1))},OP_RESERVED:{code:80,category:"reserved",description:"Reserved opcode (makes transaction invalid)",action:()=>{throw new Error("OP_RESERVED encountered")}},OP_TRUE:{code:81,category:"constants",description:"Push number 1 (true value)",action:e=>e.push(l.encode(1))},OP_1:{code:81,category:"constants",description:"Push number 1 (alias for OP_TRUE)",action:e=>e.push(l.encode(1))},OP_2:{code:82,category:"constants",description:"Push number 2",action:e=>e.push(l.encode(2))},OP_3:{code:83,category:"constants",description:"Push number 3",action:e=>e.push(l.encode(3))},OP_4:{code:84,category:"constants",description:"Push number 4",action:e=>e.push(l.encode(4))},OP_5:{code:85,category:"constants",description:"Push number 5",action:e=>e.push(l.encode(5))},OP_6:{code:86,category:"constants",description:"Push number 6",action:e=>e.push(l.encode(6))},OP_7:{code:87,category:"constants",description:"Push number 7",action:e=>e.push(l.encode(7))},OP_8:{code:88,category:"constants",description:"Push number 8",action:e=>e.push(l.encode(8))},OP_9:{code:89,category:"constants",description:"Push number 9",action:e=>e.push(l.encode(9))},OP_10:{code:90,category:"constants",description:"Push number 10",action:e=>e.push(l.encode(10))},OP_11:{code:91,category:"constants",description:"Push number 11",action:e=>e.push(l.encode(11))},OP_12:{code:92,category:"constants",description:"Push number 12",action:e=>e.push(l.encode(12))},OP_13:{code:93,category:"constants",description:"Push number 13",action:e=>e.push(l.encode(13))},OP_14:{code:94,category:"constants",description:"Push number 14",action:e=>e.push(l.encode(14))},OP_15:{code:95,category:"constants",description:"Push number 15",action:e=>e.push(l.encode(15))},OP_16:{code:96,category:"constants",description:"Push number 16",action:e=>e.push(l.encode(16))},OP_NOP:{code:97,category:"flow_control",description:"No operation (do nothing)",action:e=>{}},OP_VER:{code:98,category:"flow_control",description:"Push transaction version (disabled)",action:()=>{throw new Error("OP_VER is disabled")}},OP_IF:{code:99,category:"flow_control",description:"Execute if top stack value is true",action:"// Conditional execution (requires parser state)"},OP_NOTIF:{code:100,category:"flow_control",description:"Execute if top stack value is false",action:"// Conditional execution (requires parser state)"},OP_VERIF:{code:101,category:"flow_control",description:"Conditional execution based on transaction version (disabled)",action:()=>{throw new Error("OP_VERIF is disabled")}},OP_VERNOTIF:{code:102,category:"flow_control",description:"Conditional execution based on transaction version (disabled)",action:()=>{throw new Error("OP_VERNOTIF is disabled")}},OP_ELSE:{code:103,category:"flow_control",description:"Else branch of conditional",action:"// Conditional execution (requires parser state)"},OP_ENDIF:{code:104,category:"flow_control",description:"End conditional block",action:"// Conditional execution (requires parser state)"},OP_VERIFY:{code:105,category:"flow_control",description:"Fail if top stack value is not true",action:e=>{let t=e.pop();if(!t||t.length===0||l.decode(t)===0)throw new Error("OP_VERIFY failed")}},OP_RETURN:{code:106,category:"flow_control",description:"Terminate script execution immediately",action:()=>{throw new Error("Script terminated by OP_RETURN")}},OP_TOALTSTACK:{code:107,category:"stack",description:"Move top item from main stack to alt stack",action:(e,t)=>t.push(e.pop())},OP_FROMALTSTACK:{code:108,category:"stack",description:"Move top item from alt stack to main stack",action:(e,t)=>e.push(t.pop())},OP_2DROP:{code:109,category:"stack",description:"Remove top two stack items",action:e=>{e.pop(),e.pop()}},OP_2DUP:{code:110,category:"stack",description:"Duplicate top two stack items",action:e=>{let t=e[e.length-1],r=e[e.length-2];e.push(u.Buffer.from(r),u.Buffer.from(t))}},OP_3DUP:{code:111,category:"stack",description:"Duplicate top three stack items",action:e=>{let t=e[e.length-1],r=e[e.length-2],i=e[e.length-3];e.push(u.Buffer.from(i),u.Buffer.from(r),u.Buffer.from(t))}},OP_2OVER:{code:112,category:"stack",description:"Copy 3rd and 4th items to top",action:e=>{let t=e[e.length-3],r=e[e.length-4];e.push(u.Buffer.from(r),u.Buffer.from(t))}},OP_2ROT:{code:113,category:"stack",description:"Move 5th and 6th items to top",action:e=>{let t=e.splice(-5,1)[0],r=e.splice(-5,1)[0];e.push(t,r)}},OP_2SWAP:{code:114,category:"stack",description:"Swap top two pairs of items",action:e=>{let t=e.pop(),r=e.pop(),i=e.pop(),n=e.pop();e.push(r,t,n,i)}},OP_IFDUP:{code:115,category:"stack",description:"Duplicate top item if it is not zero",action:e=>{let t=e[e.length-1];t.length>0&&l.decode(t)!==0&&e.push(u.Buffer.from(t))}},OP_DEPTH:{code:116,category:"stack",description:"Push stack size as number",action:e=>e.push(l.encode(e.length))},OP_DROP:{code:117,category:"stack",description:"Remove top stack item",action:e=>e.pop()},OP_DUP:{code:118,category:"stack",description:"Duplicate top stack item",action:e=>e.push(u.Buffer.from(e[e.length-1]))},OP_NIP:{code:119,category:"stack",description:"Remove second-to-top item",action:e=>{let t=e.pop();e.pop(),e.push(t)}},OP_OVER:{code:120,category:"stack",description:"Copy second-to-top item to top",action:e=>e.push(u.Buffer.from(e[e.length-2]))},OP_PICK:{code:121,category:"stack",description:"Copy nth item to top (0-indexed from top)",action:e=>{let t=l.decode(e.pop());e.push(u.Buffer.from(e[e.length-1-t]))}},OP_ROLL:{code:122,category:"stack",description:"Move nth item to top (0-indexed from top)",action:e=>{let t=l.decode(e.pop()),r=e.splice(e.length-1-t,1)[0];e.push(r)}},OP_ROT:{code:123,category:"stack",description:"Rotate top three items left",action:e=>{let t=e.pop(),r=e.pop(),i=e.pop();e.push(r,t,i)}},OP_SWAP:{code:124,category:"stack",description:"Swap top two items",action:e=>{let t=e.pop(),r=e.pop();e.push(t,r)}},OP_TUCK:{code:125,category:"stack",description:"Copy top item below second item",action:e=>{let t=e.pop(),r=e.pop();e.push(t,r,t)}},OP_CAT:{code:126,category:"data",description:"Concatenate top two items",action:e=>{let t=e.pop(),r=e.pop();e.push(u.Buffer.concat([r,t]))}},OP_SPLIT:{code:127,category:"data",description:"Split item at position n",action:e=>{let t=l.decode(e.pop()),r=e.pop();e.push(r.slice(0,t),r.slice(t))}},OP_NUM2BIN:{code:128,category:"data",description:"Convert number to byte sequence of length n",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop()),i=u.Buffer.alloc(t),n=l.encode(r);n.copy(i,0,0,Math.min(n.length,t)),e.push(i)}},OP_BIN2NUM:{code:129,category:"data",description:"Convert byte sequence to number",action:e=>{let t=e.pop();e.push(l.encode(l.decode(t)))}},OP_SIZE:{code:130,category:"data",description:"Push size of top item (without removing item)",action:e=>e.push(l.encode(e[e.length-1].length))},OP_INVERT:{code:131,category:"bitwise",description:"Bitwise NOT of top item",action:e=>{let t=e.pop();e.push(u.Buffer.from(t.map(r=>~r)))}},OP_AND:{code:132,category:"bitwise",description:"Bitwise AND of top two items",action:e=>{let t=e.pop(),r=e.pop(),i=Math.max(t.length,r.length),n=u.Buffer.alloc(i);for(let o=0;o<i;o++)n[o]=(t[o]||0)&(r[o]||0);e.push(n)}},OP_OR:{code:133,category:"bitwise",description:"Bitwise OR of top two items",action:e=>{let t=e.pop(),r=e.pop(),i=Math.max(t.length,r.length),n=u.Buffer.alloc(i);for(let o=0;o<i;o++)n[o]=(t[o]||0)|(r[o]||0);e.push(n)}},OP_XOR:{code:134,category:"bitwise",description:"Bitwise XOR of top two items",action:e=>{let t=e.pop(),r=e.pop(),i=Math.max(t.length,r.length),n=u.Buffer.alloc(i);for(let o=0;o<i;o++)n[o]=(t[o]||0)^(r[o]||0);e.push(n)}},OP_EQUAL:{code:135,category:"bitwise",description:"Push 1 if top two items are equal, 0 otherwise",action:e=>{let t=e.pop(),r=e.pop();e.push(t.equals(r)?l.encode(1):l.encode(0))}},OP_EQUALVERIFY:{code:136,category:"bitwise",description:"Fail if top two items are not equal",action:e=>{let t=e.pop(),r=e.pop();if(!t.equals(r))throw new Error("OP_EQUALVERIFY failed")}},OP_1ADD:{code:139,category:"arithmetic",description:"Add 1 to top item",action:e=>{let t=l.decode(e.pop());e.push(l.encode(t+1))}},OP_1SUB:{code:140,category:"arithmetic",description:"Subtract 1 from top item",action:e=>{let t=l.decode(e.pop());e.push(l.encode(t-1))}},OP_2MUL:{code:141,category:"arithmetic",description:"Multiply top item by 2 (disabled)",action:()=>{throw new Error("OP_2MUL is disabled")}},OP_2DIV:{code:142,category:"arithmetic",description:"Divide top item by 2 (disabled)",action:()=>{throw new Error("OP_2DIV is disabled")}},OP_NEGATE:{code:143,category:"arithmetic",description:"Negate top item",action:e=>{let t=l.decode(e.pop());e.push(l.encode(-t))}},OP_ABS:{code:144,category:"arithmetic",description:"Absolute value of top item",action:e=>{let t=l.decode(e.pop());e.push(l.encode(Math.abs(t)))}},OP_NOT:{code:145,category:"arithmetic",description:"Logical NOT (0\u21921, non-zero\u21920)",action:e=>{let t=l.decode(e.pop());e.push(l.encode(t===0?1:0))}},OP_0NOTEQUAL:{code:146,category:"arithmetic",description:"Push 1 if top item is not zero, 0 otherwise",action:e=>{let t=l.decode(e.pop());e.push(l.encode(t!==0?1:0))}},OP_ADD:{code:147,category:"arithmetic",description:"Add top two items",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r+t))}},OP_SUB:{code:148,category:"arithmetic",description:"Subtract: second - first",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r-t))}},OP_MUL:{code:149,category:"arithmetic",description:"Multiply top two items",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r*t))}},OP_DIV:{code:150,category:"arithmetic",description:"Divide: second / first",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());if(t===0)throw new Error("Division by zero");e.push(l.encode(Math.floor(r/t)))}},OP_MOD:{code:151,category:"arithmetic",description:"Modulo: second % first",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());if(t===0)throw new Error("Division by zero");e.push(l.encode(r%t))}},OP_LSHIFT:{code:152,category:"arithmetic",description:"Left shift: second << first",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r<<t))}},OP_RSHIFT:{code:153,category:"arithmetic",description:"Right shift: second >> first",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r>>t))}},OP_BOOLAND:{code:154,category:"arithmetic",description:"Boolean AND: 1 if both non-zero, 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(t!==0&&r!==0?1:0))}},OP_BOOLOR:{code:155,category:"arithmetic",description:"Boolean OR: 1 if either non-zero, 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(t!==0||r!==0?1:0))}},OP_NUMEQUAL:{code:156,category:"arithmetic",description:"Push 1 if numbers are equal, 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(t===r?1:0))}},OP_NUMEQUALVERIFY:{code:157,category:"arithmetic",description:"Fail if numbers are not equal",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());if(t!==r)throw new Error("OP_NUMEQUALVERIFY failed")}},OP_NUMNOTEQUAL:{code:158,category:"arithmetic",description:"Push 1 if numbers are not equal, 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(t!==r?1:0))}},OP_LESSTHAN:{code:159,category:"arithmetic",description:"Push 1 if second < first, 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r<t?1:0))}},OP_GREATERTHAN:{code:160,category:"arithmetic",description:"Push 1 if second > first, 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r>t?1:0))}},OP_LESSTHANOREQUAL:{code:161,category:"arithmetic",description:"Push 1 if second <= first, 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r<=t?1:0))}},OP_GREATERTHANOREQUAL:{code:162,category:"arithmetic",description:"Push 1 if second >= first, 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r>=t?1:0))}},OP_MIN:{code:163,category:"arithmetic",description:"Push smaller of top two numbers",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(Math.min(t,r)))}},OP_MAX:{code:164,category:"arithmetic",description:"Push larger of top two numbers",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(Math.max(t,r)))}},OP_WITHIN:{code:165,category:"arithmetic",description:"Push 1 if x is within [min, max), 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop()),i=l.decode(e.pop());e.push(l.encode(i>=r&&i<t?1:0))}},OP_RIPEMD160:{code:166,category:"crypto",description:"RIPEMD-160 hash of top item",action:e=>{let r=F().createHash("ripemd160").update(e.pop()).digest();e.push(r)}},OP_SHA1:{code:167,category:"crypto",description:"SHA-1 hash of top item",action:e=>{let r=F().createHash("sha1").update(e.pop()).digest();e.push(r)}},OP_SHA256:{code:168,category:"crypto",description:"SHA-256 hash of top item",action:e=>{let r=F().createHash("sha256").update(e.pop()).digest();e.push(r)}},OP_HASH160:{code:169,category:"crypto",description:"SHA-256 then RIPEMD-160 hash of top item",action:e=>{let t=F(),r=t.createHash("sha256").update(e.pop()).digest(),i=t.createHash("ripemd160").update(r).digest();e.push(i)}},OP_HASH256:{code:170,category:"crypto",description:"Double SHA-256 hash of top item",action:e=>{let t=F(),r=t.createHash("sha256").update(e.pop()).digest(),i=t.createHash("sha256").update(r).digest();e.push(i)}},OP_CODESEPARATOR:{code:171,category:"crypto",description:"Mark signature checking boundary",action:e=>{}},OP_CHECKSIG:{code:172,category:"crypto",description:"Verify signature against public key",action:"// Signature verification (requires transaction context)"},OP_CHECKSIGVERIFY:{code:173,category:"crypto",description:"Verify signature, then fail if invalid",action:"// Signature verification with VERIFY (requires transaction context)"},OP_CHECKMULTISIG:{code:174,category:"crypto",description:"Verify multiple signatures against public keys",action:"// Multi-signature verification (requires transaction context)"},OP_CHECKMULTISIGVERIFY:{code:175,category:"crypto",description:"Verify multiple signatures, then fail if invalid",action:"// Multi-signature verification with VERIFY (requires transaction context)"},OP_SUBSTR:{code:179,category:"string",description:"Extract substring: string[start:start+length]",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop()),i=e.pop();e.push(i.slice(r,r+t))}},OP_LEFT:{code:180,category:"string",description:"Extract leftmost n bytes",action:e=>{let t=l.decode(e.pop()),r=e.pop();e.push(r.slice(0,t))}},OP_RIGHT:{code:181,category:"string",description:"Extract rightmost n bytes",action:e=>{let t=l.decode(e.pop()),r=e.pop();e.push(r.slice(-t))}},OP_NOP1:{code:176,category:"nop",description:"No operation (reserved for future use)",action:e=>{}},OP_NOP2:{code:177,category:"nop",description:"No operation (formerly CHECKLOCKTIMEVERIFY)",action:e=>{}},OP_NOP3:{code:178,category:"nop",description:"No operation (formerly CHECKSEQUENCEVERIFY)",action:e=>{}},OP_NOP9:{code:184,category:"nop",description:"No operation (reserved for future use)",action:e=>{}},OP_NOP10:{code:185,category:"nop",description:"No operation (reserved for future use)",action:e=>{}},OP_RESERVED1:{code:137,category:"reserved",description:"Reserved opcode (makes transaction invalid)",action:()=>{throw new Error("OP_RESERVED1 encountered")}},OP_RESERVED2:{code:138,category:"reserved",description:"Reserved opcode (makes transaction invalid)",action:()=>{throw new Error("OP_RESERVED2 encountered")}},OP_CHECKLOCKTIMEVERIFY:{code:177,category:"disabled",description:"Check locktime (disabled post-Genesis)",action:e=>{}},OP_CHECKSEQUENCEVERIFY:{code:178,category:"disabled",description:"Check sequence (disabled post-Genesis)",action:e=>{}},OP_PUBKEYHASH:{code:253,category:"pseudo",description:"Template matching: public key hash",action:"// Template matching only"},OP_PUBKEY:{code:254,category:"pseudo",description:"Template matching: public key",action:"// Template matching only"},OP_INVALIDOPCODE:{code:255,category:"pseudo",description:"Invalid opcode placeholder",action:()=>{throw new Error("Invalid opcode encountered")}}},$e={getByCategory:e=>Object.entries(X).filter(([t,r])=>r.category===e).reduce((t,[r,i])=>({...t,[r]:i}),{}),getCategories:()=>{let e=new Set;return Object.values(X).forEach(t=>e.add(t.category)),Array.from(e).sort()},createASM:e=>{let t=[];return e.forEach(r=>{if(typeof r=="string"&&X[r])t.push(r);else if(typeof r=="number")if(r>=1&&r<=16)t.push(`OP_${r}`);else if(r===0)t.push("OP_0");else if(r===-1)t.push("OP_1NEGATE");else{let i=l.encode(r);t.push(i.toString("hex"))}else if(u.Buffer.isBuffer(r))t.push(r.toString("hex"));else throw new Error(`Invalid operation: ${r}`)}),t.join(" ")},simulate:(e,t=[])=>{let r=[...t],i=[],n=[];return e.forEach((o,s)=>{if(!X[o])throw new Error(`Unknown opcode: ${o}`);let a=X[o],c=[...r];if(typeof a.action=="function")try{a.action(r,i),n.push({step:s+1,opcode:o,beforeStack:c.map(d=>d.toString("hex")),afterStack:r.map(d=>d.toString("hex")),description:a.description})}catch(d){throw n.push({step:s+1,opcode:o,beforeStack:c.map(g=>g.toString("hex")),afterStack:[],error:d.message,description:a.description}),d}else n.push({step:s+1,opcode:o,beforeStack:c.map(d=>d.toString("hex")),afterStack:c.map(d=>d.toString("hex")),note:a.action,description:a.description})}),{finalStack:r.map(o=>o.toString("hex")),finalAltStack:i.map(o=>o.toString("hex")),history:n}},opcodeToName:e=>{let t=Object.entries(X).find(([r,i])=>i.code===e);return t?t[0]:`UNKNOWN_${e.toString(16).padStart(2,"0")}`},nameToOpcode:e=>X[e]&&X[e].code,generateCovenantTemplate:(e,t)=>{let r=[];return e==="value"&&(r.push("OP_SIZE"),r.push(52),r.push("OP_SUB"),r.push("OP_SPLIT"),r.push("OP_DROP"),r.push(8),r.push("OP_SPLIT"),r.push("OP_DROP")),t&&(r.push(u.Buffer.from(t,"hex")),r.push("OP_EQUAL")),{operations:r,asm:$e.createASM(r),description:`Extract ${e} field and compare with expected value`}}};Ut.exports={opcodeMap:X,scriptNum:l,utils:$e};if(C.main===Ut){console.log("\u{1F527} Comprehensive Bitcoin Script Opcode Map"),console.log("=========================================="),console.log(`Total opcodes mapped: ${Object.keys(X).length}`),console.log(`
|
|
8
|
-
\u{1F4CA} Categories:`)
|
|
9
|
-
\u{1F9EA} Example: Stack manipulation simulation`);try{let t=["OP_1","OP_2","OP_ADD","OP_3","OP_EQUAL"],r
|
|
5
|
+
`)};S.prototype._extractSpecificField=function(e,t){var r=t[e];return r?u.Buffer.from(r,"hex"):null};S.prototype._interpretField=function(e,t,r){if(!t)return null;var i={raw:t.toString("hex"),bytes:t.length};try{switch(e){case"nVersion":i.value=t.readUInt32LE(0),i.description="Transaction version "+i.value;break;case"value":t.length===8&&(i.satoshis=t.readBigUInt64LE(0).toString(),i.description=i.satoshis+" satoshis");break;case"sighashType":var n=t.readUInt32LE(0),o={1:"SIGHASH_ALL",65:"SIGHASH_ALL | FORKID",2:"SIGHASH_NONE",66:"SIGHASH_NONE | FORKID",3:"SIGHASH_SINGLE",67:"SIGHASH_SINGLE | FORKID"};i.value=n,i.description=o[n]||"Custom ("+n+")";break;case"outpoint_vout":i.value=t.readUInt32LE(0),i.description="Output index "+i.value;break;case"scriptLen":i.varintSize=r.scriptLenSize,i.scriptLength=r.scriptLen,i.description=r.scriptLen+" bytes encoded as "+r.scriptLenSize+"-byte varint";break;case"scriptCode":t.length===25&&t[0]===118&&t[1]===169?(i.description="Standard P2PKH script (25 bytes)",i.type="P2PKH"):t.length>0&&t[0]===106?(i.description="OP_RETURN data script ("+t.length+" bytes)",i.type="OP_RETURN"):(i.description="Custom script ("+t.length+" bytes)",i.type="CUSTOM");break;default:if(["hashPrevouts","hashSequence","hashOutputs"].includes(e)){var a=u.Buffer.alloc(32);t.equals(a)?(i.isZero=!0,i.description="Zero hash (check SIGHASH flags)"):i.description="32-byte hash"}}}catch(s){i.error=s.message}return i};S.prototype._getExtractionStrategy=function(e){var t=["value","nSequence","hashOutputs","nLocktime","sighashType"],r=["nVersion","hashPrevouts","hashSequence","outpoint_txid","outpoint_vout"];return t.includes(e)?"RIGHT":r.includes(e)?"LEFT":e==="scriptCode"?"DYNAMIC":e==="scriptLen"?"VARINT":"UNKNOWN"};S.decodeCompactSize=function(e,t){if(t>=e.length)throw new Error("CompactSize read past end of preimage buffer (offset "+t+", length "+e.length+")");var r=e[t];if(r<253)return{value:r,nextOffset:t+1,bytes:1};if(r===253){if(t+3>e.length)throw new Error("Truncated 2-byte CompactSize in preimage at offset "+t);var i=e.readUInt16LE(t+1);return{value:i,nextOffset:t+3,bytes:3}}else if(r===254){if(t+5>e.length)throw new Error("Truncated 4-byte CompactSize in preimage at offset "+t);var n=e.readUInt32LE(t+1);return{value:n,nextOffset:t+5,bytes:5}}else throw new Error("Invalid CompactSize: 8-byte length prefix (0xff) is not a valid script length")};S.fromTransaction=function(e,t,r,i,n){var o=qo.sighashPreimage(e,n,t,r,new Do(i));return new S(o,{transaction:e,inputIndex:t,subscript:r,satoshis:i,sighashType:n})};S.createExample=function(e){var t=Go.fromRandom(),r=t.toAddress(),i={txId:"0".repeat(64),outputIndex:0,script:ci.buildPublicKeyHashOut(r).toHex(),satoshis:1e5},n=new Mo().from(i).to(r,99e3),o=ci.fromHex(i.script);return S.fromTransaction(n,0,o,i.satoshis,e)};S.extractFromHex=function(e,t,r){var i=new S(e,{deferExtraction:!0});return i.extractField(t,r)};S.generateASMFromHex=function(e,t,r){var i=new S(e,{deferExtraction:!0});return i.generateASM(t,r)};S.extractMultipleFromHex=function(e,t){var r=new S(e,{deferExtraction:!0});return r.extractFields(t)};S.validateFromHex=function(e){var t=new S(e);return t.validate()};S.analyzeFromHex=function(e){var t=new S(e),r=t._parsePreimageStructure(),i=t.validate();return{hex:e,length:e.length/2,structure:r._structure,fields:r,validation:i,sighashInfo:t.getSighashInfo(),extractField:function(n){return t.extractField(n)},generateASM:function(n){return t.generateASM(n)},getSummary:function(){return{totalBytes:r._structure.totalActual,scriptLength:r.scriptLen,scriptVarintSize:r.scriptLenSize,sighashType:r.sighashType,valid:i.valid,warnings:i.warnings}}}};ui.exports=S});var li=O((Pc,pi)=>{"use strict";f();var z=Ee(),Vo=M(),Ko=D(),zo=ze(),hi=b(),$o=_e();function N(e){if(!(this instanceof N))return new N(e);this.sighashType=e||z.SIGHASH_ALL|z.SIGHASH_FORKID,this.analysis=this._analyzeFlags()}N.prototype.analyze=function(){return this.analysis};N.prototype.getZeroHashBehavior=function(){var e={hashPrevouts:!1,hashSequence:!1,hashOutputs:!1,explanation:[],criticalNote:null};return this.analysis.anyoneCanPay&&(e.hashPrevouts=!0,e.explanation.push("ANYONECANPAY: hashPrevouts becomes zero hash (0x00...00)")),this.analysis.baseType==="NONE"&&(e.hashSequence=!0,e.hashOutputs=!0,e.explanation.push("SIGHASH_NONE: hashSequence and hashOutputs become zero hash")),this.analysis.baseType==="SINGLE"&&(e.hashSequence=!0,e.hashOutputs=!0,e.explanation.push("SIGHASH_SINGLE: hashSequence becomes zero hash, hashOutputs covers only corresponding output")),(e.hashPrevouts||e.hashSequence||e.hashOutputs)&&(e.criticalNote="These zero hashes are NOT bugs - they are correct BIP-143 behavior for the specified SIGHASH flags!"),e};N.prototype.generateExample=function(){var e=zo.fromRandom(),t=e.toAddress(),r={txId:"a".repeat(64),outputIndex:0,script:hi.buildPublicKeyHashOut(t).toHex(),satoshis:1e5},i=new Ko().from(r).to(t,99e3),n=hi.fromHex(r.script),o=$o.sighashPreimage(i,this.sighashType,0,n,new Vo(r.satoshis)),a=J(),s=new a(o);return{transaction:i,preimage:s,sighashType:this.sighashType,analysis:this.analysis,zeroHashBehavior:this.getZeroHashBehavior(),fields:s.extract(),validation:s.validate()}};N.prototype.createDemonstration=function(){var e=this.generateExample(),t=u.Buffer.alloc(32).toString("hex"),r={sighashType:this.sighashType,analysis:this.analysis,zeroHashBehavior:this.getZeroHashBehavior(),preimageFields:{},observations:[],educationalNotes:[]},i=e.preimage.toObject().fields;return r.preimageFields=i,i.hashPrevouts===t&&r.observations.push({field:"hashPrevouts",value:"ZERO HASH (00...00)",reason:"ANYONECANPAY flag - this input can be combined with any other inputs"}),i.hashSequence===t&&r.observations.push({field:"hashSequence",value:"ZERO HASH (00...00)",reason:this.analysis.baseType+" flag - sequence numbers not covered by signature"}),i.hashOutputs===t&&r.observations.push({field:"hashOutputs",value:"ZERO HASH (00...00)",reason:this.analysis.baseType+" flag - outputs not fully covered by signature"}),r.educationalNotes=["Zero hashes in preimages are NOT errors - they indicate specific SIGHASH flag behavior","BIP-143 mandates these zero values when certain flags are used","ANYONECANPAY allows this input to be combined with different sets of inputs","SIGHASH_NONE means the signer doesn't care about any outputs","SIGHASH_SINGLE means the signer only cares about the corresponding output","Always check SIGHASH flags when you see 'mysterious' zero hashes in preimages"],r};N.prototype.checkCompliance=function(e){var t=e.toObject().fields,r=u.Buffer.alloc(32).toString("hex"),i={compliant:!0,issues:[],expectedZeros:[],unexpectedZeros:[]},n=this.getZeroHashBehavior();return n.hashPrevouts&&t.hashPrevouts!==r?(i.compliant=!1,i.issues.push("hashPrevouts should be zero due to ANYONECANPAY flag")):!n.hashPrevouts&&t.hashPrevouts===r&&i.unexpectedZeros.push("hashPrevouts is zero but ANYONECANPAY not set"),n.hashSequence&&t.hashSequence!==r?(i.compliant=!1,i.issues.push("hashSequence should be zero due to "+this.analysis.baseType+" flag")):!n.hashSequence&&t.hashSequence===r&&i.unexpectedZeros.push("hashSequence is zero but "+this.analysis.baseType+" allows sequence coverage"),n.hashOutputs&&t.hashOutputs!==r?(i.compliant=!1,i.issues.push("hashOutputs should be zero due to "+this.analysis.baseType+" flag")):!n.hashOutputs&&t.hashOutputs===r&&i.unexpectedZeros.push("hashOutputs is zero but "+this.analysis.baseType+" should cover outputs"),i};N.prototype._analyzeFlags=function(){var e=this.sighashType&31,t=(this.sighashType&128)!==0,r=(this.sighashType&64)!==0,i="UNKNOWN";e===1?i="ALL":e===2?i="NONE":e===3&&(i="SINGLE");var n=[];return n.push(i),t&&n.push("ANYONECANPAY"),r&&n.push("FORKID"),{sighashType:this.sighashType,baseType:i,anyoneCanPay:t,forkId:r,flagName:n.join(" | "),hex:"0x"+this.sighashType.toString(16).padStart(8,"0"),binary:"0b"+this.sighashType.toString(2).padStart(32,"0")}};N.getAllTypes=function(){var e=z.SIGHASH_FORKID;return[{name:"ALL",value:z.SIGHASH_ALL|e},{name:"NONE",value:z.SIGHASH_NONE|e},{name:"SINGLE",value:z.SIGHASH_SINGLE|e},{name:"ALL | ANYONECANPAY",value:z.SIGHASH_ALL|z.SIGHASH_ANYONECANPAY|e},{name:"NONE | ANYONECANPAY",value:z.SIGHASH_NONE|z.SIGHASH_ANYONECANPAY|e},{name:"SINGLE | ANYONECANPAY",value:z.SIGHASH_SINGLE|z.SIGHASH_ANYONECANPAY|e}]};N.generateAllDemonstrations=function(){return N.getAllTypes().map(function(e){var t=new N(e.value);return{typeName:e.name,demonstration:t.createDemonstration()}})};N.explainZeroMystery=function(){return{title:"The 'Extra Zero' Mystery in Bitcoin Preimages",problem:"Developers often see zero hashes (0x00...00) in preimage fields and think it's a bug",reality:"These zeros are CORRECT behavior mandated by BIP-143 for specific SIGHASH flags",explanation:["ANYONECANPAY sets hashPrevouts to zero - allows input combination flexibility","SIGHASH_NONE sets hashSequence and hashOutputs to zero - signer doesn't care about outputs","SIGHASH_SINGLE sets hashSequence to zero - only corresponding output matters","These are features, not bugs - they enable advanced Bitcoin transaction patterns"],solution:"Always check SIGHASH flags when analyzing preimages with zero hashes",toolTip:"Use SIGHASH.checkCompliance() to verify if zero hashes match expected flag behavior"}};pi.exports=N});var gi=O((Ec,fi)=>{"use strict";f();var bt=Object.create(null),kt=[],Ht=!(typeof m.default<"u"&&m.default.env&&m.default.env.BSV_NO_DEPRECATION_WARNINGS==="1");function di(e,t){if(!e||typeof e.what!="string"||e.what==="")throw new TypeError(t+"() requires { what: string }")}function Yo(e){var t="[@smartledger/bsv] "+e.what+" is deprecated";return e.since&&(t+=" since "+e.since),t+=".",e.why&&(t+=" "+e.why.charAt(0).toUpperCase()+e.why.slice(1)+"."),e.use&&(t+=" Use "+e.use+" instead."),t+=e.removeIn?" It will be removed in "+e.removeIn+".":" A removal version has not been set; it will not be removed in a 9.x release.",t}function se(e){if(!e||!e.what)throw new TypeError("deprecate() requires { what }");if(bt[e.what])return!1;bt[e.what]=!0;var t=Yo(e);return kt.push({what:e.what,since:e.since||null,removeIn:e.removeIn||null,use:e.use||null,message:t}),Ht&&console.warn(t),!0}se.fn=function(e,t){if(typeof e!="function")throw new TypeError("deprecate.fn() requires a function");di(t,"deprecate.fn");var r=function(){return se(t),e.apply(this,arguments)};return Object.defineProperty(r,"name",{value:e.name,configurable:!0}),Object.defineProperty(r,"length",{value:e.length,configurable:!0}),r.__wrapped=e,r.__deprecation=t,r};se.property=function(e,t,r,i){di(i,"deprecate.property");var n,o=!1;return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get:function(){return se(i),o||(n=r(),o=!0),n}}),e};se.fired=function(){return kt.slice()};se.setEnabled=function(e){Ht=!!e};se.isEnabled=function(){return Ht};se.reset=function(){bt=Object.create(null),kt.length=0};fi.exports=se});var vi=O((Tc,Si)=>{"use strict";f();var Ft=_e(),Ce=ge(),mi=Ee(),yi=fe(),rt=M(),Xo=D(),ye=b(),jo=gi();function k(e,t){if(!(this instanceof k))return new k(e,t);this.privateKey=e,this.publicKey=e?e.publicKey:null,this.options=t||{},this.allowNonEnforcing=this.options.allowNonEnforcing===!0,this.conditions=[],this.preimageFields=[],this.scriptTemplate=null,this.validationRules=[],this.sighashType=this.options.sighashType||mi.SIGHASH_ALL|mi.SIGHASH_FORKID}k.prototype._assertEnforcingAllowed=function(){if(this.allowNonEnforcing){jo({what:"SmartContract.Builder ({ allowNonEnforcing: true })",since:"9.1.0",removeIn:"10.0.0",use:"SmartContract.policy(), or SmartContract.PushTx / Token / valueCovenant",why:"the scripts it emits reduce to plain P2PK and constrain nothing about the spend"});return}if(!this.allowNonEnforcing)throw new Error("SmartContract.Builder produces a NON-ENFORCING script (constant hash-lock \u2192 plain P2PK; it does not constrain the spend). Use SmartContract.policy() (declarative OP_PUSH_TX), or SmartContract.PushTx / Token / valueCovenant for real covenants. To use this demo anyway, construct with { allowNonEnforcing: true }.")};k.prototype.validateField=function(e,t,r){r=r||{};var i={field:e,expectedValue:t,operator:r.operator||"EQUAL",required:r.required!==!1,description:r.description||"Validate "+e};return this.validationRules.push(i),this};k.prototype.addCondition=function(e,t){t=t||{};var r={type:typeof e=="function"?"CUSTOM":"OPCODE",condition:e,description:t.description||"Custom condition",required:t.required!==!1};return this.conditions.push(r),this};k.prototype.useTemplate=function(e,t){return this.scriptTemplate={name:e,params:t||{},customScript:typeof e=="object"?e:null},this};k.prototype.buildLockingScript=function(e){this._assertEnforcingAllowed();var t=new ye;return this.scriptTemplate?this._buildFromTemplate(e):this._buildMultiFieldCovenant(e)};k.prototype.buildUnlockingScript=function(e,t,r){var i=new ye,n=ye.fromHex(r.script),o=Ft.sign(e,this.privateKey,this.sighashType,t,n,new rt(r.satoshis)),a=u.Buffer.concat([o.toDER(),u.Buffer.from([this.sighashType])]);return i.add(a),r.originalPreimage&&i.add(u.Buffer.from(r.originalPreimage,"hex")),this.conditions.forEach(function(s){s.type==="UNLOCK_DATA"&&i.add(s.data)}),i};k.prototype.createCovenant=function(e,t){this._assertEnforcingAllowed(),t=t||{};var r=new Xo().from({txId:e.txid,outputIndex:e.vout,script:e.script,satoshis:e.satoshis}).to(this.privateKey.toAddress(),e.satoshis-(t.fee||1e3)),i=ye.fromHex(e.script),n=Ft.sighashPreimage(r,this.sighashType,0,i,new rt(e.satoshis)),o=J(),a=new o(n),s=a.extract(),c=this.buildLockingScript({preimage:n,fields:s,transaction:r});r.outputs[0].setScript(c),r.sign(this.privateKey);var d={txid:r.id,vout:0,satoshis:e.satoshis-(t.fee||1e3),script:c.toHex(),originalPreimage:n.toString("hex"),preimageFields:s,validationRules:this.validationRules.slice(),conditions:this.conditions.slice(),template:this.scriptTemplate,createdAt:new Date().toISOString(),type:"builder_covenant"};return{creationTx:r,covenantUtxo:d,lockingScript:c,preimageData:{preimage:n,fields:s}}};k.prototype.validateSpending=function(e,t){var r={valid:!0,errors:[],warnings:[],fieldValidations:[]},i=ye.fromHex(t.script),n=Ft.sighashPreimage(e,this.sighashType,0,i,new rt(t.satoshis)),o=J(),a=new o(n),s=a.extract();t.validationRules&&t.validationRules.forEach(function(x){var re=this._validateFieldRule(x,s,t.preimageFields);r.fieldValidations.push(re),!re.passed&&x.required&&(r.valid=!1,r.errors.push(re.error))}.bind(this));var c=new Ce,d=Ce.SCRIPT_VERIFY_P2SH|Ce.SCRIPT_VERIFY_STRICTENC|Ce.SCRIPT_VERIFY_DERSIG|Ce.SCRIPT_VERIFY_LOW_S|Ce.SCRIPT_ENABLE_SIGHASH_FORKID,g=e.inputs[0].script,y=ye.fromHex(t.script),P=c.verify(g,y,e,0,d,new rt(t.satoshis));return P||(r.valid=!1,r.errors.push("Script interpreter validation failed: "+c.errstr)),r};k.prototype._buildFromTemplate=function(e){var t=this.scriptTemplate;if(t.name==="HASH_LOCK")return this._buildHashLockTemplate(e,t.params);if(t.name==="MULTI_FIELD")return this._buildMultiFieldTemplate(e,t.params);if(t.customScript)return t.customScript;throw new Error("Unknown template: "+t.name)};k.prototype._buildMultiFieldCovenant=function(e){var t=new ye;return t.add("OP_DUP"),this.validationRules.forEach(function(r,i){if(i>0&&t.add("OP_DUP"),t.add("OP_HASH256"),r.expectedValue){var n=yi.sha256sha256(u.Buffer.from(r.expectedValue,"hex"));t.add(n),t.add("OP_EQUALVERIFY")}}),t.add("OP_DROP"),this.publicKey&&(t.add(this.publicKey.toBuffer()),t.add("OP_CHECKSIG")),t};k.prototype._buildHashLockTemplate=function(e,t){var r=new ye;r.add("OP_DUP"),r.add("OP_HASH256");var i=t.hash||yi.sha256sha256(e.preimage);return r.add(i),r.add("OP_EQUALVERIFY"),r.add("OP_DROP"),this.publicKey&&(r.add(this.publicKey.toBuffer()),r.add("OP_CHECKSIG")),r};k.prototype._validateFieldRule=function(e,t,r){var i=t[e.field],n=e.expectedValue;if(typeof n=="string"&&n.startsWith("ORIGINAL_")){var o=n.replace("ORIGINAL_","");n=r[o]}var a=!1,s=null;switch(e.operator){case"EQUAL":a=i&&i.equals?i.equals(n):i===n,a||(s=e.field+" does not equal expected value");break;case"NOT_EQUAL":a=i&&i.equals?!i.equals(n):i!==n,a||(s=e.field+" should not equal specified value");break;case"PRESENT":a=!!i,a||(s=e.field+" is required but not present");break;default:s="Unknown validation operator: "+e.operator}return{field:e.field,operator:e.operator,passed:a,error:s,description:e.description}};k.createHashLock=function(e,t){return new k(e).useTemplate("HASH_LOCK",{hash:t})};k.createMultiField=function(e,t){var r=new k(e);return t.forEach(function(i){r.validateField(i.field,i.expectedValue,i.options)}),r};Si.exports=k});var xi=O((Ac,Oi)=>{f();Oi.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Networks});var _i=O((kc,Pi)=>{f();Pi.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.crypto.Random});var wi=O((Fc,Ei)=>{f();Ei.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv});var ki=O((Lc,Rt)=>{f();var w=function(){(typeof m.default<"u"&&m.default.env&&m.default.env.BSV_DEBUG||typeof window<"u"&&window.BSV_DEBUG)&&console.log.apply(console,arguments)},Wo,Se,Ct,Le;if(typeof window>"u"&&typeof L=="function")try{Se=C(),Ct=C(),Le=Ct.join(__dirname,"blockchain-state.json")}catch{w("BlockchainState: Running in browser mode - persistence disabled")}else Wo=typeof window<"u"&&window.bsv||wi();function it(){return{metadata:{createdAt:new Date().toISOString(),lastUpdated:new Date().toISOString(),totalWallets:0,totalUTXOs:0,totalValue:0,blockHeight:0},wallets:{},globalUTXOSet:{},spentUTXOs:{},transactionHistory:[]}}function Re(){try{if(!Se||!Le)return it();if(!Se.existsSync(Le)){w("\u{1F195} Creating new blockchain state...");let t=it();return Be(t),t}let e=JSON.parse(Se.readFileSync(Le,"utf8"));return w("\u{1F4D6} Loaded existing blockchain state"),e}catch(e){return console.error("\u274C Error loading blockchain state:",e.message),it()}}function Be(e){try{e.metadata.lastUpdated=new Date().toISOString(),Se&&Le&&(Se.writeFileSync(Le,JSON.stringify(e,null,2)),w("\u{1F4BE} Blockchain state saved"))}catch(t){console.error("\u274C Error saving blockchain state:",t.message)}}function Ti(e,t){w(`\u{1F4DD} Registering wallet: ${e}`);let r=Re();return r.wallets[e]&&w("\u2139\uFE0F Wallet already exists, updating..."),r.wallets[e]={address:e,registeredAt:t.registeredAt||new Date().toISOString(),utxos:t.utxos||[],totalValue:0},t.utxos&&t.utxos.forEach(i=>{let n=`${i.txid}:${i.vout}`;r.globalUTXOSet[n]={...i,ownerAddress:e}}),r.metadata.totalWallets=Object.keys(r.wallets).length,Lt(r),Be(r),w(`\u2705 Wallet registered: ${e}`),r}function Ii(e,t){let r=Re(),i=`${e}:${t}`;return r.spentUTXOs[i]?{exists:!1,spent:!0,utxo:r.spentUTXOs[i]}:r.globalUTXOSet[i]?{exists:!0,spent:!1,utxo:r.globalUTXOSet[i]}:{exists:!1,spent:!1,utxo:null}}function Qo(e,t){let r=Ii(e,t);return r.exists&&!r.spent}function Zo(e,t,r){let i=Re(),n=`${e}:${t}`;if(!i.globalUTXOSet[n])throw new Error(`UTXO ${n} does not exist`);if(i.spentUTXOs[n])throw new Error(`UTXO ${n} already spent`);let o=i.globalUTXOSet[n];i.spentUTXOs[n]={...o,spentInTx:r,spentAt:new Date().toISOString()},delete i.globalUTXOSet[n];let a=i.wallets[o.ownerAddress];a&&(a.utxos=a.utxos.filter(s=>!(s.txid===e&&s.vout===t))),Lt(i),Be(i),w(`\u274C UTXO spent: ${n} in tx ${r}`)}function Jo(e,t){let r=Re(),i=`${e.txid}:${e.vout}`;if(r.globalUTXOSet[i]){w(`\u26A0\uFE0F UTXO ${i} already exists, skipping`);return}r.globalUTXOSet[i]={...e,ownerAddress:t,createdAt:new Date().toISOString()},r.wallets[t]||(r.wallets[t]={address:t,registeredAt:new Date().toISOString(),utxos:[],totalValue:0}),r.wallets[t].utxos.some(o=>o.txid===e.txid&&o.vout===e.vout)||r.wallets[t].utxos.push(e),Lt(r),Be(r),w(`\u2705 UTXO added: ${i} for ${t}`)}function Lt(e){let t=Object.keys(e.globalUTXOSet).length,r=Object.values(e.globalUTXOSet).reduce((i,n)=>i+n.satoshis,0);e.metadata.totalUTXOs=t,e.metadata.totalValue=r,Object.values(e.wallets).forEach(i=>{i.totalValue=i.utxos.reduce((n,o)=>n+o.satoshis,0)})}function Ai(){let e=Re();return w("\u{1F310} Blockchain State Statistics:"),w("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),w(`\u{1F4CA} Total Wallets: ${e.metadata.totalWallets}`),w(`\u{1F4B0} Total UTXOs: ${e.metadata.totalUTXOs}`),w(`\u{1F48E} Total Value: ${e.metadata.totalValue} satoshis`),w(`\u{1F3D7}\uFE0F Block Height: ${e.metadata.blockHeight}`),w(`\u{1F550} Last Updated: ${e.metadata.lastUpdated}
|
|
6
|
+
`),Object.keys(e.wallets).length>0&&(w("\u{1F45B} Registered Wallets:"),Object.entries(e.wallets).forEach(([t,r])=>{w(` ${t}: ${r.utxos.length} UTXOs, ${r.totalValue} sats`)})),e}function bi(){let e=Ct.join(__dirname,"wallet.json");if(!Se.existsSync(e))return w("\u274C No wallet.json found to import"),!1;try{let t=JSON.parse(Se.readFileSync(e,"utf8"));w("\u{1F4E5} Importing wallet from wallet.json...");let r={registeredAt:new Date().toISOString(),utxos:t.availableUTXOs||[t.utxo]};return Ti(t.wallet.address,r),w("\u2705 Wallet imported successfully"),!0}catch(t){return console.error("\u274C Error importing wallet:",t.message),!1}}if(L.main===Rt){let e=m.default.argv.slice(2);if(e[0]==="import")bi();else if(e[0]==="init"){let t=it();Be(t),w("\u{1F195} Initialized new blockchain state")}Ai()}Rt.exports={loadBlockchainState:Re,saveBlockchainState:Be,registerWallet:Ti,getUTXO:Ii,isUTXOAvailable:Qo,spendUTXO:Zo,addUTXO:Jo,getBlockchainStats:Ai,importWalletFromFile:bi}});var Ci=O((Nc,Fi)=>{"use strict";f();var Y=function(){(typeof m.default<"u"&&m.default.env&&m.default.env.BSV_DEBUG||typeof window<"u"&&window.BSV_DEBUG)&&console.log.apply(console,arguments)},ea=b(),ta=It(),ra=_i(),Bt,Hi,ia,ce;if(typeof window>"u"&&typeof L=="function")try{Bt=C(),Hi=C(),ia=C(),ce=ki()}catch{Y("SmartUTXO: Running in browser mode - some features may be limited")}var Nt=class{constructor(t={}){this.options=t||{},this.loadState()}loadState(){try{return ce.loadBlockchainState()}catch(t){return Y("\u26A0\uFE0F Could not load blockchain state:",t.message),null}}saveState(){try{let t=ce.loadBlockchainState();ce.saveBlockchainState(t);let r=Object.keys(t.globalUTXOSet||{}).length;Y(`\u{1F4BE} Saved blockchain state with ${r} UTXOs`)}catch(t){Y("\u26A0\uFE0F Could not save blockchain state:",t.message)}}getUTXOsForAddress(t){try{let r=ce.loadBlockchainState();return!r.wallets||!r.wallets[t]?[]:r.wallets[t].utxos||[]}catch(r){return Y("\u26A0\uFE0F Error getting UTXOs:",r.message),[]}}addUTXO(t){try{ce.addUTXO(t,t.address)}catch(r){Y("\u26A0\uFE0F Error adding UTXO:",r.message)}}spendUTXOs(t,r="manual-spend"){try{for(let i of t)ce.spendUTXO(i.txid,i.vout,r)}catch(i){Y("\u26A0\uFE0F Error spending UTXOs:",i.message)}}createMockUTXOs(t,r=5,i=1e5){let n=ea.buildPublicKeyHashOut(ta.fromString(t)).toHex(),o=[];for(let a=0;a<r;a++)o.push({txid:ra.getRandomBuffer(32).toString("hex"),vout:a,address:t,satoshis:i,script:n});return o}getBalance(t){try{let r=ce.loadBlockchainState();return!r.wallets||!r.wallets[t]?0:r.wallets[t].totalValue||0}catch(r){return Y("\u26A0\uFE0F Error getting balance:",r.message),0}}getStats(){try{let t=ce.getBlockchainStats();return{totalUTXOs:t.metadata.totalUTXOs,totalValue:t.metadata.totalValue,totalWallets:t.metadata.totalWallets,blockHeight:t.metadata.blockHeight,lastUpdated:t.metadata.lastUpdated}}catch(t){return Y("\u26A0\uFE0F Error getting stats:",t.message),{totalUTXOs:0,totalValue:0,totalWallets:0,blockHeight:0}}}reset(){try{let t=Hi.join(__dirname,"../utilities/blockchain-state.json");Bt.existsSync(t)&&(Bt.unlinkSync(t),Y("\u{1F504} Blockchain state reset"))}catch(t){Y("\u26A0\uFE0F Could not reset blockchain state:",t.message)}}};Fi.exports=Nt});var Bi=O((Dc,Ri)=>{"use strict";f();var na=_e(),Li=Ee(),oa=M(),aa=D(),sa=ze(),ca=xi(),Ne=b(),ua=C();function G(e){if(!(this instanceof G))return new G(e);this.options=e||{},this.network=this.options.network||ca.mainnet,this.keyRing={},this.utxoPool=[];try{var t=Ci();this.smartUTXO=new t(this.options)}catch{}}G.prototype.generateKeypair=function(e){e=e||"key_"+Date.now();var t=sa.fromRandom(this.network),r=t.toPublicKey(),i=t.toAddress(this.network),n={label:e,privateKey:t,publicKey:r,address:i,wif:t.toWIF(),addressString:i.toString()};return this.keyRing[e]=n,n};G.prototype.createRealUTXOs=function(e){e=e||{};for(var t=e.count||3,r=e.satoshis||1e5,i=e.scriptType||"P2PKH",n=e.keypair||this.generateKeypair("utxo_owner"),o=[],a=0;a<t;a++){var s=this._createSingleUTXO({keypair:n,satoshis:r,scriptType:i,vout:a});o.push(s),this.utxoPool.push(s),this.smartUTXO&&this.smartUTXO.addUTXO(s)}return o};G.prototype._createSingleUTXO=function(e){var t=ua.randomBytes(32).toString("hex"),r,i;switch(e.scriptType){case"P2PKH":r=Ne.buildPublicKeyHashOut(e.keypair.address),i=r.toHex();break;case"P2SH":var n=Ne.buildMultisigOut([e.keypair.publicKey],1);r=Ne.buildScriptHashOut(n),i=r.toHex();break;case"CUSTOM":r=e.customScript||Ne.buildPublicKeyHashOut(e.keypair.address),i=r.toHex();break;default:r=Ne.buildPublicKeyHashOut(e.keypair.address),i=r.toHex()}return{txid:t,vout:e.vout,address:e.keypair.addressString,script:i,satoshis:e.satoshis,keypair:e.keypair,scriptType:e.scriptType,scriptObj:r,created:new Date().toISOString()}};G.prototype.createTestTransaction=function(e){e=e||{};var t=e.inputs||this.utxoPool.slice(0,1);if(t.length===0)throw new Error("No UTXOs available for transaction. Call createRealUTXOs() first.");var r=t.reduce(function(s,c){return s+c.satoshis},0),i=new aa;t.forEach(function(s){i.from({txId:s.txid,outputIndex:s.vout,address:s.address,script:s.script,satoshis:s.satoshis})});var n=e.outputAddress||t[0].keypair.addressString,o=e.outputAmount||r-1e4,a=e.fee||1e4;return i.to(n,o),i.fee(a),{transaction:i,inputUTXOs:t,unsignedHex:i.toString(),inputTotal:r,outputAmount:o,fee:a,sign:function(){return t.forEach(function(s){i.sign(s.keypair.privateKey)}),{signedTransaction:i,signedHex:i.toString(),txid:i.id}},generatePreimage:function(s,c){c=c||Li.SIGHASH_ALL|Li.SIGHASH_FORKID;var d=t[s];return na.sighashPreimage(i,c,s,Ne.fromHex(d.script),new oa(d.satoshis))}}};G.prototype.createCovenantTest=function(e){e=e||{};var t=this.generateKeypair("covenant_test"),r=this.createRealUTXOs({count:e.utxoCount||2,satoshis:e.satoshis||5e4,keypair:t,scriptType:e.scriptType||"P2PKH"}),i={inputs:r.slice(0,1),outputAmount:e.covenantAmount||4e4,fee:1e4},n=this.createTestTransaction(i),o=n.generatePreimage(0),a=o.toString("hex");return{keypair:t,utxos:r,transaction:n,preimage:{buffer:o,hex:a,length:o.length},extractField:function(s){try{var c=J();return c.extractFromHex(a,s)}catch(d){throw new Error("SmartContract.Preimage not available: "+d.message)}},validateCovenant:function(s){return{preimageValid:o.length>=182,covenantLogic:s,testPassed:!0}},getSummary:function(){return{keypair:t.addressString,utxoCount:r.length,totalValue:r.reduce(function(s,c){return s+c.satoshis},0),preimageLength:o.length,transactionId:n.transaction.id}}}};G.prototype.getKeypairs=function(){return this.keyRing};G.prototype.getUTXOs=function(){return this.utxoPool};G.prototype.reset=function(){this.keyRing={},this.utxoPool=[]};G.createTestEnvironment=function(e){var t=new G(e),r=t.createCovenantTest(e);return{generator:t,test:r,getPreimage:function(){return r.preimage.hex},getKeypair:function(){return r.keypair},extractField:function(i){return r.extractField(i)},generateASM:function(i){try{var n=J();return n.generateASMFromHex(r.preimage.hex,i)}catch(o){throw new Error("Cannot generate ASM: "+o.message)}}}};Ri.exports=G});var $e=O((Gc,Ni)=>{f();Ni.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Transaction.Output});var V=O((Kc,Ui)=>{f();Ui.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Opcode});var Mi=O(($c,Di)=>{"use strict";f();var qi=$e(),ha=He(),Ut=ge(),pa=M(),la=D(),da=V(),ve=b();function H(e){if(!(this instanceof H))return new H(e);this.options=e||{},this.flags=this.options.flags||Ut.SCRIPT_ENABLE_SIGHASH_FORKID,this.satoshis=this.options.satoshis||1e5}H.prototype.execute=function(e){var t=this._parseScript(e.unlocking),r=this._parseScript(e.locking),i=this._createDummyTransaction(),n=new Ut,o=new pa(this.satoshis);try{var a=n.verify(t,r,i,0,this.flags,o);return{success:a,unlocking:t.toASM(),locking:r.toASM(),finalStack:n.stack.map(function(s){return s.toString("hex")}),altStack:n.altstack.map(function(s){return s.toString("hex")}),error:null}}catch(s){return{success:!1,unlocking:t.toASM(),locking:r.toASM(),finalStack:[],altStack:[],error:s.message}}};H.prototype.debug=function(e){var t=this._createCombinedScript(e),r=this._createDummyTransaction(),i=new Ut;i.script=t,i.tx=r,i.nIn=0,i.flags=this.flags;var n=[],o=t.chunks;try{for(var a=0;a<o.length;a++){var s=o[a],c=da.reverseMap[s.opcodenum]||"PUSH",d=i.stack.map(function(x){return x.toString("hex")}),g=i.altstack.map(function(x){return x.toString("hex")});try{i.step();var y=i.stack.map(function(x){return x.toString("hex")}),P=i.altstack.map(function(x){return x.toString("hex")});n.push({step:a+1,opcode:c,beforeStack:d,afterStack:y,beforeAltStack:g,afterAltStack:P,success:!0,error:null})}catch(x){n.push({step:a+1,opcode:c,beforeStack:d,afterStack:d,beforeAltStack:g,afterAltStack:g,success:!1,error:x.message});break}}}catch(x){n.push({step:0,opcode:"INITIALIZATION",beforeStack:[],afterStack:[],beforeAltStack:[],afterAltStack:[],success:!1,error:x.message})}return{script:t.toASM(),steps:n,totalSteps:o.length,success:n.length>0&&n[n.length-1].success}};H.prototype.testCovenant=function(e){var t=e.preimage,r=e.constraints||{},i=this._buildCovenantScript(r,t),n=this.execute({unlocking:t,locking:i});return n.covenant={preimageLength:t.length/2,constraints:r,constraintResults:this._analyzeConstraints(t,r)},n};H.prototype.testFieldExtraction=function(e,t){try{var r=J(),i=r.extractFromHex(e,t,{includeComments:!1}),n=this._cleanASM(i.asm),o=this.execute({unlocking:e,locking:n+" OP_DROP OP_TRUE"});return o.fieldExtraction={field:t,strategy:i.strategy,value:i.value,interpretation:i.interpretation,asmGenerated:i.asm,cleanedASM:n},o}catch(a){return{success:!1,error:a.message,fieldExtraction:{field:t,error:a.message}}}};H.prototype._parseScript=function(e){if(!e)return new ve;var t=e.trim(),r=/^[0-9a-fA-F]+$/.test(t.replace(/\s+/g,""));try{if(r){var i=t.length/2;return i>=180&&i<=250?new ve().add(u.Buffer.from(t,"hex")):ve.fromHex(t)}else return ve.fromASM(t)}catch(n){throw new Error("Failed to parse script: "+n.message)}};H.prototype._createCombinedScript=function(e){if(e.combined)return this._parseScript(e.combined);var t=this._parseScript(e.unlocking),r=this._parseScript(e.locking),i=u.Buffer.concat([t.toBuffer(),r.toBuffer()]);return ve.fromBuffer(i)};H.prototype._createDummyTransaction=function(){var e=new la,t=new ha({prevTxId:"0".repeat(64),outputIndex:0,script:ve.empty(),satoshis:this.satoshis,output:new qi({satoshis:this.satoshis,script:ve.empty()})});return e.addInput(t),e.addOutput(new qi({satoshis:this.satoshis,script:ve.empty()})),e};H.prototype._buildCovenantScript=function(e,t){var r=[];try{var i=J();if(e.minimumAmount){var n=i.generateASMFromHex(t,"value",!1);r.push(n),r.push("OP_BIN2NUM"),r.push(e.minimumAmount.toString()),r.push("OP_GREATERTHANOREQUAL"),r.push("OP_VERIFY")}if(e.requiredSighash){var o=i.generateASMFromHex(t,"sighashType",!1);r.push(o),r.push("OP_BIN2NUM"),r.push(e.requiredSighash.toString()),r.push("OP_EQUAL"),r.push("OP_VERIFY")}r.push("OP_TRUE");var a=r.join(" ");return this._cleanASM(a)}catch(s){throw new Error("Failed to build covenant script: "+s.message)}};H.prototype._cleanASM=function(e){var t=e.split(`
|
|
7
|
+
`).map(function(r){return r.split("#")[0].trim()}).filter(function(r){return r.length>0}).join(" ").replace(/\s+/g," ").trim();return t=t.replace(/\b(\d+)\b/g,function(r,i){var n=parseInt(i);if(n>=1&&n<=16)return"OP_"+n;if(n===0)return"OP_0";if(n===-1)return"OP_1NEGATE";var o=n,a=o<0;a&&(o=-o);for(var s=[];o>0;)s.push(o&255),o=Math.floor(o/256);return s.length===0&&s.push(0),a?s[s.length-1]>=128?s.push(128):s[s.length-1]|=128:s.length>0&&s[s.length-1]>=128&&s.push(0),u.Buffer.from(s).toString("hex")}),t};H.prototype._analyzeConstraints=function(e,t){var r={};try{var i=J();if(t.minimumAmount){var n=i.extractFromHex(e,"value",{includeComments:!1}),o=parseInt(n.interpretation.satoshis);r.amountCheck={constraint:t.minimumAmount,actual:o,satisfied:o>=t.minimumAmount}}if(t.requiredSighash){var a=i.extractFromHex(e,"sighashType",{includeComments:!1}),s=parseInt(a.value,16);r.sighashCheck={constraint:t.requiredSighash,actual:s,satisfied:(s&255)===t.requiredSighash}}}catch(c){r.error=c.message}return r};H.test=function(e,t,r){var i=new H(r);return i.execute({unlocking:e,locking:t})};H.testCovenant=function(e,t,r){var i=new H(r);return i.testCovenant({preimage:e,constraints:t})};H.testFieldExtraction=function(e,t,r){var i=new H(r);return i.testFieldExtraction(e,t)};Di.exports=H});var Dt=O((Xc,qt)=>{f();var l={encode:e=>{if(e===0)return u.Buffer.alloc(0);let t=e<0,r=Math.abs(e),i=[],n=r;for(;n>0;)i.push(n&255),n>>=8;return i[i.length-1]&128?i.push(t?128:0):t&&(i[i.length-1]|=128),u.Buffer.from(i)},decode:e=>{if(e.length===0)return 0;let t=Array.from(e),r=t[t.length-1]&128;r&&(t[t.length-1]&=127);let i=0;for(let n=t.length-1;n>=0;n--)i=(i<<8)+t[n];return r?-i:i}},X={OP_FALSE:{code:0,category:"constants",description:"Push empty array (false value)",action:e=>e.push(u.Buffer.alloc(0))},OP_0:{code:0,category:"constants",description:"Push empty array (alias for OP_FALSE)",action:e=>e.push(u.Buffer.alloc(0))},OP_PUSHDATA1:{code:76,category:"pushdata",description:"Push next [1 byte] bytes of data",action:"Read next byte as length; push that many bytes"},OP_PUSHDATA2:{code:77,category:"pushdata",description:"Push next [2 bytes LE] bytes of data",action:"Read next 2 bytes as length; push that many bytes"},OP_PUSHDATA4:{code:78,category:"pushdata",description:"Push next [4 bytes LE] bytes of data",action:"Read next 4 bytes as length; push that many bytes"},OP_1NEGATE:{code:79,category:"constants",description:"Push number -1",action:e=>e.push(l.encode(-1))},OP_RESERVED:{code:80,category:"reserved",description:"Reserved opcode (makes transaction invalid)",action:()=>{throw new Error("OP_RESERVED encountered")}},OP_TRUE:{code:81,category:"constants",description:"Push number 1 (true value)",action:e=>e.push(l.encode(1))},OP_1:{code:81,category:"constants",description:"Push number 1 (alias for OP_TRUE)",action:e=>e.push(l.encode(1))},OP_2:{code:82,category:"constants",description:"Push number 2",action:e=>e.push(l.encode(2))},OP_3:{code:83,category:"constants",description:"Push number 3",action:e=>e.push(l.encode(3))},OP_4:{code:84,category:"constants",description:"Push number 4",action:e=>e.push(l.encode(4))},OP_5:{code:85,category:"constants",description:"Push number 5",action:e=>e.push(l.encode(5))},OP_6:{code:86,category:"constants",description:"Push number 6",action:e=>e.push(l.encode(6))},OP_7:{code:87,category:"constants",description:"Push number 7",action:e=>e.push(l.encode(7))},OP_8:{code:88,category:"constants",description:"Push number 8",action:e=>e.push(l.encode(8))},OP_9:{code:89,category:"constants",description:"Push number 9",action:e=>e.push(l.encode(9))},OP_10:{code:90,category:"constants",description:"Push number 10",action:e=>e.push(l.encode(10))},OP_11:{code:91,category:"constants",description:"Push number 11",action:e=>e.push(l.encode(11))},OP_12:{code:92,category:"constants",description:"Push number 12",action:e=>e.push(l.encode(12))},OP_13:{code:93,category:"constants",description:"Push number 13",action:e=>e.push(l.encode(13))},OP_14:{code:94,category:"constants",description:"Push number 14",action:e=>e.push(l.encode(14))},OP_15:{code:95,category:"constants",description:"Push number 15",action:e=>e.push(l.encode(15))},OP_16:{code:96,category:"constants",description:"Push number 16",action:e=>e.push(l.encode(16))},OP_NOP:{code:97,category:"flow_control",description:"No operation (do nothing)",action:e=>{}},OP_VER:{code:98,category:"flow_control",description:"Push transaction version (disabled)",action:()=>{throw new Error("OP_VER is disabled")}},OP_IF:{code:99,category:"flow_control",description:"Execute if top stack value is true",action:"// Conditional execution (requires parser state)"},OP_NOTIF:{code:100,category:"flow_control",description:"Execute if top stack value is false",action:"// Conditional execution (requires parser state)"},OP_VERIF:{code:101,category:"flow_control",description:"Conditional execution based on transaction version (disabled)",action:()=>{throw new Error("OP_VERIF is disabled")}},OP_VERNOTIF:{code:102,category:"flow_control",description:"Conditional execution based on transaction version (disabled)",action:()=>{throw new Error("OP_VERNOTIF is disabled")}},OP_ELSE:{code:103,category:"flow_control",description:"Else branch of conditional",action:"// Conditional execution (requires parser state)"},OP_ENDIF:{code:104,category:"flow_control",description:"End conditional block",action:"// Conditional execution (requires parser state)"},OP_VERIFY:{code:105,category:"flow_control",description:"Fail if top stack value is not true",action:e=>{let t=e.pop();if(!t||t.length===0||l.decode(t)===0)throw new Error("OP_VERIFY failed")}},OP_RETURN:{code:106,category:"flow_control",description:"Terminate script execution immediately",action:()=>{throw new Error("Script terminated by OP_RETURN")}},OP_TOALTSTACK:{code:107,category:"stack",description:"Move top item from main stack to alt stack",action:(e,t)=>t.push(e.pop())},OP_FROMALTSTACK:{code:108,category:"stack",description:"Move top item from alt stack to main stack",action:(e,t)=>e.push(t.pop())},OP_2DROP:{code:109,category:"stack",description:"Remove top two stack items",action:e=>{e.pop(),e.pop()}},OP_2DUP:{code:110,category:"stack",description:"Duplicate top two stack items",action:e=>{let t=e[e.length-1],r=e[e.length-2];e.push(u.Buffer.from(r),u.Buffer.from(t))}},OP_3DUP:{code:111,category:"stack",description:"Duplicate top three stack items",action:e=>{let t=e[e.length-1],r=e[e.length-2],i=e[e.length-3];e.push(u.Buffer.from(i),u.Buffer.from(r),u.Buffer.from(t))}},OP_2OVER:{code:112,category:"stack",description:"Copy 3rd and 4th items to top",action:e=>{let t=e[e.length-3],r=e[e.length-4];e.push(u.Buffer.from(r),u.Buffer.from(t))}},OP_2ROT:{code:113,category:"stack",description:"Move 5th and 6th items to top",action:e=>{let t=e.splice(-5,1)[0],r=e.splice(-5,1)[0];e.push(t,r)}},OP_2SWAP:{code:114,category:"stack",description:"Swap top two pairs of items",action:e=>{let t=e.pop(),r=e.pop(),i=e.pop(),n=e.pop();e.push(r,t,n,i)}},OP_IFDUP:{code:115,category:"stack",description:"Duplicate top item if it is not zero",action:e=>{let t=e[e.length-1];t.length>0&&l.decode(t)!==0&&e.push(u.Buffer.from(t))}},OP_DEPTH:{code:116,category:"stack",description:"Push stack size as number",action:e=>e.push(l.encode(e.length))},OP_DROP:{code:117,category:"stack",description:"Remove top stack item",action:e=>e.pop()},OP_DUP:{code:118,category:"stack",description:"Duplicate top stack item",action:e=>e.push(u.Buffer.from(e[e.length-1]))},OP_NIP:{code:119,category:"stack",description:"Remove second-to-top item",action:e=>{let t=e.pop();e.pop(),e.push(t)}},OP_OVER:{code:120,category:"stack",description:"Copy second-to-top item to top",action:e=>e.push(u.Buffer.from(e[e.length-2]))},OP_PICK:{code:121,category:"stack",description:"Copy nth item to top (0-indexed from top)",action:e=>{let t=l.decode(e.pop());e.push(u.Buffer.from(e[e.length-1-t]))}},OP_ROLL:{code:122,category:"stack",description:"Move nth item to top (0-indexed from top)",action:e=>{let t=l.decode(e.pop()),r=e.splice(e.length-1-t,1)[0];e.push(r)}},OP_ROT:{code:123,category:"stack",description:"Rotate top three items left",action:e=>{let t=e.pop(),r=e.pop(),i=e.pop();e.push(r,t,i)}},OP_SWAP:{code:124,category:"stack",description:"Swap top two items",action:e=>{let t=e.pop(),r=e.pop();e.push(t,r)}},OP_TUCK:{code:125,category:"stack",description:"Copy top item below second item",action:e=>{let t=e.pop(),r=e.pop();e.push(t,r,t)}},OP_CAT:{code:126,category:"data",description:"Concatenate top two items",action:e=>{let t=e.pop(),r=e.pop();e.push(u.Buffer.concat([r,t]))}},OP_SPLIT:{code:127,category:"data",description:"Split item at position n",action:e=>{let t=l.decode(e.pop()),r=e.pop();e.push(r.slice(0,t),r.slice(t))}},OP_NUM2BIN:{code:128,category:"data",description:"Convert number to byte sequence of length n",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop()),i=u.Buffer.alloc(t),n=l.encode(r);n.copy(i,0,0,Math.min(n.length,t)),e.push(i)}},OP_BIN2NUM:{code:129,category:"data",description:"Convert byte sequence to number",action:e=>{let t=e.pop();e.push(l.encode(l.decode(t)))}},OP_SIZE:{code:130,category:"data",description:"Push size of top item (without removing item)",action:e=>e.push(l.encode(e[e.length-1].length))},OP_INVERT:{code:131,category:"bitwise",description:"Bitwise NOT of top item",action:e=>{let t=e.pop();e.push(u.Buffer.from(t.map(r=>~r)))}},OP_AND:{code:132,category:"bitwise",description:"Bitwise AND of top two items",action:e=>{let t=e.pop(),r=e.pop(),i=Math.max(t.length,r.length),n=u.Buffer.alloc(i);for(let o=0;o<i;o++)n[o]=(t[o]||0)&(r[o]||0);e.push(n)}},OP_OR:{code:133,category:"bitwise",description:"Bitwise OR of top two items",action:e=>{let t=e.pop(),r=e.pop(),i=Math.max(t.length,r.length),n=u.Buffer.alloc(i);for(let o=0;o<i;o++)n[o]=(t[o]||0)|(r[o]||0);e.push(n)}},OP_XOR:{code:134,category:"bitwise",description:"Bitwise XOR of top two items",action:e=>{let t=e.pop(),r=e.pop(),i=Math.max(t.length,r.length),n=u.Buffer.alloc(i);for(let o=0;o<i;o++)n[o]=(t[o]||0)^(r[o]||0);e.push(n)}},OP_EQUAL:{code:135,category:"bitwise",description:"Push 1 if top two items are equal, 0 otherwise",action:e=>{let t=e.pop(),r=e.pop();e.push(t.equals(r)?l.encode(1):l.encode(0))}},OP_EQUALVERIFY:{code:136,category:"bitwise",description:"Fail if top two items are not equal",action:e=>{let t=e.pop(),r=e.pop();if(!t.equals(r))throw new Error("OP_EQUALVERIFY failed")}},OP_1ADD:{code:139,category:"arithmetic",description:"Add 1 to top item",action:e=>{let t=l.decode(e.pop());e.push(l.encode(t+1))}},OP_1SUB:{code:140,category:"arithmetic",description:"Subtract 1 from top item",action:e=>{let t=l.decode(e.pop());e.push(l.encode(t-1))}},OP_2MUL:{code:141,category:"arithmetic",description:"Multiply top item by 2 (disabled)",action:()=>{throw new Error("OP_2MUL is disabled")}},OP_2DIV:{code:142,category:"arithmetic",description:"Divide top item by 2 (disabled)",action:()=>{throw new Error("OP_2DIV is disabled")}},OP_NEGATE:{code:143,category:"arithmetic",description:"Negate top item",action:e=>{let t=l.decode(e.pop());e.push(l.encode(-t))}},OP_ABS:{code:144,category:"arithmetic",description:"Absolute value of top item",action:e=>{let t=l.decode(e.pop());e.push(l.encode(Math.abs(t)))}},OP_NOT:{code:145,category:"arithmetic",description:"Logical NOT (0\u21921, non-zero\u21920)",action:e=>{let t=l.decode(e.pop());e.push(l.encode(t===0?1:0))}},OP_0NOTEQUAL:{code:146,category:"arithmetic",description:"Push 1 if top item is not zero, 0 otherwise",action:e=>{let t=l.decode(e.pop());e.push(l.encode(t!==0?1:0))}},OP_ADD:{code:147,category:"arithmetic",description:"Add top two items",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r+t))}},OP_SUB:{code:148,category:"arithmetic",description:"Subtract: second - first",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r-t))}},OP_MUL:{code:149,category:"arithmetic",description:"Multiply top two items",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r*t))}},OP_DIV:{code:150,category:"arithmetic",description:"Divide: second / first",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());if(t===0)throw new Error("Division by zero");e.push(l.encode(Math.floor(r/t)))}},OP_MOD:{code:151,category:"arithmetic",description:"Modulo: second % first",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());if(t===0)throw new Error("Division by zero");e.push(l.encode(r%t))}},OP_LSHIFT:{code:152,category:"arithmetic",description:"Left shift: second << first",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r<<t))}},OP_RSHIFT:{code:153,category:"arithmetic",description:"Right shift: second >> first",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r>>t))}},OP_BOOLAND:{code:154,category:"arithmetic",description:"Boolean AND: 1 if both non-zero, 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(t!==0&&r!==0?1:0))}},OP_BOOLOR:{code:155,category:"arithmetic",description:"Boolean OR: 1 if either non-zero, 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(t!==0||r!==0?1:0))}},OP_NUMEQUAL:{code:156,category:"arithmetic",description:"Push 1 if numbers are equal, 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(t===r?1:0))}},OP_NUMEQUALVERIFY:{code:157,category:"arithmetic",description:"Fail if numbers are not equal",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());if(t!==r)throw new Error("OP_NUMEQUALVERIFY failed")}},OP_NUMNOTEQUAL:{code:158,category:"arithmetic",description:"Push 1 if numbers are not equal, 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(t!==r?1:0))}},OP_LESSTHAN:{code:159,category:"arithmetic",description:"Push 1 if second < first, 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r<t?1:0))}},OP_GREATERTHAN:{code:160,category:"arithmetic",description:"Push 1 if second > first, 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r>t?1:0))}},OP_LESSTHANOREQUAL:{code:161,category:"arithmetic",description:"Push 1 if second <= first, 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r<=t?1:0))}},OP_GREATERTHANOREQUAL:{code:162,category:"arithmetic",description:"Push 1 if second >= first, 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r>=t?1:0))}},OP_MIN:{code:163,category:"arithmetic",description:"Push smaller of top two numbers",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(Math.min(t,r)))}},OP_MAX:{code:164,category:"arithmetic",description:"Push larger of top two numbers",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(Math.max(t,r)))}},OP_WITHIN:{code:165,category:"arithmetic",description:"Push 1 if x is within [min, max), 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop()),i=l.decode(e.pop());e.push(l.encode(i>=r&&i<t?1:0))}},OP_RIPEMD160:{code:166,category:"crypto",description:"RIPEMD-160 hash of top item",action:e=>{let r=C().createHash("ripemd160").update(e.pop()).digest();e.push(r)}},OP_SHA1:{code:167,category:"crypto",description:"SHA-1 hash of top item",action:e=>{let r=C().createHash("sha1").update(e.pop()).digest();e.push(r)}},OP_SHA256:{code:168,category:"crypto",description:"SHA-256 hash of top item",action:e=>{let r=C().createHash("sha256").update(e.pop()).digest();e.push(r)}},OP_HASH160:{code:169,category:"crypto",description:"SHA-256 then RIPEMD-160 hash of top item",action:e=>{let t=C(),r=t.createHash("sha256").update(e.pop()).digest(),i=t.createHash("ripemd160").update(r).digest();e.push(i)}},OP_HASH256:{code:170,category:"crypto",description:"Double SHA-256 hash of top item",action:e=>{let t=C(),r=t.createHash("sha256").update(e.pop()).digest(),i=t.createHash("sha256").update(r).digest();e.push(i)}},OP_CODESEPARATOR:{code:171,category:"crypto",description:"Mark signature checking boundary",action:e=>{}},OP_CHECKSIG:{code:172,category:"crypto",description:"Verify signature against public key",action:"// Signature verification (requires transaction context)"},OP_CHECKSIGVERIFY:{code:173,category:"crypto",description:"Verify signature, then fail if invalid",action:"// Signature verification with VERIFY (requires transaction context)"},OP_CHECKMULTISIG:{code:174,category:"crypto",description:"Verify multiple signatures against public keys",action:"// Multi-signature verification (requires transaction context)"},OP_CHECKMULTISIGVERIFY:{code:175,category:"crypto",description:"Verify multiple signatures, then fail if invalid",action:"// Multi-signature verification with VERIFY (requires transaction context)"},OP_SUBSTR:{code:179,category:"string",description:"Extract substring: string[start:start+length]",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop()),i=e.pop();e.push(i.slice(r,r+t))}},OP_LEFT:{code:180,category:"string",description:"Extract leftmost n bytes",action:e=>{let t=l.decode(e.pop()),r=e.pop();e.push(r.slice(0,t))}},OP_RIGHT:{code:181,category:"string",description:"Extract rightmost n bytes",action:e=>{let t=l.decode(e.pop()),r=e.pop();e.push(r.slice(-t))}},OP_NOP1:{code:176,category:"nop",description:"No operation (reserved for future use)",action:e=>{}},OP_NOP2:{code:177,category:"nop",description:"No operation (formerly CHECKLOCKTIMEVERIFY)",action:e=>{}},OP_NOP3:{code:178,category:"nop",description:"No operation (formerly CHECKSEQUENCEVERIFY)",action:e=>{}},OP_NOP9:{code:184,category:"nop",description:"No operation (reserved for future use)",action:e=>{}},OP_NOP10:{code:185,category:"nop",description:"No operation (reserved for future use)",action:e=>{}},OP_RESERVED1:{code:137,category:"reserved",description:"Reserved opcode (makes transaction invalid)",action:()=>{throw new Error("OP_RESERVED1 encountered")}},OP_RESERVED2:{code:138,category:"reserved",description:"Reserved opcode (makes transaction invalid)",action:()=>{throw new Error("OP_RESERVED2 encountered")}},OP_CHECKLOCKTIMEVERIFY:{code:177,category:"disabled",description:"Check locktime (disabled post-Genesis)",action:e=>{}},OP_CHECKSEQUENCEVERIFY:{code:178,category:"disabled",description:"Check sequence (disabled post-Genesis)",action:e=>{}},OP_PUBKEYHASH:{code:253,category:"pseudo",description:"Template matching: public key hash",action:"// Template matching only"},OP_PUBKEY:{code:254,category:"pseudo",description:"Template matching: public key",action:"// Template matching only"},OP_INVALIDOPCODE:{code:255,category:"pseudo",description:"Invalid opcode placeholder",action:()=>{throw new Error("Invalid opcode encountered")}}},Ye={getByCategory:e=>Object.entries(X).filter(([t,r])=>r.category===e).reduce((t,[r,i])=>({...t,[r]:i}),{}),getCategories:()=>{let e=new Set;return Object.values(X).forEach(t=>e.add(t.category)),Array.from(e).sort()},createASM:e=>{let t=[];return e.forEach(r=>{if(typeof r=="string"&&X[r])t.push(r);else if(typeof r=="number")if(r>=1&&r<=16)t.push(`OP_${r}`);else if(r===0)t.push("OP_0");else if(r===-1)t.push("OP_1NEGATE");else{let i=l.encode(r);t.push(i.toString("hex"))}else if(u.Buffer.isBuffer(r))t.push(r.toString("hex"));else throw new Error(`Invalid operation: ${r}`)}),t.join(" ")},simulate:(e,t=[])=>{let r=[...t],i=[],n=[];return e.forEach((o,a)=>{if(!X[o])throw new Error(`Unknown opcode: ${o}`);let s=X[o],c=[...r];if(typeof s.action=="function")try{s.action(r,i),n.push({step:a+1,opcode:o,beforeStack:c.map(d=>d.toString("hex")),afterStack:r.map(d=>d.toString("hex")),description:s.description})}catch(d){throw n.push({step:a+1,opcode:o,beforeStack:c.map(g=>g.toString("hex")),afterStack:[],error:d.message,description:s.description}),d}else n.push({step:a+1,opcode:o,beforeStack:c.map(d=>d.toString("hex")),afterStack:c.map(d=>d.toString("hex")),note:s.action,description:s.description})}),{finalStack:r.map(o=>o.toString("hex")),finalAltStack:i.map(o=>o.toString("hex")),history:n}},opcodeToName:e=>{let t=Object.entries(X).find(([r,i])=>i.code===e);return t?t[0]:`UNKNOWN_${e.toString(16).padStart(2,"0")}`},nameToOpcode:e=>X[e]&&X[e].code,generateCovenantTemplate:(e,t)=>{let r=[];return e==="value"&&(r.push("OP_SIZE"),r.push(52),r.push("OP_SUB"),r.push("OP_SPLIT"),r.push("OP_DROP"),r.push(8),r.push("OP_SPLIT"),r.push("OP_DROP")),t&&(r.push(u.Buffer.from(t,"hex")),r.push("OP_EQUAL")),{operations:r,asm:Ye.createASM(r),description:`Extract ${e} field and compare with expected value`}}};qt.exports={opcodeMap:X,scriptNum:l,utils:Ye};if(L.main===qt){console.log("\u{1F527} Comprehensive Bitcoin Script Opcode Map"),console.log("=========================================="),console.log(`Total opcodes mapped: ${Object.keys(X).length}`),console.log(`
|
|
8
|
+
\u{1F4CA} Categories:`),Ye.getCategories().forEach(t=>{let r=Object.values(X).filter(i=>i.category===t).length;console.log(` ${t}: ${r} opcodes`)}),console.log(`
|
|
9
|
+
\u{1F9EA} Example: Stack manipulation simulation`);try{let t=["OP_1","OP_2","OP_ADD","OP_3","OP_EQUAL"],r=Ye.simulate(t);console.log("Operations:",t.join(" ")),console.log("Final stack:",r.finalStack),console.log("Expected: ['01'] (true, since 1+2=3)"),console.log(`
|
|
10
10
|
\u{1F4DD} Step-by-step execution:`),r.history.forEach(i=>{console.log(` ${i.step}. ${i.opcode}: ${i.description}`),console.log(` Stack: [${i.beforeStack.join(", ")}] \u2192 [${i.afterStack.join(", ")}]`)})}catch(t){console.log("\u274C Simulation error:",t.message)}console.log(`
|
|
11
|
-
\u{1F3AF} Example: Covenant template generation`);let e
|
|
12
|
-
\u{1F4CA} Example 1: Value Lock Covenant`);let t=
|
|
11
|
+
\u{1F3AF} Example: Covenant template generation`);let e=Ye.generateCovenantTemplate("value","50c3000000000000");console.log("Generated ASM:",e.asm),console.log("Description:",e.description)}});var Vt=O((Qc,Gt)=>{"use strict";f();var{opcodeMap:Mt,scriptNum:Gi,utils:fa}=Dt(),ue=class{constructor(){this.operations=[],this.comments=[]}comment(t){return this.comments.push(`// ${t}`),this}push(t){if(typeof t=="number")if(t>=-1&&t<=16)t===-1?this.operations.push("OP_1NEGATE"):t===0?this.operations.push("OP_0"):this.operations.push(`OP_${t}`);else{let r=Gi.encode(t);this.operations.push(r.toString("hex"))}else if(typeof t=="string")this.operations.push(t);else if(u.Buffer.isBuffer(t))this.operations.push(t.toString("hex"));else throw new Error(`Invalid value type: ${typeof t}`);return this}dup(){return this.operations.push("OP_DUP"),this}drop(){return this.operations.push("OP_DROP"),this}nip(){return this.operations.push("OP_NIP"),this}swap(){return this.operations.push("OP_SWAP"),this}over(){return this.operations.push("OP_OVER"),this}rot(){return this.operations.push("OP_ROT"),this}pick(t){return this.push(t),this.operations.push("OP_PICK"),this}roll(t){return this.push(t),this.operations.push("OP_ROLL"),this}depth(){return this.operations.push("OP_DEPTH"),this}add(){return this.operations.push("OP_ADD"),this}sub(){return this.operations.push("OP_SUB"),this}mul(){return this.operations.push("OP_MUL"),this}div(){return this.operations.push("OP_DIV"),this}mod(){return this.operations.push("OP_MOD"),this}negate(){return this.operations.push("OP_NEGATE"),this}abs(){return this.operations.push("OP_ABS"),this}min(){return this.operations.push("OP_MIN"),this}max(){return this.operations.push("OP_MAX"),this}equal(){return this.operations.push("OP_EQUAL"),this}equalVerify(){return this.operations.push("OP_EQUALVERIFY"),this}numEqual(){return this.operations.push("OP_NUMEQUAL"),this}numNotEqual(){return this.operations.push("OP_NUMNOTEQUAL"),this}lessThan(){return this.operations.push("OP_LESSTHAN"),this}greaterThan(){return this.operations.push("OP_GREATERTHAN"),this}lessThanOrEqual(){return this.operations.push("OP_LESSTHANOREQUAL"),this}greaterThanOrEqual(){return this.operations.push("OP_GREATERTHANOREQUAL"),this}within(){return this.operations.push("OP_WITHIN"),this}not(){return this.operations.push("OP_NOT"),this}boolAnd(){return this.operations.push("OP_BOOLAND"),this}boolOr(){return this.operations.push("OP_BOOLOR"),this}and(){return this.operations.push("OP_AND"),this}or(){return this.operations.push("OP_OR"),this}xor(){return this.operations.push("OP_XOR"),this}invert(){return this.operations.push("OP_INVERT"),this}cat(){return this.operations.push("OP_CAT"),this}split(){return this.operations.push("OP_SPLIT"),this}size(){return this.operations.push("OP_SIZE"),this}left(t){return this.push(t),this.operations.push("OP_LEFT"),this}right(t){return this.push(t),this.operations.push("OP_RIGHT"),this}substr(t,r){return this.push(r).push(t),this.operations.push("OP_SUBSTR"),this}sha256(){return this.operations.push("OP_SHA256"),this}hash256(){return this.operations.push("OP_HASH256"),this}hash160(){return this.operations.push("OP_HASH160"),this}ripemd160(){return this.operations.push("OP_RIPEMD160"),this}verify(){return this.operations.push("OP_VERIFY"),this}return(){return this.operations.push("OP_RETURN"),this}extractField(t){this.comment(`Extract ${t} field from preimage`);let i={nVersion:{strategy:"LEFT",offset:0,length:4},hashPrevouts:{strategy:"LEFT",offset:4,length:32},hashSequence:{strategy:"LEFT",offset:36,length:32},outpoint:{strategy:"LEFT",offset:68,length:36},scriptLen:{strategy:"DYNAMIC",position:"after_outpoint"},scriptCode:{strategy:"DYNAMIC",variable_length:!0},value:{strategy:"RIGHT",offsetFromEnd:52,length:8},nSequence:{strategy:"RIGHT",offsetFromEnd:44,length:4},hashOutputs:{strategy:"RIGHT",offsetFromEnd:40,length:32},nLocktime:{strategy:"RIGHT",offsetFromEnd:8,length:4},sighashType:{strategy:"RIGHT",offsetFromEnd:4,length:4}}[t];if(!i)throw new Error(`Unknown field: ${t}`);if(i.strategy==="LEFT")this.push(i.offset+i.length).split().drop().push(i.offset).split().swap().drop();else if(i.strategy==="RIGHT")this.size().push(i.offsetFromEnd).sub().split().nip().push(i.length).split().drop();else if(i.strategy==="DYNAMIC")if(t==="scriptLen")this.push(104).split().nip().push(1).split().drop();else throw new Error(`Dynamic extraction for ${t} not implemented`);return this}validateField(t,r){return this.comment(`Validate ${t} equals expected value`),this.extractField(t),this.push(r),this.equalVerify(),this}validateRange(t,r,i){return this.comment(`Validate ${t} is within range [${r}, ${i})`),this.extractField(t),this.dup(),this.push(r),this.greaterThanOrEqual(),this.verify(),this.push(i),this.lessThan(),this.verify(),this}validateFields(t){return this.comment("Multi-field validation"),Object.entries(t).forEach(([r,i])=>{i.equals?this.validateField(r,i.equals):(i.min!==void 0||i.max!==void 0)&&this.validateRange(r,i.min||0,i.max||Number.MAX_SAFE_INTEGER)}),this}if(t){return this.comment("Begin IF block"),typeof t=="function"&&t(this),this.operations.push("OP_IF"),this}else(){return this.comment("ELSE block"),this.operations.push("OP_ELSE"),this}endif(){return this.comment("End IF block"),this.operations.push("OP_ENDIF"),this}build(){let t=this.operations.join(" "),r=this._cleanASM(t);return{operations:[...this.operations],comments:[...this.comments],asm:t,cleanedASM:r,hex:this._asmToHex(r),size:r.split(" ").length}}_cleanASM(t){return t.split(" ").map(r=>{if(/^\d+$/.test(r)){let i=parseInt(r);return i>=1&&i<=75?i.toString(16).padStart(2,"0"):Gi.encode(i).toString("hex")}return r}).join(" ")}_asmToHex(t){return t.split(" ").map(r=>Mt[r]?Mt[r].code.toString(16).padStart(2,"0"):/^[0-9a-fA-F]+$/.test(r)?r:"00").join("")}simulate(t=[]){return fa.simulate(this.operations,t)}document(){let t=this.build();return{title:"Covenant Script Documentation",operations:t.operations.length,size:t.size,asm:t.cleanedASM,comments:this.comments,structure:this._analyzeStructure()}}_analyzeStructure(){let t={stack_operations:0,arithmetic:0,comparisons:0,crypto:0,data_manipulation:0,flow_control:0};return this.operations.forEach(r=>{let i=Mt[r];if(i)switch(i.category){case"stack":t.stack_operations++;break;case"arithmetic":t.arithmetic++;break;case"bitwise":t.comparisons++;break;case"crypto":t.crypto++;break;case"data":t.data_manipulation++;break;case"flow_control":t.flow_control++;break}}),t}},Vi={valueLock:e=>new ue().comment("Value Lock Covenant").comment(`Expected value: ${e}`).validateField("value",e).push(1),hashLock:e=>new ue().comment("Hash Lock Covenant").comment(`Expected hash: ${e}`).sha256().push(e).equalVerify().push(1),multiSigWithValidation:(e,t,r)=>{let i=new ue().comment("Multi-Signature Covenant with Field Validation").comment(`Required signatures: ${e}`);return i.validateFields(r),i.comment("Signature validation (placeholder)").push(1),i},timeLock:e=>new ue().comment("Time Lock Covenant").comment(`Locktime: ${e}`).validateField("nLocktime",e).push(1),complexValidation:e=>{let t=new ue().comment("Complex Validation Covenant");return e.valueRange&&t.validateRange("value",e.valueRange.min,e.valueRange.max),e.fields&&t.validateFields(e.fields),e.hashValidation&&t.sha256().push(e.hashValidation.expectedHash).equalVerify(),t.push(1),t}};Gt.exports={CovenantBuilder:ue,CovenantTemplates:Vi};if(L.main===Gt){console.log("\u{1F3D7}\uFE0F Covenant Builder Demonstration"),console.log("=================================="),console.log(`
|
|
12
|
+
\u{1F4CA} Example 1: Value Lock Covenant`);let t=Vi.valueLock("50c3000000000000").build();console.log("ASM:",t.cleanedASM),console.log("Size:",t.size,"operations"),console.log(`
|
|
13
13
|
\u{1F4CA} Example 2: Custom Arithmetic Covenant`);let r=new ue().comment("Validate that value field equals 5 + 3").extractField("value").push(5).push(3).add().numEqual().verify().push(1),i=r.build();console.log("Operations:",i.operations.length),console.log("ASM:",i.cleanedASM),console.log(`
|
|
14
|
-
\u{1F4CA} Example 3: Documentation Generation`);let n=r.document();console.log("Structure analysis:",n.structure),console.log("Comments:"),n.comments.forEach(o=>console.log(" "+o))}});var
|
|
15
|
-
`),console.log("\u{1F510} Locking Script:",e),console.log("\u{1F513} Unlocking Script:",t),console.log("-------------------------------------------");try{let r=
|
|
16
|
-
\u{1F9E9} Step ${P+1}: ${
|
|
17
|
-
===========================================`),console.log("\u2705 Final Result:",y?"TRUE (Success)":"\u274C FALSE (Failure)"),console.log("Final Stack:",
|
|
18
|
-
`),console.log("Script:",e.toASM()),console.log("-------------------------------------------");for(let
|
|
19
|
-
[${
|
|
20
|
-
[${
|
|
21
|
-
===========================================`),console.log("\u2705 Final Stack State:"),
|
|
22
|
-
`);let i=new at,n=new Hs(1e5),o=i.verify(e,t,r,0,at.SCRIPT_ENABLE_SIGHASH_FORKID,n);console.log("\u{1F510} Locking Script:",t.toASM()),console.log("\u{1F513} Unlocking Script:",e.toASM()),console.log("-------------------------------------------"),console.log("\u2705 Result:",o?"TRUE (Success)":"\u274C FALSE (Failure)"),console.log("Final Stack:",i.stack.map(s=>s.toString("hex"))),console.log("AltStack:",i.altstack.map(s=>s.toString("hex"))),console.log("===========================================")}async function Ji(){if(typeof m.default>"u"||!m.default.argv){console.log("\u2699\uFE0F CLI mode not available in browser environment");return}let e=m.default.argv.slice(2),t=P=>{let O=e.indexOf(P);return O!==-1&&e[O+1]?e[O+1]:null},r=t("--unlocking"),i=t("--locking"),n=t("--combined"),o=e.includes("--step"),s=e.includes("--truth"),a,c,d;if(n)d=ot(n);else{a=ot(r),c=ot(i);let P=u.Buffer.concat([a.toBuffer(),c.toBuffer()]);d=he.fromBuffer(P)}let g=new Fs,y=new Cs({prevTxId:"0".repeat(64),outputIndex:0,script:he.empty(),satoshis:1e5,output:new Wi({satoshis:1e5,script:he.empty()})});g.addInput(y),g.addOutput(new Wi({satoshis:1e5,script:he.empty()})),o?await Qi(d,g,!0):s?Zi(a||he.empty(),c||he.empty(),g):console.log("\u2699\uFE0F No mode specified. Use --step or --truth")}Xt.exports={parseScript:ot,printStack:Yt,stepThroughScript:Qi,runFullEvaluation:Zi,main:Ji};typeof C<"u"&&C.main===Xt&&Ji()});var pe=x((su,un)=>{"use strict";f();var rn=A(),nn=ge(),jt=G(),Wt=q(),Ls=He(),on=Ke(),sn=_e(),ct=D(),Rs=fe(),tn=Ee(),Qt=tn.SIGHASH_ALL|tn.SIGHASH_FORKID;function an(){return nn.mainnetFlags()}function Bs(e,t,r){r=r||{};var i=new nn,n=i.verify(e,t,r.tx||new Wt,r.inputIndex||0,r.flags||an(),new ct(r.satoshis||0));return{ok:n,err:i.errstr||""}}function cn(e,t,r,i,n){return sn.sighashPreimage(e,n||Qt,t,r,new ct(i))}function Ns(e,t,r,i,n){return Rs.sha256sha256(cn(e,t,r,i,n))}function Us(e,t,r,i,n,o){o=o||Qt;var s=sn.sign(e,t,o,r,i,new ct(n));return u.Buffer.concat([s.toDER(),u.Buffer.from([o])])}function qs(e,t,r){r=r||{};var i=new Wt().addOutput(new on({script:e,satoshis:t})),n=new Wt;return n.addInput(new Ls({prevTxId:i.hash,outputIndex:0,script:rn.empty()}),e,t),r.outputs&&r.outputs.forEach(function(o){n.addOutput(o)}),{funding:i,spend:n}}function Ds(e,t){var r=e.toAddress?e.toAddress():e;return new on({script:rn.buildPublicKeyHashOut(r),satoshis:t})}function Ms(e){return e===0?jt.OP_0:e===-1?jt.OP_1NEGATE:e>=1&&e<=16?jt["OP_"+e]:new ct(e).toScriptNumBuffer()}un.exports={SIGHASH:Qt,flags:an,verify:Bs,rawPreimage:cn,sighashDigest:Ns,signInput:Us,fundAndSpend:qs,p2pkhOutput:Ds,scriptNum:Ms}});var ln=x((cu,pn)=>{"use strict";f();var Gs=fe(),Vs=pe(),qe=A(),Ue=G(),hn=Vs.signInput;function zs(e){var t=Gs.sha256(e),r=new qe().add(Ue.OP_SHA256).add(t).add(Ue.OP_EQUAL);return{lock:r,meta:{name:"hash-lock",digest:t.toString("hex")},unlock:function(i,n,o){return new qe().add(o||e)}}}function Ks(e){var t=e.toPublicKey(),r=qe.buildPublicKeyHashOut(t.toAddress());return{lock:r,meta:{name:"p2pkh",address:t.toAddress().toString()},unlock:function(i,n){return new qe().add(hn(i,e,0,r,n)).add(t.toBuffer())}}}function $s(e,t){var r=t.map(function(n){return n.toPublicKey()}),i=new qe().add(Ue["OP_"+e]);return r.forEach(function(n){i.add(n.toBuffer())}),i.add(Ue["OP_"+r.length]).add(Ue.OP_CHECKMULTISIG),{lock:i,meta:{name:e+"-of-"+r.length+"-multisig"},unlock:function(n,o,s){s=s||t.slice(0,e);var a=new qe().add(Ue.OP_0);return s.forEach(function(c){a.add(hn(n,c,0,i,o))}),a}}}pn.exports={hashLock:zs,p2pkh:Ks,multisig:$s}});var Xe=x((hu,xn)=>{"use strict";f();var dn=A(),_=G(),ee=Ee(),ut=D(),fn=fe(),Jt=pe(),er=Jt.SIGHASH,ht=Jt.scriptNum,De=u.Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),tr=new ut("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",16),Ys=u.Buffer.concat([u.Buffer.from([2]),De]),gn=u.Buffer.from(De).reverse(),mn=u.Buffer.concat([u.Buffer.from(tr.toBuffer()).reverse(),u.Buffer.from([0])]),Xs=u.Buffer.concat([u.Buffer.from([48,68,2,32]),De,u.Buffer.from([2,32])]);function Zt(e,t){var r;for(r=0;r<t-1;r++)e.add(_.OP_1).add(_.OP_SPLIT);for(r=0;r<t-1;r++)e.add(_.OP_SWAP).add(_.OP_CAT);return e}var js=ee.SIGHASH_ALL|ee.SIGHASH_FORKID,Ws=ee.SIGHASH_SINGLE|ee.SIGHASH_FORKID,Qs=ee.SIGHASH_SINGLE|ee.SIGHASH_ANYONECANPAY|ee.SIGHASH_FORKID,Zs=ee.SIGHASH_ALL|ee.SIGHASH_ANYONECANPAY|ee.SIGHASH_FORKID;function rr(e,t){var r=t&&t.sighashType||er;return e.add(_.OP_HASH256),Zt(e,32),e.add(gn).add(_.OP_ADD),e.add(mn).add(_.OP_MOD),e.add(ht(32)).add(_.OP_NUM2BIN),Zt(e,32),e.add(De).add(_.OP_DUP),e.add(_.OP_2).add(_.OP_SWAP).add(_.OP_CAT),e.add(_.OP_TOALTSTACK),e.add(u.Buffer.from([48,68,2,32])).add(_.OP_SWAP).add(_.OP_CAT),e.add(u.Buffer.from([2,32])).add(_.OP_CAT),e.add(_.OP_SWAP).add(_.OP_CAT),e.add(u.Buffer.from([r])).add(_.OP_CAT),e.add(_.OP_FROMALTSTACK).add(_.OP_CHECKSIG),e}function Js(){return rr(new dn)}function yn(e){return e.add(ht(40)).add(_.OP_RIGHT).add(ht(32)).add(_.OP_LEFT),e}function ea(e){return Sn(e,er)}function Sn(e,t){var r=u.Buffer.from([t&255,0,0,0]);return e.add(_.OP_DUP).add(ht(4)).add(_.OP_RIGHT).add(r).add(_.OP_EQUALVERIFY),e}function ta(e){var t=u.Buffer.concat(e.map(function(r){return r.toBufferWriter().toBuffer()}));return fn.sha256sha256(t)}function ra(e){var t=new dn().add(_.OP_DUP);return rr(t),t.add(_.OP_VERIFY),yn(t),t.add(u.Buffer.from(e)).add(_.OP_EQUAL),t}var ia=new ut("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex");function vn(e){var t=fn.sha256sha256(e);if(t[0]<1||t[0]>127)return null;var r=new ut(t).add(new ut(De)).mod(tr);if(r.gt(ia))return null;var i=r.toBuffer("be",32);return i[0]>=1?i:null}function na(e,t,r,i,n){typeof n=="number"&&(n={maxTries:n}),n=n||{};var o=n.maxTries||5e3,s=n.start||0,a=n.field||"nLockTime",c=n.sighashType||er;if(a!=="nLockTime"&&a!=="sequence")throw new Error("grind field must be 'nLockTime' or 'sequence'");for(var d=e.inputs[t],g=0;g<o;g++){var y=s+g;a==="nLockTime"?e.nLockTime=y:d.sequenceNumber=4294967294-y;var P=Jt.rawPreimage(e,t,r,i,c);if(vn(P))return{preimage:P,tries:g+1,field:a,nonce:y}}throw new Error("OP_PUSH_TX grind failed after "+o+" tries")}xn.exports={Gx:De,N:tr,PUBKEY:Ys,gxLe:gn,N_LE:mn,DER_PREFIX:Xs,reverseBytes:Zt,pushTxCore:rr,authenticator:Js,extractHashOutputs:yn,assertSighashAll:ea,assertSighashType:Sn,SIGHASH_ALL_FORKID:js,SIGHASH_SINGLE_FORKID:Ws,SIGHASH_SINGLE_ANYONECANPAY_FORKID:Qs,SIGHASH_ALL_ANYONECANPAY_FORKID:Zs,hashOutputs:ta,valueCovenant:ra,sFromPreimage:vn,grind:na}});var nr=x((lu,On)=>{"use strict";f();var ir=Xe(),oa=pe(),sa=A(),T=G(),Me=oa.scriptNum;function aa(e){var t=new sa;return t.add(T.OP_DUP),ir.pushTxCore(t),t.add(T.OP_VERIFY),ir.assertSighashAll(t),t.add(T.OP_DUP),t.add(Me(104)).add(T.OP_SPLIT).add(T.OP_NIP),t.add(T.OP_SIZE).add(Me(52)).add(T.OP_SUB).add(T.OP_SPLIT).add(T.OP_DROP),t.add(T.OP_OVER),t.add(Me(52)).add(T.OP_RIGHT).add(Me(8)).add(T.OP_LEFT),t.add(T.OP_BIN2NUM).add(Me(e)).add(T.OP_SUB),t.add(Me(8)).add(T.OP_NUM2BIN),t.add(T.OP_SWAP).add(T.OP_CAT),t.add(T.OP_HASH256),t.add(T.OP_SWAP),ir.extractHashOutputs(t),t.add(T.OP_EQUAL),t}On.exports={pelsCovenant:aa}});var _n=x((fu,Pn)=>{f();Pn.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.PublicKey});var ar=x((mu,wn)=>{"use strict";f();var ca=ze(),ua=_n(),ha=A(),En=fe(),sr=pe(),E=G(),Ge=sr.scriptNum;function pt(e){return e instanceof ca?e.toPublicKey().toBuffer():e instanceof ua?e.toBuffer():e}function pa(){return{name:"single-key",commit:function(e){return En.sha256ripemd160(pt(e))},emit:function(e){return e.add(E.OP_OVER).add(E.OP_HASH160).add(E.OP_EQUALVERIFY),e.add(E.OP_CHECKSIGVERIFY),e},unlockArgs:function(e,t,r,i,n){var o=sr.signInput(e,n,t,r,i);return[o,n.toPublicKey().toBuffer()]}}}function or(e,t){var r=t.length;if(e<1||e>r||r<1||r>16)throw new Error("multisig requires 1 <= m <= n <= 16");var i=new ha().add(E["OP_"+e]);return t.forEach(function(n){i.add(u.Buffer.from(n))}),i.add(E["OP_"+r]).add(E.OP_CHECKMULTISIG),i.toBuffer()}function la(e,t){if(typeof t!="number"||!Number.isInteger(t))throw new Error("multisig(m, nKeys): nKeys is the NUMBER of keys, not the keys themselves"+(Array.isArray(t)?" \u2014 pass "+t.length+" instead of the array":""));if(typeof e!="number"||!Number.isInteger(e))throw new Error("multisig(m, nKeys): m must be an integer");if(e<1||e>t||t<1||t>16)throw new Error("multisig requires 1 <= m <= n <= 16");return{name:e+"-of-"+t+"-multisig",m:e,n:t,commit:function(r){if(r.length!==t)throw new Error("expected "+t+" public keys");return En.sha256ripemd160(or(e,r.map(pt)))},emit:function(r){r.add(E.OP_OVER).add(E.OP_HASH160).add(E.OP_EQUALVERIFY),r.add(Ge(1)).add(E.OP_SPLIT).add(E.OP_NIP),r.add(E.OP_SIZE).add(Ge(2)).add(E.OP_SUB).add(E.OP_SPLIT).add(E.OP_DROP);for(var i=0;i<this.n;i++)r.add(Ge(34)).add(E.OP_SPLIT),r.add(E.OP_SWAP).add(Ge(1)).add(E.OP_SPLIT).add(E.OP_NIP),r.add(E.OP_TOALTSTACK);for(r.add(E.OP_DROP),r.add(Ge(this.m)),i=0;i<this.n;i++)r.add(E.OP_FROMALTSTACK);return r.add(Ge(this.n)),r.add(E.OP_CHECKMULTISIGVERIFY),r},unlockArgs:function(r,i,n,o,s){var a=s.keys;if(a.length!==t)throw new Error("expected "+t+" public keys in signer.keys");var c=or(e,a.map(pt)),d=a.map(pt).map(function(P){return P.toString("hex")}),g=s.signWith.map(function(P){var O=d.indexOf(P.toPublicKey().toBuffer().toString("hex"));if(O<0)throw new Error("signWith key is not in the committed key set");return{idx:O,priv:P}}).sort(function(P,O){return O.idx-P.idx}).slice(0,e);if(g.length<e)throw new Error("need at least "+e+" signing keys");var y=g.map(function(P){return sr.signInput(r,P.priv,i,n,o)});return[E.OP_0].concat(y).concat([c])}}}function da(e){if(!e||typeof e.emit!="function"||typeof e.unlockArgs!="function"||typeof e.commit!="function")throw new Error("predicate authorizer needs { commit, emit, unlockArgs } functions");return{name:e.name||"predicate",commit:e.commit,emit:e.emit,unlockArgs:e.unlockArgs}}wn.exports={singleKey:pa,multisig:la,predicate:da,redeemScript:or}});var ur=x((Su,Cn)=>{"use strict";f();var fa=D(),je=Xe(),cr=pe(),We=ar(),lt=A(),v=G(),te=cr.scriptNum;function Tn(e,t){var r=u.Buffer.isBuffer(e)?e:t.commit(e);if(r.length!==20)throw new Error("owner commitment must be 20 bytes (HASH160)");return r}function In(e,t){return t.length?e.add(u.Buffer.from(t)):e.add(v.OP_0)}function An(e,t){return e.add(v.OP_DUP),je.pushTxCore(e),e.add(v.OP_VERIFY),je.assertSighashAll(e),e.add(v.OP_DUP).add(te(52)).add(v.OP_RIGHT).add(te(8)).add(v.OP_LEFT).add(v.OP_TOALTSTACK),e.add(v.OP_DUP),je.extractHashOutputs(e),e.add(v.OP_TOALTSTACK),e.add(te(104)).add(v.OP_SPLIT).add(v.OP_NIP).add(v.OP_SIZE).add(te(52)).add(v.OP_SUB).add(v.OP_SPLIT).add(v.OP_DROP),e.add(v.OP_DUP).add(te(4)).add(te(20)).add(v.OP_SUBSTR),e.add(v.OP_SWAP).add(v.OP_TOALTSTACK),t.emit(e),e.add(v.OP_FROMALTSTACK),e}function bn(e){return e.add(te(4)).add(v.OP_SPLIT).add(te(20)).add(v.OP_SPLIT).add(v.OP_NIP),e.add(v.OP_TOALTSTACK),e.add(v.OP_SWAP).add(v.OP_CAT),e.add(v.OP_FROMALTSTACK).add(v.OP_CAT),e}function kn(e){var t=e.toBuffer().length;if(t<=252||t>65535)throw new Error("token script length must use a 3-byte varint (253..65535); got "+t);return e}function ga(e,t,r){r=r||We.singleKey();var i=new lt;return i.add(Tn(t,r)),i.add(v.OP_DROP),An(i,r),bn(i),i.add(v.OP_FROMALTSTACK),i.add(v.OP_SWAP),i.add(v.OP_FROMALTSTACK),i.add(v.OP_BIN2NUM).add(te(e)).add(v.OP_SUB).add(te(8)).add(v.OP_NUM2BIN),i.add(v.OP_SWAP).add(v.OP_CAT),i.add(v.OP_HASH256),i.add(v.OP_EQUAL),kn(i)}function Hn(e,t){t=t||We.singleKey();var r=new lt;return r.add(Tn(e,t)),r.add(v.OP_DROP),An(r,t),bn(r),r.add(v.OP_CAT),r.add(v.OP_SWAP).add(v.OP_CAT),r.add(v.OP_CAT),r.add(v.OP_FROMALTSTACK),r.add(v.OP_FROMALTSTACK).add(v.OP_DROP),r.add(v.OP_SWAP).add(v.OP_HASH256).add(v.OP_EQUAL),kn(r)}function ma(e){return We.singleKey().commit(e)}function ya(e,t,r,i,n,o){o=o||{};var s=o.auth||We.singleKey(),a=o.inputIndex||0;if(t.length!==20)throw new Error("newOwnerHash must be 20 bytes (HASH160)");if(i<=1&&!o.allowLowValue)throw new Error("unlockTransfer: single-output token sets output = input - fee, which burns a "+i+"-sat UTXO (e.g. a 1-sat ordinal). Use Token.transferOrdinal / ownershipTokenMulti to preserve the satoshi.");je.grind(r,a,n,i,o.grind);var c=cr.rawPreimage(r,a,n,i),d=s.unlockArgs(r,a,n,i,e),g=new lt().add(u.Buffer.from(t));return d.forEach(function(y){g.add(y)}),g.add(u.Buffer.from(c)),g}function Fn(e,t,r,i,n,o,s){s=s||{};var a=s.auth||We.singleKey(),c=s.inputIndex||0;if(t.length!==20)throw new Error("newOwnerHash must be 20 bytes (HASH160)");if(!o||o.tokenValue==null||o.tokenValue.length!==8)throw new Error("layout.tokenValue must be the 8-byte LE value of the token output");je.grind(r,c,n,i,s.grind);var d=cr.rawPreimage(r,c,n,i),g=a.unlockArgs(r,c,n,i,e),y=new lt;return In(y,o.before||u.Buffer.alloc(0)),In(y,o.after||u.Buffer.alloc(0)),y.add(u.Buffer.from(o.tokenValue)),y.add(u.Buffer.from(t)),g.forEach(function(P){y.add(P)}),y.add(u.Buffer.from(d)),y}function Sa(e,t){return Hn(e,t)}function va(e,t,r,i,n,o){o=o||{},i==null&&(i=1);var s=o.tokenIndex||0,a=r.outputs||[],c=a[s];if(!c)throw new Error("transferOrdinal: spend has no output at tokenIndex "+s);if(c.satoshis!==i)throw new Error("transferOrdinal: token output value ("+c.satoshis+" sat) must equal the ordinal value ("+i+" sat) to avoid burning the inscription");function d(O){return O.toBufferWriter().toBuffer()}var g=u.Buffer.concat(a.slice(0,s).map(d)),y=u.Buffer.concat(a.slice(s+1).map(d)),P=new fa(i).toBuffer({endian:"little",size:8});return Fn(e,t,r,i,n,{before:g,after:y,tokenValue:P},o)}Cn.exports={ownershipToken:ga,ownershipTokenMulti:Hn,ordinalLock:Sa,ownerId:ma,unlockTransfer:ya,unlockTransferMulti:Fn,transferOrdinal:va}});var gr=x((xu,Ln)=>{"use strict";f();var dt=Xe(),xa=nr(),Oa=ur(),dr=pe(),pr=A(),$=G(),lr=q(),hr=dr.scriptNum;function Pa(e,t){return e instanceof lr.Output?e:e instanceof pr?new lr.Output({script:e,satoshis:t}):dr.p2pkhOutput(e,t)}function _a(e,t,r,i,n,o){o=o||5e4;for(var s=0;s<o;s++){e.nLockTime=n+s;var a=dr.rawPreimage(e,t,r,i);if(dt.sFromPreimage(a))return a}throw new Error("covenant grind failed after "+o+" tries")}function le(){if(!(this instanceof le))return new le;this._outputs=[],this._minLockTime=null}le.prototype.payTo=function(e,t){return this._outputs.push(Pa(e,t)),this};le.prototype.lockUntil=function(e){return this._minLockTime=e,this};le.prototype.outputs=function(){return this._outputs.map(function(e){return new lr.Output(e.toObject())})};le.prototype.describe=function(){var e=[];return this._outputs.forEach(function(t,r){e.push("output["+r+"] = "+t.satoshis+" sat to "+t.script.toASM().slice(0,24)+"...")}),this._minLockTime!==null&&e.push("nLockTime >= "+this._minLockTime),"spend allowed iff: "+e.join(" AND ")};le.prototype.compile=function(){if(this._outputs.length===0&&this._minLockTime===null)throw new Error("empty policy: add at least one constraint (payTo / lockUntil)");var e=this,t=new pr().add($.OP_DUP);if(dt.pushTxCore(t),t.add($.OP_VERIFY),this._outputs.length){var r=dt.hashOutputs(this._outputs);t.add($.OP_DUP),dt.extractHashOutputs(t),t.add(u.Buffer.from(r)).add($.OP_EQUALVERIFY)}return this._minLockTime!==null&&(t.add($.OP_DUP),t.add(hr(8)).add($.OP_RIGHT).add(hr(4)).add($.OP_LEFT),t.add($.OP_BIN2NUM).add(hr(this._minLockTime)).add($.OP_GREATERTHANOREQUAL).add($.OP_VERIFY)),t.add($.OP_DROP).add($.OP_1),{lock:t,outputs:e.outputs(),describe:function(){return e.describe()},unlock:function(i,n,o){o=o||0;var s=e._minLockTime===null?0:e._minLockTime;return e._minLockTime!==null&&(i.inputs[o].sequenceNumber=4294967294),new pr().add(_a(i,o,t,n,s))}}};function fr(){return new le}fr.perpetual=function(e){return xa.pelsCovenant(e)};fr.token=function(e,t){return Oa.ownershipToken(e,t)};Ln.exports={policy:fr,Policy:le}});var qn=x((Pu,Un)=>{"use strict";f();var Ea=ge(),wa=D(),Ia=q(),Ta=G(),Aa=pe();function Bn(e){if(e===0)return"OP_0";if(e>=1&&e<=75)return"PUSH("+e+")";if(e===76)return"OP_PUSHDATA1";if(e===77)return"OP_PUSHDATA2";if(e===78)return"OP_PUSHDATA4";try{return Ta.fromNumber(e).toString()}catch{return"0x"+e.toString(16)}}function Rn(e,t){t=t||16;var r=u.Buffer.from(e).toString("hex");return r.length<=t*2?r||"0":r.slice(0,t*2)+"...("+e.length+"B)"}function ba(e,t,r){r=r||{};var i=new Ea,n=[];i.stepListener=function(s,a,c){n.push({phase:i.script===t?"lock":"unlock",op:Bn(s.opcode&&typeof s.opcode.toNumber=="function"?s.opcode.toNumber():s.opcode.num),stack:a.map(function(d){return Rn(d)}),altstack:c.map(function(d){return Rn(d)})})};var o=i.verify(e,t,r.tx||new Ia,r.inputIndex||0,typeof r.flags=="number"?r.flags:Aa.flags(),new wa(r.satoshis||0));return{ok:o,err:i.errstr||"",steps:n}}function Nn(e){var t=[],r=null;return e.steps.forEach(function(i,n){i.phase!==r&&(t.push("-- "+i.phase+" script --"),r=i.phase);var o=i.stack.length?i.stack.join(" | "):"(empty)",s=i.altstack.length?" alt:["+i.altstack.join(" | ")+"]":"";t.push(String(n).padStart(3)+" "+i.op.padEnd(16)+" -> ["+o+"]"+s)}),t.push((e.ok?"VALID":"INVALID")+(e.err?" ("+e.err+")":"")),t.join(`
|
|
23
|
-
`)}function
|
|
14
|
+
\u{1F4CA} Example 3: Documentation Generation`);let n=r.document();console.log("Structure analysis:",n.structure),console.log("Comments:"),n.comments.forEach(o=>console.log(" "+o))}});var Xi=O((eu,Yi)=>{"use strict";f();var ga=V(),$=b();function we(e){if(u.Buffer.isBuffer(e))return $.fromBuffer(e).toASM();if(e&&typeof e.toASM=="function")return e.toASM();throw new Error("Input must be a Buffer or Script object")}function ma(e){try{return $.fromASM(e)}catch(t){throw new Error(`Invalid ASM string: ${t.message}`)}}function ya(e){try{return $.fromASM(e).toBuffer().toString("hex")}catch(t){throw new Error(`Cannot convert ASM to hex: ${t.message}`)}}function Sa(e){try{let t=u.Buffer.from(e,"hex");return $.fromBuffer(t).toASM()}catch(t){throw new Error(`Cannot convert hex to ASM: ${t.message}`)}}function va(e){if(u.Buffer.isBuffer(e))return e.toString("hex");if(e&&typeof e.toBuffer=="function")return e.toBuffer().toString("hex");throw new Error("Input must be a Buffer or Script object")}function Ki(e){try{return $.fromASM(e),{valid:!0,error:null}}catch(t){return{valid:!1,error:t.message}}}function zt(e){try{let t;if(typeof e=="string")t=$.fromASM(e);else if(u.Buffer.isBuffer(e))t=$.fromBuffer(e);else if(e&&typeof e.toBuffer=="function")t=e;else return{valid:!1,error:"Invalid script input type"};let r=t.toBuffer(),i=t.toASM();return{valid:!0,error:null,size:r.length,asm:i,operations:i.split(" ").length}}catch(t){return{valid:!1,error:t.message}}}function Oa(e){let t=Ki(e);if(!t.valid)return t;let r=e.split(" "),i=[];for(let n=0;n<r.length;n++){let o=r[n];o.startsWith("OP_")&&!ga.map[o]&&i.push(`Unknown opcode: ${o} at position ${n}`),!o.startsWith("OP_")&&o.length>0&&(/^[0-9a-fA-F]*$/.test(o)||i.push(`Invalid hex data: ${o} at position ${n}`))}return{valid:i.length===0,error:i.length>0?i.join("; "):null,issues:i,operations:r.length}}function Kt(e){try{let t;if(typeof e=="string")t=$.fromASM(e);else if(Array.isArray(e))t=$.fromASM(e.join(" "));else{if(u.Buffer.isBuffer(e))return e.length;if(e&&typeof e.toBuffer=="function")t=e;else throw new Error("Invalid script input")}return t.toBuffer().length}catch(t){return{error:t.message}}}function $t(e){try{let t=zt(e);if(!t.valid)return{error:t.error};let r=t.asm,i=r.split(" ").filter(c=>c.length>0),n=t.size,o=i.filter(c=>c.startsWith("OP_")).length,a=i.filter(c=>!c.startsWith("OP_")&&c.length>0).length,s=0;return i.forEach(c=>{c.startsWith("OP_")&&(["OP_CHECKSIG","OP_CHECKSIGVERIFY"].includes(c)?s+=100:["OP_SHA256","OP_HASH160","OP_HASH256"].includes(c)?s+=10:s+=1)}),{length:n,size:n,operations:i.length,opcodeCount:o,opcodes:o,dataElements:a,estimatedCost:s,complexity:s>50?"high":s>10?"medium":"low",asm:r}}catch(t){return{error:t.message}}}function zi(e){let t=$t(e);if(t.error)return t;let r={size:t.size,operations:t.operations,complexity:t.complexity,recommendations:[]};return t.size>520&&r.recommendations.push("Script exceeds standard size limit (520 bytes)"),t.estimatedCost>100&&r.recommendations.push("High execution cost - consider optimization"),t.operations>200&&r.recommendations.push("Many operations - may hit operation limits"),r}function xa(e){try{let t;typeof e=="string"?t=e:Array.isArray(e)?t=e.join(" "):t=we(e);let r=t.split(" "),i=[];for(let c=0;c<r.length;c++){let d=r[c],g=r[c+1];if(!(!d||d.trim()==="")){if(d==="OP_DUP"&&g==="OP_DROP"){c++;continue}!d.startsWith("OP_")&&g&&g.startsWith("OP_"),i.push(d)}}let n=i.join(" "),o=Kt(t),a=Kt(n),s=null;try{s=$.fromASM(n)}catch{s=null}return{original:t,optimized:n,originalSize:o,optimizedSize:a,savings:o-a,improvement:o>0?((o-a)/o*100).toFixed(1)+"%":"0%",script:s}}catch(t){return{error:t.message}}}function Pa(e){let t=[];try{let r;typeof e=="string"?r=e:r=we(e);let i=r.split(" ");for(let n=0;n<i.length-1;n++){let o=i[n],a=i[n+1];if(o==="OP_DUP"&&a==="OP_DROP"&&t.push({type:"redundant_operation",position:n,description:"Remove redundant OP_DUP OP_DROP pair",savings:2}),o.match(/^[0-9a-fA-F]+$/)&&o.length===2){let s=parseInt(o,16);s>=1&&s<=16&&t.push({type:"inefficient_push",position:n,description:`Use OP_${s} instead of pushing ${o}`,savings:1})}}return{optimizations:t,totalSavings:t.reduce((n,o)=>n+o.savings,0)}}catch(r){return{error:r.message}}}function _a(e,t){try{let r,i;return typeof e=="string"?r=$.fromASM(e).toBuffer():u.Buffer.isBuffer(e)?r=e:r=e.toBuffer(),typeof t=="string"?i=$.fromASM(t).toBuffer():u.Buffer.isBuffer(t)?i=t:i=t.toBuffer(),{identical:r.equals(i),scriptA:{size:r.length,asm:we(r)},scriptB:{size:i.length,asm:we(i)}}}catch(r){return{error:r.message}}}function $i(e){try{let t;typeof e=="string"?t=e:t=we(e);let r=t.split(" "),i=[];return r.forEach((n,o)=>{let a="";if(n.startsWith("OP_"))switch(n){case"OP_DUP":a="Duplicate the top stack item";break;case"OP_DROP":a="Remove the top stack item";break;case"OP_SWAP":a="Swap the top two stack items";break;case"OP_ADD":a="Add the top two numbers";break;case"OP_SUB":a="Subtract: second - first";break;case"OP_EQUAL":a="Check if top two items are equal";break;case"OP_VERIFY":a="Assert that top item is true (non-zero)";break;case"OP_CHECKSIG":a="Verify signature against public key";break;case"OP_SHA256":a="Calculate SHA256 hash of top item";break;case"OP_HASH160":a="Calculate RIPEMD160(SHA256(x)) hash";break;case"OP_IF":a="Begin conditional execution";break;case"OP_ELSE":a="Alternative branch of conditional";break;case"OP_ENDIF":a="End conditional execution";break;default:a=`Execute ${n}`}else n.length>0&&(a=`Push data: ${n} (${n.length/2} bytes)`);a&&i.push({operation:n,position:o,explanation:a})}),{asm:t,operations:r.length,explanations:i,summary:`Script with ${r.length} operations: ${i.map(n=>n.explanation).join(" \u2192 ")}`}}catch(t){return{error:t.message}}}function Ea(e){try{let t=$i(e);if(t.error)return t;let r=[];return t.explanations.forEach(i=>{switch(i.operation){case"OP_VERIFY":r.push("The condition must be true for the script to succeed.");break;case"OP_CHECKSIG":r.push("A valid signature must be provided.");break;case"OP_EQUAL":r.push("Two values must be identical.");break;case"OP_ADD":r.push("Two numbers are added together.");break;default:i.explanation.includes("Push data")&&r.push("Some data is made available for processing.")}}),{english:r.join(" "),technical:t.summary,operations:t.operations}}catch(t){return{error:t.message}}}function wa(e,t={}){let r=[];e.forEach((n,o)=>{try{let a=zt(n),s=$t(n),c=zi(n);r.push({index:o,script:typeof n=="string"?n:we(n),valid:a.valid,size:a.size,operations:a.operations,complexity:c.complexity,estimatedCost:s.estimatedCost,recommendations:c.recommendations})}catch(a){r.push({index:o,script:typeof n=="string"?n:"Invalid script",valid:!1,error:a.message})}});let i={total:e.length,valid:r.filter(n=>n.valid).length,invalid:r.filter(n=>!n.valid).length,averageSize:r.filter(n=>n.size).reduce((n,o)=>n+o.size,0)/r.filter(n=>n.size).length||0,complexityDistribution:{low:r.filter(n=>n.complexity==="low").length,medium:r.filter(n=>n.complexity==="medium").length,high:r.filter(n=>n.complexity==="high").length}};return{results:r,summary:i}}Yi.exports={scriptToASM:we,asmToScript:ma,asmToHex:ya,hexToASM:Sa,scriptToHex:va,validateASM:Ki,validateScript:zt,validateSyntax:Oa,estimateScriptSize:Kt,scriptMetrics:$t,analyzeComplexity:zi,optimizeScript:xa,findOptimizations:Pa,compareScripts:_a,explainScript:$i,covenantToEnglish:Ea,batchTestScripts:wa}});var Wi=O((iu,Yt)=>{f();var U=typeof window<"u"&&window.bsv?window.bsv:null,nt=U?U.Script:b(),ot=U?U.Script.Interpreter:ge(),Ta=U?U.Opcode:V(),Ia=U?U.Transaction:D(),Aa=U?U.Transaction.Input:He(),ba=U?U.Transaction.Output:$e(),ka=U?U.crypto.BN:M(),ru=C();function Xe(e){return e.map(t=>t.toString("hex"))}function ji(e,t){console.log("==========================================="),console.log("\u{1F50D} STACK EXAMINATION TOOL"),console.log(`===========================================
|
|
15
|
+
`),console.log("\u{1F510} Locking Script:",e),console.log("\u{1F513} Unlocking Script:",t),console.log("-------------------------------------------");try{let r=nt.fromHex(e),i=nt.fromHex(t),n=nt.fromBuffer(u.Buffer.concat([i.toBuffer(),r.toBuffer()])),o=new ot,a=new Ia,s=new Aa({prevTxId:"0".repeat(64),outputIndex:0,script:nt.empty()});a.addInput(s),a.addOutput(new ba({satoshis:1e5,script:r}));let c=n.chunks,d=new ot;d.script=n,d.tx=a,d.nIn=0,d.flags=ot.SCRIPT_ENABLE_SIGHASH_FORKID;for(let P=0;P<c.length;P++){let x=c[P];try{if(typeof d.step=="function")d.step();else{console.log("\u26A0\uFE0F Step-by-step execution not supported in this BSV version");break}console.log(`
|
|
16
|
+
\u{1F9E9} Step ${P+1}: ${Ta.reverseMap[x.opcodenum]||"PUSH"}`),console.log("Stack:",Xe(d.stack)),console.log("AltStack:",Xe(d.altstack))}catch(re){console.log(`\u26A0\uFE0F Error executing opcode ${P+1}:`,re.message);break}}let g=new ka(1e5),y=o.verify(i,r,a,0,ot.SCRIPT_ENABLE_SIGHASH_FORKID,g);return console.log(`
|
|
17
|
+
===========================================`),console.log("\u2705 Final Result:",y?"TRUE (Success)":"\u274C FALSE (Failure)"),console.log("Final Stack:",Xe(d.stack||[])),console.log("AltStack:",Xe(d.altstack||[])),console.log("==========================================="),y}catch(r){return console.error("\u274C Error in script execution:",r.message),!1}}if(typeof L<"u"&&L.main===Yt){m.default.argv.length<4&&(console.log("Usage: node stack_examiner.js <locking_script_hex> <unlocking_script_hex>"),m.default.exit(1));let e=m.default.argv[2],t=m.default.argv[3];ji(e,t)}Yt.exports={runScript:ji,bufferToHexArray:Xe}});var tn=O((au,jt)=>{f();var st=null;try{typeof window>"u"&&typeof L<"u"&&(st=C())}catch{st=null}var q=typeof window<"u"&&window.bsv?window.bsv:null,he=q?q.Script:b(),ct=q?q.Script.Interpreter:ge(),Ha=q?q.Opcode:V(),Fa=q?q.crypto.BN:M(),Ca=q?q.Transaction:D(),La=q?q.Transaction.Input:He(),Qi=q?q.Transaction.Output:$e();function at(e){if(!e)return new he;let t=e.trim(),r=/^[0-9a-fA-F]+$/.test(t.replace(/\s+/g,""));try{return r?he.fromHex(t):he.fromASM(t)}catch(i){console.error("\u274C Error parsing script:",i.message),m.default.exit(1)}}function Xt(e,t=[]){let r=n=>n.length?n.toString("hex"):"(empty)",i=e.map(r);console.log("Stack:",i.length?i:["(empty)"]),t.length&&console.log("AltStack:",t.map(r))}async function Zi(e,t,r=!0){let i=new ct;i.script=e,i.tx=t,i.nIn=0,i.flags=ct.SCRIPT_ENABLE_SIGHASH_FORKID;let n=e.chunks,o=null;st&&typeof m.default<"u"&&m.default.stdin&&(o=st.createInterface({input:m.default.stdin,output:m.default.stdout})),console.log("==========================================="),console.log("\u{1F50D} SCRIPT INTERPRETER DEBUGGER (STEP MODE)"),console.log(`===========================================
|
|
18
|
+
`),console.log("Script:",e.toASM()),console.log("-------------------------------------------");for(let a=0;a<n.length;a++){let s=n[a],c=Ha.reverseMap[s.opcodenum]||"PUSH";r&&o?await new Promise(d=>o.question(`
|
|
19
|
+
[${a+1}/${n.length}] Step (${c}) \u2014 press Enter to execute...`,d)):r&&console.log(`
|
|
20
|
+
[${a+1}/${n.length}] Step (${c})`);try{if(typeof i.step=="function")i.step();else{console.log("\u26A0\uFE0F Step-by-step execution not supported in this BSV version"),console.log("\u{1F4A1} Consider using runFullEvaluation instead");break}console.log(`\u{1F9E9} Executed: ${c}`),Xt(i.stack,i.altstack)}catch(d){console.log(`\u26A0\uFE0F Error executing ${c}: ${d.message}`);break}}o&&o.close(),console.log(`
|
|
21
|
+
===========================================`),console.log("\u2705 Final Stack State:"),Xt(i.stack||[],i.altstack||[]),console.log("===========================================")}function Ji(e,t,r){console.log("==========================================="),console.log("\u{1F50D} SCRIPT INTERPRETER DEBUGGER (FULL RUN)"),console.log(`===========================================
|
|
22
|
+
`);let i=new ct,n=new Fa(1e5),o=i.verify(e,t,r,0,ct.SCRIPT_ENABLE_SIGHASH_FORKID,n);console.log("\u{1F510} Locking Script:",t.toASM()),console.log("\u{1F513} Unlocking Script:",e.toASM()),console.log("-------------------------------------------"),console.log("\u2705 Result:",o?"TRUE (Success)":"\u274C FALSE (Failure)"),console.log("Final Stack:",i.stack.map(a=>a.toString("hex"))),console.log("AltStack:",i.altstack.map(a=>a.toString("hex"))),console.log("===========================================")}async function en(){if(typeof m.default>"u"||!m.default.argv){console.log("\u2699\uFE0F CLI mode not available in browser environment");return}let e=m.default.argv.slice(2),t=P=>{let x=e.indexOf(P);return x!==-1&&e[x+1]?e[x+1]:null},r=t("--unlocking"),i=t("--locking"),n=t("--combined"),o=e.includes("--step"),a=e.includes("--truth"),s,c,d;if(n)d=at(n);else{s=at(r),c=at(i);let P=u.Buffer.concat([s.toBuffer(),c.toBuffer()]);d=he.fromBuffer(P)}let g=new Ca,y=new La({prevTxId:"0".repeat(64),outputIndex:0,script:he.empty(),satoshis:1e5,output:new Qi({satoshis:1e5,script:he.empty()})});g.addInput(y),g.addOutput(new Qi({satoshis:1e5,script:he.empty()})),o?await Zi(d,g,!0):a?Ji(s||he.empty(),c||he.empty(),g):console.log("\u2699\uFE0F No mode specified. Use --step or --truth")}jt.exports={parseScript:at,printStack:Xt,stepThroughScript:Zi,runFullEvaluation:Ji,main:en};typeof L<"u"&&L.main===jt&&en()});var pe=O((uu,hn)=>{"use strict";f();var nn=b(),on=ge(),Wt=V(),Qt=D(),Ra=He(),an=$e(),sn=_e(),ut=M(),Ba=fe(),rn=Ee(),Zt=rn.SIGHASH_ALL|rn.SIGHASH_FORKID;function cn(){return on.mainnetFlags()}function Na(e,t,r){r=r||{};var i=new on,n=i.verify(e,t,r.tx||new Qt,r.inputIndex||0,r.flags||cn(),new ut(r.satoshis||0));return{ok:n,err:i.errstr||""}}function un(e,t,r,i,n){return sn.sighashPreimage(e,n||Zt,t,r,new ut(i))}function Ua(e,t,r,i,n){return Ba.sha256sha256(un(e,t,r,i,n))}function qa(e,t,r,i,n,o){o=o||Zt;var a=sn.sign(e,t,o,r,i,new ut(n));return u.Buffer.concat([a.toDER(),u.Buffer.from([o])])}function Da(e,t,r){r=r||{};var i=new Qt().addOutput(new an({script:e,satoshis:t})),n=new Qt;return n.addInput(new Ra({prevTxId:i.hash,outputIndex:0,script:nn.empty()}),e,t),r.outputs&&r.outputs.forEach(function(o){n.addOutput(o)}),{funding:i,spend:n}}function Ma(e,t){var r=e.toAddress?e.toAddress():e;return new an({script:nn.buildPublicKeyHashOut(r),satoshis:t})}function Ga(e){return e===0?Wt.OP_0:e===-1?Wt.OP_1NEGATE:e>=1&&e<=16?Wt["OP_"+e]:new ut(e).toScriptNumBuffer()}hn.exports={SIGHASH:Zt,flags:cn,verify:Na,rawPreimage:un,sighashDigest:Ua,signInput:qa,fundAndSpend:Da,p2pkhOutput:Ma,scriptNum:Ga}});var dn=O((pu,ln)=>{"use strict";f();var Va=fe(),Ka=pe(),qe=b(),Ue=V(),pn=Ka.signInput;function za(e){var t=Va.sha256(e),r=new qe().add(Ue.OP_SHA256).add(t).add(Ue.OP_EQUAL);return{lock:r,meta:{name:"hash-lock",digest:t.toString("hex")},unlock:function(i,n,o){return new qe().add(o||e)}}}function $a(e){var t=e.toPublicKey(),r=qe.buildPublicKeyHashOut(t.toAddress());return{lock:r,meta:{name:"p2pkh",address:t.toAddress().toString()},unlock:function(i,n){return new qe().add(pn(i,e,0,r,n)).add(t.toBuffer())}}}function Ya(e,t){var r=t.map(function(n){return n.toPublicKey()}),i=new qe().add(Ue["OP_"+e]);return r.forEach(function(n){i.add(n.toBuffer())}),i.add(Ue["OP_"+r.length]).add(Ue.OP_CHECKMULTISIG),{lock:i,meta:{name:e+"-of-"+r.length+"-multisig"},unlock:function(n,o,a){a=a||t.slice(0,e);var s=new qe().add(Ue.OP_0);return a.forEach(function(c){s.add(pn(n,c,0,i,o))}),s}}}ln.exports={hashLock:za,p2pkh:$a,multisig:Ya}});var je=O((du,xn)=>{"use strict";f();var fn=b(),_=V(),ee=Ee(),ht=M(),gn=fe(),er=pe(),tr=er.SIGHASH,pt=er.scriptNum,De=u.Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),rr=new ht("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",16),Xa=u.Buffer.concat([u.Buffer.from([2]),De]),mn=u.Buffer.from(De).reverse(),yn=u.Buffer.concat([u.Buffer.from(rr.toBuffer()).reverse(),u.Buffer.from([0])]),ja=u.Buffer.concat([u.Buffer.from([48,68,2,32]),De,u.Buffer.from([2,32])]);function Jt(e,t){var r;for(r=0;r<t-1;r++)e.add(_.OP_1).add(_.OP_SPLIT);for(r=0;r<t-1;r++)e.add(_.OP_SWAP).add(_.OP_CAT);return e}var Wa=ee.SIGHASH_ALL|ee.SIGHASH_FORKID,Qa=ee.SIGHASH_SINGLE|ee.SIGHASH_FORKID,Za=ee.SIGHASH_SINGLE|ee.SIGHASH_ANYONECANPAY|ee.SIGHASH_FORKID,Ja=ee.SIGHASH_ALL|ee.SIGHASH_ANYONECANPAY|ee.SIGHASH_FORKID;function ir(e,t){var r=t&&t.sighashType||tr;return e.add(_.OP_HASH256),Jt(e,32),e.add(mn).add(_.OP_ADD),e.add(yn).add(_.OP_MOD),e.add(pt(32)).add(_.OP_NUM2BIN),Jt(e,32),e.add(De).add(_.OP_DUP),e.add(_.OP_2).add(_.OP_SWAP).add(_.OP_CAT),e.add(_.OP_TOALTSTACK),e.add(u.Buffer.from([48,68,2,32])).add(_.OP_SWAP).add(_.OP_CAT),e.add(u.Buffer.from([2,32])).add(_.OP_CAT),e.add(_.OP_SWAP).add(_.OP_CAT),e.add(u.Buffer.from([r])).add(_.OP_CAT),e.add(_.OP_FROMALTSTACK).add(_.OP_CHECKSIG),e}function es(){return ir(new fn)}function Sn(e){return e.add(pt(40)).add(_.OP_RIGHT).add(pt(32)).add(_.OP_LEFT),e}function ts(e){return vn(e,tr)}function vn(e,t){var r=u.Buffer.from([t&255,0,0,0]);return e.add(_.OP_DUP).add(pt(4)).add(_.OP_RIGHT).add(r).add(_.OP_EQUALVERIFY),e}function rs(e){var t=u.Buffer.concat(e.map(function(r){return r.toBufferWriter().toBuffer()}));return gn.sha256sha256(t)}function is(e){var t=new fn().add(_.OP_DUP);return ir(t),t.add(_.OP_VERIFY),Sn(t),t.add(u.Buffer.from(e)).add(_.OP_EQUAL),t}var ns=new ht("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex");function On(e){var t=gn.sha256sha256(e);if(t[0]<1||t[0]>127)return null;var r=new ht(t).add(new ht(De)).mod(rr);if(r.gt(ns))return null;var i=r.toBuffer("be",32);return i[0]>=1?i:null}function os(e,t,r,i,n){typeof n=="number"&&(n={maxTries:n}),n=n||{};var o=n.maxTries||5e3,a=n.start||0,s=n.field||"nLockTime",c=n.sighashType||tr;if(s!=="nLockTime"&&s!=="sequence")throw new Error("grind field must be 'nLockTime' or 'sequence'");for(var d=e.inputs[t],g=0;g<o;g++){var y=a+g;s==="nLockTime"?e.nLockTime=y:d.sequenceNumber=4294967294-y;var P=er.rawPreimage(e,t,r,i,c);if(On(P))return{preimage:P,tries:g+1,field:s,nonce:y}}throw new Error("OP_PUSH_TX grind failed after "+o+" tries")}xn.exports={Gx:De,N:rr,PUBKEY:Xa,gxLe:mn,N_LE:yn,DER_PREFIX:ja,reverseBytes:Jt,pushTxCore:ir,authenticator:es,extractHashOutputs:Sn,assertSighashAll:ts,assertSighashType:vn,SIGHASH_ALL_FORKID:Wa,SIGHASH_SINGLE_FORKID:Qa,SIGHASH_SINGLE_ANYONECANPAY_FORKID:Za,SIGHASH_ALL_ANYONECANPAY_FORKID:Ja,hashOutputs:rs,valueCovenant:is,sFromPreimage:On,grind:os}});var or=O((gu,Pn)=>{"use strict";f();var nr=je(),as=pe(),ss=b(),A=V(),Me=as.scriptNum;function cs(e){var t=new ss;return t.add(A.OP_DUP),nr.pushTxCore(t),t.add(A.OP_VERIFY),nr.assertSighashAll(t),t.add(A.OP_DUP),t.add(Me(104)).add(A.OP_SPLIT).add(A.OP_NIP),t.add(A.OP_SIZE).add(Me(52)).add(A.OP_SUB).add(A.OP_SPLIT).add(A.OP_DROP),t.add(A.OP_OVER),t.add(Me(52)).add(A.OP_RIGHT).add(Me(8)).add(A.OP_LEFT),t.add(A.OP_BIN2NUM).add(Me(e)).add(A.OP_SUB),t.add(Me(8)).add(A.OP_NUM2BIN),t.add(A.OP_SWAP).add(A.OP_CAT),t.add(A.OP_HASH256),t.add(A.OP_SWAP),nr.extractHashOutputs(t),t.add(A.OP_EQUAL),t}Pn.exports={pelsCovenant:cs}});var En=O((yu,_n)=>{f();_n.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.PublicKey});var cr=O((vu,Tn)=>{"use strict";f();var us=ze(),hs=En(),ps=b(),wn=fe(),sr=pe(),E=V(),Ge=sr.scriptNum;function lt(e){return e instanceof us?e.toPublicKey().toBuffer():e instanceof hs?e.toBuffer():e}function ls(){return{name:"single-key",commit:function(e){return wn.sha256ripemd160(lt(e))},emit:function(e){return e.add(E.OP_OVER).add(E.OP_HASH160).add(E.OP_EQUALVERIFY),e.add(E.OP_CHECKSIGVERIFY),e},unlockArgs:function(e,t,r,i,n){var o=sr.signInput(e,n,t,r,i);return[o,n.toPublicKey().toBuffer()]}}}function ar(e,t){var r=t.length;if(e<1||e>r||r<1||r>16)throw new Error("multisig requires 1 <= m <= n <= 16");var i=new ps().add(E["OP_"+e]);return t.forEach(function(n){i.add(u.Buffer.from(n))}),i.add(E["OP_"+r]).add(E.OP_CHECKMULTISIG),i.toBuffer()}function ds(e,t){if(typeof t!="number"||!Number.isInteger(t))throw new Error("multisig(m, nKeys): nKeys is the NUMBER of keys, not the keys themselves"+(Array.isArray(t)?" \u2014 pass "+t.length+" instead of the array":""));if(typeof e!="number"||!Number.isInteger(e))throw new Error("multisig(m, nKeys): m must be an integer");if(e<1||e>t||t<1||t>16)throw new Error("multisig requires 1 <= m <= n <= 16");return{name:e+"-of-"+t+"-multisig",m:e,n:t,commit:function(r){if(r.length!==t)throw new Error("expected "+t+" public keys");return wn.sha256ripemd160(ar(e,r.map(lt)))},emit:function(r){r.add(E.OP_OVER).add(E.OP_HASH160).add(E.OP_EQUALVERIFY),r.add(Ge(1)).add(E.OP_SPLIT).add(E.OP_NIP),r.add(E.OP_SIZE).add(Ge(2)).add(E.OP_SUB).add(E.OP_SPLIT).add(E.OP_DROP);for(var i=0;i<this.n;i++)r.add(Ge(34)).add(E.OP_SPLIT),r.add(E.OP_SWAP).add(Ge(1)).add(E.OP_SPLIT).add(E.OP_NIP),r.add(E.OP_TOALTSTACK);for(r.add(E.OP_DROP),r.add(Ge(this.m)),i=0;i<this.n;i++)r.add(E.OP_FROMALTSTACK);return r.add(Ge(this.n)),r.add(E.OP_CHECKMULTISIGVERIFY),r},unlockArgs:function(r,i,n,o,a){var s=a.keys;if(s.length!==t)throw new Error("expected "+t+" public keys in signer.keys");var c=ar(e,s.map(lt)),d=s.map(lt).map(function(P){return P.toString("hex")}),g=a.signWith.map(function(P){var x=d.indexOf(P.toPublicKey().toBuffer().toString("hex"));if(x<0)throw new Error("signWith key is not in the committed key set");return{idx:x,priv:P}}).sort(function(P,x){return x.idx-P.idx}).slice(0,e);if(g.length<e)throw new Error("need at least "+e+" signing keys");var y=g.map(function(P){return sr.signInput(r,P.priv,i,n,o)});return[E.OP_0].concat(y).concat([c])}}}function fs(e){if(!e||typeof e.emit!="function"||typeof e.unlockArgs!="function"||typeof e.commit!="function")throw new Error("predicate authorizer needs { commit, emit, unlockArgs } functions");return{name:e.name||"predicate",commit:e.commit,emit:e.emit,unlockArgs:e.unlockArgs}}Tn.exports={singleKey:ls,multisig:ds,predicate:fs,redeemScript:ar}});var hr=O((xu,Ln)=>{"use strict";f();var gs=M(),We=je(),ur=pe(),Qe=cr(),dt=b(),v=V(),te=ur.scriptNum;function An(e,t){var r=u.Buffer.isBuffer(e)?e:t.commit(e);if(r.length!==20)throw new Error("owner commitment must be 20 bytes (HASH160)");return r}function In(e,t){return t.length?e.add(u.Buffer.from(t)):e.add(v.OP_0)}function bn(e,t){return e.add(v.OP_DUP),We.pushTxCore(e),e.add(v.OP_VERIFY),We.assertSighashAll(e),e.add(v.OP_DUP).add(te(52)).add(v.OP_RIGHT).add(te(8)).add(v.OP_LEFT).add(v.OP_TOALTSTACK),e.add(v.OP_DUP),We.extractHashOutputs(e),e.add(v.OP_TOALTSTACK),e.add(te(104)).add(v.OP_SPLIT).add(v.OP_NIP).add(v.OP_SIZE).add(te(52)).add(v.OP_SUB).add(v.OP_SPLIT).add(v.OP_DROP),e.add(v.OP_DUP).add(te(4)).add(te(20)).add(v.OP_SUBSTR),e.add(v.OP_SWAP).add(v.OP_TOALTSTACK),t.emit(e),e.add(v.OP_FROMALTSTACK),e}function kn(e){return e.add(te(4)).add(v.OP_SPLIT).add(te(20)).add(v.OP_SPLIT).add(v.OP_NIP),e.add(v.OP_TOALTSTACK),e.add(v.OP_SWAP).add(v.OP_CAT),e.add(v.OP_FROMALTSTACK).add(v.OP_CAT),e}function Hn(e){var t=e.toBuffer().length;if(t<=252||t>65535)throw new Error("token script length must use a 3-byte varint (253..65535); got "+t);return e}function ms(e,t,r){r=r||Qe.singleKey();var i=new dt;return i.add(An(t,r)),i.add(v.OP_DROP),bn(i,r),kn(i),i.add(v.OP_FROMALTSTACK),i.add(v.OP_SWAP),i.add(v.OP_FROMALTSTACK),i.add(v.OP_BIN2NUM).add(te(e)).add(v.OP_SUB).add(te(8)).add(v.OP_NUM2BIN),i.add(v.OP_SWAP).add(v.OP_CAT),i.add(v.OP_HASH256),i.add(v.OP_EQUAL),Hn(i)}function Fn(e,t){t=t||Qe.singleKey();var r=new dt;return r.add(An(e,t)),r.add(v.OP_DROP),bn(r,t),kn(r),r.add(v.OP_CAT),r.add(v.OP_SWAP).add(v.OP_CAT),r.add(v.OP_CAT),r.add(v.OP_FROMALTSTACK),r.add(v.OP_FROMALTSTACK).add(v.OP_DROP),r.add(v.OP_SWAP).add(v.OP_HASH256).add(v.OP_EQUAL),Hn(r)}function ys(e){return Qe.singleKey().commit(e)}function Ss(e,t,r,i,n,o){o=o||{};var a=o.auth||Qe.singleKey(),s=o.inputIndex||0;if(t.length!==20)throw new Error("newOwnerHash must be 20 bytes (HASH160)");if(i<=1&&!o.allowLowValue)throw new Error("unlockTransfer: single-output token sets output = input - fee, which burns a "+i+"-sat UTXO (e.g. a 1-sat ordinal). Use Token.transferOrdinal / ownershipTokenMulti to preserve the satoshi.");We.grind(r,s,n,i,o.grind);var c=ur.rawPreimage(r,s,n,i),d=a.unlockArgs(r,s,n,i,e),g=new dt().add(u.Buffer.from(t));return d.forEach(function(y){g.add(y)}),g.add(u.Buffer.from(c)),g}function Cn(e,t,r,i,n,o,a){a=a||{};var s=a.auth||Qe.singleKey(),c=a.inputIndex||0;if(t.length!==20)throw new Error("newOwnerHash must be 20 bytes (HASH160)");if(!o||o.tokenValue==null||o.tokenValue.length!==8)throw new Error("layout.tokenValue must be the 8-byte LE value of the token output");We.grind(r,c,n,i,a.grind);var d=ur.rawPreimage(r,c,n,i),g=s.unlockArgs(r,c,n,i,e),y=new dt;return In(y,o.before||u.Buffer.alloc(0)),In(y,o.after||u.Buffer.alloc(0)),y.add(u.Buffer.from(o.tokenValue)),y.add(u.Buffer.from(t)),g.forEach(function(P){y.add(P)}),y.add(u.Buffer.from(d)),y}function vs(e,t){return Fn(e,t)}function Os(e,t,r,i,n,o){o=o||{},i==null&&(i=1);var a=o.tokenIndex||0,s=r.outputs||[],c=s[a];if(!c)throw new Error("transferOrdinal: spend has no output at tokenIndex "+a);if(c.satoshis!==i)throw new Error("transferOrdinal: token output value ("+c.satoshis+" sat) must equal the ordinal value ("+i+" sat) to avoid burning the inscription");function d(x){return x.toBufferWriter().toBuffer()}var g=u.Buffer.concat(s.slice(0,a).map(d)),y=u.Buffer.concat(s.slice(a+1).map(d)),P=new gs(i).toBuffer({endian:"little",size:8});return Cn(e,t,r,i,n,{before:g,after:y,tokenValue:P},o)}Ln.exports={ownershipToken:ms,ownershipTokenMulti:Fn,ordinalLock:vs,ownerId:ys,unlockTransfer:Ss,unlockTransferMulti:Cn,transferOrdinal:Os}});var mr=O((_u,Rn)=>{"use strict";f();var ft=je(),xs=or(),Ps=hr(),fr=pe(),pr=b(),T=V(),lr=D(),Ve=fr.scriptNum,dr=5e8,_s=u.Buffer.from([255,255,255,255]),Es=u.Buffer.from([0]);function ws(e,t){return e instanceof lr.Output?e:e instanceof pr?new lr.Output({script:e,satoshis:t}):fr.p2pkhOutput(e,t)}function Ts(e,t,r,i,n,o){o=o||5e4;for(var a=0;a<o;a++){e.nLockTime=n+a;var s=fr.rawPreimage(e,t,r,i);if(ft.sFromPreimage(s))return s}throw new Error("covenant grind failed after "+o+" tries")}function le(){if(!(this instanceof le))return new le;this._outputs=[],this._minLockTime=null}le.prototype.payTo=function(e,t){return this._outputs.push(ws(e,t)),this};le.prototype.lockUntil=function(e){if(!Number.isInteger(e)||e<1||e>4294967295)throw new Error("lockUntil: expected an integer in 1..4294967295, got "+e+' (nLockTime 0 means "no lock" \u2014 consensus treats such a transaction as final)');return this._minLockTime=e,this};le.prototype.outputs=function(){return this._outputs.map(function(e){return new lr.Output(e.toObject())})};le.prototype.describe=function(){var e=[];if(this._outputs.forEach(function(r,i){e.push("output["+i+"] = "+r.satoshis+" sat to "+r.script.toASM().slice(0,24)+"...")}),this._minLockTime!==null){var t=this._minLockTime<dr?"block height":"unix time";e.push("nLockTime >= "+this._minLockTime+" as a "+t),e.push("this input is non-final (nSequence != 0xffffffff)")}return"spend allowed iff: "+e.join(" AND ")};le.prototype.compile=function(){if(this._outputs.length===0&&this._minLockTime===null)throw new Error("empty policy: add at least one constraint (payTo / lockUntil)");var e=this,t=new pr().add(T.OP_DUP);if(ft.pushTxCore(t),t.add(T.OP_VERIFY),this._outputs.length){var r=ft.hashOutputs(this._outputs);t.add(T.OP_DUP),ft.extractHashOutputs(t),t.add(u.Buffer.from(r)).add(T.OP_EQUALVERIFY)}return this._minLockTime!==null&&(t.add(T.OP_DUP),t.add(Ve(44)).add(T.OP_RIGHT).add(Ve(4)).add(T.OP_LEFT),t.add(_s).add(T.OP_EQUAL).add(T.OP_NOT).add(T.OP_VERIFY),t.add(T.OP_DUP),t.add(Ve(8)).add(T.OP_RIGHT).add(Ve(4)).add(T.OP_LEFT),t.add(Es).add(T.OP_CAT).add(T.OP_BIN2NUM),this._minLockTime<dr&&t.add(T.OP_DUP).add(Ve(dr)).add(T.OP_LESSTHAN).add(T.OP_VERIFY),t.add(Ve(this._minLockTime)).add(T.OP_GREATERTHANOREQUAL).add(T.OP_VERIFY)),t.add(T.OP_DROP).add(T.OP_1),{lock:t,outputs:e.outputs(),describe:function(){return e.describe()},unlock:function(i,n,o){o=o||0;var a=e._minLockTime===null?0:e._minLockTime;return e._minLockTime!==null&&(i.inputs[o].sequenceNumber=4294967294),new pr().add(Ts(i,o,t,n,a))}}};function gr(){return new le}gr.perpetual=function(e){return xs.pelsCovenant(e)};gr.token=function(e,t){return Ps.ownershipToken(e,t)};Rn.exports={policy:gr,Policy:le}});var Dn=O((wu,qn)=>{"use strict";f();var Is=ge(),As=M(),bs=D(),ks=V(),Hs=pe();function Nn(e){if(e===0)return"OP_0";if(e>=1&&e<=75)return"PUSH("+e+")";if(e===76)return"OP_PUSHDATA1";if(e===77)return"OP_PUSHDATA2";if(e===78)return"OP_PUSHDATA4";try{return ks.fromNumber(e).toString()}catch{return"0x"+e.toString(16)}}function Bn(e,t){t=t||16;var r=u.Buffer.from(e).toString("hex");return r.length<=t*2?r||"0":r.slice(0,t*2)+"...("+e.length+"B)"}function Fs(e,t,r){r=r||{};var i=new Is,n=[];i.stepListener=function(a,s,c){n.push({phase:i.script===t?"lock":"unlock",op:Nn(a.opcode&&typeof a.opcode.toNumber=="function"?a.opcode.toNumber():a.opcode.num),stack:s.map(function(d){return Bn(d)}),altstack:c.map(function(d){return Bn(d)})})};var o=i.verify(e,t,r.tx||new bs,r.inputIndex||0,typeof r.flags=="number"?r.flags:Hs.flags(),new As(r.satoshis||0));return{ok:o,err:i.errstr||"",steps:n}}function Un(e){var t=[],r=null;return e.steps.forEach(function(i,n){i.phase!==r&&(t.push("-- "+i.phase+" script --"),r=i.phase);var o=i.stack.length?i.stack.join(" | "):"(empty)",a=i.altstack.length?" alt:["+i.altstack.join(" | ")+"]":"";t.push(String(n).padStart(3)+" "+i.op.padEnd(16)+" -> ["+o+"]"+a)}),t.push((e.ok?"VALID":"INVALID")+(e.err?" ("+e.err+")":"")),t.join(`
|
|
23
|
+
`)}function Cs(e){return console.log(Un(e)),e}qn.exports={trace:Fs,format:Un,print:Cs,opLabel:Nn}});var Gn=O((Iu,Mn)=>{"use strict";f();Mn.exports="9.4.0"});var zn=O((bu,Kn)=>{"use strict";f();var Ls=fe(),Vn=D(),Rs=It(),Bs=b(),p={Covenant:ai(),Preimage:J(),SIGHASH:li(),Builder:vi(),UTXOGenerator:Bi(),ScriptTester:Mi(),CovenantBuilder:Vt().CovenantBuilder,CovenantTemplates:Vt().CovenantTemplates,OpcodeMap:Dt(),ScriptUtils:Xi(),StackExaminer:Wi(),ScriptInterpreter:tn(),CovenantHelpers:pe(),Locks:dn(),PushTx:je(),PELS:or(),Token:hr(),Authorizers:cr(),DSL:mr(),Policy:mr().Policy,Debugger:Dn()};p.policy=p.DSL.policy;p.trace=function(e,t,r){return p.Debugger.trace(e,t,r)};p.verifyScript=function(e,t,r){return p.CovenantHelpers.verify(e,t,r)};p.perpetualCovenant=function(e){return p.PELS.pelsCovenant(e)};p.ownershipToken=function(e,t,r){return p.Token.ownershipToken(e,t,r)};p.valueCovenant=function(e){return p.PushTx.valueCovenant(e)};p.ordinalLock=function(e,t){return p.Token.ordinalLock(e,t)};p.transferOrdinal=function(e,t,r,i,n,o){return p.Token.transferOrdinal(e,t,r,i,n,o)};p.createCovenant=function(e,t){return new p.Covenant(e,t)};p.extractPreimage=function(e,t){return new p.Preimage(e,t)};p.analyzeSIGHASH=function(e){return new p.SIGHASH(e)};p.buildCovenant=function(e,t){return new p.Builder(e,t)};p.createUTXOGenerator=function(e){return new p.UTXOGenerator(e)};p.createTestEnvironment=function(e){return p.UTXOGenerator.createTestEnvironment(e)};p.testScript=function(e,t,r){return p.ScriptTester.test(e,t,r)};p.testCovenant=function(e,t,r){return p.ScriptTester.testCovenant(e,t,r)};p.testFieldExtraction=function(e,t,r){return p.ScriptTester.testFieldExtraction(e,t,r)};p.debugScript=function(e,t){var r=new p.ScriptTester(t);return r.debug(e)};p.explainZeroHashes=function(){return p.SIGHASH.explainZeroMystery()};p.getAllSIGHASHTypes=function(){return p.SIGHASH.getAllTypes()};p.demonstrateAllSIGHASH=function(){return p.SIGHASH.generateAllDemonstrations()};p.createCovenantBuilder=function(){return new p.CovenantBuilder};p.createValueLockCovenant=function(e){return p.CovenantTemplates.valueLock(e)};p.createHashLockCovenant=function(e){return p.CovenantTemplates.hashLock(e)};p.createComplexValidationCovenant=function(e){return p.CovenantTemplates.complexValidation(e)};p.getOpcodeMap=function(){return p.OpcodeMap.opcodeMap};p.simulateScript=function(e,t){return p.OpcodeMap.utils.simulate(e,t)};p.createASMFromJS=function(e){return p.OpcodeMap.utils.createASM(e)};p.scriptToASM=function(e){return p.ScriptUtils.scriptToASM(e)};p.asmToScript=function(e){return p.ScriptUtils.asmToScript(e)};p.asmToHex=function(e){return p.ScriptUtils.asmToHex(e)};p.hexToASM=function(e){return p.ScriptUtils.hexToASM(e)};p.scriptToHex=function(e){return p.ScriptUtils.scriptToHex(e)};p.validateASM=function(e){return p.ScriptUtils.validateASM(e)};p.validateScript=function(e){return p.ScriptUtils.validateScript(e)};p.estimateScriptSize=function(e){return p.ScriptUtils.estimateScriptSize(e)};p.optimizeScript=function(e){return p.ScriptUtils.optimizeScript(e)};p.compareScripts=function(e,t){return p.ScriptUtils.compareScripts(e,t)};p.explainScript=function(e){return p.ScriptUtils.explainScript(e)};p.scriptMetrics=function(e){return p.ScriptUtils.scriptMetrics(e)};p.analyzeComplexity=function(e){return p.ScriptUtils.analyzeComplexity(e)};p.findOptimizations=function(e){return p.ScriptUtils.findOptimizations(e)};p.covenantToEnglish=function(e){return p.ScriptUtils.covenantToEnglish(e)};p.batchTestScripts=function(e,t){return p.ScriptUtils.batchTestScripts(e,t)};p.examineStack=function(e,t){return p.StackExaminer.runScript(e,t)};p.debugScriptExecution=function(e,t,r){return r=r||{},r.stepMode?p.ScriptInterpreter.stepThroughScript(p.ScriptInterpreter.parseScript(e+" "+t),new Vn,!0):p.ScriptInterpreter.runFullEvaluation(p.ScriptInterpreter.parseScript(e),p.ScriptInterpreter.parseScript(t),new Vn)};p.parseScript=function(e){return p.ScriptInterpreter.parseScript(e)};p.printStack=function(e,t){return p.ScriptInterpreter.printStack(e,t)};p.createQuickCovenant=function(e,t){let r=p.createCovenantBuilder();switch(e){case"value_lock":return r.comment(`Value lock: minimum ${t.value} satoshis`).extractField("value").push(t.value).greaterThanOrEqual().verify().build();case"hash_lock":return r.comment(`Hash lock: requires preimage of ${t.hash}`).push("secret_placeholder").sha256().push(t.hash).equalVerify().build();case"time_lock":return r.comment(`Time lock: requires nLockTime > ${t.timestamp}`).extractField("nLockTime").push(t.timestamp).greaterThan().verify().build();case"multi_condition":let i=r.comment("Multi-condition covenant");return t.conditions.forEach(n=>{switch(n.type){case"value":i=i.extractField("value").push(n.value).greaterThanOrEqual().verify();break;case"hash":i=i.push("secret_placeholder").sha256().push(n.hash).equalVerify();break;case"time":i=i.extractField("nLockTime").push(n.timestamp).greaterThan().verify();break}}),i.build();default:throw new Error(`Unknown covenant type: ${e}`)}};p.completeCovenantFlow=function(e,t,r){var i=new p.Covenant(e);return i.completeFlow(t,r)};p.getEducationalResources=function(){return{zeroHashMystery:p.SIGHASH.explainZeroMystery(),sighashTypes:p.SIGHASH.getAllTypes(),exampleDemonstrations:p.SIGHASH.generateAllDemonstrations()}};p.utils={};p.utils.reconstructP2pkhScript=function(e){return Bs.buildPublicKeyHashOut(e).toHex()};p.utils.createCovenantAddress=function(e){var t=Ls.sha256ripemd160(e.toBuffer());return Rs.fromScriptHash(t)};p.utils.decodeCompactSize=function(e,t){return p.Preimage.decodeCompactSize(e,t)};p.version=Gn();p.description="Smart Contract Framework for Bitcoin SV";p.features={BIP143_PREIMAGE:!0,COMPACT_SIZE_VARINT:!0,BIDIRECTIONAL_EXTRACTION:!0,SIGHASH_DETECTION:!0,ZERO_HASH_WARNINGS:!0,MULTI_FIELD_VALIDATION:!0,REAL_UTXO_GENERATION:!0,SCRIPT_TESTING:!0,LOCAL_VERIFICATION:!0,JAVASCRIPT_TO_SCRIPT:!0,OPCODE_MAPPING:!0,COVENANT_BUILDER:!0,SCRIPT_ANALYSIS:!0,SCRIPT_OPTIMIZATION:!0,SCRIPT_CONVERSION:!0,BATCH_TESTING:!0,QUICK_COVENANTS:!0,SCRIPT_EXPLANATIONS:!0,STACK_EXAMINATION:!0,SCRIPT_DEBUGGING:!0,STEP_BY_STEP_EXECUTION:!0,INTERACTIVE_DEBUGGING:!0};p.interpretScript=p.debugScriptExecution;p.getScriptMetrics=p.scriptMetrics;Kn.exports=p});var Ns=O((Hu,$n)=>{f();$n.exports=zn()});return Ns();})();
|
|
24
24
|
if(typeof module!=="undefined"&&module.exports){module.exports=bsvSmartContract}else if(typeof define==="function"&&define.amd){define([],function(){return bsvSmartContract})}
|