@smartledger/bsv 8.3.1 → 9.0.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 +91 -0
- package/README.md +74 -64
- package/bsv-gdaf.min.js +49 -49
- package/bsv-script-helper.min.js +1 -1
- package/bsv-smartcontract.min.js +21 -21
- package/bsv.bundle.js +49 -49
- package/bsv.d.ts +0 -4
- package/bsv.min.js +49 -49
- package/docs/BRC220_BATCH_LEAF_AMENDMENT.md +82 -7
- package/docs/MODULE_REFERENCE_COMPLETE.md +27 -27
- package/docs/README.md +2 -1
- package/docs/THREAT_MODEL.md +10 -2
- 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/index.js +10 -26
- package/lib/covenant/helpers.js +34 -35
- package/lib/covenant/pushtx.js +2 -2
- package/lib/custom-script-helper.js +0 -16
- package/lib/ordinals/ordlock.js +1 -1
- package/lib/smart_contract/debugger.js +2 -2
- package/lib/smart_contract/dsl.js +2 -2
- package/lib/smart_contract/index.js +0 -3
- package/lib/smart_contract/locks.js +1 -41
- package/lib/smart_contract/pels.js +1 -1
- package/lib/smart_contract/token.js +1 -1
- package/package.json +1 -1
- package/test/build/esm_wrapper.js +32 -8
- package/test/data/brc220-batch-vector.json +129 -0
- package/test/notaryhash/batch_vector.js +282 -0
- package/test/ordinals/inscription.js +24 -14
- package/test/ordinals/ordlock.js +0 -46
- package/test/smart_contract/covenants.js +0 -38
- package/test/smart_contract/dsl_debugger.js +0 -9
- package/test/smart_contract/ordinal_transfer.js +0 -10
- package/test/smart_contract/sighash_marketplace.js +0 -10
- package/test/smart_contract/token_generalized.js +0 -10
- package/tools/gen-brc220-batch-vector.js +205 -0
- package/version.js +1 -1
package/bsv-smartcontract.min.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
var bsvSmartContract=(()=>{var Vn=Object.create;var fr=Object.defineProperty;var Kn=Object.getOwnPropertyDescriptor;var zn=Object.getOwnPropertyNames;var Yn=Object.getPrototypeOf,$n=Object.prototype.hasOwnProperty;var R=(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 Xn=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var P=(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 zn(t))!$n.call(e,n)&&n!==r&&fr(e,n,{get:()=>t[n],enumerable:!(i=Kn(t,n))||i.enumerable});return e};var gr=(e,t,r)=>(r=e!=null?Vn(Yn(e)):{},jn(t||!e||!e.__esModule?fr(r,"default",{value:e,enumerable:!0}):r,e));var Pr=P((Ha,Or)=>{f();var I=Or.exports={},Q,Z;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"?Q=setTimeout:Q=ft}catch{Q=ft}try{typeof clearTimeout=="function"?Z=clearTimeout:Z=gt}catch{Z=gt}})();function mr(e){if(Q===setTimeout)return setTimeout(e,0);if((Q===ft||!Q)&&setTimeout)return Q=setTimeout,setTimeout(e,0);try{return Q(e,0)}catch{try{return Q.call(null,e,0)}catch{return Q.call(this,e,0)}}}function Wn(e){if(Z===clearTimeout)return clearTimeout(e);if((Z===gt||!Z)&&clearTimeout)return Z=clearTimeout,clearTimeout(e);try{return Z(e)}catch{try{return Z.call(null,e)}catch{return Z.call(this,e)}}}var oe=[],Te=!1,xe,Qe=-1;function Qn(){!Te||!xe||(Te=!1,xe.length?oe=xe.concat(oe):Qe=-1,oe.length&&Sr())}function Sr(){if(!Te){var e=mr(Qn);Te=!0;for(var t=oe.length;t;){for(xe=oe,oe=[];++Qe<t;)xe&&xe[Qe].run();Qe=-1,t=oe.length}xe=null,Te=!1,Wn(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];oe.push(new yr(e,t)),oe.length===1&&!Te&&mr(Sr)};function yr(e,t){this.fun=e,this.array=t}yr.prototype.run=function(){this.fun.apply(null,this.array)};I.title="browser";I.browser=!0;I.env={};I.argv=[];I.version="";I.versions={};function se(){}I.on=se;I.addListener=se;I.once=se;I.off=se;I.removeListener=se;I.removeAllListeners=se;I.emit=se;I.prependListener=se;I.prependOnceListener=se;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 _r=P(Ze=>{"use strict";f();Ze.byteLength=Jn;Ze.toByteArray=to;Ze.fromByteArray=no;var J=[],K=[],Zn=typeof Uint8Array<"u"?Uint8Array:Array,mt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(ve=0,xr=mt.length;ve<xr;++ve)J[ve]=mt[ve],K[mt.charCodeAt(ve)]=ve;var ve,xr;K[45]=62;K[95]=63;function vr(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 Jn(e){var t=vr(e),r=t[0],i=t[1];return(r+i)*3/4-i}function eo(e,t,r){return(t+r)*3/4-r}function to(e){var t,r=vr(e),i=r[0],n=r[1],o=new Zn(eo(e,i,n)),s=0,a=n>0?i-4:i,c;for(c=0;c<a;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[s++]=t>>16&255,o[s++]=t>>8&255,o[s++]=t&255;return n===2&&(t=K[e.charCodeAt(c)]<<2|K[e.charCodeAt(c+1)]>>4,o[s++]=t&255),n===1&&(t=K[e.charCodeAt(c)]<<10|K[e.charCodeAt(c+1)]<<4|K[e.charCodeAt(c+2)]>>2,o[s++]=t>>8&255,o[s++]=t&255),o}function ro(e){return J[e>>18&63]+J[e>>12&63]+J[e>>6&63]+J[e&63]}function io(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(ro(i));return n.join("")}function no(e){for(var t,r=e.length,i=r%3,n=[],o=16383,s=0,a=r-i;s<a;s+=o)n.push(io(e,s,s+o>a?a:s+o));return i===1?(t=e[r-1],n.push(J[t>>2]+J[t<<4&63]+"==")):i===2&&(t=(e[r-2]<<8)+e[r-1],n.push(J[t>>10]+J[t>>4&63]+J[t<<2&63]+"=")),n.join("")}});var Er=P(St=>{f();St.read=function(e,t,r,i,n){var o,s,a=n*8-i-1,c=(1<<a)-1,d=c>>1,g=-7,m=r?n-1:0,v=r?-1:1,x=e[t+m];for(m+=v,o=x&(1<<-g)-1,x>>=-g,g+=a;g>0;o=o*256+e[t+m],m+=v,g-=8);for(s=o&(1<<-g)-1,o>>=-g,g+=i;g>0;s=s*256+e[t+m],m+=v,g-=8);if(o===0)o=1-d;else{if(o===c)return s?NaN:(x?-1:1)*(1/0);s=s+Math.pow(2,i),o=o-d}return(x?-1:1)*s*Math.pow(2,o-i)};St.write=function(e,t,r,i,n,o){var s,a,c,d=o*8-n-1,g=(1<<d)-1,m=g>>1,v=n===23?Math.pow(2,-24)-Math.pow(2,-77):0,x=i?0:o-1,ne=i?1:-1,Gn=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+m>=1?t+=v/c:t+=v*Math.pow(2,1-m),t*c>=2&&(s++,c/=2),s+m>=g?(a=0,s=g):s+m>=1?(a=(t*c-1)*Math.pow(2,n),s=s+m):(a=t*Math.pow(2,m-1)*Math.pow(2,n),s=0));n>=8;e[r+x]=a&255,x+=ne,a/=256,n-=8);for(s=s<<n|a,d+=n;d>0;e[r+x]=s&255,x+=ne,s/=256,d-=8);e[r+x-ne]|=Gn*128}});var Mr=P(He=>{"use strict";f();var yt=_r(),be=Er(),wr=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;He.Buffer=p;He.SlowBuffer=po;He.INSPECT_MAX_BYTES=50;var Je=2147483647;He.kMaxLength=Je;p.TYPED_ARRAY_SUPPORT=oo();!p.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 oo(){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(p.prototype,"parent",{enumerable:!0,get:function(){if(p.isBuffer(this))return this.buffer}});Object.defineProperty(p.prototype,"offset",{enumerable:!0,get:function(){if(p.isBuffer(this))return this.byteOffset}});function ae(e){if(e>Je)throw new RangeError('The value "'+e+'" is invalid for option "size"');let t=new Uint8Array(e);return Object.setPrototypeOf(t,p.prototype),t}function p(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 vt(e)}return br(e,t,r)}p.poolSize=8192;function br(e,t,r){if(typeof e=="string")return ao(e,t);if(ArrayBuffer.isView(e))return co(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(ee(e,ArrayBuffer)||e&&ee(e.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(ee(e,SharedArrayBuffer)||e&&ee(e.buffer,SharedArrayBuffer)))return Pt(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 p.from(i,t,r);let n=uo(e);if(n)return n;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof e[Symbol.toPrimitive]=="function")return p.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)}p.from=function(e,t,r){return br(e,t,r)};Object.setPrototypeOf(p.prototype,Uint8Array.prototype);Object.setPrototypeOf(p,Uint8Array);function kr(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 so(e,t,r){return kr(e),e<=0?ae(e):t!==void 0?typeof r=="string"?ae(e).fill(t,r):ae(e).fill(t):ae(e)}p.alloc=function(e,t,r){return so(e,t,r)};function vt(e){return kr(e),ae(e<0?0:_t(e)|0)}p.allocUnsafe=function(e){return vt(e)};p.allocUnsafeSlow=function(e){return vt(e)};function ao(e,t){if((typeof t!="string"||t==="")&&(t="utf8"),!p.isEncoding(t))throw new TypeError("Unknown encoding: "+t);let r=Hr(e,t)|0,i=ae(r),n=i.write(e,t);return n!==r&&(i=i.slice(0,n)),i}function Ot(e){let t=e.length<0?0:_t(e.length)|0,r=ae(t);for(let i=0;i<t;i+=1)r[i]=e[i]&255;return r}function co(e){if(ee(e,Uint8Array)){let t=new Uint8Array(e);return Pt(t.buffer,t.byteOffset,t.byteLength)}return Ot(e)}function Pt(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,p.prototype),i}function uo(e){if(p.isBuffer(e)){let t=_t(e.length)|0,r=ae(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)?ae(0):Ot(e);if(e.type==="Buffer"&&Array.isArray(e.data))return Ot(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 po(e){return+e!=e&&(e=0),p.alloc(+e)}p.isBuffer=function(t){return t!=null&&t._isBuffer===!0&&t!==p.prototype};p.compare=function(t,r){if(ee(t,Uint8Array)&&(t=p.from(t,t.offset,t.byteLength)),ee(r,Uint8Array)&&(r=p.from(r,r.offset,r.byteLength)),!p.isBuffer(t)||!p.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};p.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}};p.concat=function(t,r){if(!Array.isArray(t))throw new TypeError('"list" argument must be an Array of Buffers');if(t.length===0)return p.alloc(0);let i;if(r===void 0)for(r=0,i=0;i<t.length;++i)r+=t[i].length;let n=p.allocUnsafe(r),o=0;for(i=0;i<t.length;++i){let s=t[i];if(ee(s,Uint8Array))o+s.length>n.length?(p.isBuffer(s)||(s=p.from(s)),s.copy(n,o)):Uint8Array.prototype.set.call(n,s,o);else if(p.isBuffer(s))s.copy(n,o);else throw new TypeError('"list" argument must be an Array of Buffers');o+=s.length}return n};function Hr(e,t){if(p.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||ee(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 xt(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return Dr(e).length;default:if(n)return i?-1:xt(e).length;t=(""+t).toLowerCase(),n=!0}}p.byteLength=Hr;function ho(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 vo(this,t,r);case"utf8":case"utf-8":return Cr(this,t,r);case"ascii":return Po(this,t,r);case"latin1":case"binary":return xo(this,t,r);case"base64":return yo(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _o(this,t,r);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}p.prototype._isBuffer=!0;function _e(e,t,r){let i=e[t];e[t]=e[r],e[r]=i}p.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)_e(this,r,r+1);return this};p.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)_e(this,r,r+3),_e(this,r+1,r+2);return this};p.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)_e(this,r,r+7),_e(this,r+1,r+6),_e(this,r+2,r+5),_e(this,r+3,r+4);return this};p.prototype.toString=function(){let t=this.length;return t===0?"":arguments.length===0?Cr(this,0,t):ho.apply(this,arguments)};p.prototype.toLocaleString=p.prototype.toString;p.prototype.equals=function(t){if(!p.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t?!0:p.compare(this,t)===0};p.prototype.inspect=function(){let t="",r=He.INSPECT_MAX_BYTES;return t=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(t+=" ... "),"<Buffer "+t+">"};wr&&(p.prototype[wr]=p.prototype.inspect);p.prototype.compare=function(t,r,i,n,o){if(ee(t,Uint8Array)&&(t=p.from(t,t.offset,t.byteLength)),!p.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 m=0;m<c;++m)if(d[m]!==g[m]){s=d[m],a=g[m];break}return s<a?-1:a<s?1:0};function Fr(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=p.from(t,i)),p.isBuffer(t))return t.length===0?-1:Ir(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):Ir(e,[t],r,i,n);throw new TypeError("val must be string, number or Buffer")}function Ir(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,m){return o===1?g[m]:g.readUInt16BE(m*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 m=0;m<a;m++)if(c(e,d+m)!==c(t,m)){g=!1;break}if(g)return d}return-1}p.prototype.includes=function(t,r,i){return this.indexOf(t,r,i)!==-1};p.prototype.indexOf=function(t,r,i){return Fr(this,t,r,i,!0)};p.prototype.lastIndexOf=function(t,r,i){return Fr(this,t,r,i,!1)};function lo(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 fo(e,t,r,i){return et(xt(t,e.length-r),e,r,i)}function go(e,t,r,i){return et(To(t),e,r,i)}function mo(e,t,r,i){return et(Dr(t),e,r,i)}function So(e,t,r,i){return et(Ao(t,e.length-r),e,r,i)}p.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 lo(this,t,r,i);case"utf8":case"utf-8":return fo(this,t,r,i);case"ascii":case"latin1":case"binary":return go(this,t,r,i);case"base64":return mo(this,t,r,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return So(this,t,r,i);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),s=!0}};p.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function yo(e,t,r){return t===0&&r===e.length?yt.fromByteArray(e):yt.fromByteArray(e.slice(t,r))}function Cr(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,m;switch(a){case 1:o<128&&(s=o);break;case 2:c=e[n+1],(c&192)===128&&(m=(o&31)<<6|c&63,m>127&&(s=m));break;case 3:c=e[n+1],d=e[n+2],(c&192)===128&&(d&192)===128&&(m=(o&15)<<12|(c&63)<<6|d&63,m>2047&&(m<55296||m>57343)&&(s=m));break;case 4:c=e[n+1],d=e[n+2],g=e[n+3],(c&192)===128&&(d&192)===128&&(g&192)===128&&(m=(o&15)<<18|(c&63)<<12|(d&63)<<6|g&63,m>65535&&m<1114112&&(s=m))}}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 Oo(i)}var Tr=4096;function Oo(e){let t=e.length;if(t<=Tr)return String.fromCharCode.apply(String,e);let r="",i=0;for(;i<t;)r+=String.fromCharCode.apply(String,e.slice(i,i+=Tr));return r}function Po(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 xo(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 vo(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+=bo[e[o]];return n}function _o(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}p.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,p.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")}p.prototype.readUintLE=p.prototype.readUIntLE=function(t,r,i){t=t>>>0,r=r>>>0,i||F(t,r,this.length);let n=this[t],o=1,s=0;for(;++s<r&&(o*=256);)n+=this[t+s]*o;return n};p.prototype.readUintBE=p.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};p.prototype.readUint8=p.prototype.readUInt8=function(t,r){return t=t>>>0,r||F(t,1,this.length),this[t]};p.prototype.readUint16LE=p.prototype.readUInt16LE=function(t,r){return t=t>>>0,r||F(t,2,this.length),this[t]|this[t+1]<<8};p.prototype.readUint16BE=p.prototype.readUInt16BE=function(t,r){return t=t>>>0,r||F(t,2,this.length),this[t]<<8|this[t+1]};p.prototype.readUint32LE=p.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};p.prototype.readUint32BE=p.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])};p.prototype.readBigUInt64LE=fe(function(t){t=t>>>0,ke(t,"offset");let r=this[t],i=this[t+7];(r===void 0||i===void 0)&&Ge(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))});p.prototype.readBigUInt64BE=fe(function(t){t=t>>>0,ke(t,"offset");let r=this[t],i=this[t+7];(r===void 0||i===void 0)&&Ge(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)});p.prototype.readIntLE=function(t,r,i){t=t>>>0,r=r>>>0,i||F(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};p.prototype.readIntBE=function(t,r,i){t=t>>>0,r=r>>>0,i||F(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};p.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]};p.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};p.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};p.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};p.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]};p.prototype.readBigInt64LE=fe(function(t){t=t>>>0,ke(t,"offset");let r=this[t],i=this[t+7];(r===void 0||i===void 0)&&Ge(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)});p.prototype.readBigInt64BE=fe(function(t){t=t>>>0,ke(t,"offset");let r=this[t],i=this[t+7];(r===void 0||i===void 0)&&Ge(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)});p.prototype.readFloatLE=function(t,r){return t=t>>>0,r||F(t,4,this.length),be.read(this,t,!0,23,4)};p.prototype.readFloatBE=function(t,r){return t=t>>>0,r||F(t,4,this.length),be.read(this,t,!1,23,4)};p.prototype.readDoubleLE=function(t,r){return t=t>>>0,r||F(t,8,this.length),be.read(this,t,!0,52,8)};p.prototype.readDoubleBE=function(t,r){return t=t>>>0,r||F(t,8,this.length),be.read(this,t,!1,52,8)};function L(e,t,r,i,n,o){if(!p.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")}p.prototype.writeUintLE=p.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};p.prototype.writeUintBE=p.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};p.prototype.writeUint8=p.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};p.prototype.writeUint16LE=p.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};p.prototype.writeUint16BE=p.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};p.prototype.writeUint32LE=p.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};p.prototype.writeUint32BE=p.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 Rr(e,t,r,i,n){qr(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 Lr(e,t,r,i,n){qr(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}p.prototype.writeBigUInt64LE=fe(function(t,r=0){return Rr(this,t,r,BigInt(0),BigInt("0xffffffffffffffff"))});p.prototype.writeBigUInt64BE=fe(function(t,r=0){return Lr(this,t,r,BigInt(0),BigInt("0xffffffffffffffff"))});p.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};p.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};p.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};p.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};p.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};p.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};p.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};p.prototype.writeBigInt64LE=fe(function(t,r=0){return Rr(this,t,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});p.prototype.writeBigInt64BE=fe(function(t,r=0){return Lr(this,t,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Br(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 Nr(e,t,r,i,n){return t=+t,r=r>>>0,n||Br(e,t,r,4,34028234663852886e22,-34028234663852886e22),be.write(e,t,r,i,23,4),r+4}p.prototype.writeFloatLE=function(t,r,i){return Nr(this,t,r,!0,i)};p.prototype.writeFloatBE=function(t,r,i){return Nr(this,t,r,!1,i)};function Ur(e,t,r,i,n){return t=+t,r=r>>>0,n||Br(e,t,r,8,17976931348623157e292,-17976931348623157e292),be.write(e,t,r,i,52,8),r+8}p.prototype.writeDoubleLE=function(t,r,i){return Ur(this,t,r,!0,i)};p.prototype.writeDoubleBE=function(t,r,i){return Ur(this,t,r,!1,i)};p.prototype.copy=function(t,r,i,n){if(!p.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};p.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"&&!p.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=p.isBuffer(t)?t:p.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 Ae={};function Et(e,t,r){Ae[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=Ar(String(r)):typeof r=="bigint"&&(n=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(n=Ar(n)),n+="n"),i+=` It must be ${t}. Received ${n}`,i},RangeError);function Ar(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 Eo(e,t,r){ke(t,"offset"),(e[t]===void 0||e[t+r]===void 0)&&Ge(t,e.length-(r+1))}function qr(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 Ae.ERR_OUT_OF_RANGE("value",a,e)}Eo(i,n,o)}function ke(e,t){if(typeof e!="number")throw new Ae.ERR_INVALID_ARG_TYPE(t,"number",e)}function Ge(e,t,r){throw Math.floor(e)!==e?(ke(e,r),new Ae.ERR_OUT_OF_RANGE(r||"offset","an integer",e)):t<0?new Ae.ERR_BUFFER_OUT_OF_BOUNDS:new Ae.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}var wo=/[^+/0-9A-Za-z-_]/g;function Io(e){if(e=e.split("=")[0],e=e.trim().replace(wo,""),e.length<2)return"";for(;e.length%4!==0;)e=e+"=";return e}function xt(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 To(e){let t=[];for(let r=0;r<e.length;++r)t.push(e.charCodeAt(r)&255);return t}function Ao(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 Dr(e){return yt.toByteArray(Io(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 ee(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 bo=(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 fe(e){return typeof BigInt>"u"?ko:e}function ko(){throw new Error("BigInt not supported")}});var S,u,f=Xn(()=>{S=gr(Pr()),u=gr(Mr())});var ge=P((Ma,Gr)=>{f();Gr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.crypto.Hash});var D=P((Va,Vr)=>{f();Vr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Transaction});var It=P((za,Kr)=>{f();Kr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Address});var b=P(($a,zr)=>{f();zr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Script});var Ee=P((ja,Yr)=>{f();Yr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Transaction.sighash});var Fe=P((Qa,$r)=>{f();$r.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Transaction.Input});var me=P((Ja,Xr)=>{f();Xr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Script.Interpreter});var we=P((tc,jr)=>{f();jr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.crypto.Signature});var M=P((ic,Wr)=>{f();Wr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.crypto.BN});var C=P((oc,Qr)=>{"use strict";f();Qr.exports={}});var ii=P((ac,ri)=>{"use strict";f();var ei=Ee(),Ho=Fe(),Ce=me(),Zr=we(),Fo=ge(),Tt=M(),ti=D(),Se=b(),Jr=C(),ce;try{ce=C()}catch{ce=null}var Co=function(){var e=typeof S.default<"u"&&S.default.env&&S.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 S.default<"u"?Jr.join(S.default.cwd(),".bsv-covenants"):".bsv-covenants"),this.covenantUtxoPath=Jr.join(this.storageDir,"covenant_utxos.json"),this.sighashType=Zr.SIGHASH_ALL|Zr.SIGHASH_FORKID,this.allowNonEnforcing=t.allowNonEnforcing===!0,ce&&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 ti().from({txId:e.txid,outputIndex:e.vout,script:e.script,satoshis:e.satoshis}).to(this.address,e.satoshis-1e3),r=Se.fromHex(e.script),i=ei.sighashPreimage(t,this.sighashType,0,r,new Tt(e.satoshis)),n=Fo.sha256sha256(i),o=new Se().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}};B.prototype.createSpendingTx=function(e,t,r){var i=t||this.address,n=r||e.satoshis-500,o=new ti;o.addInput(new Ho({prevTxId:e.txid,outputIndex:e.vout,script:Se.empty()}),Se.fromHex(e.script),e.satoshis),o.to(i,n);var s=Se.fromHex(e.script),a=ei.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 Se().add(c).add(d);return o.inputs[0].setScript(g),o};B.prototype.validate=function(e,t){var r=new Ce,i=Ce.SCRIPT_VERIFY_P2SH|Ce.SCRIPT_VERIFY_STRICTENC|Ce.SCRIPT_VERIFY_DERSIG|Ce.SCRIPT_VERIFY_LOW_S|Ce.SCRIPT_ENABLE_SIGHASH_FORKID,n=e.inputs[0].script,o=Se.fromHex(t.script),s=r.verify(n,o,e,0,i,new Tt(t.satoshis));return{valid:s,error:s?null:r.errstr}};B.prototype.save=function(e){if(!ce)return Co("File system operations not available in browser environment"),e;var t=this.list();return t.push(e),ce.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 ce.existsSync(this.covenantUtxoPath)?JSON.parse(ce.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(){ce.existsSync(this.storageDir)||ce.mkdirSync(this.storageDir,{recursive:!0})};B.reconstructP2pkhScript=function(e){return Se.buildPublicKeyHashOut(e).toHex()};ri.exports=B});var Ve=P((uc,ni)=>{f();ni.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.PrivateKey});var te=P((lc,si)=>{"use strict";f();var Ro=Ee(),Lo=M(),Bo=D(),No=Ve(),oi=b(),hc=C();function y(e,t){if(!(this instanceof y))return new y(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()}y.LEFT_FIXED_LENGTH=104;y.RIGHT_FIXED_LENGTH=52;y.MIN_PREIMAGE_LENGTH=y.LEFT_FIXED_LENGTH+1+y.RIGHT_FIXED_LENGTH;y.prototype.extract=function(e){return this.strategy=e||this.strategy,this._extractFields(),this.fields};y.prototype.getSighashInfo=function(){return this.fields||this._extractFields(),this.sighashInfo};y.prototype.getField=function(e){return this.fields||this._extractFields(),this.fields[e]};y.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}};y.prototype.generateASM=function(e,t){var r=this._parsePreimageStructure();return this._generateBidirectionalASM(e,r,t)};y.prototype.extractFields=function(e){var t={};return e.forEach(function(r){t[r]=this.extractField(r)}.bind(this)),t};y.prototype.validate=function(){var e=[],t=[];if(this.preimage.length<y.MIN_PREIMAGE_LENGTH)return e.push("Preimage too short: "+this.preimage.length+" bytes (BIP-143 preimage requires at least "+y.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}};y.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()}};y.prototype._extractFields=function(){if(this.fields={},this.sighashInfo={flag:null,hasZeroHashes:!1,zeroFields:[],warnings:[]},this.preimage.length<y.MIN_PREIMAGE_LENGTH)throw new Error("Preimage too short: "+this.preimage.length+" bytes (BIP-143 preimage requires at least "+y.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}};y.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=y.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)};y.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=y.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)};y.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(" | ")}};y.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=y.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(v,x){return v+x.len},0),m=n.reduce(function(v,x){return v+x.len},0);return r._structure={leftFixed:g,scriptLenVarint:a.bytes,scriptCode:r.scriptLen,rightFixed:m,totalCalculated:g+a.bytes+r.scriptLen+m,totalActual:e.length},r};y.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)};y.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(`
|
|
2
|
-
`)};
|
|
3
|
-
`)};
|
|
4
|
-
`)};
|
|
5
|
-
`)};y.prototype._extractSpecificField=function(e,t){var r=t[e];return r?u.Buffer.from(r,"hex"):null};y.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};y.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"};y.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")};y.fromTransaction=function(e,t,r,i,n){var o=Ro.sighashPreimage(e,n,t,r,new Lo(i));return new y(o,{transaction:e,inputIndex:t,subscript:r,satoshis:i,sighashType:n})};y.createExample=function(e){var t=No.fromRandom(),r=t.toAddress(),i={txId:"0".repeat(64),outputIndex:0,script:oi.buildPublicKeyHashOut(r).toHex(),satoshis:1e5},n=new Bo().from(i).to(r,99e3),o=oi.fromHex(i.script);return y.fromTransaction(n,0,o,i.satoshis,e)};y.extractFromHex=function(e,t,r){var i=new y(e,{deferExtraction:!0});return i.extractField(t,r)};y.generateASMFromHex=function(e,t,r){var i=new y(e,{deferExtraction:!0});return i.generateASM(t,r)};y.extractMultipleFromHex=function(e,t){var r=new y(e,{deferExtraction:!0});return r.extractFields(t)};y.validateFromHex=function(e){var t=new y(e);return t.validate()};y.analyzeFromHex=function(e){var t=new y(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}}}};si.exports=y});var ui=P((fc,ci)=>{"use strict";f();var z=we(),Uo=M(),qo=D(),Do=Ve(),ai=b(),Mo=Ee();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=Do.fromRandom(),t=e.toAddress(),r={txId:"a".repeat(64),outputIndex:0,script:ai.buildPublicKeyHashOut(t).toHex(),satoshis:1e5},i=new qo().from(r).to(t,99e3),n=ai.fromHex(r.script),o=Mo.sighashPreimage(i,this.sighashType,0,n,new Uo(r.satoshis)),s=te(),a=new s(o);return{transaction:i,preimage:a,sighashType:this.sighashType,analysis:this.analysis,zeroHashBehavior:this.getZeroHashBehavior(),fields:a.extract(),validation:a.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"}};ci.exports=N});var di=P((mc,li)=>{"use strict";f();var At=Ee(),Re=me(),pi=we(),hi=ge(),tt=M(),Go=D(),ye=b();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||pi.SIGHASH_ALL|pi.SIGHASH_FORKID}k.prototype._assertEnforcingAllowed=function(){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=At.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};k.prototype.createCovenant=function(e,t){this._assertEnforcingAllowed(),t=t||{};var r=new Go().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=At.sighashPreimage(r,this.sighashType,0,i,new tt(e.satoshis)),o=te(),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}}};k.prototype.validateSpending=function(e,t){var r={valid:!0,errors:[],warnings:[],fieldValidations:[]},i=ye.fromHex(t.script),n=At.sighashPreimage(e,this.sighashType,0,i,new tt(t.satoshis)),o=te(),s=new o(n),a=s.extract();t.validationRules&&t.validationRules.forEach(function(x){var ne=this._validateFieldRule(x,a,t.preimageFields);r.fieldValidations.push(ne),!ne.passed&&x.required&&(r.valid=!1,r.errors.push(ne.error))}.bind(this));var c=new Re,d=Re.SCRIPT_VERIFY_P2SH|Re.SCRIPT_VERIFY_STRICTENC|Re.SCRIPT_VERIFY_DERSIG|Re.SCRIPT_VERIFY_LOW_S|Re.SCRIPT_ENABLE_SIGHASH_FORKID,g=e.inputs[0].script,m=ye.fromHex(t.script),v=c.verify(g,m,e,0,d,new tt(t.satoshis));return v||(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=hi.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||hi.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 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}};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};li.exports=k});var gi=P((yc,fi)=>{f();fi.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Networks});var Si=P((Pc,mi)=>{f();mi.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.crypto.Random});var Oi=P((vc,yi)=>{f();yi.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv});var Ei=P((Ec,Ht)=>{f();var w=function(){(typeof S.default<"u"&&S.default.env&&S.default.env.BSV_DEBUG||typeof window<"u"&&window.BSV_DEBUG)&&console.log.apply(console,arguments)},Vo,Oe,bt,Le;if(typeof window>"u"&&typeof R=="function")try{Oe=C(),bt=C(),Le=bt.join(__dirname,"blockchain-state.json")}catch{w("BlockchainState: Running in browser mode - persistence disabled")}else Vo=typeof window<"u"&&window.bsv||Oi();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 Be(){try{if(!Oe||!Le)return rt();if(!Oe.existsSync(Le)){w("\u{1F195} Creating new blockchain state...");let t=rt();return Ne(t),t}let e=JSON.parse(Oe.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 Ne(e){try{e.metadata.lastUpdated=new Date().toISOString(),Oe&&Le&&(Oe.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 Pi(e,t){w(`\u{1F4DD} Registering wallet: ${e}`);let r=Be();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,kt(r),Ne(r),w(`\u2705 Wallet registered: ${e}`),r}function xi(e,t){let r=Be(),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 Ko(e,t){let r=xi(e,t);return r.exists&&!r.spent}function zo(e,t,r){let i=Be(),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))),kt(i),Ne(i),w(`\u274C UTXO spent: ${n} in tx ${r}`)}function Yo(e,t){let r=Be(),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),kt(r),Ne(r),w(`\u2705 UTXO added: ${i} for ${t}`)}function kt(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 vi(){let e=Be();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 _i(){let e=bt.join(__dirname,"wallet.json");if(!Oe.existsSync(e))return w("\u274C No wallet.json found to import"),!1;try{let t=JSON.parse(Oe.readFileSync(e,"utf8"));w("\u{1F4E5} Importing wallet from wallet.json...");let r={registeredAt:new Date().toISOString(),utxos:t.availableUTXOs||[t.utxo]};return Pi(t.wallet.address,r),w("\u2705 Wallet imported successfully"),!0}catch(t){return console.error("\u274C Error importing wallet:",t.message),!1}}if(R.main===Ht){let e=S.default.argv.slice(2);if(e[0]==="import")_i();else if(e[0]==="init"){let t=rt();Ne(t),w("\u{1F195} Initialized new blockchain state")}vi()}Ht.exports={loadBlockchainState:Be,saveBlockchainState:Ne,registerWallet:Pi,getUTXO:xi,isUTXOAvailable:Ko,spendUTXO:zo,addUTXO:Yo,getBlockchainStats:vi,importWalletFromFile:_i}});var Ti=P((Tc,Ii)=>{"use strict";f();var X=function(){(typeof S.default<"u"&&S.default.env&&S.default.env.BSV_DEBUG||typeof window<"u"&&window.BSV_DEBUG)&&console.log.apply(console,arguments)},$o=b(),Xo=It(),jo=Si(),Ft,wi,Wo,ue;if(typeof window>"u"&&typeof R=="function")try{Ft=C(),wi=C(),Wo=C(),ue=Ei()}catch{X("SmartUTXO: Running in browser mode - some features may be limited")}var Ct=class{constructor(t={}){this.options=t||{},this.loadState()}loadState(){try{return ue.loadBlockchainState()}catch(t){return X("\u26A0\uFE0F Could not load blockchain state:",t.message),null}}saveState(){try{let t=ue.loadBlockchainState();ue.saveBlockchainState(t);let r=Object.keys(t.globalUTXOSet||{}).length;X(`\u{1F4BE} Saved blockchain state with ${r} UTXOs`)}catch(t){X("\u26A0\uFE0F Could not save blockchain state:",t.message)}}getUTXOsForAddress(t){try{let r=ue.loadBlockchainState();return!r.wallets||!r.wallets[t]?[]:r.wallets[t].utxos||[]}catch(r){return X("\u26A0\uFE0F Error getting UTXOs:",r.message),[]}}addUTXO(t){try{ue.addUTXO(t,t.address)}catch(r){X("\u26A0\uFE0F Error adding UTXO:",r.message)}}spendUTXOs(t,r="manual-spend"){try{for(let i of t)ue.spendUTXO(i.txid,i.vout,r)}catch(i){X("\u26A0\uFE0F Error spending UTXOs:",i.message)}}createMockUTXOs(t,r=5,i=1e5){let n=$o.buildPublicKeyHashOut(Xo.fromString(t)).toHex(),o=[];for(let s=0;s<r;s++)o.push({txid:jo.getRandomBuffer(32).toString("hex"),vout:s,address:t,satoshis:i,script:n});return o}getBalance(t){try{let r=ue.loadBlockchainState();return!r.wallets||!r.wallets[t]?0:r.wallets[t].totalValue||0}catch(r){return X("\u26A0\uFE0F Error getting balance:",r.message),0}}getStats(){try{let t=ue.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 X("\u26A0\uFE0F Error getting stats:",t.message),{totalUTXOs:0,totalValue:0,totalWallets:0,blockHeight:0}}}reset(){try{let t=wi.join(__dirname,"../utilities/blockchain-state.json");Ft.existsSync(t)&&(Ft.unlinkSync(t),X("\u{1F504} Blockchain state reset"))}catch(t){X("\u26A0\uFE0F Could not reset blockchain state:",t.message)}}};Ii.exports=Ct});var ki=P((kc,bi)=>{"use strict";f();var Qo=Ee(),Ai=we(),Zo=M(),Jo=D(),es=Ve(),ts=gi(),Ue=b(),rs=C();function G(e){if(!(this instanceof G))return new G(e);this.options=e||{},this.network=this.options.network||ts.mainnet,this.keyRing={},this.utxoPool=[];try{var t=Ti();this.smartUTXO=new t(this.options)}catch{}}G.prototype.generateKeypair=function(e){e=e||"key_"+Date.now();var t=es.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=[],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};G.prototype._createSingleUTXO=function(e){var t=rs.randomBytes(32).toString("hex"),r,i;switch(e.scriptType){case"P2PKH":r=Ue.buildPublicKeyHashOut(e.keypair.address),i=r.toHex();break;case"P2SH":var n=Ue.buildMultisigOut([e.keypair.publicKey],1);r=Ue.buildScriptHashOut(n),i=r.toHex();break;case"CUSTOM":r=e.customScript||Ue.buildPublicKeyHashOut(e.keypair.address),i=r.toHex();break;default:r=Ue.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(a,c){return a+c.satoshis},0),i=new Jo;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||Ai.SIGHASH_ALL|Ai.SIGHASH_FORKID;var d=t[a];return Qo.sighashPreimage(i,c,a,Ue.fromHex(d.script),new Zo(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),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=te();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}}}};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=te();return n.generateASMFromHex(r.preimage.hex,i)}catch(o){throw new Error("Cannot generate ASM: "+o.message)}}}};bi.exports=G});var Ke=P((Fc,Hi)=>{f();Hi.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Transaction.Output});var V=P((Rc,Fi)=>{f();Fi.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Opcode});var Li=P((Bc,Ri)=>{"use strict";f();var Ci=Ke(),is=Fe(),Rt=me(),ns=M(),os=D(),ss=V(),Pe=b();function H(e){if(!(this instanceof H))return new H(e);this.options=e||{},this.flags=this.options.flags||Rt.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 Rt,o=new ns(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}}};H.prototype.debug=function(e){var t=this._createCombinedScript(e),r=this._createDummyTransaction(),i=new Rt;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=ss.reverseMap[a.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 m=i.stack.map(function(x){return x.toString("hex")}),v=i.altstack.map(function(x){return x.toString("hex")});n.push({step:s+1,opcode:c,beforeStack:d,afterStack:m,beforeAltStack:g,afterAltStack:v,success:!0,error:null})}catch(x){n.push({step:s+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=te(),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}}}};H.prototype._parseScript=function(e){if(!e)return new Pe;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 Pe().add(u.Buffer.from(t,"hex")):Pe.fromHex(t)}else return Pe.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 Pe.fromBuffer(i)};H.prototype._createDummyTransaction=function(){var e=new os,t=new is({prevTxId:"0".repeat(64),outputIndex:0,script:Pe.empty(),satoshis:this.satoshis,output:new Ci({satoshis:this.satoshis,script:Pe.empty()})});return e.addInput(t),e.addOutput(new Ci({satoshis:this.satoshis,script:Pe.empty()})),e};H.prototype._buildCovenantScript=function(e,t){var r=[];try{var i=te();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)}};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,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};H.prototype._analyzeConstraints=function(e,t){var r={};try{var i=te();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};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)};Ri.exports=H});var Bt=P((Uc,Lt)=>{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}},j={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")}}},ze={getByCategory:e=>Object.entries(j).filter(([t,r])=>r.category===e).reduce((t,[r,i])=>({...t,[r]:i}),{}),getCategories:()=>{let e=new Set;return Object.values(j).forEach(t=>e.add(t.category)),Array.from(e).sort()},createASM:e=>{let t=[];return e.forEach(r=>{if(typeof r=="string"&&j[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(!j[o])throw new Error(`Unknown opcode: ${o}`);let a=j[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(j).find(([r,i])=>i.code===e);return t?t[0]:`UNKNOWN_${e.toString(16).padStart(2,"0")}`},nameToOpcode:e=>j[e]&&j[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:ze.createASM(r),description:`Extract ${e} field and compare with expected value`}}};Lt.exports={opcodeMap:j,scriptNum:l,utils:ze};if(R.main===Lt){console.log("\u{1F527} Comprehensive Bitcoin Script Opcode Map"),console.log("=========================================="),console.log(`Total opcodes mapped: ${Object.keys(j).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=
|
|
1
|
+
var bsvSmartContract=(()=>{var Dn=Object.create;var lr=Object.defineProperty;var Mn=Object.getOwnPropertyDescriptor;var Gn=Object.getOwnPropertyNames;var Vn=Object.getPrototypeOf,zn=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 Kn=(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 $n=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Gn(t))!zn.call(e,n)&&n!==r&&lr(e,n,{get:()=>t[n],enumerable:!(i=Mn(t,n))||i.enumerable});return e};var dr=(e,t,r)=>(r=e!=null?Dn(Vn(e)):{},$n(t||!e||!e.__esModule?lr(r,"default",{value:e,enumerable:!0}):r,e));var Sr=O((Ia,yr)=>{f();var T=yr.exports={},j,W;function dt(){throw new Error("setTimeout has not been defined")}function ft(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?j=setTimeout:j=dt}catch{j=dt}try{typeof clearTimeout=="function"?W=clearTimeout:W=ft}catch{W=ft}})();function fr(e){if(j===setTimeout)return setTimeout(e,0);if((j===dt||!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 Yn(e){if(W===clearTimeout)return clearTimeout(e);if((W===ft||!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=[],we=!1,xe,We=-1;function Xn(){!we||!xe||(we=!1,xe.length?ie=xe.concat(ie):We=-1,ie.length&&gr())}function gr(){if(!we){var e=fr(Xn);we=!0;for(var t=ie.length;t;){for(xe=ie,ie=[];++We<t;)xe&&xe[We].run();We=-1,t=ie.length}xe=null,we=!1,Yn(e)}}T.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 mr(e,t)),ie.length===1&&!we&&fr(gr)};function mr(e,t){this.fun=e,this.array=t}mr.prototype.run=function(){this.fun.apply(null,this.array)};T.title="browser";T.browser=!0;T.env={};T.argv=[];T.version="";T.versions={};function ne(){}T.on=ne;T.addListener=ne;T.once=ne;T.off=ne;T.removeListener=ne;T.removeAllListeners=ne;T.emit=ne;T.prependListener=ne;T.prependOnceListener=ne;T.listeners=function(e){return[]};T.binding=function(e){throw new Error("process.binding is not supported")};T.cwd=function(){return"/"};T.chdir=function(e){throw new Error("process.chdir is not supported")};T.umask=function(){return 0}});var vr=O(Qe=>{"use strict";f();Qe.byteLength=Wn;Qe.toByteArray=Zn;Qe.fromByteArray=to;var Q=[],V=[],jn=typeof Uint8Array<"u"?Uint8Array:Array,gt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Oe=0,xr=gt.length;Oe<xr;++Oe)Q[Oe]=gt[Oe],V[gt.charCodeAt(Oe)]=Oe;var Oe,xr;V[45]=62;V[95]=63;function Or(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 Wn(e){var t=Or(e),r=t[0],i=t[1];return(r+i)*3/4-i}function Qn(e,t,r){return(t+r)*3/4-r}function Zn(e){var t,r=Or(e),i=r[0],n=r[1],o=new jn(Qn(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 Jn(e){return Q[e>>18&63]+Q[e>>12&63]+Q[e>>6&63]+Q[e&63]}function eo(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(Jn(i));return n.join("")}function to(e){for(var t,r=e.length,i=r%3,n=[],o=16383,s=0,a=r-i;s<a;s+=o)n.push(eo(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 Pr=O(mt=>{f();mt.read=function(e,t,r,i,n){var o,s,a=n*8-i-1,c=(1<<a)-1,d=c>>1,g=-7,m=r?n-1:0,P=r?-1:1,v=e[t+m];for(m+=P,o=v&(1<<-g)-1,v>>=-g,g+=a;g>0;o=o*256+e[t+m],m+=P,g-=8);for(s=o&(1<<-g)-1,o>>=-g,g+=i;g>0;s=s*256+e[t+m],m+=P,g-=8);if(o===0)o=1-d;else{if(o===c)return s?NaN:(v?-1:1)*(1/0);s=s+Math.pow(2,i),o=o-d}return(v?-1:1)*s*Math.pow(2,o-i)};mt.write=function(e,t,r,i,n,o){var s,a,c,d=o*8-n-1,g=(1<<d)-1,m=g>>1,P=n===23?Math.pow(2,-24)-Math.pow(2,-77):0,v=i?0:o-1,re=i?1:-1,qn=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+m>=1?t+=P/c:t+=P*Math.pow(2,1-m),t*c>=2&&(s++,c/=2),s+m>=g?(a=0,s=g):s+m>=1?(a=(t*c-1)*Math.pow(2,n),s=s+m):(a=t*Math.pow(2,m-1)*Math.pow(2,n),s=0));n>=8;e[r+v]=a&255,v+=re,a/=256,n-=8);for(s=s<<n|a,d+=n;d>0;e[r+v]=s&255,v+=re,s/=256,d-=8);e[r+v-re]|=qn*128}});var qr=O(be=>{"use strict";f();var yt=vr(),Ie=Pr(),_r=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;be.Buffer=p;be.SlowBuffer=ao;be.INSPECT_MAX_BYTES=50;var Ze=2147483647;be.kMaxLength=Ze;p.TYPED_ARRAY_SUPPORT=ro();!p.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 ro(){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(p.prototype,"parent",{enumerable:!0,get:function(){if(p.isBuffer(this))return this.buffer}});Object.defineProperty(p.prototype,"offset",{enumerable:!0,get:function(){if(p.isBuffer(this))return this.byteOffset}});function oe(e){if(e>Ze)throw new RangeError('The value "'+e+'" is invalid for option "size"');let t=new Uint8Array(e);return Object.setPrototypeOf(t,p.prototype),t}function p(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 vt(e)}return Ir(e,t,r)}p.poolSize=8192;function Ir(e,t,r){if(typeof e=="string")return no(e,t);if(ArrayBuffer.isView(e))return oo(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 p.from(i,t,r);let n=so(e);if(n)return n;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof e[Symbol.toPrimitive]=="function")return p.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)}p.from=function(e,t,r){return Ir(e,t,r)};Object.setPrototypeOf(p.prototype,Uint8Array.prototype);Object.setPrototypeOf(p,Uint8Array);function Ar(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 io(e,t,r){return Ar(e),e<=0?oe(e):t!==void 0?typeof r=="string"?oe(e).fill(t,r):oe(e).fill(t):oe(e)}p.alloc=function(e,t,r){return io(e,t,r)};function vt(e){return Ar(e),oe(e<0?0:Pt(e)|0)}p.allocUnsafe=function(e){return vt(e)};p.allocUnsafeSlow=function(e){return vt(e)};function no(e,t){if((typeof t!="string"||t==="")&&(t="utf8"),!p.isEncoding(t))throw new TypeError("Unknown encoding: "+t);let r=br(e,t)|0,i=oe(r),n=i.write(e,t);return n!==r&&(i=i.slice(0,n)),i}function St(e){let t=e.length<0?0:Pt(e.length)|0,r=oe(t);for(let i=0;i<t;i+=1)r[i]=e[i]&255;return r}function oo(e){if(Z(e,Uint8Array)){let t=new Uint8Array(e);return xt(t.buffer,t.byteOffset,t.byteLength)}return St(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,p.prototype),i}function so(e){if(p.isBuffer(e)){let t=Pt(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"||Et(e.length)?oe(0):St(e);if(e.type==="Buffer"&&Array.isArray(e.data))return St(e.data)}function Pt(e){if(e>=Ze)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Ze.toString(16)+" bytes");return e|0}function ao(e){return+e!=e&&(e=0),p.alloc(+e)}p.isBuffer=function(t){return t!=null&&t._isBuffer===!0&&t!==p.prototype};p.compare=function(t,r){if(Z(t,Uint8Array)&&(t=p.from(t,t.offset,t.byteLength)),Z(r,Uint8Array)&&(r=p.from(r,r.offset,r.byteLength)),!p.isBuffer(t)||!p.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};p.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}};p.concat=function(t,r){if(!Array.isArray(t))throw new TypeError('"list" argument must be an Array of Buffers');if(t.length===0)return p.alloc(0);let i;if(r===void 0)for(r=0,i=0;i<t.length;++i)r+=t[i].length;let n=p.allocUnsafe(r),o=0;for(i=0;i<t.length;++i){let s=t[i];if(Z(s,Uint8Array))o+s.length>n.length?(p.isBuffer(s)||(s=p.from(s)),s.copy(n,o)):Uint8Array.prototype.set.call(n,s,o);else if(p.isBuffer(s))s.copy(n,o);else throw new TypeError('"list" argument must be an Array of Buffers');o+=s.length}return n};function br(e,t){if(p.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 Ur(e).length;default:if(n)return i?-1:Ot(e).length;t=(""+t).toLowerCase(),n=!0}}p.byteLength=br;function co(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 xo(this,t,r);case"utf8":case"utf-8":return Hr(this,t,r);case"ascii":return yo(this,t,r);case"latin1":case"binary":return So(this,t,r);case"base64":return go(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Oo(this,t,r);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}p.prototype._isBuffer=!0;function ve(e,t,r){let i=e[t];e[t]=e[r],e[r]=i}p.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)ve(this,r,r+1);return this};p.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)ve(this,r,r+3),ve(this,r+1,r+2);return this};p.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)ve(this,r,r+7),ve(this,r+1,r+6),ve(this,r+2,r+5),ve(this,r+3,r+4);return this};p.prototype.toString=function(){let t=this.length;return t===0?"":arguments.length===0?Hr(this,0,t):co.apply(this,arguments)};p.prototype.toLocaleString=p.prototype.toString;p.prototype.equals=function(t){if(!p.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t?!0:p.compare(this,t)===0};p.prototype.inspect=function(){let t="",r=be.INSPECT_MAX_BYTES;return t=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(t+=" ... "),"<Buffer "+t+">"};_r&&(p.prototype[_r]=p.prototype.inspect);p.prototype.compare=function(t,r,i,n,o){if(Z(t,Uint8Array)&&(t=p.from(t,t.offset,t.byteLength)),!p.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 m=0;m<c;++m)if(d[m]!==g[m]){s=d[m],a=g[m];break}return s<a?-1:a<s?1:0};function kr(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,Et(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=p.from(t,i)),p.isBuffer(t))return t.length===0?-1:Er(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):Er(e,[t],r,i,n);throw new TypeError("val must be string, number or Buffer")}function Er(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,m){return o===1?g[m]:g.readUInt16BE(m*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 m=0;m<a;m++)if(c(e,d+m)!==c(t,m)){g=!1;break}if(g)return d}return-1}p.prototype.includes=function(t,r,i){return this.indexOf(t,r,i)!==-1};p.prototype.indexOf=function(t,r,i){return kr(this,t,r,i,!0)};p.prototype.lastIndexOf=function(t,r,i){return kr(this,t,r,i,!1)};function uo(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(Et(a))return s;e[r+s]=a}return s}function po(e,t,r,i){return Je(Ot(t,e.length-r),e,r,i)}function ho(e,t,r,i){return Je(Eo(t),e,r,i)}function lo(e,t,r,i){return Je(Ur(t),e,r,i)}function fo(e,t,r,i){return Je(wo(t,e.length-r),e,r,i)}p.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 uo(this,t,r,i);case"utf8":case"utf-8":return po(this,t,r,i);case"ascii":case"latin1":case"binary":return ho(this,t,r,i);case"base64":return lo(this,t,r,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return fo(this,t,r,i);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),s=!0}};p.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function go(e,t,r){return t===0&&r===e.length?yt.fromByteArray(e):yt.fromByteArray(e.slice(t,r))}function Hr(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,m;switch(a){case 1:o<128&&(s=o);break;case 2:c=e[n+1],(c&192)===128&&(m=(o&31)<<6|c&63,m>127&&(s=m));break;case 3:c=e[n+1],d=e[n+2],(c&192)===128&&(d&192)===128&&(m=(o&15)<<12|(c&63)<<6|d&63,m>2047&&(m<55296||m>57343)&&(s=m));break;case 4:c=e[n+1],d=e[n+2],g=e[n+3],(c&192)===128&&(d&192)===128&&(g&192)===128&&(m=(o&15)<<18|(c&63)<<12|(d&63)<<6|g&63,m>65535&&m<1114112&&(s=m))}}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 mo(i)}var wr=4096;function mo(e){let t=e.length;if(t<=wr)return String.fromCharCode.apply(String,e);let r="",i=0;for(;i<t;)r+=String.fromCharCode.apply(String,e.slice(i,i+=wr));return r}function yo(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 So(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 xo(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+=To[e[o]];return n}function Oo(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}p.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,p.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")}p.prototype.readUintLE=p.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};p.prototype.readUintBE=p.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};p.prototype.readUint8=p.prototype.readUInt8=function(t,r){return t=t>>>0,r||H(t,1,this.length),this[t]};p.prototype.readUint16LE=p.prototype.readUInt16LE=function(t,r){return t=t>>>0,r||H(t,2,this.length),this[t]|this[t+1]<<8};p.prototype.readUint16BE=p.prototype.readUInt16BE=function(t,r){return t=t>>>0,r||H(t,2,this.length),this[t]<<8|this[t+1]};p.prototype.readUint32LE=p.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};p.prototype.readUint32BE=p.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])};p.prototype.readBigUInt64LE=le(function(t){t=t>>>0,Ae(t,"offset");let r=this[t],i=this[t+7];(r===void 0||i===void 0)&&Ge(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))});p.prototype.readBigUInt64BE=le(function(t){t=t>>>0,Ae(t,"offset");let r=this[t],i=this[t+7];(r===void 0||i===void 0)&&Ge(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)});p.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};p.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};p.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]};p.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};p.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};p.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};p.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]};p.prototype.readBigInt64LE=le(function(t){t=t>>>0,Ae(t,"offset");let r=this[t],i=this[t+7];(r===void 0||i===void 0)&&Ge(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)});p.prototype.readBigInt64BE=le(function(t){t=t>>>0,Ae(t,"offset");let r=this[t],i=this[t+7];(r===void 0||i===void 0)&&Ge(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)});p.prototype.readFloatLE=function(t,r){return t=t>>>0,r||H(t,4,this.length),Ie.read(this,t,!0,23,4)};p.prototype.readFloatBE=function(t,r){return t=t>>>0,r||H(t,4,this.length),Ie.read(this,t,!1,23,4)};p.prototype.readDoubleLE=function(t,r){return t=t>>>0,r||H(t,8,this.length),Ie.read(this,t,!0,52,8)};p.prototype.readDoubleBE=function(t,r){return t=t>>>0,r||H(t,8,this.length),Ie.read(this,t,!1,52,8)};function L(e,t,r,i,n,o){if(!p.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")}p.prototype.writeUintLE=p.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};p.prototype.writeUintBE=p.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};p.prototype.writeUint8=p.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};p.prototype.writeUint16LE=p.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};p.prototype.writeUint16BE=p.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};p.prototype.writeUint32LE=p.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};p.prototype.writeUint32BE=p.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 Fr(e,t,r,i,n){Nr(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 Cr(e,t,r,i,n){Nr(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}p.prototype.writeBigUInt64LE=le(function(t,r=0){return Fr(this,t,r,BigInt(0),BigInt("0xffffffffffffffff"))});p.prototype.writeBigUInt64BE=le(function(t,r=0){return Cr(this,t,r,BigInt(0),BigInt("0xffffffffffffffff"))});p.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};p.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};p.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};p.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};p.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};p.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};p.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};p.prototype.writeBigInt64LE=le(function(t,r=0){return Fr(this,t,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});p.prototype.writeBigInt64BE=le(function(t,r=0){return Cr(this,t,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Lr(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 Rr(e,t,r,i,n){return t=+t,r=r>>>0,n||Lr(e,t,r,4,34028234663852886e22,-34028234663852886e22),Ie.write(e,t,r,i,23,4),r+4}p.prototype.writeFloatLE=function(t,r,i){return Rr(this,t,r,!0,i)};p.prototype.writeFloatBE=function(t,r,i){return Rr(this,t,r,!1,i)};function Br(e,t,r,i,n){return t=+t,r=r>>>0,n||Lr(e,t,r,8,17976931348623157e292,-17976931348623157e292),Ie.write(e,t,r,i,52,8),r+8}p.prototype.writeDoubleLE=function(t,r,i){return Br(this,t,r,!0,i)};p.prototype.writeDoubleBE=function(t,r,i){return Br(this,t,r,!1,i)};p.prototype.copy=function(t,r,i,n){if(!p.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};p.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"&&!p.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=p.isBuffer(t)?t:p.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 _t(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}`}}}_t("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError);_t("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError);_t("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=Tr(String(r)):typeof r=="bigint"&&(n=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(n=Tr(n)),n+="n"),i+=` It must be ${t}. Received ${n}`,i},RangeError);function Tr(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 vo(e,t,r){Ae(t,"offset"),(e[t]===void 0||e[t+r]===void 0)&&Ge(t,e.length-(r+1))}function Nr(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)}vo(i,n,o)}function Ae(e,t){if(typeof e!="number")throw new Te.ERR_INVALID_ARG_TYPE(t,"number",e)}function Ge(e,t,r){throw Math.floor(e)!==e?(Ae(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 Po=/[^+/0-9A-Za-z-_]/g;function _o(e){if(e=e.split("=")[0],e=e.trim().replace(Po,""),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 Eo(e){let t=[];for(let r=0;r<e.length;++r)t.push(e.charCodeAt(r)&255);return t}function wo(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 Ur(e){return yt.toByteArray(_o(e))}function Je(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 Et(e){return e!==e}var To=(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 le(e){return typeof BigInt>"u"?Io:e}function Io(){throw new Error("BigInt not supported")}});var y,u,f=Kn(()=>{y=dr(Sr()),u=dr(qr())});var de=O((Na,Dr)=>{f();Dr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.crypto.Hash});var q=O((qa,Mr)=>{f();Mr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Transaction});var wt=O((Ma,Gr)=>{f();Gr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Address});var A=O((Va,Vr)=>{f();Vr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Script});var Pe=O((Ka,zr)=>{f();zr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Transaction.sighash});var ke=O((Ya,Kr)=>{f();Kr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Transaction.Input});var fe=O((ja,$r)=>{f();$r.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Script.Interpreter});var _e=O((Qa,Yr)=>{f();Yr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.crypto.Signature});var D=O((Ja,Xr)=>{f();Xr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.crypto.BN});var F=O((tc,jr)=>{"use strict";f();jr.exports={}});var ti=O((ic,ei)=>{"use strict";f();var Zr=Pe(),Ao=ke(),He=fe(),Wr=_e(),bo=de(),Tt=D(),Jr=q(),ge=A(),Qr=F(),se;try{se=F()}catch{se=null}var ko=function(){var e=typeof y.default<"u"&&y.default.env&&y.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 y.default<"u"?Qr.join(y.default.cwd(),".bsv-covenants"):".bsv-covenants"),this.covenantUtxoPath=Qr.join(this.storageDir,"covenant_utxos.json"),this.sighashType=Wr.SIGHASH_ALL|Wr.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 Jr().from({txId:e.txid,outputIndex:e.vout,script:e.script,satoshis:e.satoshis}).to(this.address,e.satoshis-1e3),r=ge.fromHex(e.script),i=Zr.sighashPreimage(t,this.sighashType,0,r,new Tt(e.satoshis)),n=bo.sha256sha256(i),o=new ge().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 Jr;o.addInput(new Ao({prevTxId:e.txid,outputIndex:e.vout,script:ge.empty()}),ge.fromHex(e.script),e.satoshis),o.to(i,n);var s=ge.fromHex(e.script),a=Zr.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 ge().add(c).add(d);return o.inputs[0].setScript(g),o};R.prototype.validate=function(e,t){var r=new He,i=He.SCRIPT_VERIFY_P2SH|He.SCRIPT_VERIFY_STRICTENC|He.SCRIPT_VERIFY_DERSIG|He.SCRIPT_VERIFY_LOW_S|He.SCRIPT_ENABLE_SIGHASH_FORKID,n=e.inputs[0].script,o=ge.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 ko("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 ge.buildPublicKeyHashOut(e).toHex()};ei.exports=R});var Ve=O((oc,ri)=>{f();ri.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.PrivateKey});var J=O((cc,ni)=>{"use strict";f();var Ho=Pe(),Fo=D(),Co=q(),Lo=Ve(),ii=A(),ac=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,v){return P+v.len},0),m=n.reduce(function(P,v){return P+v.len},0);return r._structure={leftFixed:g,scriptLenVarint:a.bytes,scriptCode:r.scriptLen,rightFixed:m,totalCalculated:g+a.bytes+r.scriptLen+m,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(`
|
|
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
|
+
`)};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
|
+
`)};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=Ho.sighashPreimage(e,n,t,r,new Fo(i));return new S(o,{transaction:e,inputIndex:t,subscript:r,satoshis:i,sighashType:n})};S.createExample=function(e){var t=Lo.fromRandom(),r=t.toAddress(),i={txId:"0".repeat(64),outputIndex:0,script:ii.buildPublicKeyHashOut(r).toHex(),satoshis:1e5},n=new Co().from(i).to(r,99e3),o=ii.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}}}};ni.exports=S});var ai=O((pc,si)=>{"use strict";f();var z=_e(),Ro=D(),Bo=q(),No=Ve(),oi=A(),Uo=Pe();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=No.fromRandom(),t=e.toAddress(),r={txId:"a".repeat(64),outputIndex:0,script:oi.buildPublicKeyHashOut(t).toHex(),satoshis:1e5},i=new Bo().from(r).to(t,99e3),n=oi.fromHex(r.script),o=Uo.sighashPreimage(i,this.sighashType,0,n,new Ro(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"}};si.exports=B});var hi=O((lc,pi)=>{"use strict";f();var It=Pe(),Fe=fe(),ci=_e(),ui=de(),et=D(),qo=q(),me=A();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||ci.SIGHASH_ALL|ci.SIGHASH_FORKID}b.prototype._assertEnforcingAllowed=function(){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 me;return this.scriptTemplate?this._buildFromTemplate(e):this._buildMultiFieldCovenant(e)};b.prototype.buildUnlockingScript=function(e,t,r){var i=new me,n=me.fromHex(r.script),o=It.sign(e,this.privateKey,this.sighashType,t,n,new et(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 qo().from({txId:e.txid,outputIndex:e.vout,script:e.script,satoshis:e.satoshis}).to(this.privateKey.toAddress(),e.satoshis-(t.fee||1e3)),i=me.fromHex(e.script),n=It.sighashPreimage(r,this.sighashType,0,i,new et(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=me.fromHex(t.script),n=It.sighashPreimage(e,this.sighashType,0,i,new et(t.satoshis)),o=J(),s=new o(n),a=s.extract();t.validationRules&&t.validationRules.forEach(function(v){var re=this._validateFieldRule(v,a,t.preimageFields);r.fieldValidations.push(re),!re.passed&&v.required&&(r.valid=!1,r.errors.push(re.error))}.bind(this));var c=new Fe,d=Fe.SCRIPT_VERIFY_P2SH|Fe.SCRIPT_VERIFY_STRICTENC|Fe.SCRIPT_VERIFY_DERSIG|Fe.SCRIPT_VERIFY_LOW_S|Fe.SCRIPT_ENABLE_SIGHASH_FORKID,g=e.inputs[0].script,m=me.fromHex(t.script),P=c.verify(g,m,e,0,d,new et(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 me;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=ui.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 me;r.add("OP_DUP"),r.add("OP_HASH256");var i=t.hash||ui.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};pi.exports=b});var di=O((fc,li)=>{f();li.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Networks});var gi=O((mc,fi)=>{f();fi.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.crypto.Random});var yi=O((Sc,mi)=>{f();mi.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv});var Pi=O((Oc,kt)=>{f();var w=function(){(typeof y.default<"u"&&y.default.env&&y.default.env.BSV_DEBUG||typeof window<"u"&&window.BSV_DEBUG)&&console.log.apply(console,arguments)},Do,ye,At,Ce;if(typeof window>"u"&&typeof C=="function")try{ye=F(),At=F(),Ce=At.join(__dirname,"blockchain-state.json")}catch{w("BlockchainState: Running in browser mode - persistence disabled")}else Do=typeof window<"u"&&window.bsv||yi();function tt(){return{metadata:{createdAt:new Date().toISOString(),lastUpdated:new Date().toISOString(),totalWallets:0,totalUTXOs:0,totalValue:0,blockHeight:0},wallets:{},globalUTXOSet:{},spentUTXOs:{},transactionHistory:[]}}function Le(){try{if(!ye||!Ce)return tt();if(!ye.existsSync(Ce)){w("\u{1F195} Creating new blockchain state...");let t=tt();return Re(t),t}let e=JSON.parse(ye.readFileSync(Ce,"utf8"));return w("\u{1F4D6} Loaded existing blockchain state"),e}catch(e){return console.error("\u274C Error loading blockchain state:",e.message),tt()}}function Re(e){try{e.metadata.lastUpdated=new Date().toISOString(),ye&&Ce&&(ye.writeFileSync(Ce,JSON.stringify(e,null,2)),w("\u{1F4BE} Blockchain state saved"))}catch(t){console.error("\u274C Error saving blockchain state:",t.message)}}function Si(e,t){w(`\u{1F4DD} Registering wallet: ${e}`);let r=Le();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,bt(r),Re(r),w(`\u2705 Wallet registered: ${e}`),r}function xi(e,t){let r=Le(),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 Mo(e,t){let r=xi(e,t);return r.exists&&!r.spent}function Go(e,t,r){let i=Le(),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))),bt(i),Re(i),w(`\u274C UTXO spent: ${n} in tx ${r}`)}function Vo(e,t){let r=Le(),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),bt(r),Re(r),w(`\u2705 UTXO added: ${i} for ${t}`)}function bt(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 Oi(){let e=Le();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 vi(){let e=At.join(__dirname,"wallet.json");if(!ye.existsSync(e))return w("\u274C No wallet.json found to import"),!1;try{let t=JSON.parse(ye.readFileSync(e,"utf8"));w("\u{1F4E5} Importing wallet from wallet.json...");let r={registeredAt:new Date().toISOString(),utxos:t.availableUTXOs||[t.utxo]};return Si(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===kt){let e=y.default.argv.slice(2);if(e[0]==="import")vi();else if(e[0]==="init"){let t=tt();Re(t),w("\u{1F195} Initialized new blockchain state")}Oi()}kt.exports={loadBlockchainState:Le,saveBlockchainState:Re,registerWallet:Si,getUTXO:xi,isUTXOAvailable:Mo,spendUTXO:Go,addUTXO:Vo,getBlockchainStats:Oi,importWalletFromFile:vi}});var wi=O((_c,Ei)=>{"use strict";f();var Y=function(){(typeof y.default<"u"&&y.default.env&&y.default.env.BSV_DEBUG||typeof window<"u"&&window.BSV_DEBUG)&&console.log.apply(console,arguments)},zo=A(),Ko=wt(),$o=gi(),Ht,_i,Yo,ae;if(typeof window>"u"&&typeof C=="function")try{Ht=F(),_i=F(),Yo=F(),ae=Pi()}catch{Y("SmartUTXO: Running in browser mode - some features may be limited")}var Ft=class{constructor(t={}){this.options=t||{},this.loadState()}loadState(){try{return ae.loadBlockchainState()}catch(t){return Y("\u26A0\uFE0F Could not load blockchain state:",t.message),null}}saveState(){try{let t=ae.loadBlockchainState();ae.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=ae.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{ae.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)ae.spendUTXO(i.txid,i.vout,r)}catch(i){Y("\u26A0\uFE0F Error spending UTXOs:",i.message)}}createMockUTXOs(t,r=5,i=1e5){let n=zo.buildPublicKeyHashOut(Ko.fromString(t)).toHex(),o=[];for(let s=0;s<r;s++)o.push({txid:$o.getRandomBuffer(32).toString("hex"),vout:s,address:t,satoshis:i,script:n});return o}getBalance(t){try{let r=ae.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=ae.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=_i.join(__dirname,"../utilities/blockchain-state.json");Ht.existsSync(t)&&(Ht.unlinkSync(t),Y("\u{1F504} Blockchain state reset"))}catch(t){Y("\u26A0\uFE0F Could not reset blockchain state:",t.message)}}};Ei.exports=Ft});var Ai=O((Tc,Ii)=>{"use strict";f();var Xo=Pe(),Ti=_e(),jo=D(),Wo=q(),Qo=Ve(),Zo=di(),Be=A(),Jo=F();function M(e){if(!(this instanceof M))return new M(e);this.options=e||{},this.network=this.options.network||Zo.mainnet,this.keyRing={},this.utxoPool=[];try{var t=wi();this.smartUTXO=new t(this.options)}catch{}}M.prototype.generateKeypair=function(e){e=e||"key_"+Date.now();var t=Qo.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=Jo.randomBytes(32).toString("hex"),r,i;switch(e.scriptType){case"P2PKH":r=Be.buildPublicKeyHashOut(e.keypair.address),i=r.toHex();break;case"P2SH":var n=Be.buildMultisigOut([e.keypair.publicKey],1);r=Be.buildScriptHashOut(n),i=r.toHex();break;case"CUSTOM":r=e.customScript||Be.buildPublicKeyHashOut(e.keypair.address),i=r.toHex();break;default:r=Be.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 Wo;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||Ti.SIGHASH_ALL|Ti.SIGHASH_FORKID;var d=t[a];return Xo.sighashPreimage(i,c,a,Be.fromHex(d.script),new jo(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)}}}};Ii.exports=M});var ze=O((Ac,bi)=>{f();bi.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Transaction.Output});var G=O((kc,ki)=>{f();ki.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Opcode});var Ci=O((Fc,Fi)=>{"use strict";f();var Hi=ze(),es=ke(),Ct=fe(),ts=D(),rs=q(),is=G(),Se=A();function k(e){if(!(this instanceof k))return new k(e);this.options=e||{},this.flags=this.options.flags||Ct.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 Ct,o=new ts(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 Ct;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=is.reverseMap[a.opcodenum]||"PUSH",d=i.stack.map(function(v){return v.toString("hex")}),g=i.altstack.map(function(v){return v.toString("hex")});try{i.step();var m=i.stack.map(function(v){return v.toString("hex")}),P=i.altstack.map(function(v){return v.toString("hex")});n.push({step:s+1,opcode:c,beforeStack:d,afterStack:m,beforeAltStack:g,afterAltStack:P,success:!0,error:null})}catch(v){n.push({step:s+1,opcode:c,beforeStack:d,afterStack:d,beforeAltStack:g,afterAltStack:g,success:!1,error:v.message});break}}}catch(v){n.push({step:0,opcode:"INITIALIZATION",beforeStack:[],afterStack:[],beforeAltStack:[],afterAltStack:[],success:!1,error:v.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 Se;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 Se().add(u.Buffer.from(t,"hex")):Se.fromHex(t)}else return Se.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 Se.fromBuffer(i)};k.prototype._createDummyTransaction=function(){var e=new rs,t=new es({prevTxId:"0".repeat(64),outputIndex:0,script:Se.empty(),satoshis:this.satoshis,output:new Hi({satoshis:this.satoshis,script:Se.empty()})});return e.addInput(t),e.addOutput(new Hi({satoshis:this.satoshis,script:Se.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)};Fi.exports=k});var Rt=O((Lc,Lt)=>{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")}}},Ke={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:Ke.createASM(r),description:`Extract ${e} field and compare with expected value`}}};Lt.exports={opcodeMap:X,scriptNum:l,utils:Ke};if(C.main===Lt){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:`),Ke.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=Ke.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=
|
|
13
|
-
\u{1F4CA} Example 2: Custom Arithmetic Covenant`);let r=new
|
|
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 ${
|
|
17
|
-
===========================================`),console.log("\u2705 Final Result:",m?"TRUE (Success)":"\u274C FALSE (Failure)"),console.log("Final Stack:"
|
|
18
|
-
`),console.log("Script:",e.toASM()),console.log("-------------------------------------------");for(let s=0;s<n.length;s++){let a=n[s],c=
|
|
11
|
+
\u{1F3AF} Example: Covenant template generation`);let e=Ke.generateCovenantTemplate("value","50c3000000000000");console.log("Generated ASM:",e.asm),console.log("Description:",e.description)}});var Ut=O((Nc,Nt)=>{"use strict";f();var{opcodeMap:Bt,scriptNum:Li,utils:ns}=Rt(),ce=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=Li.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"):Li.encode(i).toString("hex")}return r}).join(" ")}_asmToHex(t){return t.split(" ").map(r=>Bt[r]?Bt[r].code.toString(16).padStart(2,"0"):/^[0-9a-fA-F]+$/.test(r)?r:"00").join("")}simulate(t=[]){return ns.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=Bt[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}},Ri={valueLock:e=>new ce().comment("Value Lock Covenant").comment(`Expected value: ${e}`).validateField("value",e).push(1),hashLock:e=>new ce().comment("Hash Lock Covenant").comment(`Expected hash: ${e}`).sha256().push(e).equalVerify().push(1),multiSigWithValidation:(e,t,r)=>{let i=new ce().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 ce().comment("Time Lock Covenant").comment(`Locktime: ${e}`).validateField("nLocktime",e).push(1),complexValidation:e=>{let t=new ce().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}};Nt.exports={CovenantBuilder:ce,CovenantTemplates:Ri};if(C.main===Nt){console.log("\u{1F3D7}\uFE0F Covenant Builder Demonstration"),console.log("=================================="),console.log(`
|
|
12
|
+
\u{1F4CA} Example 1: Value Lock Covenant`);let t=Ri.valueLock("50c3000000000000").build();console.log("ASM:",t.cleanedASM),console.log("Size:",t.size,"operations"),console.log(`
|
|
13
|
+
\u{1F4CA} Example 2: Custom Arithmetic Covenant`);let r=new ce().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 Di=O((Dc,qi)=>{"use strict";f();var os=G(),K=A();function Ee(e){if(u.Buffer.isBuffer(e))return K.fromBuffer(e).toASM();if(e&&typeof e.toASM=="function")return e.toASM();throw new Error("Input must be a Buffer or Script object")}function ss(e){try{return K.fromASM(e)}catch(t){throw new Error(`Invalid ASM string: ${t.message}`)}}function as(e){try{return K.fromASM(e).toBuffer().toString("hex")}catch(t){throw new Error(`Cannot convert ASM to hex: ${t.message}`)}}function cs(e){try{let t=u.Buffer.from(e,"hex");return K.fromBuffer(t).toASM()}catch(t){throw new Error(`Cannot convert hex to ASM: ${t.message}`)}}function us(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 Bi(e){try{return K.fromASM(e),{valid:!0,error:null}}catch(t){return{valid:!1,error:t.message}}}function Dt(e){try{let t;if(typeof e=="string")t=K.fromASM(e);else if(u.Buffer.isBuffer(e))t=K.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 ps(e){let t=Bi(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_")&&!os.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 qt(e){try{let t;if(typeof e=="string")t=K.fromASM(e);else if(Array.isArray(e))t=K.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 Mt(e){try{let t=Dt(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,s=i.filter(c=>!c.startsWith("OP_")&&c.length>0).length,a=0;return i.forEach(c=>{c.startsWith("OP_")&&(["OP_CHECKSIG","OP_CHECKSIGVERIFY"].includes(c)?a+=100:["OP_SHA256","OP_HASH160","OP_HASH256"].includes(c)?a+=10:a+=1)}),{length:n,size:n,operations:i.length,opcodeCount:o,opcodes:o,dataElements:s,estimatedCost:a,complexity:a>50?"high":a>10?"medium":"low",asm:r}}catch(t){return{error:t.message}}}function Ni(e){let t=Mt(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 hs(e){try{let t;typeof e=="string"?t=e:Array.isArray(e)?t=e.join(" "):t=Ee(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=qt(t),s=qt(n),a=null;try{a=K.fromASM(n)}catch{a=null}return{original:t,optimized:n,originalSize:o,optimizedSize:s,savings:o-s,improvement:o>0?((o-s)/o*100).toFixed(1)+"%":"0%",script:a}}catch(t){return{error:t.message}}}function ls(e){let t=[];try{let r;typeof e=="string"?r=e:r=Ee(e);let i=r.split(" ");for(let n=0;n<i.length-1;n++){let o=i[n],s=i[n+1];if(o==="OP_DUP"&&s==="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 a=parseInt(o,16);a>=1&&a<=16&&t.push({type:"inefficient_push",position:n,description:`Use OP_${a} 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 ds(e,t){try{let r,i;return typeof e=="string"?r=K.fromASM(e).toBuffer():u.Buffer.isBuffer(e)?r=e:r=e.toBuffer(),typeof t=="string"?i=K.fromASM(t).toBuffer():u.Buffer.isBuffer(t)?i=t:i=t.toBuffer(),{identical:r.equals(i),scriptA:{size:r.length,asm:Ee(r)},scriptB:{size:i.length,asm:Ee(i)}}}catch(r){return{error:r.message}}}function Ui(e){try{let t;typeof e=="string"?t=e:t=Ee(e);let r=t.split(" "),i=[];return r.forEach((n,o)=>{let s="";if(n.startsWith("OP_"))switch(n){case"OP_DUP":s="Duplicate the top stack item";break;case"OP_DROP":s="Remove the top stack item";break;case"OP_SWAP":s="Swap the top two stack items";break;case"OP_ADD":s="Add the top two numbers";break;case"OP_SUB":s="Subtract: second - first";break;case"OP_EQUAL":s="Check if top two items are equal";break;case"OP_VERIFY":s="Assert that top item is true (non-zero)";break;case"OP_CHECKSIG":s="Verify signature against public key";break;case"OP_SHA256":s="Calculate SHA256 hash of top item";break;case"OP_HASH160":s="Calculate RIPEMD160(SHA256(x)) hash";break;case"OP_IF":s="Begin conditional execution";break;case"OP_ELSE":s="Alternative branch of conditional";break;case"OP_ENDIF":s="End conditional execution";break;default:s=`Execute ${n}`}else n.length>0&&(s=`Push data: ${n} (${n.length/2} bytes)`);s&&i.push({operation:n,position:o,explanation:s})}),{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 fs(e){try{let t=Ui(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 gs(e,t={}){let r=[];e.forEach((n,o)=>{try{let s=Dt(n),a=Mt(n),c=Ni(n);r.push({index:o,script:typeof n=="string"?n:Ee(n),valid:s.valid,size:s.size,operations:s.operations,complexity:c.complexity,estimatedCost:a.estimatedCost,recommendations:c.recommendations})}catch(s){r.push({index:o,script:typeof n=="string"?n:"Invalid script",valid:!1,error:s.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}}qi.exports={scriptToASM:Ee,asmToScript:ss,asmToHex:as,hexToASM:cs,scriptToHex:us,validateASM:Bi,validateScript:Dt,validateSyntax:ps,estimateScriptSize:qt,scriptMetrics:Mt,analyzeComplexity:Ni,optimizeScript:hs,findOptimizations:ls,compareScripts:ds,explainScript:Ui,covenantToEnglish:fs,batchTestScripts:gs}});var Gi=O((Vc,Gt)=>{f();var N=typeof window<"u"&&window.bsv?window.bsv:null,rt=N?N.Script:A(),it=N?N.Script.Interpreter:fe(),ms=N?N.Opcode:G(),ys=N?N.Transaction:q(),Ss=N?N.Transaction.Input:ke(),xs=N?N.Transaction.Output:ze(),Os=N?N.crypto.BN:D(),Gc=F();function $e(e){return e.map(t=>t.toString("hex"))}function Mi(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=rt.fromHex(e),i=rt.fromHex(t),n=rt.fromBuffer(u.Buffer.concat([i.toBuffer(),r.toBuffer()])),o=new it,s=new ys,a=new Ss({prevTxId:"0".repeat(64),outputIndex:0,script:rt.empty()});s.addInput(a),s.addOutput(new xs({satoshis:1e5,script:r}));let c=n.chunks,d=new it;d.script=n,d.tx=s,d.nIn=0,d.flags=it.SCRIPT_ENABLE_SIGHASH_FORKID;for(let P=0;P<c.length;P++){let v=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}: ${ms.reverseMap[v.opcodenum]||"PUSH"}`),console.log("Stack:",$e(d.stack)),console.log("AltStack:",$e(d.altstack))}catch(re){console.log(`\u26A0\uFE0F Error executing opcode ${P+1}:`,re.message);break}}let g=new Os(1e5),m=o.verify(i,r,s,0,it.SCRIPT_ENABLE_SIGHASH_FORKID,g);return console.log(`
|
|
17
|
+
===========================================`),console.log("\u2705 Final Result:",m?"TRUE (Success)":"\u274C FALSE (Failure)"),console.log("Final Stack:",$e(d.stack||[])),console.log("AltStack:",$e(d.altstack||[])),console.log("==========================================="),m}catch(r){return console.error("\u274C Error in script execution:",r.message),!1}}if(typeof C<"u"&&C.main===Gt){y.default.argv.length<4&&(console.log("Usage: node stack_examiner.js <locking_script_hex> <unlocking_script_hex>"),y.default.exit(1));let e=y.default.argv[2],t=y.default.argv[3];Mi(e,t)}Gt.exports={runScript:Mi,bufferToHexArray:$e}});var Yi=O(($c,zt)=>{f();var ot=null;try{typeof window>"u"&&typeof C<"u"&&(ot=F())}catch{ot=null}var U=typeof window<"u"&&window.bsv?window.bsv:null,ue=U?U.Script:A(),st=U?U.Script.Interpreter:fe(),vs=U?U.Opcode:G(),Ps=U?U.crypto.BN:D(),_s=U?U.Transaction:q(),Es=U?U.Transaction.Input:ke(),Vi=U?U.Transaction.Output:ze();function nt(e){if(!e)return new ue;let t=e.trim(),r=/^[0-9a-fA-F]+$/.test(t.replace(/\s+/g,""));try{return r?ue.fromHex(t):ue.fromASM(t)}catch(i){console.error("\u274C Error parsing script:",i.message),y.default.exit(1)}}function Vt(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 st;i.script=e,i.tx=t,i.nIn=0,i.flags=st.SCRIPT_ENABLE_SIGHASH_FORKID;let n=e.chunks,o=null;ot&&typeof y.default<"u"&&y.default.stdin&&(o=ot.createInterface({input:y.default.stdin,output:y.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 s=0;s<n.length;s++){let a=n[s],c=vs.reverseMap[a.opcodenum]||"PUSH";r&&o?await new Promise(d=>o.question(`
|
|
19
19
|
[${s+1}/${n.length}] Step (${c}) \u2014 press Enter to execute...`,d)):r&&console.log(`
|
|
20
|
-
[${s+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}`),
|
|
21
|
-
===========================================`),console.log("\u2705 Final Stack State:"),
|
|
22
|
-
`);let i=new at,n=new ws(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 Xi(){if(typeof S.default>"u"||!S.default.argv){console.log("\u2699\uFE0F CLI mode not available in browser environment");return}let e=S.default.argv.slice(2),t=v=>{let x=e.indexOf(v);return x!==-1&&e[x+1]?e[x+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 v=u.Buffer.concat([a.toBuffer(),c.toBuffer()]);d=he.fromBuffer(v)}let g=new Is,m=new Ts({prevTxId:"0".repeat(64),outputIndex:0,script:he.empty(),satoshis:1e5,output:new zi({satoshis:1e5,script:he.empty()})});g.addInput(m),g.addOutput(new zi({satoshis:1e5,script:he.empty()})),o?await Yi(d,g,!0):s?$i(a||he.empty(),c||he.empty(),g):console.log("\u2699\uFE0F No mode specified. Use --step or --truth")}zt.exports={parseScript:ot,printStack:Kt,stepThroughScript:Yi,runFullEvaluation:$i,main:Xi};typeof R<"u"&&R.main===zt&&Xi()});var le=P((Jc,rn)=>{"use strict";f();var Qi=b(),Xt=me(),Yt=V(),$t=D(),As=Fe(),Zi=Ke(),Ji=Ee(),ct=M(),bs=ge(),Wi=we(),jt=Wi.SIGHASH_ALL|Wi.SIGHASH_FORKID;function en(){var e=Xt;return e.SCRIPT_VERIFY_P2SH|e.SCRIPT_VERIFY_STRICTENC|e.SCRIPT_VERIFY_DERSIG|e.SCRIPT_VERIFY_LOW_S|e.SCRIPT_VERIFY_MINIMALDATA|e.SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY|e.SCRIPT_VERIFY_CHECKSEQUENCEVERIFY|e.SCRIPT_ENABLE_SIGHASH_FORKID|e.SCRIPT_ENABLE_MAGNETIC_OPCODES|e.SCRIPT_ENABLE_MONOLITH_OPCODES|e.SCRIPT_ENABLE_CHRONICLE}function ks(e){return Xt.useGenesisLimits(e)}function Hs(e,t,r){r=r||{};var i=new Xt,n=i.verify(e,t,r.tx||new $t,r.inputIndex||0,r.flags||en(),new ct(r.satoshis||0));return{ok:n,err:i.errstr||""}}function tn(e,t,r,i,n){return Ji.sighashPreimage(e,n||jt,t,r,new ct(i))}function Fs(e,t,r,i,n){return bs.sha256sha256(tn(e,t,r,i,n))}function Cs(e,t,r,i,n,o){o=o||jt;var s=Ji.sign(e,t,o,r,i,new ct(n));return u.Buffer.concat([s.toDER(),u.Buffer.from([o])])}function Rs(e,t,r){r=r||{};var i=new $t().addOutput(new Zi({script:e,satoshis:t})),n=new $t;return n.addInput(new As({prevTxId:i.hash,outputIndex:0,script:Qi.empty()}),e,t),r.outputs&&r.outputs.forEach(function(o){n.addOutput(o)}),{funding:i,spend:n}}function Ls(e,t){var r=e.toAddress?e.toAddress():e;return new Zi({script:Qi.buildPublicKeyHashOut(r),satoshis:t})}function Bs(e){return e===0?Yt.OP_0:e===-1?Yt.OP_1NEGATE:e>=1&&e<=16?Yt["OP_"+e]:new ct(e).toScriptNumBuffer()}rn.exports={SIGHASH:jt,flags:en,enableGenesis:ks,verify:Hs,rawPreimage:tn,sighashDigest:Fs,signInput:Cs,fundAndSpend:Rs,p2pkhOutput:Ls,scriptNum:Bs}});var cn=P((tu,an)=>{"use strict";f();var nn=ge(),on=le(),W=b(),T=V(),$e=on.signInput,sn=on.scriptNum;function Ns(e){var t=nn.sha256(e),r=new W().add(T.OP_SHA256).add(t).add(T.OP_EQUAL);return{lock:r,meta:{name:"hash-lock",digest:t.toString("hex")},unlock:function(i,n,o){return new W().add(o||e)}}}function Us(e){var t=e.toPublicKey(),r=W.buildPublicKeyHashOut(t.toAddress());return{lock:r,meta:{name:"p2pkh",address:t.toAddress().toString()},unlock:function(i,n){return new W().add($e(i,e,0,r,n)).add(t.toBuffer())}}}function qs(e,t){var r=e.toPublicKey(),i=new W().add(sn(t)).add(T.OP_CHECKLOCKTIMEVERIFY).add(T.OP_DROP).add(r.toBuffer()).add(T.OP_CHECKSIG);return{lock:i,meta:{name:"cltv-timelock",locktime:t},unlock:function(n,o){return new W().add($e(n,e,0,i,o))}}}function Ds(e,t){var r=t.map(function(n){return n.toPublicKey()}),i=new W().add(T["OP_"+e]);return r.forEach(function(n){i.add(n.toBuffer())}),i.add(T["OP_"+r.length]).add(T.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 W().add(T.OP_0);return s.forEach(function(c){a.add($e(n,c,0,i,o))}),a}}}function Ms(e){var t=nn.sha256(e.secret),r=new W().add(T.OP_IF).add(T.OP_SHA256).add(t).add(T.OP_EQUALVERIFY).add(e.receiver.toPublicKey().toBuffer()).add(T.OP_CHECKSIG).add(T.OP_ELSE).add(sn(e.timeout)).add(T.OP_CHECKLOCKTIMEVERIFY).add(T.OP_DROP).add(e.sender.toPublicKey().toBuffer()).add(T.OP_CHECKSIG).add(T.OP_ENDIF);return{lock:r,meta:{name:"htlc",digest:t.toString("hex"),timeout:e.timeout},unlockClaim:function(i,n){return new W().add($e(i,e.receiver,0,r,n)).add(e.secret).add(T.OP_1)},unlockRefund:function(i,n){return new W().add($e(i,e.sender,0,r,n)).add(T.OP_0)}}}an.exports={hashLock:Ns,p2pkh:Us,timeLockCLTV:qs,multisig:Ds,htlc:Ms}});var Xe=P((iu,mn)=>{"use strict";f();var un=b(),_=V(),re=we(),ut=M(),pn=ge(),Qt=le(),Zt=Qt.SIGHASH,pt=Qt.scriptNum,qe=u.Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),Jt=new ut("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",16),Gs=u.Buffer.concat([u.Buffer.from([2]),qe]),hn=u.Buffer.from(qe).reverse(),ln=u.Buffer.concat([u.Buffer.from(Jt.toBuffer()).reverse(),u.Buffer.from([0])]),Vs=u.Buffer.concat([u.Buffer.from([48,68,2,32]),qe,u.Buffer.from([2,32])]);function Wt(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 Ks=re.SIGHASH_ALL|re.SIGHASH_FORKID,zs=re.SIGHASH_SINGLE|re.SIGHASH_FORKID,Ys=re.SIGHASH_SINGLE|re.SIGHASH_ANYONECANPAY|re.SIGHASH_FORKID,$s=re.SIGHASH_ALL|re.SIGHASH_ANYONECANPAY|re.SIGHASH_FORKID;function er(e,t){var r=t&&t.sighashType||Zt;return e.add(_.OP_HASH256),Wt(e,32),e.add(hn).add(_.OP_ADD),e.add(ln).add(_.OP_MOD),e.add(pt(32)).add(_.OP_NUM2BIN),Wt(e,32),e.add(qe).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 Xs(){return er(new un)}function dn(e){return e.add(pt(40)).add(_.OP_RIGHT).add(pt(32)).add(_.OP_LEFT),e}function js(e){return fn(e,Zt)}function fn(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 Ws(e){var t=u.Buffer.concat(e.map(function(r){return r.toBufferWriter().toBuffer()}));return pn.sha256sha256(t)}function Qs(e){var t=new un().add(_.OP_DUP);return er(t),t.add(_.OP_VERIFY),dn(t),t.add(u.Buffer.from(e)).add(_.OP_EQUAL),t}var Zs=new ut("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex");function gn(e){var t=pn.sha256sha256(e);if(t[0]<1||t[0]>127)return null;var r=new ut(t).add(new ut(qe)).mod(Jt);if(r.gt(Zs))return null;var i=r.toBuffer("be",32);return i[0]>=1?i:null}function Js(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||Zt;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 m=s+g;a==="nLockTime"?e.nLockTime=m:d.sequenceNumber=4294967294-m;var v=Qt.rawPreimage(e,t,r,i,c);if(gn(v))return{preimage:v,tries:g+1,field:a,nonce:m}}throw new Error("OP_PUSH_TX grind failed after "+o+" tries")}mn.exports={Gx:qe,N:Jt,PUBKEY:Gs,gxLe:hn,N_LE:ln,DER_PREFIX:Vs,reverseBytes:Wt,pushTxCore:er,authenticator:Xs,extractHashOutputs:dn,assertSighashAll:js,assertSighashType:fn,SIGHASH_ALL_FORKID:Ks,SIGHASH_SINGLE_FORKID:zs,SIGHASH_SINGLE_ANYONECANPAY_FORKID:Ys,SIGHASH_ALL_ANYONECANPAY_FORKID:$s,hashOutputs:Ws,valueCovenant:Qs,sFromPreimage:gn,grind:Js}});var rr=P((ou,Sn)=>{"use strict";f();var tr=Xe(),ea=le(),ta=b(),A=V(),De=ea.scriptNum;function ra(e){var t=new ta;return t.add(A.OP_DUP),tr.pushTxCore(t),t.add(A.OP_VERIFY),tr.assertSighashAll(t),t.add(A.OP_DUP),t.add(De(104)).add(A.OP_SPLIT).add(A.OP_NIP),t.add(A.OP_SIZE).add(De(52)).add(A.OP_SUB).add(A.OP_SPLIT).add(A.OP_DROP),t.add(A.OP_OVER),t.add(De(52)).add(A.OP_RIGHT).add(De(8)).add(A.OP_LEFT),t.add(A.OP_BIN2NUM).add(De(e)).add(A.OP_SUB),t.add(De(8)).add(A.OP_NUM2BIN),t.add(A.OP_SWAP).add(A.OP_CAT),t.add(A.OP_HASH256),t.add(A.OP_SWAP),tr.extractHashOutputs(t),t.add(A.OP_EQUAL),t}Sn.exports={pelsCovenant:ra}});var On=P((au,yn)=>{f();yn.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.PublicKey});var or=P((uu,xn)=>{"use strict";f();var ia=Ve(),na=On(),oa=b(),Pn=ge(),nr=le(),E=V(),Me=nr.scriptNum;function ht(e){return e instanceof ia?e.toPublicKey().toBuffer():e instanceof na?e.toBuffer():e}function sa(){return{name:"single-key",commit:function(e){return Pn.sha256ripemd160(ht(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=nr.signInput(e,n,t,r,i);return[o,n.toPublicKey().toBuffer()]}}}function ir(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 oa().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 aa(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 Pn.sha256ripemd160(ir(e,r.map(ht)))},emit:function(r){r.add(E.OP_OVER).add(E.OP_HASH160).add(E.OP_EQUALVERIFY),r.add(Me(1)).add(E.OP_SPLIT).add(E.OP_NIP),r.add(E.OP_SIZE).add(Me(2)).add(E.OP_SUB).add(E.OP_SPLIT).add(E.OP_DROP);for(var i=0;i<this.n;i++)r.add(Me(34)).add(E.OP_SPLIT),r.add(E.OP_SWAP).add(Me(1)).add(E.OP_SPLIT).add(E.OP_NIP),r.add(E.OP_TOALTSTACK);for(r.add(E.OP_DROP),r.add(Me(this.m)),i=0;i<this.n;i++)r.add(E.OP_FROMALTSTACK);return r.add(Me(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=ir(e,a.map(ht)),d=a.map(ht).map(function(v){return v.toString("hex")}),g=s.signWith.map(function(v){var x=d.indexOf(v.toPublicKey().toBuffer().toString("hex"));if(x<0)throw new Error("signWith key is not in the committed key set");return{idx:x,priv:v}}).sort(function(v,x){return x.idx-v.idx}).slice(0,e);if(g.length<e)throw new Error("need at least "+e+" signing keys");var m=g.map(function(v){return nr.signInput(r,v.priv,i,n,o)});return[E.OP_0].concat(m).concat([c])}}}function ca(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}}xn.exports={singleKey:sa,multisig:aa,predicate:ca,redeemScript:ir}});var ar=P((hu,bn)=>{"use strict";f();var ua=M(),je=Xe(),sr=le(),We=or(),lt=b(),O=V(),ie=sr.scriptNum;function _n(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 vn(e,t){return t.length?e.add(u.Buffer.from(t)):e.add(O.OP_0)}function En(e,t){return e.add(O.OP_DUP),je.pushTxCore(e),e.add(O.OP_VERIFY),je.assertSighashAll(e),e.add(O.OP_DUP).add(ie(52)).add(O.OP_RIGHT).add(ie(8)).add(O.OP_LEFT).add(O.OP_TOALTSTACK),e.add(O.OP_DUP),je.extractHashOutputs(e),e.add(O.OP_TOALTSTACK),e.add(ie(104)).add(O.OP_SPLIT).add(O.OP_NIP).add(O.OP_SIZE).add(ie(52)).add(O.OP_SUB).add(O.OP_SPLIT).add(O.OP_DROP),e.add(O.OP_DUP).add(ie(4)).add(ie(20)).add(O.OP_SUBSTR),e.add(O.OP_SWAP).add(O.OP_TOALTSTACK),t.emit(e),e.add(O.OP_FROMALTSTACK),e}function wn(e){return e.add(ie(4)).add(O.OP_SPLIT).add(ie(20)).add(O.OP_SPLIT).add(O.OP_NIP),e.add(O.OP_TOALTSTACK),e.add(O.OP_SWAP).add(O.OP_CAT),e.add(O.OP_FROMALTSTACK).add(O.OP_CAT),e}function In(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 pa(e,t,r){r=r||We.singleKey();var i=new lt;return i.add(_n(t,r)),i.add(O.OP_DROP),En(i,r),wn(i),i.add(O.OP_FROMALTSTACK),i.add(O.OP_SWAP),i.add(O.OP_FROMALTSTACK),i.add(O.OP_BIN2NUM).add(ie(e)).add(O.OP_SUB).add(ie(8)).add(O.OP_NUM2BIN),i.add(O.OP_SWAP).add(O.OP_CAT),i.add(O.OP_HASH256),i.add(O.OP_EQUAL),In(i)}function Tn(e,t){t=t||We.singleKey();var r=new lt;return r.add(_n(e,t)),r.add(O.OP_DROP),En(r,t),wn(r),r.add(O.OP_CAT),r.add(O.OP_SWAP).add(O.OP_CAT),r.add(O.OP_CAT),r.add(O.OP_FROMALTSTACK),r.add(O.OP_FROMALTSTACK).add(O.OP_DROP),r.add(O.OP_SWAP).add(O.OP_HASH256).add(O.OP_EQUAL),In(r)}function ha(e){return We.singleKey().commit(e)}function la(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=sr.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(m){g.add(m)}),g.add(u.Buffer.from(c)),g}function An(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=sr.rawPreimage(r,c,n,i),g=a.unlockArgs(r,c,n,i,e),m=new lt;return vn(m,o.before||u.Buffer.alloc(0)),vn(m,o.after||u.Buffer.alloc(0)),m.add(u.Buffer.from(o.tokenValue)),m.add(u.Buffer.from(t)),g.forEach(function(v){m.add(v)}),m.add(u.Buffer.from(d)),m}function da(e,t){return Tn(e,t)}function fa(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(x){return x.toBufferWriter().toBuffer()}var g=u.Buffer.concat(a.slice(0,s).map(d)),m=u.Buffer.concat(a.slice(s+1).map(d)),v=new ua(i).toBuffer({endian:"little",size:8});return An(e,t,r,i,n,{before:g,after:m,tokenValue:v},o)}bn.exports={ownershipToken:pa,ownershipTokenMulti:Tn,ordinalLock:da,ownerId:ha,unlockTransfer:la,unlockTransferMulti:An,transferOrdinal:fa}});var dr=P((du,kn)=>{"use strict";f();var dt=Xe(),ga=rr(),ma=ar(),hr=le(),ur=b(),$=V(),pr=D(),cr=hr.scriptNum;function Sa(e,t){return e instanceof pr.Output?e:e instanceof ur?new pr.Output({script:e,satoshis:t}):hr.p2pkhOutput(e,t)}function ya(e,t,r,i,n,o){o=o||5e4;for(var s=0;s<o;s++){e.nLockTime=n+s;var a=hr.rawPreimage(e,t,r,i);if(dt.sFromPreimage(a))return a}throw new Error("covenant grind failed after "+o+" tries")}function de(){if(!(this instanceof de))return new de;this._outputs=[],this._minLockTime=null}de.prototype.payTo=function(e,t){return this._outputs.push(Sa(e,t)),this};de.prototype.lockUntil=function(e){return this._minLockTime=e,this};de.prototype.outputs=function(){return this._outputs.map(function(e){return new pr.Output(e.toObject())})};de.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 ")};de.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 ur().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(cr(8)).add($.OP_RIGHT).add(cr(4)).add($.OP_LEFT),t.add($.OP_BIN2NUM).add(cr(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 ur().add(ya(i,o,t,n,s))}}};function lr(){return new de}lr.perpetual=function(e){return ga.pelsCovenant(e)};lr.token=function(e,t){return ma.ownershipToken(e,t)};kn.exports={policy:lr,Policy:de}});var Ln=P((gu,Rn)=>{"use strict";f();var Oa=me(),Pa=M(),xa=D(),va=V(),_a=le();function Fn(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 va.fromNumber(e).toString()}catch{return"0x"+e.toString(16)}}function Hn(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 Ea(e,t,r){r=r||{};var i=new Oa,n=[];i.stepListener=function(s,a,c){n.push({phase:i.script===t?"lock":"unlock",op:Fn(s.opcode&&typeof s.opcode.toNumber=="function"?s.opcode.toNumber():s.opcode.num),stack:a.map(function(d){return Hn(d)}),altstack:c.map(function(d){return Hn(d)})})};var o=i.verify(e,t,r.tx||new xa,r.inputIndex||0,typeof r.flags=="number"?r.flags:_a.flags(),new Pa(r.satoshis||0));return{ok:o,err:i.errstr||"",steps:n}}function Cn(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
|
|
20
|
+
[${s+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}`),Vt(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:"),Vt(i.stack||[],i.altstack||[]),console.log("===========================================")}function Ki(e,t,r){console.log("==========================================="),console.log("\u{1F50D} SCRIPT INTERPRETER DEBUGGER (FULL RUN)"),console.log(`===========================================
|
|
22
|
+
`);let i=new st,n=new Ps(1e5),o=i.verify(e,t,r,0,st.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 $i(){if(typeof y.default>"u"||!y.default.argv){console.log("\u2699\uFE0F CLI mode not available in browser environment");return}let e=y.default.argv.slice(2),t=P=>{let v=e.indexOf(P);return v!==-1&&e[v+1]?e[v+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=nt(n);else{a=nt(r),c=nt(i);let P=u.Buffer.concat([a.toBuffer(),c.toBuffer()]);d=ue.fromBuffer(P)}let g=new _s,m=new Es({prevTxId:"0".repeat(64),outputIndex:0,script:ue.empty(),satoshis:1e5,output:new Vi({satoshis:1e5,script:ue.empty()})});g.addInput(m),g.addOutput(new Vi({satoshis:1e5,script:ue.empty()})),o?await zi(d,g,!0):s?Ki(a||ue.empty(),c||ue.empty(),g):console.log("\u2699\uFE0F No mode specified. Use --step or --truth")}zt.exports={parseScript:nt,printStack:Vt,stepThroughScript:zi,runFullEvaluation:Ki,main:$i};typeof C<"u"&&C.main===zt&&$i()});var pe=O((jc,tn)=>{"use strict";f();var ji=A(),Wi=fe(),Kt=G(),$t=q(),ws=ke(),Qi=ze(),Zi=Pe(),at=D(),Ts=de(),Xi=_e(),Yt=Xi.SIGHASH_ALL|Xi.SIGHASH_FORKID;function Ji(){return Wi.mainnetFlags()}function Is(e,t,r){r=r||{};var i=new Wi,n=i.verify(e,t,r.tx||new $t,r.inputIndex||0,r.flags||Ji(),new at(r.satoshis||0));return{ok:n,err:i.errstr||""}}function en(e,t,r,i,n){return Zi.sighashPreimage(e,n||Yt,t,r,new at(i))}function As(e,t,r,i,n){return Ts.sha256sha256(en(e,t,r,i,n))}function bs(e,t,r,i,n,o){o=o||Yt;var s=Zi.sign(e,t,o,r,i,new at(n));return u.Buffer.concat([s.toDER(),u.Buffer.from([o])])}function ks(e,t,r){r=r||{};var i=new $t().addOutput(new Qi({script:e,satoshis:t})),n=new $t;return n.addInput(new ws({prevTxId:i.hash,outputIndex:0,script:ji.empty()}),e,t),r.outputs&&r.outputs.forEach(function(o){n.addOutput(o)}),{funding:i,spend:n}}function Hs(e,t){var r=e.toAddress?e.toAddress():e;return new Qi({script:ji.buildPublicKeyHashOut(r),satoshis:t})}function Fs(e){return e===0?Kt.OP_0:e===-1?Kt.OP_1NEGATE:e>=1&&e<=16?Kt["OP_"+e]:new at(e).toScriptNumBuffer()}tn.exports={SIGHASH:Yt,flags:Ji,verify:Is,rawPreimage:en,sighashDigest:As,signInput:bs,fundAndSpend:ks,p2pkhOutput:Hs,scriptNum:Fs}});var on=O((Qc,nn)=>{"use strict";f();var Cs=de(),Ls=pe(),Ue=A(),Ne=G(),rn=Ls.signInput;function Rs(e){var t=Cs.sha256(e),r=new Ue().add(Ne.OP_SHA256).add(t).add(Ne.OP_EQUAL);return{lock:r,meta:{name:"hash-lock",digest:t.toString("hex")},unlock:function(i,n,o){return new Ue().add(o||e)}}}function Bs(e){var t=e.toPublicKey(),r=Ue.buildPublicKeyHashOut(t.toAddress());return{lock:r,meta:{name:"p2pkh",address:t.toAddress().toString()},unlock:function(i,n){return new Ue().add(rn(i,e,0,r,n)).add(t.toBuffer())}}}function Ns(e,t){var r=t.map(function(n){return n.toPublicKey()}),i=new Ue().add(Ne["OP_"+e]);return r.forEach(function(n){i.add(n.toBuffer())}),i.add(Ne["OP_"+r.length]).add(Ne.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 Ue().add(Ne.OP_0);return s.forEach(function(c){a.add(rn(n,c,0,i,o))}),a}}}nn.exports={hashLock:Rs,p2pkh:Bs,multisig:Ns}});var Ye=O((Jc,dn)=>{"use strict";f();var sn=A(),_=G(),ee=_e(),ct=D(),an=de(),jt=pe(),Wt=jt.SIGHASH,ut=jt.scriptNum,qe=u.Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),Qt=new ct("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",16),Us=u.Buffer.concat([u.Buffer.from([2]),qe]),cn=u.Buffer.from(qe).reverse(),un=u.Buffer.concat([u.Buffer.from(Qt.toBuffer()).reverse(),u.Buffer.from([0])]),qs=u.Buffer.concat([u.Buffer.from([48,68,2,32]),qe,u.Buffer.from([2,32])]);function Xt(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 Ds=ee.SIGHASH_ALL|ee.SIGHASH_FORKID,Ms=ee.SIGHASH_SINGLE|ee.SIGHASH_FORKID,Gs=ee.SIGHASH_SINGLE|ee.SIGHASH_ANYONECANPAY|ee.SIGHASH_FORKID,Vs=ee.SIGHASH_ALL|ee.SIGHASH_ANYONECANPAY|ee.SIGHASH_FORKID;function Zt(e,t){var r=t&&t.sighashType||Wt;return e.add(_.OP_HASH256),Xt(e,32),e.add(cn).add(_.OP_ADD),e.add(un).add(_.OP_MOD),e.add(ut(32)).add(_.OP_NUM2BIN),Xt(e,32),e.add(qe).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 zs(){return Zt(new sn)}function pn(e){return e.add(ut(40)).add(_.OP_RIGHT).add(ut(32)).add(_.OP_LEFT),e}function Ks(e){return hn(e,Wt)}function hn(e,t){var r=u.Buffer.from([t&255,0,0,0]);return e.add(_.OP_DUP).add(ut(4)).add(_.OP_RIGHT).add(r).add(_.OP_EQUALVERIFY),e}function $s(e){var t=u.Buffer.concat(e.map(function(r){return r.toBufferWriter().toBuffer()}));return an.sha256sha256(t)}function Ys(e){var t=new sn().add(_.OP_DUP);return Zt(t),t.add(_.OP_VERIFY),pn(t),t.add(u.Buffer.from(e)).add(_.OP_EQUAL),t}var Xs=new ct("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex");function ln(e){var t=an.sha256sha256(e);if(t[0]<1||t[0]>127)return null;var r=new ct(t).add(new ct(qe)).mod(Qt);if(r.gt(Xs))return null;var i=r.toBuffer("be",32);return i[0]>=1?i:null}function js(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||Wt;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 m=s+g;a==="nLockTime"?e.nLockTime=m:d.sequenceNumber=4294967294-m;var P=jt.rawPreimage(e,t,r,i,c);if(ln(P))return{preimage:P,tries:g+1,field:a,nonce:m}}throw new Error("OP_PUSH_TX grind failed after "+o+" tries")}dn.exports={Gx:qe,N:Qt,PUBKEY:Us,gxLe:cn,N_LE:un,DER_PREFIX:qs,reverseBytes:Xt,pushTxCore:Zt,authenticator:zs,extractHashOutputs:pn,assertSighashAll:Ks,assertSighashType:hn,SIGHASH_ALL_FORKID:Ds,SIGHASH_SINGLE_FORKID:Ms,SIGHASH_SINGLE_ANYONECANPAY_FORKID:Gs,SIGHASH_ALL_ANYONECANPAY_FORKID:Vs,hashOutputs:$s,valueCovenant:Ys,sFromPreimage:ln,grind:js}});var er=O((tu,fn)=>{"use strict";f();var Jt=Ye(),Ws=pe(),Qs=A(),I=G(),De=Ws.scriptNum;function Zs(e){var t=new Qs;return t.add(I.OP_DUP),Jt.pushTxCore(t),t.add(I.OP_VERIFY),Jt.assertSighashAll(t),t.add(I.OP_DUP),t.add(De(104)).add(I.OP_SPLIT).add(I.OP_NIP),t.add(I.OP_SIZE).add(De(52)).add(I.OP_SUB).add(I.OP_SPLIT).add(I.OP_DROP),t.add(I.OP_OVER),t.add(De(52)).add(I.OP_RIGHT).add(De(8)).add(I.OP_LEFT),t.add(I.OP_BIN2NUM).add(De(e)).add(I.OP_SUB),t.add(De(8)).add(I.OP_NUM2BIN),t.add(I.OP_SWAP).add(I.OP_CAT),t.add(I.OP_HASH256),t.add(I.OP_SWAP),Jt.extractHashOutputs(t),t.add(I.OP_EQUAL),t}fn.exports={pelsCovenant:Zs}});var mn=O((iu,gn)=>{f();gn.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.PublicKey});var ir=O((ou,Sn)=>{"use strict";f();var Js=Ve(),ea=mn(),ta=A(),yn=de(),rr=pe(),E=G(),Me=rr.scriptNum;function pt(e){return e instanceof Js?e.toPublicKey().toBuffer():e instanceof ea?e.toBuffer():e}function ra(){return{name:"single-key",commit:function(e){return yn.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=rr.signInput(e,n,t,r,i);return[o,n.toPublicKey().toBuffer()]}}}function tr(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 ta().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 ia(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 yn.sha256ripemd160(tr(e,r.map(pt)))},emit:function(r){r.add(E.OP_OVER).add(E.OP_HASH160).add(E.OP_EQUALVERIFY),r.add(Me(1)).add(E.OP_SPLIT).add(E.OP_NIP),r.add(E.OP_SIZE).add(Me(2)).add(E.OP_SUB).add(E.OP_SPLIT).add(E.OP_DROP);for(var i=0;i<this.n;i++)r.add(Me(34)).add(E.OP_SPLIT),r.add(E.OP_SWAP).add(Me(1)).add(E.OP_SPLIT).add(E.OP_NIP),r.add(E.OP_TOALTSTACK);for(r.add(E.OP_DROP),r.add(Me(this.m)),i=0;i<this.n;i++)r.add(E.OP_FROMALTSTACK);return r.add(Me(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=tr(e,a.map(pt)),d=a.map(pt).map(function(P){return P.toString("hex")}),g=s.signWith.map(function(P){var v=d.indexOf(P.toPublicKey().toBuffer().toString("hex"));if(v<0)throw new Error("signWith key is not in the committed key set");return{idx:v,priv:P}}).sort(function(P,v){return v.idx-P.idx}).slice(0,e);if(g.length<e)throw new Error("need at least "+e+" signing keys");var m=g.map(function(P){return rr.signInput(r,P.priv,i,n,o)});return[E.OP_0].concat(m).concat([c])}}}function na(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}}Sn.exports={singleKey:ra,multisig:ia,predicate:na,redeemScript:tr}});var or=O((au,Tn)=>{"use strict";f();var oa=D(),Xe=Ye(),nr=pe(),je=ir(),ht=A(),x=G(),te=nr.scriptNum;function On(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 xn(e,t){return t.length?e.add(u.Buffer.from(t)):e.add(x.OP_0)}function vn(e,t){return e.add(x.OP_DUP),Xe.pushTxCore(e),e.add(x.OP_VERIFY),Xe.assertSighashAll(e),e.add(x.OP_DUP).add(te(52)).add(x.OP_RIGHT).add(te(8)).add(x.OP_LEFT).add(x.OP_TOALTSTACK),e.add(x.OP_DUP),Xe.extractHashOutputs(e),e.add(x.OP_TOALTSTACK),e.add(te(104)).add(x.OP_SPLIT).add(x.OP_NIP).add(x.OP_SIZE).add(te(52)).add(x.OP_SUB).add(x.OP_SPLIT).add(x.OP_DROP),e.add(x.OP_DUP).add(te(4)).add(te(20)).add(x.OP_SUBSTR),e.add(x.OP_SWAP).add(x.OP_TOALTSTACK),t.emit(e),e.add(x.OP_FROMALTSTACK),e}function Pn(e){return e.add(te(4)).add(x.OP_SPLIT).add(te(20)).add(x.OP_SPLIT).add(x.OP_NIP),e.add(x.OP_TOALTSTACK),e.add(x.OP_SWAP).add(x.OP_CAT),e.add(x.OP_FROMALTSTACK).add(x.OP_CAT),e}function _n(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 sa(e,t,r){r=r||je.singleKey();var i=new ht;return i.add(On(t,r)),i.add(x.OP_DROP),vn(i,r),Pn(i),i.add(x.OP_FROMALTSTACK),i.add(x.OP_SWAP),i.add(x.OP_FROMALTSTACK),i.add(x.OP_BIN2NUM).add(te(e)).add(x.OP_SUB).add(te(8)).add(x.OP_NUM2BIN),i.add(x.OP_SWAP).add(x.OP_CAT),i.add(x.OP_HASH256),i.add(x.OP_EQUAL),_n(i)}function En(e,t){t=t||je.singleKey();var r=new ht;return r.add(On(e,t)),r.add(x.OP_DROP),vn(r,t),Pn(r),r.add(x.OP_CAT),r.add(x.OP_SWAP).add(x.OP_CAT),r.add(x.OP_CAT),r.add(x.OP_FROMALTSTACK),r.add(x.OP_FROMALTSTACK).add(x.OP_DROP),r.add(x.OP_SWAP).add(x.OP_HASH256).add(x.OP_EQUAL),_n(r)}function aa(e){return je.singleKey().commit(e)}function ca(e,t,r,i,n,o){o=o||{};var s=o.auth||je.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.");Xe.grind(r,a,n,i,o.grind);var c=nr.rawPreimage(r,a,n,i),d=s.unlockArgs(r,a,n,i,e),g=new ht().add(u.Buffer.from(t));return d.forEach(function(m){g.add(m)}),g.add(u.Buffer.from(c)),g}function wn(e,t,r,i,n,o,s){s=s||{};var a=s.auth||je.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");Xe.grind(r,c,n,i,s.grind);var d=nr.rawPreimage(r,c,n,i),g=a.unlockArgs(r,c,n,i,e),m=new ht;return xn(m,o.before||u.Buffer.alloc(0)),xn(m,o.after||u.Buffer.alloc(0)),m.add(u.Buffer.from(o.tokenValue)),m.add(u.Buffer.from(t)),g.forEach(function(P){m.add(P)}),m.add(u.Buffer.from(d)),m}function ua(e,t){return En(e,t)}function pa(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(v){return v.toBufferWriter().toBuffer()}var g=u.Buffer.concat(a.slice(0,s).map(d)),m=u.Buffer.concat(a.slice(s+1).map(d)),P=new oa(i).toBuffer({endian:"little",size:8});return wn(e,t,r,i,n,{before:g,after:m,tokenValue:P},o)}Tn.exports={ownershipToken:sa,ownershipTokenMulti:En,ordinalLock:ua,ownerId:aa,unlockTransfer:ca,unlockTransferMulti:wn,transferOrdinal:pa}});var hr=O((uu,In)=>{"use strict";f();var lt=Ye(),ha=er(),la=or(),ur=pe(),ar=A(),$=G(),cr=q(),sr=ur.scriptNum;function da(e,t){return e instanceof cr.Output?e:e instanceof ar?new cr.Output({script:e,satoshis:t}):ur.p2pkhOutput(e,t)}function fa(e,t,r,i,n,o){o=o||5e4;for(var s=0;s<o;s++){e.nLockTime=n+s;var a=ur.rawPreimage(e,t,r,i);if(lt.sFromPreimage(a))return a}throw new Error("covenant grind failed after "+o+" tries")}function he(){if(!(this instanceof he))return new he;this._outputs=[],this._minLockTime=null}he.prototype.payTo=function(e,t){return this._outputs.push(da(e,t)),this};he.prototype.lockUntil=function(e){return this._minLockTime=e,this};he.prototype.outputs=function(){return this._outputs.map(function(e){return new cr.Output(e.toObject())})};he.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 ")};he.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 ar().add($.OP_DUP);if(lt.pushTxCore(t),t.add($.OP_VERIFY),this._outputs.length){var r=lt.hashOutputs(this._outputs);t.add($.OP_DUP),lt.extractHashOutputs(t),t.add(u.Buffer.from(r)).add($.OP_EQUALVERIFY)}return this._minLockTime!==null&&(t.add($.OP_DUP),t.add(sr(8)).add($.OP_RIGHT).add(sr(4)).add($.OP_LEFT),t.add($.OP_BIN2NUM).add(sr(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 ar().add(fa(i,o,t,n,s))}}};function pr(){return new he}pr.perpetual=function(e){return ha.pelsCovenant(e)};pr.token=function(e,t){return la.ownershipToken(e,t)};In.exports={policy:pr,Policy:he}});var Fn=O((hu,Hn)=>{"use strict";f();var ga=fe(),ma=D(),ya=q(),Sa=G(),xa=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 Sa.fromNumber(e).toString()}catch{return"0x"+e.toString(16)}}function An(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 Oa(e,t,r){r=r||{};var i=new ga,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 An(d)}),altstack:c.map(function(d){return An(d)})})};var o=i.verify(e,t,r.tx||new ya,r.inputIndex||0,typeof r.flags=="number"?r.flags:xa.flags(),new ma(r.satoshis||0));return{ok:o,err:i.errstr||"",steps:n}}function kn(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 va(e){return console.log(kn(e)),e}Hn.exports={trace:Oa,format:kn,print:va,opLabel:bn}});var Ln=O((du,Cn)=>{"use strict";f();Cn.exports="9.0.0"});var Nn=O((gu,Bn)=>{"use strict";f();var Pa=de(),Rn=q(),_a=wt(),Ea=A(),h={Covenant:ti(),Preimage:J(),SIGHASH:ai(),Builder:hi(),UTXOGenerator:Ai(),ScriptTester:Ci(),CovenantBuilder:Ut().CovenantBuilder,CovenantTemplates:Ut().CovenantTemplates,OpcodeMap:Rt(),ScriptUtils:Di(),StackExaminer:Gi(),ScriptInterpreter:Yi(),CovenantHelpers:pe(),Locks:on(),PushTx:Ye(),PELS:er(),Token:or(),Authorizers:ir(),DSL:hr(),Policy:hr().Policy,Debugger:Fn()};h.policy=h.DSL.policy;h.trace=function(e,t,r){return h.Debugger.trace(e,t,r)};h.verifyScript=function(e,t,r){return h.CovenantHelpers.verify(e,t,r)};h.perpetualCovenant=function(e){return h.PELS.pelsCovenant(e)};h.ownershipToken=function(e,t,r){return h.Token.ownershipToken(e,t,r)};h.valueCovenant=function(e){return h.PushTx.valueCovenant(e)};h.ordinalLock=function(e,t){return h.Token.ordinalLock(e,t)};h.transferOrdinal=function(e,t,r,i,n,o){return h.Token.transferOrdinal(e,t,r,i,n,o)};h.createCovenant=function(e,t){return new h.Covenant(e,t)};h.extractPreimage=function(e,t){return new h.Preimage(e,t)};h.analyzeSIGHASH=function(e){return new h.SIGHASH(e)};h.buildCovenant=function(e,t){return new h.Builder(e,t)};h.createUTXOGenerator=function(e){return new h.UTXOGenerator(e)};h.createTestEnvironment=function(e){return h.UTXOGenerator.createTestEnvironment(e)};h.testScript=function(e,t,r){return h.ScriptTester.test(e,t,r)};h.testCovenant=function(e,t,r){return h.ScriptTester.testCovenant(e,t,r)};h.testFieldExtraction=function(e,t,r){return h.ScriptTester.testFieldExtraction(e,t,r)};h.debugScript=function(e,t){var r=new h.ScriptTester(t);return r.debug(e)};h.explainZeroHashes=function(){return h.SIGHASH.explainZeroMystery()};h.getAllSIGHASHTypes=function(){return h.SIGHASH.getAllTypes()};h.demonstrateAllSIGHASH=function(){return h.SIGHASH.generateAllDemonstrations()};h.createCovenantBuilder=function(){return new h.CovenantBuilder};h.createValueLockCovenant=function(e){return h.CovenantTemplates.valueLock(e)};h.createHashLockCovenant=function(e){return h.CovenantTemplates.hashLock(e)};h.createComplexValidationCovenant=function(e){return h.CovenantTemplates.complexValidation(e)};h.getOpcodeMap=function(){return h.OpcodeMap.opcodeMap};h.simulateScript=function(e,t){return h.OpcodeMap.utils.simulate(e,t)};h.createASMFromJS=function(e){return h.OpcodeMap.utils.createASM(e)};h.scriptToASM=function(e){return h.ScriptUtils.scriptToASM(e)};h.asmToScript=function(e){return h.ScriptUtils.asmToScript(e)};h.asmToHex=function(e){return h.ScriptUtils.asmToHex(e)};h.hexToASM=function(e){return h.ScriptUtils.hexToASM(e)};h.scriptToHex=function(e){return h.ScriptUtils.scriptToHex(e)};h.validateASM=function(e){return h.ScriptUtils.validateASM(e)};h.validateScript=function(e){return h.ScriptUtils.validateScript(e)};h.estimateScriptSize=function(e){return h.ScriptUtils.estimateScriptSize(e)};h.optimizeScript=function(e){return h.ScriptUtils.optimizeScript(e)};h.compareScripts=function(e,t){return h.ScriptUtils.compareScripts(e,t)};h.explainScript=function(e){return h.ScriptUtils.explainScript(e)};h.scriptMetrics=function(e){return h.ScriptUtils.scriptMetrics(e)};h.analyzeComplexity=function(e){return h.ScriptUtils.analyzeComplexity(e)};h.findOptimizations=function(e){return h.ScriptUtils.findOptimizations(e)};h.covenantToEnglish=function(e){return h.ScriptUtils.covenantToEnglish(e)};h.batchTestScripts=function(e,t){return h.ScriptUtils.batchTestScripts(e,t)};h.examineStack=function(e,t){return h.StackExaminer.runScript(e,t)};h.debugScriptExecution=function(e,t,r){return r=r||{},r.stepMode?h.ScriptInterpreter.stepThroughScript(h.ScriptInterpreter.parseScript(e+" "+t),new Rn,!0):h.ScriptInterpreter.runFullEvaluation(h.ScriptInterpreter.parseScript(e),h.ScriptInterpreter.parseScript(t),new Rn)};h.parseScript=function(e){return h.ScriptInterpreter.parseScript(e)};h.printStack=function(e,t){return h.ScriptInterpreter.printStack(e,t)};h.createQuickCovenant=function(e,t){let r=h.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}`)}};h.completeCovenantFlow=function(e,t,r){var i=new h.Covenant(e);return i.completeFlow(t,r)};h.getEducationalResources=function(){return{zeroHashMystery:h.SIGHASH.explainZeroMystery(),sighashTypes:h.SIGHASH.getAllTypes(),exampleDemonstrations:h.SIGHASH.generateAllDemonstrations()}};h.utils={};h.utils.reconstructP2pkhScript=function(e){return Ea.buildPublicKeyHashOut(e).toHex()};h.utils.createCovenantAddress=function(e){var t=Pa.sha256ripemd160(e.toBuffer());return _a.fromScriptHash(t)};h.utils.decodeCompactSize=function(e,t){return h.Preimage.decodeCompactSize(e,t)};h.version=Ln();h.description="Smart Contract Framework for Bitcoin SV";h.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};h.interpretScript=h.debugScriptExecution;h.getScriptMetrics=h.scriptMetrics;Bn.exports=h});var wa=O((yu,Un)=>{f();Un.exports=Nn()});return wa();})();
|
|
24
24
|
if(typeof module!=="undefined"&&module.exports){module.exports=bsvSmartContract}else if(typeof define==="function"&&define.amd){define([],function(){return bsvSmartContract})}
|