@smartledger/bsv 9.0.0 → 9.1.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 +137 -0
- package/README.md +152 -1041
- package/STABILITY.md +134 -0
- package/bsv-gdaf.min.js +53 -48
- package/bsv-ltp.min.js +23 -18
- package/bsv-smartcontract.min.js +18 -18
- package/bsv.bundle.js +53 -48
- package/bsv.min.js +53 -48
- package/docs/MODULE_REFERENCE_COMPLETE.md +27 -27
- package/docs/advanced/UTXO_MANAGER_GUIDE.md +1 -1
- package/docs/getting-started/INSTALLATION.md +23 -23
- package/docs/getting-started/QUICK_START.md +7 -7
- package/docs/migration/FROM_BSV_1_5_6.md +5 -5
- package/docs/proposals/10.0.0-package-split.md +131 -0
- package/index.js +5 -0
- package/lib/block/merkleblock.js +19 -5
- package/lib/hdprivatekey.js +15 -0
- package/lib/script/interpreter.js +109 -1
- package/lib/smart_contract/builder.js +14 -0
- package/lib/util/deprecate.js +159 -0
- package/package.json +19 -82
- package/version.js +1 -1
- package/.mocharc.json +0 -5
- package/test/address.js +0 -629
- package/test/block/block.js +0 -239
- package/test/block/blockheader.js +0 -270
- package/test/block/merkleblock.js +0 -207
- package/test/build/bundle_crypto_shim.js +0 -104
- package/test/build/bundle_externals.js +0 -125
- package/test/build/bundle_smoke.js +0 -55
- package/test/build/esbuild_main.js +0 -65
- package/test/build/esm_wrapper.js +0 -97
- package/test/build/exports_resolution.js +0 -84
- package/test/build/version_sync.js +0 -14
- package/test/cli/smoke.js +0 -261
- package/test/consensus/base58-vectors.js +0 -120
- package/test/consensus/sv-script-vectors.js +0 -81
- package/test/consensus/sv-sighash-vectors.js +0 -51
- package/test/consensus/sv-tx-vectors.js +0 -48
- package/test/credentials-test.js +0 -332
- package/test/crypto/backend_selection.js +0 -126
- package/test/crypto/bn.js +0 -168
- package/test/crypto/ecdsa.js +0 -426
- package/test/crypto/elliptic-fixed.js +0 -61
- package/test/crypto/hash.browser.js +0 -121
- package/test/crypto/hash.js +0 -122
- package/test/crypto/point.js +0 -193
- package/test/crypto/random.js +0 -105
- package/test/crypto/security.js +0 -176
- package/test/crypto/shamir.js +0 -177
- package/test/crypto/shamir_rngcap.js +0 -29
- package/test/crypto/signature.js +0 -399
- package/test/data/bip69.json +0 -215
- package/test/data/bitcoin-sv/README.md +0 -170
- package/test/data/bitcoin-sv/base58_encode_decode.json +0 -14
- package/test/data/bitcoin-sv/base58_keys_invalid.json +0 -152
- package/test/data/bitcoin-sv/base58_keys_valid.json +0 -452
- package/test/data/bitcoin-sv/script_tests.json +0 -2591
- package/test/data/bitcoin-sv/sighash.json +0 -1003
- package/test/data/bitcoin-sv/tx_invalid.json +0 -285
- package/test/data/bitcoin-sv/tx_valid.json +0 -367
- package/test/data/bitcoind/base58_keys_invalid.json +0 -152
- package/test/data/bitcoind/base58_keys_valid.json +0 -452
- package/test/data/bitcoind/blocks.json +0 -27
- package/test/data/bitcoind/script_tests.json +0 -2244
- package/test/data/bitcoind/sig_canonical.json +0 -7
- package/test/data/bitcoind/sig_noncanonical.json +0 -22
- package/test/data/bitcoind/tx_invalid.json +0 -177
- package/test/data/bitcoind/tx_valid.json +0 -224
- package/test/data/blk86756-testnet.dat +0 -0
- package/test/data/blk86756-testnet.js +0 -12
- package/test/data/blk86756-testnet.json +0 -684
- package/test/data/brc220-batch-vector.json +0 -129
- package/test/data/ecdsa.json +0 -230
- package/test/data/merkleblocks.js +0 -486
- package/test/data/messages.json +0 -22
- package/test/data/sighash.json +0 -1004
- package/test/data/tx_creation.json +0 -85
- package/test/didweb/relationships.js +0 -144
- package/test/ecies/bitcore-ecies.js +0 -178
- package/test/ecies/electrum-ecies.js +0 -206
- package/test/encoding/base58.js +0 -131
- package/test/encoding/base58check.js +0 -145
- package/test/encoding/bufferreader.js +0 -328
- package/test/encoding/bufferwriter.js +0 -160
- package/test/encoding/varint.js +0 -104
- package/test/gdaf/anchor_no_key_leak.js +0 -146
- package/test/gdaf/anchor_spv.js +0 -163
- package/test/gdaf/canonicalization.js +0 -106
- package/test/gdaf/canonicalize.js +0 -140
- package/test/gdaf/zk_prover.js +0 -204
- package/test/hdkeys.js +0 -365
- package/test/hdprivatekey.js +0 -339
- package/test/hdpublickey.js +0 -293
- package/test/index.js +0 -16
- package/test/ltp/ids.js +0 -74
- package/test/ltp/right.js +0 -198
- package/test/ltp/verify_failclosed.js +0 -134
- package/test/message/message.js +0 -190
- package/test/mnemonic/data/fixtures.json +0 -300
- package/test/mnemonic/mnemonic.js +0 -277
- package/test/mnemonic/mocha.opts +0 -1
- package/test/mnemonic/pbkdf2.test.js +0 -43
- package/test/networks.js +0 -207
- package/test/notaryhash/batch_leaf.js +0 -140
- package/test/notaryhash/batch_vector.js +0 -282
- package/test/notaryhash/certificate.js +0 -249
- package/test/notaryhash/encoding.js +0 -186
- package/test/notaryhash/interop.js +0 -112
- package/test/notaryhash/merkle.js +0 -181
- package/test/notaryhash/script.js +0 -270
- package/test/notaryhash/verify.js +0 -342
- package/test/opcode.js +0 -186
- package/test/ordinals/bsv20.js +0 -337
- package/test/ordinals/inscription.js +0 -329
- package/test/ordinals/ordlock.js +0 -567
- package/test/privatekey.js +0 -540
- package/test/publickey.js +0 -411
- package/test/regressions.js +0 -215
- package/test/script/chronicle.js +0 -543
- package/test/script/defaults.js +0 -160
- package/test/script/genesis_limits.js +0 -203
- package/test/script/interpreter.js +0 -776
- package/test/script/script.js +0 -1259
- package/test/script/string_ops.js +0 -88
- package/test/security/fail_closed_contracts.js +0 -104
- package/test/security/threat_model_coverage.js +0 -31
- package/test/smart_contract/covenants.js +0 -207
- package/test/smart_contract/dsl_debugger.js +0 -92
- package/test/smart_contract/extract_field.js +0 -61
- package/test/smart_contract/nonenforcing_guard.js +0 -44
- package/test/smart_contract/ordinal_transfer.js +0 -71
- package/test/smart_contract/preimage.js +0 -98
- package/test/smart_contract/sighash_marketplace.js +0 -98
- package/test/smart_contract/token_generalized.js +0 -175
- package/test/spv/headerchain.js +0 -86
- package/test/spv/merkleproof.js +0 -133
- package/test/statuslist/failclosed.js +0 -78
- package/test/transaction/deserialize.js +0 -33
- package/test/transaction/input/input.js +0 -92
- package/test/transaction/input/multisig.js +0 -174
- package/test/transaction/input/multisigscripthash.js +0 -111
- package/test/transaction/input/publickey.js +0 -68
- package/test/transaction/input/publickeyhash.js +0 -59
- package/test/transaction/output.js +0 -185
- package/test/transaction/sighash.js +0 -91
- package/test/transaction/signature.js +0 -127
- package/test/transaction/transaction.js +0 -1299
- package/test/transaction/unspentoutput.js +0 -97
- package/test/types/dts_drift.js +0 -124
- package/test/types/surface_honesty.js +0 -102
- package/test/util/id.js +0 -72
- package/test/util/js.js +0 -76
- package/test/util/preconditions.js +0 -79
- package/test/vcjwt/interop.js +0 -126
package/bsv-smartcontract.min.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
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(`
|
|
1
|
+
var bsvSmartContract=(()=>{var Yn=Object.create;var mr=Object.defineProperty;var Xn=Object.getOwnPropertyDescriptor;var jn=Object.getOwnPropertyNames;var Wn=Object.getPrototypeOf,Qn=Object.prototype.hasOwnProperty;var C=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Zn=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var x=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Jn=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of jn(t))!Qn.call(e,n)&&n!==r&&mr(e,n,{get:()=>t[n],enumerable:!(i=Xn(t,n))||i.enumerable});return e};var yr=(e,t,r)=>(r=e!=null?Yn(Wn(e)):{},Jn(t||!e||!e.__esModule?mr(r,"default",{value:e,enumerable:!0}):r,e));var Pr=x((Ba,Or)=>{f();var I=Or.exports={},j,W;function ft(){throw new Error("setTimeout has not been defined")}function gt(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?j=setTimeout:j=ft}catch{j=ft}try{typeof clearTimeout=="function"?W=clearTimeout:W=gt}catch{W=gt}})();function Sr(e){if(j===setTimeout)return setTimeout(e,0);if((j===ft||!j)&&setTimeout)return j=setTimeout,setTimeout(e,0);try{return j(e,0)}catch{try{return j.call(null,e,0)}catch{return j.call(this,e,0)}}}function eo(e){if(W===clearTimeout)return clearTimeout(e);if((W===gt||!W)&&clearTimeout)return W=clearTimeout,clearTimeout(e);try{return W(e)}catch{try{return W.call(null,e)}catch{return W.call(this,e)}}}var ie=[],Ie=!1,xe,Qe=-1;function to(){!Ie||!xe||(Ie=!1,xe.length?ie=xe.concat(ie):Qe=-1,ie.length&&vr())}function vr(){if(!Ie){var e=Sr(to);Ie=!0;for(var t=ie.length;t;){for(xe=ie,ie=[];++Qe<t;)xe&&xe[Qe].run();Qe=-1,t=ie.length}xe=null,Ie=!1,eo(e)}}I.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];ie.push(new xr(e,t)),ie.length===1&&!Ie&&Sr(vr)};function xr(e,t){this.fun=e,this.array=t}xr.prototype.run=function(){this.fun.apply(null,this.array)};I.title="browser";I.browser=!0;I.env={};I.argv=[];I.version="";I.versions={};function ne(){}I.on=ne;I.addListener=ne;I.once=ne;I.off=ne;I.removeListener=ne;I.removeAllListeners=ne;I.emit=ne;I.prependListener=ne;I.prependOnceListener=ne;I.listeners=function(e){return[]};I.binding=function(e){throw new Error("process.binding is not supported")};I.cwd=function(){return"/"};I.chdir=function(e){throw new Error("process.chdir is not supported")};I.umask=function(){return 0}});var wr=x(Ze=>{"use strict";f();Ze.byteLength=io;Ze.toByteArray=oo;Ze.fromByteArray=co;var Q=[],V=[],ro=typeof Uint8Array<"u"?Uint8Array:Array,mt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Oe=0,_r=mt.length;Oe<_r;++Oe)Q[Oe]=mt[Oe],V[mt.charCodeAt(Oe)]=Oe;var Oe,_r;V[45]=62;V[95]=63;function Er(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");r===-1&&(r=t);var i=r===t?0:4-r%4;return[r,i]}function io(e){var t=Er(e),r=t[0],i=t[1];return(r+i)*3/4-i}function no(e,t,r){return(t+r)*3/4-r}function oo(e){var t,r=Er(e),i=r[0],n=r[1],o=new ro(no(e,i,n)),s=0,a=n>0?i-4:i,c;for(c=0;c<a;c+=4)t=V[e.charCodeAt(c)]<<18|V[e.charCodeAt(c+1)]<<12|V[e.charCodeAt(c+2)]<<6|V[e.charCodeAt(c+3)],o[s++]=t>>16&255,o[s++]=t>>8&255,o[s++]=t&255;return n===2&&(t=V[e.charCodeAt(c)]<<2|V[e.charCodeAt(c+1)]>>4,o[s++]=t&255),n===1&&(t=V[e.charCodeAt(c)]<<10|V[e.charCodeAt(c+1)]<<4|V[e.charCodeAt(c+2)]>>2,o[s++]=t>>8&255,o[s++]=t&255),o}function so(e){return Q[e>>18&63]+Q[e>>12&63]+Q[e>>6&63]+Q[e&63]}function ao(e,t,r){for(var i,n=[],o=t;o<r;o+=3)i=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(e[o+2]&255),n.push(so(i));return n.join("")}function co(e){for(var t,r=e.length,i=r%3,n=[],o=16383,s=0,a=r-i;s<a;s+=o)n.push(ao(e,s,s+o>a?a:s+o));return i===1?(t=e[r-1],n.push(Q[t>>2]+Q[t<<4&63]+"==")):i===2&&(t=(e[r-2]<<8)+e[r-1],n.push(Q[t>>10]+Q[t>>4&63]+Q[t<<2&63]+"=")),n.join("")}});var Ir=x(yt=>{f();yt.read=function(e,t,r,i,n){var o,s,a=n*8-i-1,c=(1<<a)-1,d=c>>1,g=-7,y=r?n-1:0,P=r?-1:1,O=e[t+y];for(y+=P,o=O&(1<<-g)-1,O>>=-g,g+=a;g>0;o=o*256+e[t+y],y+=P,g-=8);for(s=o&(1<<-g)-1,o>>=-g,g+=i;g>0;s=s*256+e[t+y],y+=P,g-=8);if(o===0)o=1-d;else{if(o===c)return s?NaN:(O?-1:1)*(1/0);s=s+Math.pow(2,i),o=o-d}return(O?-1:1)*s*Math.pow(2,o-i)};yt.write=function(e,t,r,i,n,o){var s,a,c,d=o*8-n-1,g=(1<<d)-1,y=g>>1,P=n===23?Math.pow(2,-24)-Math.pow(2,-77):0,O=i?0:o-1,re=i?1:-1,$n=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=g):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),s+y>=1?t+=P/c:t+=P*Math.pow(2,1-y),t*c>=2&&(s++,c/=2),s+y>=g?(a=0,s=g):s+y>=1?(a=(t*c-1)*Math.pow(2,n),s=s+y):(a=t*Math.pow(2,y-1)*Math.pow(2,n),s=0));n>=8;e[r+O]=a&255,O+=re,a/=256,n-=8);for(s=s<<n|a,d+=n;d>0;e[r+O]=s&255,O+=re,s/=256,d-=8);e[r+O-re]|=$n*128}});var Vr=x(ke=>{"use strict";f();var St=wr(),Ae=Ir(),Tr=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;ke.Buffer=h;ke.SlowBuffer=go;ke.INSPECT_MAX_BYTES=50;var Je=2147483647;ke.kMaxLength=Je;h.TYPED_ARRAY_SUPPORT=uo();!h.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function uo(){try{let e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),e.foo()===42}catch{return!1}}Object.defineProperty(h.prototype,"parent",{enumerable:!0,get:function(){if(h.isBuffer(this))return this.buffer}});Object.defineProperty(h.prototype,"offset",{enumerable:!0,get:function(){if(h.isBuffer(this))return this.byteOffset}});function oe(e){if(e>Je)throw new RangeError('The value "'+e+'" is invalid for option "size"');let t=new Uint8Array(e);return Object.setPrototypeOf(t,h.prototype),t}function h(e,t,r){if(typeof e=="number"){if(typeof t=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return Pt(e)}return Hr(e,t,r)}h.poolSize=8192;function Hr(e,t,r){if(typeof e=="string")return po(e,t);if(ArrayBuffer.isView(e))return lo(e);if(e==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(Z(e,ArrayBuffer)||e&&Z(e.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Z(e,SharedArrayBuffer)||e&&Z(e.buffer,SharedArrayBuffer)))return xt(e,t,r);if(typeof e=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let i=e.valueOf&&e.valueOf();if(i!=null&&i!==e)return h.from(i,t,r);let n=fo(e);if(n)return n;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof e[Symbol.toPrimitive]=="function")return h.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}h.from=function(e,t,r){return Hr(e,t,r)};Object.setPrototypeOf(h.prototype,Uint8Array.prototype);Object.setPrototypeOf(h,Uint8Array);function Fr(e){if(typeof e!="number")throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function ho(e,t,r){return Fr(e),e<=0?oe(e):t!==void 0?typeof r=="string"?oe(e).fill(t,r):oe(e).fill(t):oe(e)}h.alloc=function(e,t,r){return ho(e,t,r)};function Pt(e){return Fr(e),oe(e<0?0:_t(e)|0)}h.allocUnsafe=function(e){return Pt(e)};h.allocUnsafeSlow=function(e){return Pt(e)};function po(e,t){if((typeof t!="string"||t==="")&&(t="utf8"),!h.isEncoding(t))throw new TypeError("Unknown encoding: "+t);let r=Cr(e,t)|0,i=oe(r),n=i.write(e,t);return n!==r&&(i=i.slice(0,n)),i}function vt(e){let t=e.length<0?0:_t(e.length)|0,r=oe(t);for(let i=0;i<t;i+=1)r[i]=e[i]&255;return r}function lo(e){if(Z(e,Uint8Array)){let t=new Uint8Array(e);return xt(t.buffer,t.byteOffset,t.byteLength)}return vt(e)}function xt(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');let i;return t===void 0&&r===void 0?i=new Uint8Array(e):r===void 0?i=new Uint8Array(e,t):i=new Uint8Array(e,t,r),Object.setPrototypeOf(i,h.prototype),i}function fo(e){if(h.isBuffer(e)){let t=_t(e.length)|0,r=oe(t);return r.length===0||e.copy(r,0,0,t),r}if(e.length!==void 0)return typeof e.length!="number"||wt(e.length)?oe(0):vt(e);if(e.type==="Buffer"&&Array.isArray(e.data))return vt(e.data)}function _t(e){if(e>=Je)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Je.toString(16)+" bytes");return e|0}function go(e){return+e!=e&&(e=0),h.alloc(+e)}h.isBuffer=function(t){return t!=null&&t._isBuffer===!0&&t!==h.prototype};h.compare=function(t,r){if(Z(t,Uint8Array)&&(t=h.from(t,t.offset,t.byteLength)),Z(r,Uint8Array)&&(r=h.from(r,r.offset,r.byteLength)),!h.isBuffer(t)||!h.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(t===r)return 0;let i=t.length,n=r.length;for(let o=0,s=Math.min(i,n);o<s;++o)if(t[o]!==r[o]){i=t[o],n=r[o];break}return i<n?-1:n<i?1:0};h.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};h.concat=function(t,r){if(!Array.isArray(t))throw new TypeError('"list" argument must be an Array of Buffers');if(t.length===0)return h.alloc(0);let i;if(r===void 0)for(r=0,i=0;i<t.length;++i)r+=t[i].length;let n=h.allocUnsafe(r),o=0;for(i=0;i<t.length;++i){let s=t[i];if(Z(s,Uint8Array))o+s.length>n.length?(h.isBuffer(s)||(s=h.from(s)),s.copy(n,o)):Uint8Array.prototype.set.call(n,s,o);else if(h.isBuffer(s))s.copy(n,o);else throw new TypeError('"list" argument must be an Array of Buffers');o+=s.length}return n};function Cr(e,t){if(h.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||Z(e,ArrayBuffer))return e.byteLength;if(typeof e!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);let r=e.length,i=arguments.length>2&&arguments[2]===!0;if(!i&&r===0)return 0;let n=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return Ot(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return Gr(e).length;default:if(n)return i?-1:Ot(e).length;t=(""+t).toLowerCase(),n=!0}}h.byteLength=Cr;function mo(e,t,r){let i=!1;if((t===void 0||t<0)&&(t=0),t>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,t>>>=0,r<=t))return"";for(e||(e="utf8");;)switch(e){case"hex":return Io(this,t,r);case"utf8":case"utf-8":return Rr(this,t,r);case"ascii":return Eo(this,t,r);case"latin1":case"binary":return wo(this,t,r);case"base64":return Po(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return To(this,t,r);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}h.prototype._isBuffer=!0;function Pe(e,t,r){let i=e[t];e[t]=e[r],e[r]=i}h.prototype.swap16=function(){let t=this.length;if(t%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let r=0;r<t;r+=2)Pe(this,r,r+1);return this};h.prototype.swap32=function(){let t=this.length;if(t%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let r=0;r<t;r+=4)Pe(this,r,r+3),Pe(this,r+1,r+2);return this};h.prototype.swap64=function(){let t=this.length;if(t%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let r=0;r<t;r+=8)Pe(this,r,r+7),Pe(this,r+1,r+6),Pe(this,r+2,r+5),Pe(this,r+3,r+4);return this};h.prototype.toString=function(){let t=this.length;return t===0?"":arguments.length===0?Rr(this,0,t):mo.apply(this,arguments)};h.prototype.toLocaleString=h.prototype.toString;h.prototype.equals=function(t){if(!h.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t?!0:h.compare(this,t)===0};h.prototype.inspect=function(){let t="",r=ke.INSPECT_MAX_BYTES;return t=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(t+=" ... "),"<Buffer "+t+">"};Tr&&(h.prototype[Tr]=h.prototype.inspect);h.prototype.compare=function(t,r,i,n,o){if(Z(t,Uint8Array)&&(t=h.from(t,t.offset,t.byteLength)),!h.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(r===void 0&&(r=0),i===void 0&&(i=t?t.length:0),n===void 0&&(n=0),o===void 0&&(o=this.length),r<0||i>t.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&r>=i)return 0;if(n>=o)return-1;if(r>=i)return 1;if(r>>>=0,i>>>=0,n>>>=0,o>>>=0,this===t)return 0;let s=o-n,a=i-r,c=Math.min(s,a),d=this.slice(n,o),g=t.slice(r,i);for(let y=0;y<c;++y)if(d[y]!==g[y]){s=d[y],a=g[y];break}return s<a?-1:a<s?1:0};function Lr(e,t,r,i,n){if(e.length===0)return-1;if(typeof r=="string"?(i=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,wt(r)&&(r=n?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(n)return-1;r=e.length-1}else if(r<0)if(n)r=0;else return-1;if(typeof t=="string"&&(t=h.from(t,i)),h.isBuffer(t))return t.length===0?-1:Ar(e,t,r,i,n);if(typeof t=="number")return t=t&255,typeof Uint8Array.prototype.indexOf=="function"?n?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):Ar(e,[t],r,i,n);throw new TypeError("val must be string, number or Buffer")}function Ar(e,t,r,i,n){let o=1,s=e.length,a=t.length;if(i!==void 0&&(i=String(i).toLowerCase(),i==="ucs2"||i==="ucs-2"||i==="utf16le"||i==="utf-16le")){if(e.length<2||t.length<2)return-1;o=2,s/=2,a/=2,r/=2}function c(g,y){return o===1?g[y]:g.readUInt16BE(y*o)}let d;if(n){let g=-1;for(d=r;d<s;d++)if(c(e,d)===c(t,g===-1?0:d-g)){if(g===-1&&(g=d),d-g+1===a)return g*o}else g!==-1&&(d-=d-g),g=-1}else for(r+a>s&&(r=s-a),d=r;d>=0;d--){let g=!0;for(let y=0;y<a;y++)if(c(e,d+y)!==c(t,y)){g=!1;break}if(g)return d}return-1}h.prototype.includes=function(t,r,i){return this.indexOf(t,r,i)!==-1};h.prototype.indexOf=function(t,r,i){return Lr(this,t,r,i,!0)};h.prototype.lastIndexOf=function(t,r,i){return Lr(this,t,r,i,!1)};function yo(e,t,r,i){r=Number(r)||0;let n=e.length-r;i?(i=Number(i),i>n&&(i=n)):i=n;let o=t.length;i>o/2&&(i=o/2);let s;for(s=0;s<i;++s){let a=parseInt(t.substr(s*2,2),16);if(wt(a))return s;e[r+s]=a}return s}function So(e,t,r,i){return et(Ot(t,e.length-r),e,r,i)}function vo(e,t,r,i){return et(Ho(t),e,r,i)}function xo(e,t,r,i){return et(Gr(t),e,r,i)}function Oo(e,t,r,i){return et(Fo(t,e.length-r),e,r,i)}h.prototype.write=function(t,r,i,n){if(r===void 0)n="utf8",i=this.length,r=0;else if(i===void 0&&typeof r=="string")n=r,i=this.length,r=0;else if(isFinite(r))r=r>>>0,isFinite(i)?(i=i>>>0,n===void 0&&(n="utf8")):(n=i,i=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let o=this.length-r;if((i===void 0||i>o)&&(i=o),t.length>0&&(i<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let s=!1;for(;;)switch(n){case"hex":return yo(this,t,r,i);case"utf8":case"utf-8":return So(this,t,r,i);case"ascii":case"latin1":case"binary":return vo(this,t,r,i);case"base64":return xo(this,t,r,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Oo(this,t,r,i);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),s=!0}};h.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Po(e,t,r){return t===0&&r===e.length?St.fromByteArray(e):St.fromByteArray(e.slice(t,r))}function Rr(e,t,r){r=Math.min(e.length,r);let i=[],n=t;for(;n<r;){let o=e[n],s=null,a=o>239?4:o>223?3:o>191?2:1;if(n+a<=r){let c,d,g,y;switch(a){case 1:o<128&&(s=o);break;case 2:c=e[n+1],(c&192)===128&&(y=(o&31)<<6|c&63,y>127&&(s=y));break;case 3:c=e[n+1],d=e[n+2],(c&192)===128&&(d&192)===128&&(y=(o&15)<<12|(c&63)<<6|d&63,y>2047&&(y<55296||y>57343)&&(s=y));break;case 4:c=e[n+1],d=e[n+2],g=e[n+3],(c&192)===128&&(d&192)===128&&(g&192)===128&&(y=(o&15)<<18|(c&63)<<12|(d&63)<<6|g&63,y>65535&&y<1114112&&(s=y))}}s===null?(s=65533,a=1):s>65535&&(s-=65536,i.push(s>>>10&1023|55296),s=56320|s&1023),i.push(s),n+=a}return _o(i)}var br=4096;function _o(e){let t=e.length;if(t<=br)return String.fromCharCode.apply(String,e);let r="",i=0;for(;i<t;)r+=String.fromCharCode.apply(String,e.slice(i,i+=br));return r}function Eo(e,t,r){let i="";r=Math.min(e.length,r);for(let n=t;n<r;++n)i+=String.fromCharCode(e[n]&127);return i}function wo(e,t,r){let i="";r=Math.min(e.length,r);for(let n=t;n<r;++n)i+=String.fromCharCode(e[n]);return i}function Io(e,t,r){let i=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>i)&&(r=i);let n="";for(let o=t;o<r;++o)n+=Co[e[o]];return n}function To(e,t,r){let i=e.slice(t,r),n="";for(let o=0;o<i.length-1;o+=2)n+=String.fromCharCode(i[o]+i[o+1]*256);return n}h.prototype.slice=function(t,r){let i=this.length;t=~~t,r=r===void 0?i:~~r,t<0?(t+=i,t<0&&(t=0)):t>i&&(t=i),r<0?(r+=i,r<0&&(r=0)):r>i&&(r=i),r<t&&(r=t);let n=this.subarray(t,r);return Object.setPrototypeOf(n,h.prototype),n};function H(e,t,r){if(e%1!==0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}h.prototype.readUintLE=h.prototype.readUIntLE=function(t,r,i){t=t>>>0,r=r>>>0,i||H(t,r,this.length);let n=this[t],o=1,s=0;for(;++s<r&&(o*=256);)n+=this[t+s]*o;return n};h.prototype.readUintBE=h.prototype.readUIntBE=function(t,r,i){t=t>>>0,r=r>>>0,i||H(t,r,this.length);let n=this[t+--r],o=1;for(;r>0&&(o*=256);)n+=this[t+--r]*o;return n};h.prototype.readUint8=h.prototype.readUInt8=function(t,r){return t=t>>>0,r||H(t,1,this.length),this[t]};h.prototype.readUint16LE=h.prototype.readUInt16LE=function(t,r){return t=t>>>0,r||H(t,2,this.length),this[t]|this[t+1]<<8};h.prototype.readUint16BE=h.prototype.readUInt16BE=function(t,r){return t=t>>>0,r||H(t,2,this.length),this[t]<<8|this[t+1]};h.prototype.readUint32LE=h.prototype.readUInt32LE=function(t,r){return t=t>>>0,r||H(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+this[t+3]*16777216};h.prototype.readUint32BE=h.prototype.readUInt32BE=function(t,r){return t=t>>>0,r||H(t,4,this.length),this[t]*16777216+(this[t+1]<<16|this[t+2]<<8|this[t+3])};h.prototype.readBigUInt64LE=de(function(t){t=t>>>0,be(t,"offset");let r=this[t],i=this[t+7];(r===void 0||i===void 0)&&Ve(t,this.length-8);let n=r+this[++t]*2**8+this[++t]*2**16+this[++t]*2**24,o=this[++t]+this[++t]*2**8+this[++t]*2**16+i*2**24;return BigInt(n)+(BigInt(o)<<BigInt(32))});h.prototype.readBigUInt64BE=de(function(t){t=t>>>0,be(t,"offset");let r=this[t],i=this[t+7];(r===void 0||i===void 0)&&Ve(t,this.length-8);let n=r*2**24+this[++t]*2**16+this[++t]*2**8+this[++t],o=this[++t]*2**24+this[++t]*2**16+this[++t]*2**8+i;return(BigInt(n)<<BigInt(32))+BigInt(o)});h.prototype.readIntLE=function(t,r,i){t=t>>>0,r=r>>>0,i||H(t,r,this.length);let n=this[t],o=1,s=0;for(;++s<r&&(o*=256);)n+=this[t+s]*o;return o*=128,n>=o&&(n-=Math.pow(2,8*r)),n};h.prototype.readIntBE=function(t,r,i){t=t>>>0,r=r>>>0,i||H(t,r,this.length);let n=r,o=1,s=this[t+--n];for(;n>0&&(o*=256);)s+=this[t+--n]*o;return o*=128,s>=o&&(s-=Math.pow(2,8*r)),s};h.prototype.readInt8=function(t,r){return t=t>>>0,r||H(t,1,this.length),this[t]&128?(255-this[t]+1)*-1:this[t]};h.prototype.readInt16LE=function(t,r){t=t>>>0,r||H(t,2,this.length);let i=this[t]|this[t+1]<<8;return i&32768?i|4294901760:i};h.prototype.readInt16BE=function(t,r){t=t>>>0,r||H(t,2,this.length);let i=this[t+1]|this[t]<<8;return i&32768?i|4294901760:i};h.prototype.readInt32LE=function(t,r){return t=t>>>0,r||H(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24};h.prototype.readInt32BE=function(t,r){return t=t>>>0,r||H(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]};h.prototype.readBigInt64LE=de(function(t){t=t>>>0,be(t,"offset");let r=this[t],i=this[t+7];(r===void 0||i===void 0)&&Ve(t,this.length-8);let n=this[t+4]+this[t+5]*2**8+this[t+6]*2**16+(i<<24);return(BigInt(n)<<BigInt(32))+BigInt(r+this[++t]*2**8+this[++t]*2**16+this[++t]*2**24)});h.prototype.readBigInt64BE=de(function(t){t=t>>>0,be(t,"offset");let r=this[t],i=this[t+7];(r===void 0||i===void 0)&&Ve(t,this.length-8);let n=(r<<24)+this[++t]*2**16+this[++t]*2**8+this[++t];return(BigInt(n)<<BigInt(32))+BigInt(this[++t]*2**24+this[++t]*2**16+this[++t]*2**8+i)});h.prototype.readFloatLE=function(t,r){return t=t>>>0,r||H(t,4,this.length),Ae.read(this,t,!0,23,4)};h.prototype.readFloatBE=function(t,r){return t=t>>>0,r||H(t,4,this.length),Ae.read(this,t,!1,23,4)};h.prototype.readDoubleLE=function(t,r){return t=t>>>0,r||H(t,8,this.length),Ae.read(this,t,!0,52,8)};h.prototype.readDoubleBE=function(t,r){return t=t>>>0,r||H(t,8,this.length),Ae.read(this,t,!1,52,8)};function L(e,t,r,i,n,o){if(!h.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>n||t<o)throw new RangeError('"value" argument is out of bounds');if(r+i>e.length)throw new RangeError("Index out of range")}h.prototype.writeUintLE=h.prototype.writeUIntLE=function(t,r,i,n){if(t=+t,r=r>>>0,i=i>>>0,!n){let a=Math.pow(2,8*i)-1;L(this,t,r,i,a,0)}let o=1,s=0;for(this[r]=t&255;++s<i&&(o*=256);)this[r+s]=t/o&255;return r+i};h.prototype.writeUintBE=h.prototype.writeUIntBE=function(t,r,i,n){if(t=+t,r=r>>>0,i=i>>>0,!n){let a=Math.pow(2,8*i)-1;L(this,t,r,i,a,0)}let o=i-1,s=1;for(this[r+o]=t&255;--o>=0&&(s*=256);)this[r+o]=t/s&255;return r+i};h.prototype.writeUint8=h.prototype.writeUInt8=function(t,r,i){return t=+t,r=r>>>0,i||L(this,t,r,1,255,0),this[r]=t&255,r+1};h.prototype.writeUint16LE=h.prototype.writeUInt16LE=function(t,r,i){return t=+t,r=r>>>0,i||L(this,t,r,2,65535,0),this[r]=t&255,this[r+1]=t>>>8,r+2};h.prototype.writeUint16BE=h.prototype.writeUInt16BE=function(t,r,i){return t=+t,r=r>>>0,i||L(this,t,r,2,65535,0),this[r]=t>>>8,this[r+1]=t&255,r+2};h.prototype.writeUint32LE=h.prototype.writeUInt32LE=function(t,r,i){return t=+t,r=r>>>0,i||L(this,t,r,4,4294967295,0),this[r+3]=t>>>24,this[r+2]=t>>>16,this[r+1]=t>>>8,this[r]=t&255,r+4};h.prototype.writeUint32BE=h.prototype.writeUInt32BE=function(t,r,i){return t=+t,r=r>>>0,i||L(this,t,r,4,4294967295,0),this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=t&255,r+4};function Br(e,t,r,i,n){Mr(t,i,n,e,r,7);let o=Number(t&BigInt(4294967295));e[r++]=o,o=o>>8,e[r++]=o,o=o>>8,e[r++]=o,o=o>>8,e[r++]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=s,s=s>>8,e[r++]=s,s=s>>8,e[r++]=s,s=s>>8,e[r++]=s,r}function Nr(e,t,r,i,n){Mr(t,i,n,e,r,7);let o=Number(t&BigInt(4294967295));e[r+7]=o,o=o>>8,e[r+6]=o,o=o>>8,e[r+5]=o,o=o>>8,e[r+4]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=s,s=s>>8,e[r+2]=s,s=s>>8,e[r+1]=s,s=s>>8,e[r]=s,r+8}h.prototype.writeBigUInt64LE=de(function(t,r=0){return Br(this,t,r,BigInt(0),BigInt("0xffffffffffffffff"))});h.prototype.writeBigUInt64BE=de(function(t,r=0){return Nr(this,t,r,BigInt(0),BigInt("0xffffffffffffffff"))});h.prototype.writeIntLE=function(t,r,i,n){if(t=+t,r=r>>>0,!n){let c=Math.pow(2,8*i-1);L(this,t,r,i,c-1,-c)}let o=0,s=1,a=0;for(this[r]=t&255;++o<i&&(s*=256);)t<0&&a===0&&this[r+o-1]!==0&&(a=1),this[r+o]=(t/s>>0)-a&255;return r+i};h.prototype.writeIntBE=function(t,r,i,n){if(t=+t,r=r>>>0,!n){let c=Math.pow(2,8*i-1);L(this,t,r,i,c-1,-c)}let o=i-1,s=1,a=0;for(this[r+o]=t&255;--o>=0&&(s*=256);)t<0&&a===0&&this[r+o+1]!==0&&(a=1),this[r+o]=(t/s>>0)-a&255;return r+i};h.prototype.writeInt8=function(t,r,i){return t=+t,r=r>>>0,i||L(this,t,r,1,127,-128),t<0&&(t=255+t+1),this[r]=t&255,r+1};h.prototype.writeInt16LE=function(t,r,i){return t=+t,r=r>>>0,i||L(this,t,r,2,32767,-32768),this[r]=t&255,this[r+1]=t>>>8,r+2};h.prototype.writeInt16BE=function(t,r,i){return t=+t,r=r>>>0,i||L(this,t,r,2,32767,-32768),this[r]=t>>>8,this[r+1]=t&255,r+2};h.prototype.writeInt32LE=function(t,r,i){return t=+t,r=r>>>0,i||L(this,t,r,4,2147483647,-2147483648),this[r]=t&255,this[r+1]=t>>>8,this[r+2]=t>>>16,this[r+3]=t>>>24,r+4};h.prototype.writeInt32BE=function(t,r,i){return t=+t,r=r>>>0,i||L(this,t,r,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=t&255,r+4};h.prototype.writeBigInt64LE=de(function(t,r=0){return Br(this,t,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});h.prototype.writeBigInt64BE=de(function(t,r=0){return Nr(this,t,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Ur(e,t,r,i,n,o){if(r+i>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function qr(e,t,r,i,n){return t=+t,r=r>>>0,n||Ur(e,t,r,4,34028234663852886e22,-34028234663852886e22),Ae.write(e,t,r,i,23,4),r+4}h.prototype.writeFloatLE=function(t,r,i){return qr(this,t,r,!0,i)};h.prototype.writeFloatBE=function(t,r,i){return qr(this,t,r,!1,i)};function Dr(e,t,r,i,n){return t=+t,r=r>>>0,n||Ur(e,t,r,8,17976931348623157e292,-17976931348623157e292),Ae.write(e,t,r,i,52,8),r+8}h.prototype.writeDoubleLE=function(t,r,i){return Dr(this,t,r,!0,i)};h.prototype.writeDoubleBE=function(t,r,i){return Dr(this,t,r,!1,i)};h.prototype.copy=function(t,r,i,n){if(!h.isBuffer(t))throw new TypeError("argument should be a Buffer");if(i||(i=0),!n&&n!==0&&(n=this.length),r>=t.length&&(r=t.length),r||(r=0),n>0&&n<i&&(n=i),n===i||t.length===0||this.length===0)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-r<n-i&&(n=t.length-r+i);let o=n-i;return this===t&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(r,i,n):Uint8Array.prototype.set.call(t,this.subarray(i,n),r),o};h.prototype.fill=function(t,r,i,n){if(typeof t=="string"){if(typeof r=="string"?(n=r,r=0,i=this.length):typeof i=="string"&&(n=i,i=this.length),n!==void 0&&typeof n!="string")throw new TypeError("encoding must be a string");if(typeof n=="string"&&!h.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(t.length===1){let s=t.charCodeAt(0);(n==="utf8"&&s<128||n==="latin1")&&(t=s)}}else typeof t=="number"?t=t&255:typeof t=="boolean"&&(t=Number(t));if(r<0||this.length<r||this.length<i)throw new RangeError("Out of range index");if(i<=r)return this;r=r>>>0,i=i===void 0?this.length:i>>>0,t||(t=0);let o;if(typeof t=="number")for(o=r;o<i;++o)this[o]=t;else{let s=h.isBuffer(t)?t:h.from(t,n),a=s.length;if(a===0)throw new TypeError('The value "'+t+'" is invalid for argument "value"');for(o=0;o<i-r;++o)this[o+r]=s[o%a]}return this};var Te={};function Et(e,t,r){Te[e]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(n){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:n,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}Et("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError);Et("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError);Et("ERR_OUT_OF_RANGE",function(e,t,r){let i=`The value of "${e}" is out of range.`,n=r;return Number.isInteger(r)&&Math.abs(r)>2**32?n=kr(String(r)):typeof r=="bigint"&&(n=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(n=kr(n)),n+="n"),i+=` It must be ${t}. Received ${n}`,i},RangeError);function kr(e){let t="",r=e.length,i=e[0]==="-"?1:0;for(;r>=i+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function Ao(e,t,r){be(t,"offset"),(e[t]===void 0||e[t+r]===void 0)&&Ve(t,e.length-(r+1))}function Mr(e,t,r,i,n,o){if(e>r||e<t){let s=typeof t=="bigint"?"n":"",a;throw o>3?t===0||t===BigInt(0)?a=`>= 0${s} and < 2${s} ** ${(o+1)*8}${s}`:a=`>= -(2${s} ** ${(o+1)*8-1}${s}) and < 2 ** ${(o+1)*8-1}${s}`:a=`>= ${t}${s} and <= ${r}${s}`,new Te.ERR_OUT_OF_RANGE("value",a,e)}Ao(i,n,o)}function be(e,t){if(typeof e!="number")throw new Te.ERR_INVALID_ARG_TYPE(t,"number",e)}function Ve(e,t,r){throw Math.floor(e)!==e?(be(e,r),new Te.ERR_OUT_OF_RANGE(r||"offset","an integer",e)):t<0?new Te.ERR_BUFFER_OUT_OF_BOUNDS:new Te.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}var bo=/[^+/0-9A-Za-z-_]/g;function ko(e){if(e=e.split("=")[0],e=e.trim().replace(bo,""),e.length<2)return"";for(;e.length%4!==0;)e=e+"=";return e}function Ot(e,t){t=t||1/0;let r,i=e.length,n=null,o=[];for(let s=0;s<i;++s){if(r=e.charCodeAt(s),r>55295&&r<57344){if(!n){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}else if(s+1===i){(t-=3)>-1&&o.push(239,191,189);continue}n=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),n=r;continue}r=(n-55296<<10|r-56320)+65536}else n&&(t-=3)>-1&&o.push(239,191,189);if(n=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,r&63|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return o}function Ho(e){let t=[];for(let r=0;r<e.length;++r)t.push(e.charCodeAt(r)&255);return t}function Fo(e,t){let r,i,n,o=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)r=e.charCodeAt(s),i=r>>8,n=r%256,o.push(n),o.push(i);return o}function Gr(e){return St.toByteArray(ko(e))}function et(e,t,r,i){let n;for(n=0;n<i&&!(n+r>=t.length||n>=e.length);++n)t[n+r]=e[n];return n}function Z(e,t){return e instanceof t||e!=null&&e.constructor!=null&&e.constructor.name!=null&&e.constructor.name===t.name}function wt(e){return e!==e}var Co=(function(){let e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){let i=r*16;for(let n=0;n<16;++n)t[i+n]=e[r]+e[n]}return t})();function de(e){return typeof BigInt>"u"?Lo:e}function Lo(){throw new Error("BigInt not supported")}});var m,u,f=Zn(()=>{m=yr(Pr()),u=yr(Vr())});var fe=x(($a,zr)=>{f();zr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.crypto.Hash});var q=x((Xa,Kr)=>{f();Kr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Transaction});var It=x((Wa,$r)=>{f();$r.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Address});var A=x((Za,Yr)=>{f();Yr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Script});var _e=x((ec,Xr)=>{f();Xr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Transaction.sighash});var He=x((rc,jr)=>{f();jr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Transaction.Input});var ge=x((nc,Wr)=>{f();Wr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Script.Interpreter});var Ee=x((sc,Qr)=>{f();Qr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.crypto.Signature});var D=x((cc,Zr)=>{f();Zr.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.crypto.BN});var F=x((hc,Jr)=>{"use strict";f();Jr.exports={}});var oi=x((lc,ni)=>{"use strict";f();var ri=_e(),Ro=He(),Fe=ge(),ei=Ee(),Bo=fe(),Tt=D(),ii=q(),me=A(),ti=F(),se;try{se=F()}catch{se=null}var No=function(){var e=typeof m.default<"u"&&m.default.env&&m.default.env.BSV_DEBUG||typeof window<"u"&&window.BSV_DEBUG;e&&console.log.apply(console,arguments)};function R(e,t){if(!(this instanceof R))return new R(e,t);this.privateKey=e,this.publicKey=e.publicKey,this.address=e.toAddress(),t=t||{},this.storageDir=t.storageDir||(typeof m.default<"u"?ti.join(m.default.cwd(),".bsv-covenants"):".bsv-covenants"),this.covenantUtxoPath=ti.join(this.storageDir,"covenant_utxos.json"),this.sighashType=ei.SIGHASH_ALL|ei.SIGHASH_FORKID,this.allowNonEnforcing=t.allowNonEnforcing===!0,se&&this._ensureStorageDir()}R.prototype.createFromP2PKH=function(e){if(!this.allowNonEnforcing)throw new Error("SmartContract.Covenant builds a NON-ENFORCING script that reduces to plain P2PK \u2014 it does not constrain the spend. Use SmartContract.PushTx.valueCovenant (output binding) or SmartContract.Token / perpetualCovenant (stateful covenants) for real covenants. To use this demo anyway, construct with { allowNonEnforcing: true }.");e.script||(e.script=R.reconstructP2pkhScript(this.address));var t=new ii().from({txId:e.txid,outputIndex:e.vout,script:e.script,satoshis:e.satoshis}).to(this.address,e.satoshis-1e3),r=me.fromHex(e.script),i=ri.sighashPreimage(t,this.sighashType,0,r,new Tt(e.satoshis)),n=Bo.sha256sha256(i),o=new me().add("OP_DUP").add("OP_HASH256").add(n).add("OP_EQUALVERIFY").add("OP_DROP").add(this.publicKey.toBuffer()).add("OP_CHECKSIG");t.outputs[0].setScript(o),t.sign(this.privateKey);var s={txid:t.id,vout:0,satoshis:e.satoshis-1e3,script:o.toHex(),scriptPubKey:o.toHex(),preimageHash:n.toString("hex"),originalPreimage:i.toString("hex"),status:"local",createdAt:new Date().toISOString(),type:"preimage_covenant"};return{transaction:t,covenantUtxo:s}};R.prototype.createSpendingTx=function(e,t,r){var i=t||this.address,n=r||e.satoshis-500,o=new ii;o.addInput(new Ro({prevTxId:e.txid,outputIndex:e.vout,script:me.empty()}),me.fromHex(e.script),e.satoshis),o.to(i,n);var s=me.fromHex(e.script),a=ri.sign(o,this.privateKey,this.sighashType,0,s,new Tt(e.satoshis)),c=u.Buffer.concat([a.toDER(),u.Buffer.from([this.sighashType])]),d=u.Buffer.from(e.originalPreimage,"hex"),g=new me().add(c).add(d);return o.inputs[0].setScript(g),o};R.prototype.validate=function(e,t){var r=new Fe,i=Fe.SCRIPT_VERIFY_P2SH|Fe.SCRIPT_VERIFY_STRICTENC|Fe.SCRIPT_VERIFY_DERSIG|Fe.SCRIPT_VERIFY_LOW_S|Fe.SCRIPT_ENABLE_SIGHASH_FORKID,n=e.inputs[0].script,o=me.fromHex(t.script),s=r.verify(n,o,e,0,i,new Tt(t.satoshis));return{valid:s,error:s?null:r.errstr}};R.prototype.save=function(e){if(!se)return No("File system operations not available in browser environment"),e;var t=this.list();return t.push(e),se.writeFileSync(this.covenantUtxoPath,JSON.stringify(t,null,2)),e};R.prototype.load=function(e){var t=this.list();if(e){var r=t.find(function(i){return i.txid===e});if(!r)throw new Error("Covenant UTXO with TXID "+e+" not found");return r}else{var r=t.find(function(n){return n.type==="preimage_covenant"});if(!r)throw new Error("No preimage covenant UTXO found");return r}};R.prototype.list=function(){return se.existsSync(this.covenantUtxoPath)?JSON.parse(se.readFileSync(this.covenantUtxoPath,"utf8")):[]};R.prototype.getPortfolio=function(){var e=this.list(),t={total:e.length,totalValue:e.reduce(function(r,i){return r+i.satoshis},0),byStatus:{},recent:e.slice(-5)};return e.forEach(function(r){var i=r.status||"local";t.byStatus[i]||(t.byStatus[i]={count:0,value:0}),t.byStatus[i].count++,t.byStatus[i].value+=r.satoshis}),t};R.prototype.completeFlow=function(e,t){var r=this.createFromP2PKH(e),i=this.save(r.covenantUtxo);t&&t(r.transaction,"creation");var n=this.createSpendingTx(i),o=this.validate(n,i);return t&&o.valid&&t(n,"spending"),{creationTx:r.transaction,spendingTx:n,covenantUtxo:i,validation:o,success:o.valid}};R.prototype._ensureStorageDir=function(){se.existsSync(this.storageDir)||se.mkdirSync(this.storageDir,{recursive:!0})};R.reconstructP2pkhScript=function(e){return me.buildPublicKeyHashOut(e).toHex()};ni.exports=R});var ze=x((fc,si)=>{f();si.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.PrivateKey});var J=x((yc,ci)=>{"use strict";f();var Uo=_e(),qo=D(),Do=q(),Mo=ze(),ai=A(),mc=F();function S(e,t){if(!(this instanceof S))return new S(e,t);this.preimage=u.Buffer.isBuffer(e)?e:u.Buffer.from(e,"hex"),this.options=t||{},this.strategy=this.options.strategy||"DYNAMIC",this.fields=null,this.sighashInfo=null,this.options.deferExtraction||this._extractFields()}S.LEFT_FIXED_LENGTH=104;S.RIGHT_FIXED_LENGTH=52;S.MIN_PREIMAGE_LENGTH=S.LEFT_FIXED_LENGTH+1+S.RIGHT_FIXED_LENGTH;S.prototype.extract=function(e){return this.strategy=e||this.strategy,this._extractFields(),this.fields};S.prototype.getSighashInfo=function(){return this.fields||this._extractFields(),this.sighashInfo};S.prototype.getField=function(e){return this.fields||this._extractFields(),this.fields[e]};S.prototype.extractField=function(e,t){t=t||{},this.fields||this._extractFields();var r=this._parsePreimageStructure(),i=this._generateBidirectionalASM(e,r,t.includeComments),n=this._extractSpecificField(e,r),o=this._interpretField(e,n,r);return{field:e,value:n?n.toString("hex"):null,buffer:n,asm:i,interpretation:o,strategy:this._getExtractionStrategy(e),structure:r._structure}};S.prototype.generateASM=function(e,t){var r=this._parsePreimageStructure();return this._generateBidirectionalASM(e,r,t)};S.prototype.extractFields=function(e){var t={};return e.forEach(function(r){t[r]=this.extractField(r)}.bind(this)),t};S.prototype.validate=function(){var e=[],t=[];if(this.preimage.length<S.MIN_PREIMAGE_LENGTH)return e.push("Preimage too short: "+this.preimage.length+" bytes (BIP-143 preimage requires at least "+S.MIN_PREIMAGE_LENGTH+")"),{valid:!1,errors:e,warnings:t,sighashInfo:this.sighashInfo};this.fields||this._extractFields();var r=["version","hashPrevouts","hashSequence","outpoint","scriptCode","amount","sequence","hashOutputs","locktime","sighash"];return r.forEach(function(i){this.fields[i]||e.push("Missing required field: "+i)}.bind(this)),this.sighashInfo.hasZeroHashes&&t.push("Zero hashes detected - check SIGHASH flags: "+this.sighashInfo.zeroFields.join(", ")),{valid:e.length===0,errors:e,warnings:t,sighashInfo:this.sighashInfo}};S.prototype.toObject=function(){return this.fields||this._extractFields(),{preimage:this.preimage.toString("hex"),length:this.preimage.length,strategy:this.strategy,fields:{version:this.fields.version?this.fields.version.toString("hex"):null,hashPrevouts:this.fields.hashPrevouts?this.fields.hashPrevouts.toString("hex"):null,hashSequence:this.fields.hashSequence?this.fields.hashSequence.toString("hex"):null,outpoint:this.fields.outpoint?this.fields.outpoint.toString("hex"):null,scriptCode:this.fields.scriptCode?this.fields.scriptCode.toString("hex"):null,scriptCodeLength:this.fields.scriptCodeLength,amount:this.fields.amount?this.fields.amount.toString("hex"):null,sequence:this.fields.sequence?this.fields.sequence.toString("hex"):null,hashOutputs:this.fields.hashOutputs?this.fields.hashOutputs.toString("hex"):null,locktime:this.fields.locktime?this.fields.locktime.toString("hex"):null,sighash:this.fields.sighash?this.fields.sighash.toString("hex"):null},sighashInfo:this.sighashInfo,validation:this.validate()}};S.prototype._extractFields=function(){if(this.fields={},this.sighashInfo={flag:null,hasZeroHashes:!1,zeroFields:[],warnings:[]},this.preimage.length<S.MIN_PREIMAGE_LENGTH)throw new Error("Preimage too short: "+this.preimage.length+" bytes (BIP-143 preimage requires at least "+S.MIN_PREIMAGE_LENGTH+")");try{this.strategy==="LEFT"||this.strategy==="DYNAMIC"?this._extractFromLeft():this.strategy==="RIGHT"&&this._extractFromRight(),this._analyzeSighash()}catch(e){if(this.strategy==="DYNAMIC")try{this.strategy="RIGHT",this._extractFromRight(),this._analyzeSighash()}catch{throw new Error("Failed to extract preimage fields with any strategy: "+e.message)}else throw e}};S.prototype._extractFromLeft=function(){var e=0;this.fields.version=this.preimage.slice(e,e+4),e+=4,this.fields.hashPrevouts=this.preimage.slice(e,e+32),e+=32,this.fields.hashSequence=this.preimage.slice(e,e+32),e+=32,this.fields.outpoint=this.preimage.slice(e,e+36),e+=36;var t=S.decodeCompactSize(this.preimage,e);this.fields.scriptCodeLength=t.value,e=t.nextOffset,this.fields.scriptCode=this.preimage.slice(e,e+this.fields.scriptCodeLength),e+=this.fields.scriptCodeLength,this.fields.amount=this.preimage.slice(e,e+8),e+=8,this.fields.sequence=this.preimage.slice(e,e+4),e+=4,this.fields.hashOutputs=this.preimage.slice(e,e+32),e+=32,this.fields.locktime=this.preimage.slice(e,e+4),e+=4,this.fields.sighash=this.preimage.slice(e,e+4)};S.prototype._extractFromRight=function(){var e=this.preimage.length,t=e;t-=4,this.fields.sighash=this.preimage.slice(t,t+4),t-=4,this.fields.locktime=this.preimage.slice(t,t+4),t-=32,this.fields.hashOutputs=this.preimage.slice(t,t+32),t-=4,this.fields.sequence=this.preimage.slice(t,t+4),t-=8,this.fields.amount=this.preimage.slice(t,t+8);var r=104,i=S.decodeCompactSize(this.preimage,r);this.fields.scriptCodeLength=i.value,this.fields.scriptCode=this.preimage.slice(i.nextOffset,i.nextOffset+this.fields.scriptCodeLength),this.fields.version=this.preimage.slice(0,4),this.fields.hashPrevouts=this.preimage.slice(4,36),this.fields.hashSequence=this.preimage.slice(36,68),this.fields.outpoint=this.preimage.slice(68,104)};S.prototype._analyzeSighash=function(){if(this.fields.sighash){var e=this.fields.sighash.readUInt32LE(0);this.sighashInfo.flag=e;var t=e&31,r=(e&128)!==0,i=(e&64)!==0,n=u.Buffer.alloc(32);r&&this.fields.hashPrevouts.equals(n)&&(this.sighashInfo.hasZeroHashes=!0,this.sighashInfo.zeroFields.push("hashPrevouts"),this.sighashInfo.warnings.push("ANYONECANPAY flag detected - hashPrevouts is zero")),t===2&&this.fields.hashSequence.equals(n)&&(this.sighashInfo.hasZeroHashes=!0,this.sighashInfo.zeroFields.push("hashSequence"),this.sighashInfo.warnings.push("SIGHASH_NONE flag detected - hashSequence is zero")),(t===2||t===3)&&this.fields.hashOutputs.equals(n)&&(this.sighashInfo.hasZeroHashes=!0,this.sighashInfo.zeroFields.push("hashOutputs"),this.sighashInfo.warnings.push("SIGHASH_NONE/SINGLE flag detected - hashOutputs is zero"));var o=[];t===1?o.push("ALL"):t===2?o.push("NONE"):t===3&&o.push("SINGLE"),r&&o.push("ANYONECANPAY"),i&&o.push("FORKID"),this.sighashInfo.flagName=o.join(" | ")}};S.prototype._parsePreimageStructure=function(){for(var e=this.preimage,t=0,r={},i=[{name:"nVersion",len:4},{name:"hashPrevouts",len:32},{name:"hashSequence",len:32},{name:"outpoint_txid",len:32},{name:"outpoint_vout",len:4}],n=[{name:"value",len:8},{name:"nSequence",len:4},{name:"hashOutputs",len:32},{name:"nLocktime",len:4},{name:"sighashType",len:4}],o=0;o<i.length;o++){var s=i[o];r[s.name]=e.slice(t,t+s.len).toString("hex"),t+=s.len}var a=S.decodeCompactSize(e,t);r.scriptLen=a.value,r.scriptLenSize=a.bytes,r.scriptLenRaw=e.slice(t,t+a.bytes).toString("hex"),t+=a.bytes,r.scriptCode=e.slice(t,t+r.scriptLen).toString("hex"),t+=r.scriptLen;for(var c=0;c<n.length;c++){var d=n[c];r[d.name]=e.slice(t,t+d.len).toString("hex"),t+=d.len}var g=i.reduce(function(P,O){return P+O.len},0),y=n.reduce(function(P,O){return P+O.len},0);return r._structure={leftFixed:g,scriptLenVarint:a.bytes,scriptCode:r.scriptLen,rightFixed:y,totalCalculated:g+a.bytes+r.scriptLen+y,totalActual:e.length},r};S.prototype._generateBidirectionalASM=function(e,t,r){var i=["value","nSequence","hashOutputs","nLocktime","sighashType"],n=["nVersion","hashPrevouts","hashSequence","outpoint_txid","outpoint_vout"];if(i.includes(e))return this._generateRightExtractionASM(e,r);if(n.includes(e))return this._generateLeftExtractionASM(e,r);if(e==="scriptCode")return this._generateDynamicExtractionASM(t,r);if(e==="scriptLen")return this._generateScriptLenExtractionASM(t,r);throw new Error("Unknown field: "+e)};S.prototype._generateRightExtractionASM=function(e,t){for(var r=[{name:"value",len:8},{name:"nSequence",len:4},{name:"hashOutputs",len:32},{name:"nLocktime",len:4},{name:"sighashType",len:4}],i=0,n=0,o=!1,s=0;s<r.length;s++){var a=r[s];if(a.name===e){n=a.len,o=!0;break}i+=a.len}if(!o)throw new Error("Field not found in RIGHT fields: "+e);var c=52,d=c-i,g=[];return t?(g.push("# \u{1F504} Extract "+e+" from RIGHT side (bidirectional strategy)"),g.push("OP_SIZE # Push preimage size: [preimage, size]")):g.push("OP_SIZE"),t?g=g.concat([d+" OP_SUB # Calculate split point: [preimage, split_point]","OP_SPLIT # Split: [left_part, right_part]","OP_NIP # Drop left (OP_SPLIT leaves right on top): [right_part]",n+" OP_SPLIT # Extract field: ["+e+", remaining]","OP_DROP # Clean up: ["+e+"]","# \u2705 Result: "+e+" is now on top of stack"]):g=g.concat([d+" OP_SUB","OP_SPLIT","OP_NIP",n+" OP_SPLIT","OP_DROP"]),g.join(`
|
|
2
2
|
`)};S.prototype._generateLeftExtractionASM=function(e,t){var r=[{name:"nVersion",len:4,offset:0},{name:"hashPrevouts",len:32,offset:4},{name:"hashSequence",len:32,offset:36},{name:"outpoint_txid",len:32,offset:68},{name:"outpoint_vout",len:4,offset:100}],i=r.find(function(o){return o.name===e});if(!i)throw new Error("Field not found in LEFT fields: "+e);var n=[];return t?n=["# \u{1F504} Extract "+e+" from LEFT side (bidirectional strategy)",i.offset+" OP_SPLIT # Skip to field: [prefix, remainder]","OP_NIP # Drop prefix (OP_SPLIT leaves remainder on top): [remainder]",i.len+" OP_SPLIT # Extract field: ["+e+", suffix]","OP_DROP # Clean up: ["+e+"]","# \u2705 Result: "+e+" is now on top of stack"]:n=[i.offset+" OP_SPLIT","OP_NIP",i.len+" OP_SPLIT","OP_DROP"],n.join(`
|
|
3
3
|
`)};S.prototype._generateDynamicExtractionASM=function(e,t){var r=104+e.scriptLenSize;return["# \u{1F3AF} Extract scriptCode DYNAMICALLY with CompactSize varint support",r+" OP_SPLIT # Skip left zone + scriptLen varint: [left_zone, remainder]","OP_NIP # Drop left (OP_SPLIT leaves remainder on top): [remainder]",e.scriptLen+" OP_SPLIT # Extract scriptCode: [scriptCode, right_zone]","OP_DROP # Clean up: [scriptCode]","# \u2705 Result: scriptCode extracted with "+e.scriptLenSize+"-byte varint awareness"].join(`
|
|
4
4
|
`)};S.prototype._generateScriptLenExtractionASM=function(e,t){return["# \u{1F3AF} Extract scriptLen CompactSize varint ("+e.scriptLenSize+" bytes)","104 OP_SPLIT # Skip left fixed fields: [left_zone, remainder]","OP_NIP # Drop left (OP_SPLIT leaves remainder on top): [remainder]",e.scriptLenSize+" OP_SPLIT # Extract varint: [scriptLen_varint, suffix]","OP_DROP # Clean up: [scriptLen_varint]","# \u2705 Result: CompactSize varint (decode off-chain to get "+e.scriptLen+")"].join(`
|
|
5
|
-
`)};S.prototype._extractSpecificField=function(e,t){var r=t[e];return r?u.Buffer.from(r,"hex"):null};S.prototype._interpretField=function(e,t,r){if(!t)return null;var i={raw:t.toString("hex"),bytes:t.length};try{switch(e){case"nVersion":i.value=t.readUInt32LE(0),i.description="Transaction version "+i.value;break;case"value":t.length===8&&(i.satoshis=t.readBigUInt64LE(0).toString(),i.description=i.satoshis+" satoshis");break;case"sighashType":var n=t.readUInt32LE(0),o={1:"SIGHASH_ALL",65:"SIGHASH_ALL | FORKID",2:"SIGHASH_NONE",66:"SIGHASH_NONE | FORKID",3:"SIGHASH_SINGLE",67:"SIGHASH_SINGLE | FORKID"};i.value=n,i.description=o[n]||"Custom ("+n+")";break;case"outpoint_vout":i.value=t.readUInt32LE(0),i.description="Output index "+i.value;break;case"scriptLen":i.varintSize=r.scriptLenSize,i.scriptLength=r.scriptLen,i.description=r.scriptLen+" bytes encoded as "+r.scriptLenSize+"-byte varint";break;case"scriptCode":t.length===25&&t[0]===118&&t[1]===169?(i.description="Standard P2PKH script (25 bytes)",i.type="P2PKH"):t.length>0&&t[0]===106?(i.description="OP_RETURN data script ("+t.length+" bytes)",i.type="OP_RETURN"):(i.description="Custom script ("+t.length+" bytes)",i.type="CUSTOM");break;default:if(["hashPrevouts","hashSequence","hashOutputs"].includes(e)){var s=u.Buffer.alloc(32);t.equals(s)?(i.isZero=!0,i.description="Zero hash (check SIGHASH flags)"):i.description="32-byte hash"}}}catch(a){i.error=a.message}return i};S.prototype._getExtractionStrategy=function(e){var t=["value","nSequence","hashOutputs","nLocktime","sighashType"],r=["nVersion","hashPrevouts","hashSequence","outpoint_txid","outpoint_vout"];return t.includes(e)?"RIGHT":r.includes(e)?"LEFT":e==="scriptCode"?"DYNAMIC":e==="scriptLen"?"VARINT":"UNKNOWN"};S.decodeCompactSize=function(e,t){if(t>=e.length)throw new Error("CompactSize read past end of preimage buffer (offset "+t+", length "+e.length+")");var r=e[t];if(r<253)return{value:r,nextOffset:t+1,bytes:1};if(r===253){if(t+3>e.length)throw new Error("Truncated 2-byte CompactSize in preimage at offset "+t);var i=e.readUInt16LE(t+1);return{value:i,nextOffset:t+3,bytes:3}}else if(r===254){if(t+5>e.length)throw new Error("Truncated 4-byte CompactSize in preimage at offset "+t);var n=e.readUInt32LE(t+1);return{value:n,nextOffset:t+5,bytes:5}}else throw new Error("Invalid CompactSize: 8-byte length prefix (0xff) is not a valid script length")};S.fromTransaction=function(e,t,r,i,n){var o=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:`)
|
|
9
|
-
\u{1F9EA} Example: Stack manipulation simulation`);try{let t=["OP_1","OP_2","OP_ADD","OP_3","OP_EQUAL"],r
|
|
5
|
+
`)};S.prototype._extractSpecificField=function(e,t){var r=t[e];return r?u.Buffer.from(r,"hex"):null};S.prototype._interpretField=function(e,t,r){if(!t)return null;var i={raw:t.toString("hex"),bytes:t.length};try{switch(e){case"nVersion":i.value=t.readUInt32LE(0),i.description="Transaction version "+i.value;break;case"value":t.length===8&&(i.satoshis=t.readBigUInt64LE(0).toString(),i.description=i.satoshis+" satoshis");break;case"sighashType":var n=t.readUInt32LE(0),o={1:"SIGHASH_ALL",65:"SIGHASH_ALL | FORKID",2:"SIGHASH_NONE",66:"SIGHASH_NONE | FORKID",3:"SIGHASH_SINGLE",67:"SIGHASH_SINGLE | FORKID"};i.value=n,i.description=o[n]||"Custom ("+n+")";break;case"outpoint_vout":i.value=t.readUInt32LE(0),i.description="Output index "+i.value;break;case"scriptLen":i.varintSize=r.scriptLenSize,i.scriptLength=r.scriptLen,i.description=r.scriptLen+" bytes encoded as "+r.scriptLenSize+"-byte varint";break;case"scriptCode":t.length===25&&t[0]===118&&t[1]===169?(i.description="Standard P2PKH script (25 bytes)",i.type="P2PKH"):t.length>0&&t[0]===106?(i.description="OP_RETURN data script ("+t.length+" bytes)",i.type="OP_RETURN"):(i.description="Custom script ("+t.length+" bytes)",i.type="CUSTOM");break;default:if(["hashPrevouts","hashSequence","hashOutputs"].includes(e)){var s=u.Buffer.alloc(32);t.equals(s)?(i.isZero=!0,i.description="Zero hash (check SIGHASH flags)"):i.description="32-byte hash"}}}catch(a){i.error=a.message}return i};S.prototype._getExtractionStrategy=function(e){var t=["value","nSequence","hashOutputs","nLocktime","sighashType"],r=["nVersion","hashPrevouts","hashSequence","outpoint_txid","outpoint_vout"];return t.includes(e)?"RIGHT":r.includes(e)?"LEFT":e==="scriptCode"?"DYNAMIC":e==="scriptLen"?"VARINT":"UNKNOWN"};S.decodeCompactSize=function(e,t){if(t>=e.length)throw new Error("CompactSize read past end of preimage buffer (offset "+t+", length "+e.length+")");var r=e[t];if(r<253)return{value:r,nextOffset:t+1,bytes:1};if(r===253){if(t+3>e.length)throw new Error("Truncated 2-byte CompactSize in preimage at offset "+t);var i=e.readUInt16LE(t+1);return{value:i,nextOffset:t+3,bytes:3}}else if(r===254){if(t+5>e.length)throw new Error("Truncated 4-byte CompactSize in preimage at offset "+t);var n=e.readUInt32LE(t+1);return{value:n,nextOffset:t+5,bytes:5}}else throw new Error("Invalid CompactSize: 8-byte length prefix (0xff) is not a valid script length")};S.fromTransaction=function(e,t,r,i,n){var o=Uo.sighashPreimage(e,n,t,r,new qo(i));return new S(o,{transaction:e,inputIndex:t,subscript:r,satoshis:i,sighashType:n})};S.createExample=function(e){var t=Mo.fromRandom(),r=t.toAddress(),i={txId:"0".repeat(64),outputIndex:0,script:ai.buildPublicKeyHashOut(r).toHex(),satoshis:1e5},n=new Do().from(i).to(r,99e3),o=ai.fromHex(i.script);return S.fromTransaction(n,0,o,i.satoshis,e)};S.extractFromHex=function(e,t,r){var i=new S(e,{deferExtraction:!0});return i.extractField(t,r)};S.generateASMFromHex=function(e,t,r){var i=new S(e,{deferExtraction:!0});return i.generateASM(t,r)};S.extractMultipleFromHex=function(e,t){var r=new S(e,{deferExtraction:!0});return r.extractFields(t)};S.validateFromHex=function(e){var t=new S(e);return t.validate()};S.analyzeFromHex=function(e){var t=new S(e),r=t._parsePreimageStructure(),i=t.validate();return{hex:e,length:e.length/2,structure:r._structure,fields:r,validation:i,sighashInfo:t.getSighashInfo(),extractField:function(n){return t.extractField(n)},generateASM:function(n){return t.generateASM(n)},getSummary:function(){return{totalBytes:r._structure.totalActual,scriptLength:r.scriptLen,scriptVarintSize:r.scriptLenSize,sighashType:r.sighashType,valid:i.valid,warnings:i.warnings}}}};ci.exports=S});var pi=x((vc,hi)=>{"use strict";f();var z=Ee(),Go=D(),Vo=q(),zo=ze(),ui=A(),Ko=_e();function B(e){if(!(this instanceof B))return new B(e);this.sighashType=e||z.SIGHASH_ALL|z.SIGHASH_FORKID,this.analysis=this._analyzeFlags()}B.prototype.analyze=function(){return this.analysis};B.prototype.getZeroHashBehavior=function(){var e={hashPrevouts:!1,hashSequence:!1,hashOutputs:!1,explanation:[],criticalNote:null};return this.analysis.anyoneCanPay&&(e.hashPrevouts=!0,e.explanation.push("ANYONECANPAY: hashPrevouts becomes zero hash (0x00...00)")),this.analysis.baseType==="NONE"&&(e.hashSequence=!0,e.hashOutputs=!0,e.explanation.push("SIGHASH_NONE: hashSequence and hashOutputs become zero hash")),this.analysis.baseType==="SINGLE"&&(e.hashSequence=!0,e.hashOutputs=!0,e.explanation.push("SIGHASH_SINGLE: hashSequence becomes zero hash, hashOutputs covers only corresponding output")),(e.hashPrevouts||e.hashSequence||e.hashOutputs)&&(e.criticalNote="These zero hashes are NOT bugs - they are correct BIP-143 behavior for the specified SIGHASH flags!"),e};B.prototype.generateExample=function(){var e=zo.fromRandom(),t=e.toAddress(),r={txId:"a".repeat(64),outputIndex:0,script:ui.buildPublicKeyHashOut(t).toHex(),satoshis:1e5},i=new Vo().from(r).to(t,99e3),n=ui.fromHex(r.script),o=Ko.sighashPreimage(i,this.sighashType,0,n,new Go(r.satoshis)),s=J(),a=new s(o);return{transaction:i,preimage:a,sighashType:this.sighashType,analysis:this.analysis,zeroHashBehavior:this.getZeroHashBehavior(),fields:a.extract(),validation:a.validate()}};B.prototype.createDemonstration=function(){var e=this.generateExample(),t=u.Buffer.alloc(32).toString("hex"),r={sighashType:this.sighashType,analysis:this.analysis,zeroHashBehavior:this.getZeroHashBehavior(),preimageFields:{},observations:[],educationalNotes:[]},i=e.preimage.toObject().fields;return r.preimageFields=i,i.hashPrevouts===t&&r.observations.push({field:"hashPrevouts",value:"ZERO HASH (00...00)",reason:"ANYONECANPAY flag - this input can be combined with any other inputs"}),i.hashSequence===t&&r.observations.push({field:"hashSequence",value:"ZERO HASH (00...00)",reason:this.analysis.baseType+" flag - sequence numbers not covered by signature"}),i.hashOutputs===t&&r.observations.push({field:"hashOutputs",value:"ZERO HASH (00...00)",reason:this.analysis.baseType+" flag - outputs not fully covered by signature"}),r.educationalNotes=["Zero hashes in preimages are NOT errors - they indicate specific SIGHASH flag behavior","BIP-143 mandates these zero values when certain flags are used","ANYONECANPAY allows this input to be combined with different sets of inputs","SIGHASH_NONE means the signer doesn't care about any outputs","SIGHASH_SINGLE means the signer only cares about the corresponding output","Always check SIGHASH flags when you see 'mysterious' zero hashes in preimages"],r};B.prototype.checkCompliance=function(e){var t=e.toObject().fields,r=u.Buffer.alloc(32).toString("hex"),i={compliant:!0,issues:[],expectedZeros:[],unexpectedZeros:[]},n=this.getZeroHashBehavior();return n.hashPrevouts&&t.hashPrevouts!==r?(i.compliant=!1,i.issues.push("hashPrevouts should be zero due to ANYONECANPAY flag")):!n.hashPrevouts&&t.hashPrevouts===r&&i.unexpectedZeros.push("hashPrevouts is zero but ANYONECANPAY not set"),n.hashSequence&&t.hashSequence!==r?(i.compliant=!1,i.issues.push("hashSequence should be zero due to "+this.analysis.baseType+" flag")):!n.hashSequence&&t.hashSequence===r&&i.unexpectedZeros.push("hashSequence is zero but "+this.analysis.baseType+" allows sequence coverage"),n.hashOutputs&&t.hashOutputs!==r?(i.compliant=!1,i.issues.push("hashOutputs should be zero due to "+this.analysis.baseType+" flag")):!n.hashOutputs&&t.hashOutputs===r&&i.unexpectedZeros.push("hashOutputs is zero but "+this.analysis.baseType+" should cover outputs"),i};B.prototype._analyzeFlags=function(){var e=this.sighashType&31,t=(this.sighashType&128)!==0,r=(this.sighashType&64)!==0,i="UNKNOWN";e===1?i="ALL":e===2?i="NONE":e===3&&(i="SINGLE");var n=[];return n.push(i),t&&n.push("ANYONECANPAY"),r&&n.push("FORKID"),{sighashType:this.sighashType,baseType:i,anyoneCanPay:t,forkId:r,flagName:n.join(" | "),hex:"0x"+this.sighashType.toString(16).padStart(8,"0"),binary:"0b"+this.sighashType.toString(2).padStart(32,"0")}};B.getAllTypes=function(){var e=z.SIGHASH_FORKID;return[{name:"ALL",value:z.SIGHASH_ALL|e},{name:"NONE",value:z.SIGHASH_NONE|e},{name:"SINGLE",value:z.SIGHASH_SINGLE|e},{name:"ALL | ANYONECANPAY",value:z.SIGHASH_ALL|z.SIGHASH_ANYONECANPAY|e},{name:"NONE | ANYONECANPAY",value:z.SIGHASH_NONE|z.SIGHASH_ANYONECANPAY|e},{name:"SINGLE | ANYONECANPAY",value:z.SIGHASH_SINGLE|z.SIGHASH_ANYONECANPAY|e}]};B.generateAllDemonstrations=function(){return B.getAllTypes().map(function(e){var t=new B(e.value);return{typeName:e.name,demonstration:t.createDemonstration()}})};B.explainZeroMystery=function(){return{title:"The 'Extra Zero' Mystery in Bitcoin Preimages",problem:"Developers often see zero hashes (0x00...00) in preimage fields and think it's a bug",reality:"These zeros are CORRECT behavior mandated by BIP-143 for specific SIGHASH flags",explanation:["ANYONECANPAY sets hashPrevouts to zero - allows input combination flexibility","SIGHASH_NONE sets hashSequence and hashOutputs to zero - signer doesn't care about outputs","SIGHASH_SINGLE sets hashSequence to zero - only corresponding output matters","These are features, not bugs - they enable advanced Bitcoin transaction patterns"],solution:"Always check SIGHASH flags when analyzing preimages with zero hashes",toolTip:"Use SIGHASH.checkCompliance() to verify if zero hashes match expected flag behavior"}};hi.exports=B});var fi=x((Oc,di)=>{"use strict";f();var At=Object.create(null),bt=[],kt=!(typeof m.default<"u"&&m.default.env&&m.default.env.BSV_NO_DEPRECATION_WARNINGS==="1");function li(e,t){if(!e||typeof e.what!="string"||e.what==="")throw new TypeError(t+"() requires { what: string }")}function $o(e){var t="[@smartledger/bsv] "+e.what+" is deprecated";return e.since&&(t+=" since "+e.since),t+=".",e.why&&(t+=" "+e.why.charAt(0).toUpperCase()+e.why.slice(1)+"."),e.use&&(t+=" Use "+e.use+" instead."),t+=e.removeIn?" It will be removed in "+e.removeIn+".":" A removal version has not been set; it will not be removed in a 9.x release.",t}function ae(e){if(!e||!e.what)throw new TypeError("deprecate() requires { what }");if(At[e.what])return!1;At[e.what]=!0;var t=$o(e);return bt.push({what:e.what,since:e.since||null,removeIn:e.removeIn||null,use:e.use||null,message:t}),kt&&console.warn(t),!0}ae.fn=function(e,t){if(typeof e!="function")throw new TypeError("deprecate.fn() requires a function");li(t,"deprecate.fn");var r=function(){return ae(t),e.apply(this,arguments)};return Object.defineProperty(r,"name",{value:e.name,configurable:!0}),Object.defineProperty(r,"length",{value:e.length,configurable:!0}),r.__wrapped=e,r.__deprecation=t,r};ae.property=function(e,t,r,i){li(i,"deprecate.property");var n,o=!1;return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get:function(){return ae(i),o||(n=r(),o=!0),n}}),e};ae.fired=function(){return bt.slice()};ae.setEnabled=function(e){kt=!!e};ae.isEnabled=function(){return kt};ae.reset=function(){At=Object.create(null),bt.length=0};di.exports=ae});var Si=x((_c,yi)=>{"use strict";f();var Ht=_e(),Ce=ge(),gi=Ee(),mi=fe(),tt=D(),Yo=q(),ye=A(),Xo=fi();function b(e,t){if(!(this instanceof b))return new b(e,t);this.privateKey=e,this.publicKey=e?e.publicKey:null,this.options=t||{},this.allowNonEnforcing=this.options.allowNonEnforcing===!0,this.conditions=[],this.preimageFields=[],this.scriptTemplate=null,this.validationRules=[],this.sighashType=this.options.sighashType||gi.SIGHASH_ALL|gi.SIGHASH_FORKID}b.prototype._assertEnforcingAllowed=function(){if(this.allowNonEnforcing){Xo({what:"SmartContract.Builder ({ allowNonEnforcing: true })",since:"9.1.0",removeIn:"10.0.0",use:"SmartContract.policy(), or SmartContract.PushTx / Token / valueCovenant",why:"the scripts it emits reduce to plain P2PK and constrain nothing about the spend"});return}if(!this.allowNonEnforcing)throw new Error("SmartContract.Builder produces a NON-ENFORCING script (constant hash-lock \u2192 plain P2PK; it does not constrain the spend). Use SmartContract.policy() (declarative OP_PUSH_TX), or SmartContract.PushTx / Token / valueCovenant for real covenants. To use this demo anyway, construct with { allowNonEnforcing: true }.")};b.prototype.validateField=function(e,t,r){r=r||{};var i={field:e,expectedValue:t,operator:r.operator||"EQUAL",required:r.required!==!1,description:r.description||"Validate "+e};return this.validationRules.push(i),this};b.prototype.addCondition=function(e,t){t=t||{};var r={type:typeof e=="function"?"CUSTOM":"OPCODE",condition:e,description:t.description||"Custom condition",required:t.required!==!1};return this.conditions.push(r),this};b.prototype.useTemplate=function(e,t){return this.scriptTemplate={name:e,params:t||{},customScript:typeof e=="object"?e:null},this};b.prototype.buildLockingScript=function(e){this._assertEnforcingAllowed();var t=new ye;return this.scriptTemplate?this._buildFromTemplate(e):this._buildMultiFieldCovenant(e)};b.prototype.buildUnlockingScript=function(e,t,r){var i=new ye,n=ye.fromHex(r.script),o=Ht.sign(e,this.privateKey,this.sighashType,t,n,new tt(r.satoshis)),s=u.Buffer.concat([o.toDER(),u.Buffer.from([this.sighashType])]);return i.add(s),r.originalPreimage&&i.add(u.Buffer.from(r.originalPreimage,"hex")),this.conditions.forEach(function(a){a.type==="UNLOCK_DATA"&&i.add(a.data)}),i};b.prototype.createCovenant=function(e,t){this._assertEnforcingAllowed(),t=t||{};var r=new Yo().from({txId:e.txid,outputIndex:e.vout,script:e.script,satoshis:e.satoshis}).to(this.privateKey.toAddress(),e.satoshis-(t.fee||1e3)),i=ye.fromHex(e.script),n=Ht.sighashPreimage(r,this.sighashType,0,i,new tt(e.satoshis)),o=J(),s=new o(n),a=s.extract(),c=this.buildLockingScript({preimage:n,fields:a,transaction:r});r.outputs[0].setScript(c),r.sign(this.privateKey);var d={txid:r.id,vout:0,satoshis:e.satoshis-(t.fee||1e3),script:c.toHex(),originalPreimage:n.toString("hex"),preimageFields:a,validationRules:this.validationRules.slice(),conditions:this.conditions.slice(),template:this.scriptTemplate,createdAt:new Date().toISOString(),type:"builder_covenant"};return{creationTx:r,covenantUtxo:d,lockingScript:c,preimageData:{preimage:n,fields:a}}};b.prototype.validateSpending=function(e,t){var r={valid:!0,errors:[],warnings:[],fieldValidations:[]},i=ye.fromHex(t.script),n=Ht.sighashPreimage(e,this.sighashType,0,i,new tt(t.satoshis)),o=J(),s=new o(n),a=s.extract();t.validationRules&&t.validationRules.forEach(function(O){var re=this._validateFieldRule(O,a,t.preimageFields);r.fieldValidations.push(re),!re.passed&&O.required&&(r.valid=!1,r.errors.push(re.error))}.bind(this));var c=new Ce,d=Ce.SCRIPT_VERIFY_P2SH|Ce.SCRIPT_VERIFY_STRICTENC|Ce.SCRIPT_VERIFY_DERSIG|Ce.SCRIPT_VERIFY_LOW_S|Ce.SCRIPT_ENABLE_SIGHASH_FORKID,g=e.inputs[0].script,y=ye.fromHex(t.script),P=c.verify(g,y,e,0,d,new tt(t.satoshis));return P||(r.valid=!1,r.errors.push("Script interpreter validation failed: "+c.errstr)),r};b.prototype._buildFromTemplate=function(e){var t=this.scriptTemplate;if(t.name==="HASH_LOCK")return this._buildHashLockTemplate(e,t.params);if(t.name==="MULTI_FIELD")return this._buildMultiFieldTemplate(e,t.params);if(t.customScript)return t.customScript;throw new Error("Unknown template: "+t.name)};b.prototype._buildMultiFieldCovenant=function(e){var t=new ye;return t.add("OP_DUP"),this.validationRules.forEach(function(r,i){if(i>0&&t.add("OP_DUP"),t.add("OP_HASH256"),r.expectedValue){var n=mi.sha256sha256(u.Buffer.from(r.expectedValue,"hex"));t.add(n),t.add("OP_EQUALVERIFY")}}),t.add("OP_DROP"),this.publicKey&&(t.add(this.publicKey.toBuffer()),t.add("OP_CHECKSIG")),t};b.prototype._buildHashLockTemplate=function(e,t){var r=new ye;r.add("OP_DUP"),r.add("OP_HASH256");var i=t.hash||mi.sha256sha256(e.preimage);return r.add(i),r.add("OP_EQUALVERIFY"),r.add("OP_DROP"),this.publicKey&&(r.add(this.publicKey.toBuffer()),r.add("OP_CHECKSIG")),r};b.prototype._validateFieldRule=function(e,t,r){var i=t[e.field],n=e.expectedValue;if(typeof n=="string"&&n.startsWith("ORIGINAL_")){var o=n.replace("ORIGINAL_","");n=r[o]}var s=!1,a=null;switch(e.operator){case"EQUAL":s=i&&i.equals?i.equals(n):i===n,s||(a=e.field+" does not equal expected value");break;case"NOT_EQUAL":s=i&&i.equals?!i.equals(n):i!==n,s||(a=e.field+" should not equal specified value");break;case"PRESENT":s=!!i,s||(a=e.field+" is required but not present");break;default:a="Unknown validation operator: "+e.operator}return{field:e.field,operator:e.operator,passed:s,error:a,description:e.description}};b.createHashLock=function(e,t){return new b(e).useTemplate("HASH_LOCK",{hash:t})};b.createMultiField=function(e,t){var r=new b(e);return t.forEach(function(i){r.validateField(i.field,i.expectedValue,i.options)}),r};yi.exports=b});var xi=x((wc,vi)=>{f();vi.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Networks});var Pi=x((Tc,Oi)=>{f();Oi.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.crypto.Random});var Ei=x((bc,_i)=>{f();_i.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv});var bi=x((Hc,Lt)=>{f();var w=function(){(typeof m.default<"u"&&m.default.env&&m.default.env.BSV_DEBUG||typeof window<"u"&&window.BSV_DEBUG)&&console.log.apply(console,arguments)},jo,Se,Ft,Le;if(typeof window>"u"&&typeof C=="function")try{Se=F(),Ft=F(),Le=Ft.join(__dirname,"blockchain-state.json")}catch{w("BlockchainState: Running in browser mode - persistence disabled")}else jo=typeof window<"u"&&window.bsv||Ei();function rt(){return{metadata:{createdAt:new Date().toISOString(),lastUpdated:new Date().toISOString(),totalWallets:0,totalUTXOs:0,totalValue:0,blockHeight:0},wallets:{},globalUTXOSet:{},spentUTXOs:{},transactionHistory:[]}}function Re(){try{if(!Se||!Le)return rt();if(!Se.existsSync(Le)){w("\u{1F195} Creating new blockchain state...");let t=rt();return Be(t),t}let e=JSON.parse(Se.readFileSync(Le,"utf8"));return w("\u{1F4D6} Loaded existing blockchain state"),e}catch(e){return console.error("\u274C Error loading blockchain state:",e.message),rt()}}function Be(e){try{e.metadata.lastUpdated=new Date().toISOString(),Se&&Le&&(Se.writeFileSync(Le,JSON.stringify(e,null,2)),w("\u{1F4BE} Blockchain state saved"))}catch(t){console.error("\u274C Error saving blockchain state:",t.message)}}function wi(e,t){w(`\u{1F4DD} Registering wallet: ${e}`);let r=Re();return r.wallets[e]&&w("\u2139\uFE0F Wallet already exists, updating..."),r.wallets[e]={address:e,registeredAt:t.registeredAt||new Date().toISOString(),utxos:t.utxos||[],totalValue:0},t.utxos&&t.utxos.forEach(i=>{let n=`${i.txid}:${i.vout}`;r.globalUTXOSet[n]={...i,ownerAddress:e}}),r.metadata.totalWallets=Object.keys(r.wallets).length,Ct(r),Be(r),w(`\u2705 Wallet registered: ${e}`),r}function Ii(e,t){let r=Re(),i=`${e}:${t}`;return r.spentUTXOs[i]?{exists:!1,spent:!0,utxo:r.spentUTXOs[i]}:r.globalUTXOSet[i]?{exists:!0,spent:!1,utxo:r.globalUTXOSet[i]}:{exists:!1,spent:!1,utxo:null}}function Wo(e,t){let r=Ii(e,t);return r.exists&&!r.spent}function Qo(e,t,r){let i=Re(),n=`${e}:${t}`;if(!i.globalUTXOSet[n])throw new Error(`UTXO ${n} does not exist`);if(i.spentUTXOs[n])throw new Error(`UTXO ${n} already spent`);let o=i.globalUTXOSet[n];i.spentUTXOs[n]={...o,spentInTx:r,spentAt:new Date().toISOString()},delete i.globalUTXOSet[n];let s=i.wallets[o.ownerAddress];s&&(s.utxos=s.utxos.filter(a=>!(a.txid===e&&a.vout===t))),Ct(i),Be(i),w(`\u274C UTXO spent: ${n} in tx ${r}`)}function Zo(e,t){let r=Re(),i=`${e.txid}:${e.vout}`;if(r.globalUTXOSet[i]){w(`\u26A0\uFE0F UTXO ${i} already exists, skipping`);return}r.globalUTXOSet[i]={...e,ownerAddress:t,createdAt:new Date().toISOString()},r.wallets[t]||(r.wallets[t]={address:t,registeredAt:new Date().toISOString(),utxos:[],totalValue:0}),r.wallets[t].utxos.some(o=>o.txid===e.txid&&o.vout===e.vout)||r.wallets[t].utxos.push(e),Ct(r),Be(r),w(`\u2705 UTXO added: ${i} for ${t}`)}function Ct(e){let t=Object.keys(e.globalUTXOSet).length,r=Object.values(e.globalUTXOSet).reduce((i,n)=>i+n.satoshis,0);e.metadata.totalUTXOs=t,e.metadata.totalValue=r,Object.values(e.wallets).forEach(i=>{i.totalValue=i.utxos.reduce((n,o)=>n+o.satoshis,0)})}function Ti(){let e=Re();return w("\u{1F310} Blockchain State Statistics:"),w("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),w(`\u{1F4CA} Total Wallets: ${e.metadata.totalWallets}`),w(`\u{1F4B0} Total UTXOs: ${e.metadata.totalUTXOs}`),w(`\u{1F48E} Total Value: ${e.metadata.totalValue} satoshis`),w(`\u{1F3D7}\uFE0F Block Height: ${e.metadata.blockHeight}`),w(`\u{1F550} Last Updated: ${e.metadata.lastUpdated}
|
|
6
|
+
`),Object.keys(e.wallets).length>0&&(w("\u{1F45B} Registered Wallets:"),Object.entries(e.wallets).forEach(([t,r])=>{w(` ${t}: ${r.utxos.length} UTXOs, ${r.totalValue} sats`)})),e}function Ai(){let e=Ft.join(__dirname,"wallet.json");if(!Se.existsSync(e))return w("\u274C No wallet.json found to import"),!1;try{let t=JSON.parse(Se.readFileSync(e,"utf8"));w("\u{1F4E5} Importing wallet from wallet.json...");let r={registeredAt:new Date().toISOString(),utxos:t.availableUTXOs||[t.utxo]};return wi(t.wallet.address,r),w("\u2705 Wallet imported successfully"),!0}catch(t){return console.error("\u274C Error importing wallet:",t.message),!1}}if(C.main===Lt){let e=m.default.argv.slice(2);if(e[0]==="import")Ai();else if(e[0]==="init"){let t=rt();Be(t),w("\u{1F195} Initialized new blockchain state")}Ti()}Lt.exports={loadBlockchainState:Re,saveBlockchainState:Be,registerWallet:wi,getUTXO:Ii,isUTXOAvailable:Wo,spendUTXO:Qo,addUTXO:Zo,getBlockchainStats:Ti,importWalletFromFile:Ai}});var Fi=x((Lc,Hi)=>{"use strict";f();var Y=function(){(typeof m.default<"u"&&m.default.env&&m.default.env.BSV_DEBUG||typeof window<"u"&&window.BSV_DEBUG)&&console.log.apply(console,arguments)},Jo=A(),es=It(),ts=Pi(),Rt,ki,rs,ce;if(typeof window>"u"&&typeof C=="function")try{Rt=F(),ki=F(),rs=F(),ce=bi()}catch{Y("SmartUTXO: Running in browser mode - some features may be limited")}var Bt=class{constructor(t={}){this.options=t||{},this.loadState()}loadState(){try{return ce.loadBlockchainState()}catch(t){return Y("\u26A0\uFE0F Could not load blockchain state:",t.message),null}}saveState(){try{let t=ce.loadBlockchainState();ce.saveBlockchainState(t);let r=Object.keys(t.globalUTXOSet||{}).length;Y(`\u{1F4BE} Saved blockchain state with ${r} UTXOs`)}catch(t){Y("\u26A0\uFE0F Could not save blockchain state:",t.message)}}getUTXOsForAddress(t){try{let r=ce.loadBlockchainState();return!r.wallets||!r.wallets[t]?[]:r.wallets[t].utxos||[]}catch(r){return Y("\u26A0\uFE0F Error getting UTXOs:",r.message),[]}}addUTXO(t){try{ce.addUTXO(t,t.address)}catch(r){Y("\u26A0\uFE0F Error adding UTXO:",r.message)}}spendUTXOs(t,r="manual-spend"){try{for(let i of t)ce.spendUTXO(i.txid,i.vout,r)}catch(i){Y("\u26A0\uFE0F Error spending UTXOs:",i.message)}}createMockUTXOs(t,r=5,i=1e5){let n=Jo.buildPublicKeyHashOut(es.fromString(t)).toHex(),o=[];for(let s=0;s<r;s++)o.push({txid:ts.getRandomBuffer(32).toString("hex"),vout:s,address:t,satoshis:i,script:n});return o}getBalance(t){try{let r=ce.loadBlockchainState();return!r.wallets||!r.wallets[t]?0:r.wallets[t].totalValue||0}catch(r){return Y("\u26A0\uFE0F Error getting balance:",r.message),0}}getStats(){try{let t=ce.getBlockchainStats();return{totalUTXOs:t.metadata.totalUTXOs,totalValue:t.metadata.totalValue,totalWallets:t.metadata.totalWallets,blockHeight:t.metadata.blockHeight,lastUpdated:t.metadata.lastUpdated}}catch(t){return Y("\u26A0\uFE0F Error getting stats:",t.message),{totalUTXOs:0,totalValue:0,totalWallets:0,blockHeight:0}}}reset(){try{let t=ki.join(__dirname,"../utilities/blockchain-state.json");Rt.existsSync(t)&&(Rt.unlinkSync(t),Y("\u{1F504} Blockchain state reset"))}catch(t){Y("\u26A0\uFE0F Could not reset blockchain state:",t.message)}}};Hi.exports=Bt});var Ri=x((Nc,Li)=>{"use strict";f();var is=_e(),Ci=Ee(),ns=D(),os=q(),ss=ze(),as=xi(),Ne=A(),cs=F();function M(e){if(!(this instanceof M))return new M(e);this.options=e||{},this.network=this.options.network||as.mainnet,this.keyRing={},this.utxoPool=[];try{var t=Fi();this.smartUTXO=new t(this.options)}catch{}}M.prototype.generateKeypair=function(e){e=e||"key_"+Date.now();var t=ss.fromRandom(this.network),r=t.toPublicKey(),i=t.toAddress(this.network),n={label:e,privateKey:t,publicKey:r,address:i,wif:t.toWIF(),addressString:i.toString()};return this.keyRing[e]=n,n};M.prototype.createRealUTXOs=function(e){e=e||{};for(var t=e.count||3,r=e.satoshis||1e5,i=e.scriptType||"P2PKH",n=e.keypair||this.generateKeypair("utxo_owner"),o=[],s=0;s<t;s++){var a=this._createSingleUTXO({keypair:n,satoshis:r,scriptType:i,vout:s});o.push(a),this.utxoPool.push(a),this.smartUTXO&&this.smartUTXO.addUTXO(a)}return o};M.prototype._createSingleUTXO=function(e){var t=cs.randomBytes(32).toString("hex"),r,i;switch(e.scriptType){case"P2PKH":r=Ne.buildPublicKeyHashOut(e.keypair.address),i=r.toHex();break;case"P2SH":var n=Ne.buildMultisigOut([e.keypair.publicKey],1);r=Ne.buildScriptHashOut(n),i=r.toHex();break;case"CUSTOM":r=e.customScript||Ne.buildPublicKeyHashOut(e.keypair.address),i=r.toHex();break;default:r=Ne.buildPublicKeyHashOut(e.keypair.address),i=r.toHex()}return{txid:t,vout:e.vout,address:e.keypair.addressString,script:i,satoshis:e.satoshis,keypair:e.keypair,scriptType:e.scriptType,scriptObj:r,created:new Date().toISOString()}};M.prototype.createTestTransaction=function(e){e=e||{};var t=e.inputs||this.utxoPool.slice(0,1);if(t.length===0)throw new Error("No UTXOs available for transaction. Call createRealUTXOs() first.");var r=t.reduce(function(a,c){return a+c.satoshis},0),i=new os;t.forEach(function(a){i.from({txId:a.txid,outputIndex:a.vout,address:a.address,script:a.script,satoshis:a.satoshis})});var n=e.outputAddress||t[0].keypair.addressString,o=e.outputAmount||r-1e4,s=e.fee||1e4;return i.to(n,o),i.fee(s),{transaction:i,inputUTXOs:t,unsignedHex:i.toString(),inputTotal:r,outputAmount:o,fee:s,sign:function(){return t.forEach(function(a){i.sign(a.keypair.privateKey)}),{signedTransaction:i,signedHex:i.toString(),txid:i.id}},generatePreimage:function(a,c){c=c||Ci.SIGHASH_ALL|Ci.SIGHASH_FORKID;var d=t[a];return is.sighashPreimage(i,c,a,Ne.fromHex(d.script),new ns(d.satoshis))}}};M.prototype.createCovenantTest=function(e){e=e||{};var t=this.generateKeypair("covenant_test"),r=this.createRealUTXOs({count:e.utxoCount||2,satoshis:e.satoshis||5e4,keypair:t,scriptType:e.scriptType||"P2PKH"}),i={inputs:r.slice(0,1),outputAmount:e.covenantAmount||4e4,fee:1e4},n=this.createTestTransaction(i),o=n.generatePreimage(0),s=o.toString("hex");return{keypair:t,utxos:r,transaction:n,preimage:{buffer:o,hex:s,length:o.length},extractField:function(a){try{var c=J();return c.extractFromHex(s,a)}catch(d){throw new Error("SmartContract.Preimage not available: "+d.message)}},validateCovenant:function(a){return{preimageValid:o.length>=182,covenantLogic:a,testPassed:!0}},getSummary:function(){return{keypair:t.addressString,utxoCount:r.length,totalValue:r.reduce(function(a,c){return a+c.satoshis},0),preimageLength:o.length,transactionId:n.transaction.id}}}};M.prototype.getKeypairs=function(){return this.keyRing};M.prototype.getUTXOs=function(){return this.utxoPool};M.prototype.reset=function(){this.keyRing={},this.utxoPool=[]};M.createTestEnvironment=function(e){var t=new M(e),r=t.createCovenantTest(e);return{generator:t,test:r,getPreimage:function(){return r.preimage.hex},getKeypair:function(){return r.keypair},extractField:function(i){return r.extractField(i)},generateASM:function(i){try{var n=J();return n.generateASMFromHex(r.preimage.hex,i)}catch(o){throw new Error("Cannot generate ASM: "+o.message)}}}};Li.exports=M});var Ke=x((qc,Bi)=>{f();Bi.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Transaction.Output});var G=x((Mc,Ni)=>{f();Ni.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.Opcode});var Di=x((Vc,qi)=>{"use strict";f();var Ui=Ke(),us=He(),Nt=ge(),hs=D(),ps=q(),ls=G(),ve=A();function k(e){if(!(this instanceof k))return new k(e);this.options=e||{},this.flags=this.options.flags||Nt.SCRIPT_ENABLE_SIGHASH_FORKID,this.satoshis=this.options.satoshis||1e5}k.prototype.execute=function(e){var t=this._parseScript(e.unlocking),r=this._parseScript(e.locking),i=this._createDummyTransaction(),n=new Nt,o=new hs(this.satoshis);try{var s=n.verify(t,r,i,0,this.flags,o);return{success:s,unlocking:t.toASM(),locking:r.toASM(),finalStack:n.stack.map(function(a){return a.toString("hex")}),altStack:n.altstack.map(function(a){return a.toString("hex")}),error:null}}catch(a){return{success:!1,unlocking:t.toASM(),locking:r.toASM(),finalStack:[],altStack:[],error:a.message}}};k.prototype.debug=function(e){var t=this._createCombinedScript(e),r=this._createDummyTransaction(),i=new Nt;i.script=t,i.tx=r,i.nIn=0,i.flags=this.flags;var n=[],o=t.chunks;try{for(var s=0;s<o.length;s++){var a=o[s],c=ls.reverseMap[a.opcodenum]||"PUSH",d=i.stack.map(function(O){return O.toString("hex")}),g=i.altstack.map(function(O){return O.toString("hex")});try{i.step();var y=i.stack.map(function(O){return O.toString("hex")}),P=i.altstack.map(function(O){return O.toString("hex")});n.push({step:s+1,opcode:c,beforeStack:d,afterStack:y,beforeAltStack:g,afterAltStack:P,success:!0,error:null})}catch(O){n.push({step:s+1,opcode:c,beforeStack:d,afterStack:d,beforeAltStack:g,afterAltStack:g,success:!1,error:O.message});break}}}catch(O){n.push({step:0,opcode:"INITIALIZATION",beforeStack:[],afterStack:[],beforeAltStack:[],afterAltStack:[],success:!1,error:O.message})}return{script:t.toASM(),steps:n,totalSteps:o.length,success:n.length>0&&n[n.length-1].success}};k.prototype.testCovenant=function(e){var t=e.preimage,r=e.constraints||{},i=this._buildCovenantScript(r,t),n=this.execute({unlocking:t,locking:i});return n.covenant={preimageLength:t.length/2,constraints:r,constraintResults:this._analyzeConstraints(t,r)},n};k.prototype.testFieldExtraction=function(e,t){try{var r=J(),i=r.extractFromHex(e,t,{includeComments:!1}),n=this._cleanASM(i.asm),o=this.execute({unlocking:e,locking:n+" OP_DROP OP_TRUE"});return o.fieldExtraction={field:t,strategy:i.strategy,value:i.value,interpretation:i.interpretation,asmGenerated:i.asm,cleanedASM:n},o}catch(s){return{success:!1,error:s.message,fieldExtraction:{field:t,error:s.message}}}};k.prototype._parseScript=function(e){if(!e)return new ve;var t=e.trim(),r=/^[0-9a-fA-F]+$/.test(t.replace(/\s+/g,""));try{if(r){var i=t.length/2;return i>=180&&i<=250?new ve().add(u.Buffer.from(t,"hex")):ve.fromHex(t)}else return ve.fromASM(t)}catch(n){throw new Error("Failed to parse script: "+n.message)}};k.prototype._createCombinedScript=function(e){if(e.combined)return this._parseScript(e.combined);var t=this._parseScript(e.unlocking),r=this._parseScript(e.locking),i=u.Buffer.concat([t.toBuffer(),r.toBuffer()]);return ve.fromBuffer(i)};k.prototype._createDummyTransaction=function(){var e=new ps,t=new us({prevTxId:"0".repeat(64),outputIndex:0,script:ve.empty(),satoshis:this.satoshis,output:new Ui({satoshis:this.satoshis,script:ve.empty()})});return e.addInput(t),e.addOutput(new Ui({satoshis:this.satoshis,script:ve.empty()})),e};k.prototype._buildCovenantScript=function(e,t){var r=[];try{var i=J();if(e.minimumAmount){var n=i.generateASMFromHex(t,"value",!1);r.push(n),r.push("OP_BIN2NUM"),r.push(e.minimumAmount.toString()),r.push("OP_GREATERTHANOREQUAL"),r.push("OP_VERIFY")}if(e.requiredSighash){var o=i.generateASMFromHex(t,"sighashType",!1);r.push(o),r.push("OP_BIN2NUM"),r.push(e.requiredSighash.toString()),r.push("OP_EQUAL"),r.push("OP_VERIFY")}r.push("OP_TRUE");var s=r.join(" ");return this._cleanASM(s)}catch(a){throw new Error("Failed to build covenant script: "+a.message)}};k.prototype._cleanASM=function(e){var t=e.split(`
|
|
7
|
+
`).map(function(r){return r.split("#")[0].trim()}).filter(function(r){return r.length>0}).join(" ").replace(/\s+/g," ").trim();return t=t.replace(/\b(\d+)\b/g,function(r,i){var n=parseInt(i);if(n>=1&&n<=16)return"OP_"+n;if(n===0)return"OP_0";if(n===-1)return"OP_1NEGATE";var o=n,s=o<0;s&&(o=-o);for(var a=[];o>0;)a.push(o&255),o=Math.floor(o/256);return a.length===0&&a.push(0),s?a[a.length-1]>=128?a.push(128):a[a.length-1]|=128:a.length>0&&a[a.length-1]>=128&&a.push(0),u.Buffer.from(a).toString("hex")}),t};k.prototype._analyzeConstraints=function(e,t){var r={};try{var i=J();if(t.minimumAmount){var n=i.extractFromHex(e,"value",{includeComments:!1}),o=parseInt(n.interpretation.satoshis);r.amountCheck={constraint:t.minimumAmount,actual:o,satisfied:o>=t.minimumAmount}}if(t.requiredSighash){var s=i.extractFromHex(e,"sighashType",{includeComments:!1}),a=parseInt(s.value,16);r.sighashCheck={constraint:t.requiredSighash,actual:a,satisfied:(a&255)===t.requiredSighash}}}catch(c){r.error=c.message}return r};k.test=function(e,t,r){var i=new k(r);return i.execute({unlocking:e,locking:t})};k.testCovenant=function(e,t,r){var i=new k(r);return i.testCovenant({preimage:e,constraints:t})};k.testFieldExtraction=function(e,t,r){var i=new k(r);return i.testFieldExtraction(e,t)};qi.exports=k});var qt=x((Kc,Ut)=>{f();var l={encode:e=>{if(e===0)return u.Buffer.alloc(0);let t=e<0,r=Math.abs(e),i=[],n=r;for(;n>0;)i.push(n&255),n>>=8;return i[i.length-1]&128?i.push(t?128:0):t&&(i[i.length-1]|=128),u.Buffer.from(i)},decode:e=>{if(e.length===0)return 0;let t=Array.from(e),r=t[t.length-1]&128;r&&(t[t.length-1]&=127);let i=0;for(let n=t.length-1;n>=0;n--)i=(i<<8)+t[n];return r?-i:i}},X={OP_FALSE:{code:0,category:"constants",description:"Push empty array (false value)",action:e=>e.push(u.Buffer.alloc(0))},OP_0:{code:0,category:"constants",description:"Push empty array (alias for OP_FALSE)",action:e=>e.push(u.Buffer.alloc(0))},OP_PUSHDATA1:{code:76,category:"pushdata",description:"Push next [1 byte] bytes of data",action:"Read next byte as length; push that many bytes"},OP_PUSHDATA2:{code:77,category:"pushdata",description:"Push next [2 bytes LE] bytes of data",action:"Read next 2 bytes as length; push that many bytes"},OP_PUSHDATA4:{code:78,category:"pushdata",description:"Push next [4 bytes LE] bytes of data",action:"Read next 4 bytes as length; push that many bytes"},OP_1NEGATE:{code:79,category:"constants",description:"Push number -1",action:e=>e.push(l.encode(-1))},OP_RESERVED:{code:80,category:"reserved",description:"Reserved opcode (makes transaction invalid)",action:()=>{throw new Error("OP_RESERVED encountered")}},OP_TRUE:{code:81,category:"constants",description:"Push number 1 (true value)",action:e=>e.push(l.encode(1))},OP_1:{code:81,category:"constants",description:"Push number 1 (alias for OP_TRUE)",action:e=>e.push(l.encode(1))},OP_2:{code:82,category:"constants",description:"Push number 2",action:e=>e.push(l.encode(2))},OP_3:{code:83,category:"constants",description:"Push number 3",action:e=>e.push(l.encode(3))},OP_4:{code:84,category:"constants",description:"Push number 4",action:e=>e.push(l.encode(4))},OP_5:{code:85,category:"constants",description:"Push number 5",action:e=>e.push(l.encode(5))},OP_6:{code:86,category:"constants",description:"Push number 6",action:e=>e.push(l.encode(6))},OP_7:{code:87,category:"constants",description:"Push number 7",action:e=>e.push(l.encode(7))},OP_8:{code:88,category:"constants",description:"Push number 8",action:e=>e.push(l.encode(8))},OP_9:{code:89,category:"constants",description:"Push number 9",action:e=>e.push(l.encode(9))},OP_10:{code:90,category:"constants",description:"Push number 10",action:e=>e.push(l.encode(10))},OP_11:{code:91,category:"constants",description:"Push number 11",action:e=>e.push(l.encode(11))},OP_12:{code:92,category:"constants",description:"Push number 12",action:e=>e.push(l.encode(12))},OP_13:{code:93,category:"constants",description:"Push number 13",action:e=>e.push(l.encode(13))},OP_14:{code:94,category:"constants",description:"Push number 14",action:e=>e.push(l.encode(14))},OP_15:{code:95,category:"constants",description:"Push number 15",action:e=>e.push(l.encode(15))},OP_16:{code:96,category:"constants",description:"Push number 16",action:e=>e.push(l.encode(16))},OP_NOP:{code:97,category:"flow_control",description:"No operation (do nothing)",action:e=>{}},OP_VER:{code:98,category:"flow_control",description:"Push transaction version (disabled)",action:()=>{throw new Error("OP_VER is disabled")}},OP_IF:{code:99,category:"flow_control",description:"Execute if top stack value is true",action:"// Conditional execution (requires parser state)"},OP_NOTIF:{code:100,category:"flow_control",description:"Execute if top stack value is false",action:"// Conditional execution (requires parser state)"},OP_VERIF:{code:101,category:"flow_control",description:"Conditional execution based on transaction version (disabled)",action:()=>{throw new Error("OP_VERIF is disabled")}},OP_VERNOTIF:{code:102,category:"flow_control",description:"Conditional execution based on transaction version (disabled)",action:()=>{throw new Error("OP_VERNOTIF is disabled")}},OP_ELSE:{code:103,category:"flow_control",description:"Else branch of conditional",action:"// Conditional execution (requires parser state)"},OP_ENDIF:{code:104,category:"flow_control",description:"End conditional block",action:"// Conditional execution (requires parser state)"},OP_VERIFY:{code:105,category:"flow_control",description:"Fail if top stack value is not true",action:e=>{let t=e.pop();if(!t||t.length===0||l.decode(t)===0)throw new Error("OP_VERIFY failed")}},OP_RETURN:{code:106,category:"flow_control",description:"Terminate script execution immediately",action:()=>{throw new Error("Script terminated by OP_RETURN")}},OP_TOALTSTACK:{code:107,category:"stack",description:"Move top item from main stack to alt stack",action:(e,t)=>t.push(e.pop())},OP_FROMALTSTACK:{code:108,category:"stack",description:"Move top item from alt stack to main stack",action:(e,t)=>e.push(t.pop())},OP_2DROP:{code:109,category:"stack",description:"Remove top two stack items",action:e=>{e.pop(),e.pop()}},OP_2DUP:{code:110,category:"stack",description:"Duplicate top two stack items",action:e=>{let t=e[e.length-1],r=e[e.length-2];e.push(u.Buffer.from(r),u.Buffer.from(t))}},OP_3DUP:{code:111,category:"stack",description:"Duplicate top three stack items",action:e=>{let t=e[e.length-1],r=e[e.length-2],i=e[e.length-3];e.push(u.Buffer.from(i),u.Buffer.from(r),u.Buffer.from(t))}},OP_2OVER:{code:112,category:"stack",description:"Copy 3rd and 4th items to top",action:e=>{let t=e[e.length-3],r=e[e.length-4];e.push(u.Buffer.from(r),u.Buffer.from(t))}},OP_2ROT:{code:113,category:"stack",description:"Move 5th and 6th items to top",action:e=>{let t=e.splice(-5,1)[0],r=e.splice(-5,1)[0];e.push(t,r)}},OP_2SWAP:{code:114,category:"stack",description:"Swap top two pairs of items",action:e=>{let t=e.pop(),r=e.pop(),i=e.pop(),n=e.pop();e.push(r,t,n,i)}},OP_IFDUP:{code:115,category:"stack",description:"Duplicate top item if it is not zero",action:e=>{let t=e[e.length-1];t.length>0&&l.decode(t)!==0&&e.push(u.Buffer.from(t))}},OP_DEPTH:{code:116,category:"stack",description:"Push stack size as number",action:e=>e.push(l.encode(e.length))},OP_DROP:{code:117,category:"stack",description:"Remove top stack item",action:e=>e.pop()},OP_DUP:{code:118,category:"stack",description:"Duplicate top stack item",action:e=>e.push(u.Buffer.from(e[e.length-1]))},OP_NIP:{code:119,category:"stack",description:"Remove second-to-top item",action:e=>{let t=e.pop();e.pop(),e.push(t)}},OP_OVER:{code:120,category:"stack",description:"Copy second-to-top item to top",action:e=>e.push(u.Buffer.from(e[e.length-2]))},OP_PICK:{code:121,category:"stack",description:"Copy nth item to top (0-indexed from top)",action:e=>{let t=l.decode(e.pop());e.push(u.Buffer.from(e[e.length-1-t]))}},OP_ROLL:{code:122,category:"stack",description:"Move nth item to top (0-indexed from top)",action:e=>{let t=l.decode(e.pop()),r=e.splice(e.length-1-t,1)[0];e.push(r)}},OP_ROT:{code:123,category:"stack",description:"Rotate top three items left",action:e=>{let t=e.pop(),r=e.pop(),i=e.pop();e.push(r,t,i)}},OP_SWAP:{code:124,category:"stack",description:"Swap top two items",action:e=>{let t=e.pop(),r=e.pop();e.push(t,r)}},OP_TUCK:{code:125,category:"stack",description:"Copy top item below second item",action:e=>{let t=e.pop(),r=e.pop();e.push(t,r,t)}},OP_CAT:{code:126,category:"data",description:"Concatenate top two items",action:e=>{let t=e.pop(),r=e.pop();e.push(u.Buffer.concat([r,t]))}},OP_SPLIT:{code:127,category:"data",description:"Split item at position n",action:e=>{let t=l.decode(e.pop()),r=e.pop();e.push(r.slice(0,t),r.slice(t))}},OP_NUM2BIN:{code:128,category:"data",description:"Convert number to byte sequence of length n",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop()),i=u.Buffer.alloc(t),n=l.encode(r);n.copy(i,0,0,Math.min(n.length,t)),e.push(i)}},OP_BIN2NUM:{code:129,category:"data",description:"Convert byte sequence to number",action:e=>{let t=e.pop();e.push(l.encode(l.decode(t)))}},OP_SIZE:{code:130,category:"data",description:"Push size of top item (without removing item)",action:e=>e.push(l.encode(e[e.length-1].length))},OP_INVERT:{code:131,category:"bitwise",description:"Bitwise NOT of top item",action:e=>{let t=e.pop();e.push(u.Buffer.from(t.map(r=>~r)))}},OP_AND:{code:132,category:"bitwise",description:"Bitwise AND of top two items",action:e=>{let t=e.pop(),r=e.pop(),i=Math.max(t.length,r.length),n=u.Buffer.alloc(i);for(let o=0;o<i;o++)n[o]=(t[o]||0)&(r[o]||0);e.push(n)}},OP_OR:{code:133,category:"bitwise",description:"Bitwise OR of top two items",action:e=>{let t=e.pop(),r=e.pop(),i=Math.max(t.length,r.length),n=u.Buffer.alloc(i);for(let o=0;o<i;o++)n[o]=(t[o]||0)|(r[o]||0);e.push(n)}},OP_XOR:{code:134,category:"bitwise",description:"Bitwise XOR of top two items",action:e=>{let t=e.pop(),r=e.pop(),i=Math.max(t.length,r.length),n=u.Buffer.alloc(i);for(let o=0;o<i;o++)n[o]=(t[o]||0)^(r[o]||0);e.push(n)}},OP_EQUAL:{code:135,category:"bitwise",description:"Push 1 if top two items are equal, 0 otherwise",action:e=>{let t=e.pop(),r=e.pop();e.push(t.equals(r)?l.encode(1):l.encode(0))}},OP_EQUALVERIFY:{code:136,category:"bitwise",description:"Fail if top two items are not equal",action:e=>{let t=e.pop(),r=e.pop();if(!t.equals(r))throw new Error("OP_EQUALVERIFY failed")}},OP_1ADD:{code:139,category:"arithmetic",description:"Add 1 to top item",action:e=>{let t=l.decode(e.pop());e.push(l.encode(t+1))}},OP_1SUB:{code:140,category:"arithmetic",description:"Subtract 1 from top item",action:e=>{let t=l.decode(e.pop());e.push(l.encode(t-1))}},OP_2MUL:{code:141,category:"arithmetic",description:"Multiply top item by 2 (disabled)",action:()=>{throw new Error("OP_2MUL is disabled")}},OP_2DIV:{code:142,category:"arithmetic",description:"Divide top item by 2 (disabled)",action:()=>{throw new Error("OP_2DIV is disabled")}},OP_NEGATE:{code:143,category:"arithmetic",description:"Negate top item",action:e=>{let t=l.decode(e.pop());e.push(l.encode(-t))}},OP_ABS:{code:144,category:"arithmetic",description:"Absolute value of top item",action:e=>{let t=l.decode(e.pop());e.push(l.encode(Math.abs(t)))}},OP_NOT:{code:145,category:"arithmetic",description:"Logical NOT (0\u21921, non-zero\u21920)",action:e=>{let t=l.decode(e.pop());e.push(l.encode(t===0?1:0))}},OP_0NOTEQUAL:{code:146,category:"arithmetic",description:"Push 1 if top item is not zero, 0 otherwise",action:e=>{let t=l.decode(e.pop());e.push(l.encode(t!==0?1:0))}},OP_ADD:{code:147,category:"arithmetic",description:"Add top two items",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r+t))}},OP_SUB:{code:148,category:"arithmetic",description:"Subtract: second - first",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r-t))}},OP_MUL:{code:149,category:"arithmetic",description:"Multiply top two items",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r*t))}},OP_DIV:{code:150,category:"arithmetic",description:"Divide: second / first",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());if(t===0)throw new Error("Division by zero");e.push(l.encode(Math.floor(r/t)))}},OP_MOD:{code:151,category:"arithmetic",description:"Modulo: second % first",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());if(t===0)throw new Error("Division by zero");e.push(l.encode(r%t))}},OP_LSHIFT:{code:152,category:"arithmetic",description:"Left shift: second << first",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r<<t))}},OP_RSHIFT:{code:153,category:"arithmetic",description:"Right shift: second >> first",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r>>t))}},OP_BOOLAND:{code:154,category:"arithmetic",description:"Boolean AND: 1 if both non-zero, 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(t!==0&&r!==0?1:0))}},OP_BOOLOR:{code:155,category:"arithmetic",description:"Boolean OR: 1 if either non-zero, 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(t!==0||r!==0?1:0))}},OP_NUMEQUAL:{code:156,category:"arithmetic",description:"Push 1 if numbers are equal, 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(t===r?1:0))}},OP_NUMEQUALVERIFY:{code:157,category:"arithmetic",description:"Fail if numbers are not equal",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());if(t!==r)throw new Error("OP_NUMEQUALVERIFY failed")}},OP_NUMNOTEQUAL:{code:158,category:"arithmetic",description:"Push 1 if numbers are not equal, 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(t!==r?1:0))}},OP_LESSTHAN:{code:159,category:"arithmetic",description:"Push 1 if second < first, 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r<t?1:0))}},OP_GREATERTHAN:{code:160,category:"arithmetic",description:"Push 1 if second > first, 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r>t?1:0))}},OP_LESSTHANOREQUAL:{code:161,category:"arithmetic",description:"Push 1 if second <= first, 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r<=t?1:0))}},OP_GREATERTHANOREQUAL:{code:162,category:"arithmetic",description:"Push 1 if second >= first, 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(r>=t?1:0))}},OP_MIN:{code:163,category:"arithmetic",description:"Push smaller of top two numbers",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(Math.min(t,r)))}},OP_MAX:{code:164,category:"arithmetic",description:"Push larger of top two numbers",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop());e.push(l.encode(Math.max(t,r)))}},OP_WITHIN:{code:165,category:"arithmetic",description:"Push 1 if x is within [min, max), 0 otherwise",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop()),i=l.decode(e.pop());e.push(l.encode(i>=r&&i<t?1:0))}},OP_RIPEMD160:{code:166,category:"crypto",description:"RIPEMD-160 hash of top item",action:e=>{let r=F().createHash("ripemd160").update(e.pop()).digest();e.push(r)}},OP_SHA1:{code:167,category:"crypto",description:"SHA-1 hash of top item",action:e=>{let r=F().createHash("sha1").update(e.pop()).digest();e.push(r)}},OP_SHA256:{code:168,category:"crypto",description:"SHA-256 hash of top item",action:e=>{let r=F().createHash("sha256").update(e.pop()).digest();e.push(r)}},OP_HASH160:{code:169,category:"crypto",description:"SHA-256 then RIPEMD-160 hash of top item",action:e=>{let t=F(),r=t.createHash("sha256").update(e.pop()).digest(),i=t.createHash("ripemd160").update(r).digest();e.push(i)}},OP_HASH256:{code:170,category:"crypto",description:"Double SHA-256 hash of top item",action:e=>{let t=F(),r=t.createHash("sha256").update(e.pop()).digest(),i=t.createHash("sha256").update(r).digest();e.push(i)}},OP_CODESEPARATOR:{code:171,category:"crypto",description:"Mark signature checking boundary",action:e=>{}},OP_CHECKSIG:{code:172,category:"crypto",description:"Verify signature against public key",action:"// Signature verification (requires transaction context)"},OP_CHECKSIGVERIFY:{code:173,category:"crypto",description:"Verify signature, then fail if invalid",action:"// Signature verification with VERIFY (requires transaction context)"},OP_CHECKMULTISIG:{code:174,category:"crypto",description:"Verify multiple signatures against public keys",action:"// Multi-signature verification (requires transaction context)"},OP_CHECKMULTISIGVERIFY:{code:175,category:"crypto",description:"Verify multiple signatures, then fail if invalid",action:"// Multi-signature verification with VERIFY (requires transaction context)"},OP_SUBSTR:{code:179,category:"string",description:"Extract substring: string[start:start+length]",action:e=>{let t=l.decode(e.pop()),r=l.decode(e.pop()),i=e.pop();e.push(i.slice(r,r+t))}},OP_LEFT:{code:180,category:"string",description:"Extract leftmost n bytes",action:e=>{let t=l.decode(e.pop()),r=e.pop();e.push(r.slice(0,t))}},OP_RIGHT:{code:181,category:"string",description:"Extract rightmost n bytes",action:e=>{let t=l.decode(e.pop()),r=e.pop();e.push(r.slice(-t))}},OP_NOP1:{code:176,category:"nop",description:"No operation (reserved for future use)",action:e=>{}},OP_NOP2:{code:177,category:"nop",description:"No operation (formerly CHECKLOCKTIMEVERIFY)",action:e=>{}},OP_NOP3:{code:178,category:"nop",description:"No operation (formerly CHECKSEQUENCEVERIFY)",action:e=>{}},OP_NOP9:{code:184,category:"nop",description:"No operation (reserved for future use)",action:e=>{}},OP_NOP10:{code:185,category:"nop",description:"No operation (reserved for future use)",action:e=>{}},OP_RESERVED1:{code:137,category:"reserved",description:"Reserved opcode (makes transaction invalid)",action:()=>{throw new Error("OP_RESERVED1 encountered")}},OP_RESERVED2:{code:138,category:"reserved",description:"Reserved opcode (makes transaction invalid)",action:()=>{throw new Error("OP_RESERVED2 encountered")}},OP_CHECKLOCKTIMEVERIFY:{code:177,category:"disabled",description:"Check locktime (disabled post-Genesis)",action:e=>{}},OP_CHECKSEQUENCEVERIFY:{code:178,category:"disabled",description:"Check sequence (disabled post-Genesis)",action:e=>{}},OP_PUBKEYHASH:{code:253,category:"pseudo",description:"Template matching: public key hash",action:"// Template matching only"},OP_PUBKEY:{code:254,category:"pseudo",description:"Template matching: public key",action:"// Template matching only"},OP_INVALIDOPCODE:{code:255,category:"pseudo",description:"Invalid opcode placeholder",action:()=>{throw new Error("Invalid opcode encountered")}}},$e={getByCategory:e=>Object.entries(X).filter(([t,r])=>r.category===e).reduce((t,[r,i])=>({...t,[r]:i}),{}),getCategories:()=>{let e=new Set;return Object.values(X).forEach(t=>e.add(t.category)),Array.from(e).sort()},createASM:e=>{let t=[];return e.forEach(r=>{if(typeof r=="string"&&X[r])t.push(r);else if(typeof r=="number")if(r>=1&&r<=16)t.push(`OP_${r}`);else if(r===0)t.push("OP_0");else if(r===-1)t.push("OP_1NEGATE");else{let i=l.encode(r);t.push(i.toString("hex"))}else if(u.Buffer.isBuffer(r))t.push(r.toString("hex"));else throw new Error(`Invalid operation: ${r}`)}),t.join(" ")},simulate:(e,t=[])=>{let r=[...t],i=[],n=[];return e.forEach((o,s)=>{if(!X[o])throw new Error(`Unknown opcode: ${o}`);let a=X[o],c=[...r];if(typeof a.action=="function")try{a.action(r,i),n.push({step:s+1,opcode:o,beforeStack:c.map(d=>d.toString("hex")),afterStack:r.map(d=>d.toString("hex")),description:a.description})}catch(d){throw n.push({step:s+1,opcode:o,beforeStack:c.map(g=>g.toString("hex")),afterStack:[],error:d.message,description:a.description}),d}else n.push({step:s+1,opcode:o,beforeStack:c.map(d=>d.toString("hex")),afterStack:c.map(d=>d.toString("hex")),note:a.action,description:a.description})}),{finalStack:r.map(o=>o.toString("hex")),finalAltStack:i.map(o=>o.toString("hex")),history:n}},opcodeToName:e=>{let t=Object.entries(X).find(([r,i])=>i.code===e);return t?t[0]:`UNKNOWN_${e.toString(16).padStart(2,"0")}`},nameToOpcode:e=>X[e]&&X[e].code,generateCovenantTemplate:(e,t)=>{let r=[];return e==="value"&&(r.push("OP_SIZE"),r.push(52),r.push("OP_SUB"),r.push("OP_SPLIT"),r.push("OP_DROP"),r.push(8),r.push("OP_SPLIT"),r.push("OP_DROP")),t&&(r.push(u.Buffer.from(t,"hex")),r.push("OP_EQUAL")),{operations:r,asm:$e.createASM(r),description:`Extract ${e} field and compare with expected value`}}};Ut.exports={opcodeMap:X,scriptNum:l,utils:$e};if(C.main===Ut){console.log("\u{1F527} Comprehensive Bitcoin Script Opcode Map"),console.log("=========================================="),console.log(`Total opcodes mapped: ${Object.keys(X).length}`),console.log(`
|
|
8
|
+
\u{1F4CA} Categories:`),$e.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=$e.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 ${P+1}: ${
|
|
17
|
-
===========================================`),console.log("\u2705 Final Result:",
|
|
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=$e.generateCovenantTemplate("value","50c3000000000000");console.log("Generated ASM:",e.asm),console.log("Description:",e.description)}});var Gt=x((Xc,Mt)=>{"use strict";f();var{opcodeMap:Dt,scriptNum:Mi,utils:ds}=qt(),ue=class{constructor(){this.operations=[],this.comments=[]}comment(t){return this.comments.push(`// ${t}`),this}push(t){if(typeof t=="number")if(t>=-1&&t<=16)t===-1?this.operations.push("OP_1NEGATE"):t===0?this.operations.push("OP_0"):this.operations.push(`OP_${t}`);else{let r=Mi.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"):Mi.encode(i).toString("hex")}return r}).join(" ")}_asmToHex(t){return t.split(" ").map(r=>Dt[r]?Dt[r].code.toString(16).padStart(2,"0"):/^[0-9a-fA-F]+$/.test(r)?r:"00").join("")}simulate(t=[]){return ds.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=Dt[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}},Gi={valueLock:e=>new ue().comment("Value Lock Covenant").comment(`Expected value: ${e}`).validateField("value",e).push(1),hashLock:e=>new ue().comment("Hash Lock Covenant").comment(`Expected hash: ${e}`).sha256().push(e).equalVerify().push(1),multiSigWithValidation:(e,t,r)=>{let i=new ue().comment("Multi-Signature Covenant with Field Validation").comment(`Required signatures: ${e}`);return i.validateFields(r),i.comment("Signature validation (placeholder)").push(1),i},timeLock:e=>new ue().comment("Time Lock Covenant").comment(`Locktime: ${e}`).validateField("nLocktime",e).push(1),complexValidation:e=>{let t=new ue().comment("Complex Validation Covenant");return e.valueRange&&t.validateRange("value",e.valueRange.min,e.valueRange.max),e.fields&&t.validateFields(e.fields),e.hashValidation&&t.sha256().push(e.hashValidation.expectedHash).equalVerify(),t.push(1),t}};Mt.exports={CovenantBuilder:ue,CovenantTemplates:Gi};if(C.main===Mt){console.log("\u{1F3D7}\uFE0F Covenant Builder Demonstration"),console.log("=================================="),console.log(`
|
|
12
|
+
\u{1F4CA} Example 1: Value Lock Covenant`);let t=Gi.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 ue().comment("Validate that value field equals 5 + 3").extractField("value").push(5).push(3).add().numEqual().verify().push(1),i=r.build();console.log("Operations:",i.operations.length),console.log("ASM:",i.cleanedASM),console.log(`
|
|
14
|
+
\u{1F4CA} Example 3: Documentation Generation`);let n=r.document();console.log("Structure analysis:",n.structure),console.log("Comments:"),n.comments.forEach(o=>console.log(" "+o))}});var Yi=x((Qc,$i)=>{"use strict";f();var fs=G(),K=A();function we(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 gs(e){try{return K.fromASM(e)}catch(t){throw new Error(`Invalid ASM string: ${t.message}`)}}function ms(e){try{return K.fromASM(e).toBuffer().toString("hex")}catch(t){throw new Error(`Cannot convert ASM to hex: ${t.message}`)}}function ys(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 Ss(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 Vi(e){try{return K.fromASM(e),{valid:!0,error:null}}catch(t){return{valid:!1,error:t.message}}}function zt(e){try{let t;if(typeof e=="string")t=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 vs(e){let t=Vi(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_")&&!fs.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 Vt(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 Kt(e){try{let t=zt(e);if(!t.valid)return{error:t.error};let r=t.asm,i=r.split(" ").filter(c=>c.length>0),n=t.size,o=i.filter(c=>c.startsWith("OP_")).length,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 zi(e){let t=Kt(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 xs(e){try{let t;typeof e=="string"?t=e:Array.isArray(e)?t=e.join(" "):t=we(e);let r=t.split(" "),i=[];for(let c=0;c<r.length;c++){let d=r[c],g=r[c+1];if(!(!d||d.trim()==="")){if(d==="OP_DUP"&&g==="OP_DROP"){c++;continue}!d.startsWith("OP_")&&g&&g.startsWith("OP_"),i.push(d)}}let n=i.join(" "),o=Vt(t),s=Vt(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 Os(e){let t=[];try{let r;typeof e=="string"?r=e:r=we(e);let i=r.split(" ");for(let n=0;n<i.length-1;n++){let o=i[n],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 Ps(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:we(r)},scriptB:{size:i.length,asm:we(i)}}}catch(r){return{error:r.message}}}function Ki(e){try{let t;typeof e=="string"?t=e:t=we(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 _s(e){try{let t=Ki(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 Es(e,t={}){let r=[];e.forEach((n,o)=>{try{let s=zt(n),a=Kt(n),c=zi(n);r.push({index:o,script:typeof n=="string"?n:we(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}}$i.exports={scriptToASM:we,asmToScript:gs,asmToHex:ms,hexToASM:ys,scriptToHex:Ss,validateASM:Vi,validateScript:zt,validateSyntax:vs,estimateScriptSize:Vt,scriptMetrics:Kt,analyzeComplexity:zi,optimizeScript:xs,findOptimizations:Os,compareScripts:Ps,explainScript:Ki,covenantToEnglish:_s,batchTestScripts:Es}});var ji=x((eu,$t)=>{f();var N=typeof window<"u"&&window.bsv?window.bsv:null,it=N?N.Script:A(),nt=N?N.Script.Interpreter:ge(),ws=N?N.Opcode:G(),Is=N?N.Transaction:q(),Ts=N?N.Transaction.Input:He(),As=N?N.Transaction.Output:Ke(),bs=N?N.crypto.BN:D(),Jc=F();function Ye(e){return e.map(t=>t.toString("hex"))}function Xi(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=it.fromHex(e),i=it.fromHex(t),n=it.fromBuffer(u.Buffer.concat([i.toBuffer(),r.toBuffer()])),o=new nt,s=new Is,a=new Ts({prevTxId:"0".repeat(64),outputIndex:0,script:it.empty()});s.addInput(a),s.addOutput(new As({satoshis:1e5,script:r}));let c=n.chunks,d=new nt;d.script=n,d.tx=s,d.nIn=0,d.flags=nt.SCRIPT_ENABLE_SIGHASH_FORKID;for(let P=0;P<c.length;P++){let O=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}: ${ws.reverseMap[O.opcodenum]||"PUSH"}`),console.log("Stack:",Ye(d.stack)),console.log("AltStack:",Ye(d.altstack))}catch(re){console.log(`\u26A0\uFE0F Error executing opcode ${P+1}:`,re.message);break}}let g=new bs(1e5),y=o.verify(i,r,s,0,nt.SCRIPT_ENABLE_SIGHASH_FORKID,g);return console.log(`
|
|
17
|
+
===========================================`),console.log("\u2705 Final Result:",y?"TRUE (Success)":"\u274C FALSE (Failure)"),console.log("Final Stack:",Ye(d.stack||[])),console.log("AltStack:",Ye(d.altstack||[])),console.log("==========================================="),y}catch(r){return console.error("\u274C Error in script execution:",r.message),!1}}if(typeof C<"u"&&C.main===$t){m.default.argv.length<4&&(console.log("Usage: node stack_examiner.js <locking_script_hex> <unlocking_script_hex>"),m.default.exit(1));let e=m.default.argv[2],t=m.default.argv[3];Xi(e,t)}$t.exports={runScript:Xi,bufferToHexArray:Ye}});var en=x((iu,Xt)=>{f();var st=null;try{typeof window>"u"&&typeof C<"u"&&(st=F())}catch{st=null}var U=typeof window<"u"&&window.bsv?window.bsv:null,he=U?U.Script:A(),at=U?U.Script.Interpreter:ge(),ks=U?U.Opcode:G(),Hs=U?U.crypto.BN:D(),Fs=U?U.Transaction:q(),Cs=U?U.Transaction.Input:He(),Wi=U?U.Transaction.Output:Ke();function ot(e){if(!e)return new he;let t=e.trim(),r=/^[0-9a-fA-F]+$/.test(t.replace(/\s+/g,""));try{return r?he.fromHex(t):he.fromASM(t)}catch(i){console.error("\u274C Error parsing script:",i.message),m.default.exit(1)}}function Yt(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 Qi(e,t,r=!0){let i=new at;i.script=e,i.tx=t,i.nIn=0,i.flags=at.SCRIPT_ENABLE_SIGHASH_FORKID;let n=e.chunks,o=null;st&&typeof m.default<"u"&&m.default.stdin&&(o=st.createInterface({input:m.default.stdin,output:m.default.stdout})),console.log("==========================================="),console.log("\u{1F50D} SCRIPT INTERPRETER DEBUGGER (STEP MODE)"),console.log(`===========================================
|
|
18
|
+
`),console.log("Script:",e.toASM()),console.log("-------------------------------------------");for(let s=0;s<n.length;s++){let a=n[s],c=ks.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 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
|
|
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}`),Yt(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:"),Yt(i.stack||[],i.altstack||[]),console.log("===========================================")}function Zi(e,t,r){console.log("==========================================="),console.log("\u{1F50D} SCRIPT INTERPRETER DEBUGGER (FULL RUN)"),console.log(`===========================================
|
|
22
|
+
`);let i=new at,n=new Hs(1e5),o=i.verify(e,t,r,0,at.SCRIPT_ENABLE_SIGHASH_FORKID,n);console.log("\u{1F510} Locking Script:",t.toASM()),console.log("\u{1F513} Unlocking Script:",e.toASM()),console.log("-------------------------------------------"),console.log("\u2705 Result:",o?"TRUE (Success)":"\u274C FALSE (Failure)"),console.log("Final Stack:",i.stack.map(s=>s.toString("hex"))),console.log("AltStack:",i.altstack.map(s=>s.toString("hex"))),console.log("===========================================")}async function Ji(){if(typeof m.default>"u"||!m.default.argv){console.log("\u2699\uFE0F CLI mode not available in browser environment");return}let e=m.default.argv.slice(2),t=P=>{let O=e.indexOf(P);return O!==-1&&e[O+1]?e[O+1]:null},r=t("--unlocking"),i=t("--locking"),n=t("--combined"),o=e.includes("--step"),s=e.includes("--truth"),a,c,d;if(n)d=ot(n);else{a=ot(r),c=ot(i);let P=u.Buffer.concat([a.toBuffer(),c.toBuffer()]);d=he.fromBuffer(P)}let g=new Fs,y=new Cs({prevTxId:"0".repeat(64),outputIndex:0,script:he.empty(),satoshis:1e5,output:new Wi({satoshis:1e5,script:he.empty()})});g.addInput(y),g.addOutput(new Wi({satoshis:1e5,script:he.empty()})),o?await Qi(d,g,!0):s?Zi(a||he.empty(),c||he.empty(),g):console.log("\u2699\uFE0F No mode specified. Use --step or --truth")}Xt.exports={parseScript:ot,printStack:Yt,stepThroughScript:Qi,runFullEvaluation:Zi,main:Ji};typeof C<"u"&&C.main===Xt&&Ji()});var pe=x((su,un)=>{"use strict";f();var rn=A(),nn=ge(),jt=G(),Wt=q(),Ls=He(),on=Ke(),sn=_e(),ct=D(),Rs=fe(),tn=Ee(),Qt=tn.SIGHASH_ALL|tn.SIGHASH_FORKID;function an(){return nn.mainnetFlags()}function Bs(e,t,r){r=r||{};var i=new nn,n=i.verify(e,t,r.tx||new Wt,r.inputIndex||0,r.flags||an(),new ct(r.satoshis||0));return{ok:n,err:i.errstr||""}}function cn(e,t,r,i,n){return sn.sighashPreimage(e,n||Qt,t,r,new ct(i))}function Ns(e,t,r,i,n){return Rs.sha256sha256(cn(e,t,r,i,n))}function Us(e,t,r,i,n,o){o=o||Qt;var s=sn.sign(e,t,o,r,i,new ct(n));return u.Buffer.concat([s.toDER(),u.Buffer.from([o])])}function qs(e,t,r){r=r||{};var i=new Wt().addOutput(new on({script:e,satoshis:t})),n=new Wt;return n.addInput(new Ls({prevTxId:i.hash,outputIndex:0,script:rn.empty()}),e,t),r.outputs&&r.outputs.forEach(function(o){n.addOutput(o)}),{funding:i,spend:n}}function Ds(e,t){var r=e.toAddress?e.toAddress():e;return new on({script:rn.buildPublicKeyHashOut(r),satoshis:t})}function Ms(e){return e===0?jt.OP_0:e===-1?jt.OP_1NEGATE:e>=1&&e<=16?jt["OP_"+e]:new ct(e).toScriptNumBuffer()}un.exports={SIGHASH:Qt,flags:an,verify:Bs,rawPreimage:cn,sighashDigest:Ns,signInput:Us,fundAndSpend:qs,p2pkhOutput:Ds,scriptNum:Ms}});var ln=x((cu,pn)=>{"use strict";f();var Gs=fe(),Vs=pe(),qe=A(),Ue=G(),hn=Vs.signInput;function zs(e){var t=Gs.sha256(e),r=new qe().add(Ue.OP_SHA256).add(t).add(Ue.OP_EQUAL);return{lock:r,meta:{name:"hash-lock",digest:t.toString("hex")},unlock:function(i,n,o){return new qe().add(o||e)}}}function Ks(e){var t=e.toPublicKey(),r=qe.buildPublicKeyHashOut(t.toAddress());return{lock:r,meta:{name:"p2pkh",address:t.toAddress().toString()},unlock:function(i,n){return new qe().add(hn(i,e,0,r,n)).add(t.toBuffer())}}}function $s(e,t){var r=t.map(function(n){return n.toPublicKey()}),i=new qe().add(Ue["OP_"+e]);return r.forEach(function(n){i.add(n.toBuffer())}),i.add(Ue["OP_"+r.length]).add(Ue.OP_CHECKMULTISIG),{lock:i,meta:{name:e+"-of-"+r.length+"-multisig"},unlock:function(n,o,s){s=s||t.slice(0,e);var a=new qe().add(Ue.OP_0);return s.forEach(function(c){a.add(hn(n,c,0,i,o))}),a}}}pn.exports={hashLock:zs,p2pkh:Ks,multisig:$s}});var Xe=x((hu,xn)=>{"use strict";f();var dn=A(),_=G(),ee=Ee(),ut=D(),fn=fe(),Jt=pe(),er=Jt.SIGHASH,ht=Jt.scriptNum,De=u.Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),tr=new ut("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",16),Ys=u.Buffer.concat([u.Buffer.from([2]),De]),gn=u.Buffer.from(De).reverse(),mn=u.Buffer.concat([u.Buffer.from(tr.toBuffer()).reverse(),u.Buffer.from([0])]),Xs=u.Buffer.concat([u.Buffer.from([48,68,2,32]),De,u.Buffer.from([2,32])]);function Zt(e,t){var r;for(r=0;r<t-1;r++)e.add(_.OP_1).add(_.OP_SPLIT);for(r=0;r<t-1;r++)e.add(_.OP_SWAP).add(_.OP_CAT);return e}var js=ee.SIGHASH_ALL|ee.SIGHASH_FORKID,Ws=ee.SIGHASH_SINGLE|ee.SIGHASH_FORKID,Qs=ee.SIGHASH_SINGLE|ee.SIGHASH_ANYONECANPAY|ee.SIGHASH_FORKID,Zs=ee.SIGHASH_ALL|ee.SIGHASH_ANYONECANPAY|ee.SIGHASH_FORKID;function rr(e,t){var r=t&&t.sighashType||er;return e.add(_.OP_HASH256),Zt(e,32),e.add(gn).add(_.OP_ADD),e.add(mn).add(_.OP_MOD),e.add(ht(32)).add(_.OP_NUM2BIN),Zt(e,32),e.add(De).add(_.OP_DUP),e.add(_.OP_2).add(_.OP_SWAP).add(_.OP_CAT),e.add(_.OP_TOALTSTACK),e.add(u.Buffer.from([48,68,2,32])).add(_.OP_SWAP).add(_.OP_CAT),e.add(u.Buffer.from([2,32])).add(_.OP_CAT),e.add(_.OP_SWAP).add(_.OP_CAT),e.add(u.Buffer.from([r])).add(_.OP_CAT),e.add(_.OP_FROMALTSTACK).add(_.OP_CHECKSIG),e}function Js(){return rr(new dn)}function yn(e){return e.add(ht(40)).add(_.OP_RIGHT).add(ht(32)).add(_.OP_LEFT),e}function ea(e){return Sn(e,er)}function Sn(e,t){var r=u.Buffer.from([t&255,0,0,0]);return e.add(_.OP_DUP).add(ht(4)).add(_.OP_RIGHT).add(r).add(_.OP_EQUALVERIFY),e}function ta(e){var t=u.Buffer.concat(e.map(function(r){return r.toBufferWriter().toBuffer()}));return fn.sha256sha256(t)}function ra(e){var t=new dn().add(_.OP_DUP);return rr(t),t.add(_.OP_VERIFY),yn(t),t.add(u.Buffer.from(e)).add(_.OP_EQUAL),t}var ia=new ut("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex");function vn(e){var t=fn.sha256sha256(e);if(t[0]<1||t[0]>127)return null;var r=new ut(t).add(new ut(De)).mod(tr);if(r.gt(ia))return null;var i=r.toBuffer("be",32);return i[0]>=1?i:null}function na(e,t,r,i,n){typeof n=="number"&&(n={maxTries:n}),n=n||{};var o=n.maxTries||5e3,s=n.start||0,a=n.field||"nLockTime",c=n.sighashType||er;if(a!=="nLockTime"&&a!=="sequence")throw new Error("grind field must be 'nLockTime' or 'sequence'");for(var d=e.inputs[t],g=0;g<o;g++){var y=s+g;a==="nLockTime"?e.nLockTime=y:d.sequenceNumber=4294967294-y;var P=Jt.rawPreimage(e,t,r,i,c);if(vn(P))return{preimage:P,tries:g+1,field:a,nonce:y}}throw new Error("OP_PUSH_TX grind failed after "+o+" tries")}xn.exports={Gx:De,N:tr,PUBKEY:Ys,gxLe:gn,N_LE:mn,DER_PREFIX:Xs,reverseBytes:Zt,pushTxCore:rr,authenticator:Js,extractHashOutputs:yn,assertSighashAll:ea,assertSighashType:Sn,SIGHASH_ALL_FORKID:js,SIGHASH_SINGLE_FORKID:Ws,SIGHASH_SINGLE_ANYONECANPAY_FORKID:Qs,SIGHASH_ALL_ANYONECANPAY_FORKID:Zs,hashOutputs:ta,valueCovenant:ra,sFromPreimage:vn,grind:na}});var nr=x((lu,On)=>{"use strict";f();var ir=Xe(),oa=pe(),sa=A(),T=G(),Me=oa.scriptNum;function aa(e){var t=new sa;return t.add(T.OP_DUP),ir.pushTxCore(t),t.add(T.OP_VERIFY),ir.assertSighashAll(t),t.add(T.OP_DUP),t.add(Me(104)).add(T.OP_SPLIT).add(T.OP_NIP),t.add(T.OP_SIZE).add(Me(52)).add(T.OP_SUB).add(T.OP_SPLIT).add(T.OP_DROP),t.add(T.OP_OVER),t.add(Me(52)).add(T.OP_RIGHT).add(Me(8)).add(T.OP_LEFT),t.add(T.OP_BIN2NUM).add(Me(e)).add(T.OP_SUB),t.add(Me(8)).add(T.OP_NUM2BIN),t.add(T.OP_SWAP).add(T.OP_CAT),t.add(T.OP_HASH256),t.add(T.OP_SWAP),ir.extractHashOutputs(t),t.add(T.OP_EQUAL),t}On.exports={pelsCovenant:aa}});var _n=x((fu,Pn)=>{f();Pn.exports=(typeof globalThis<"u"?globalThis:typeof self<"u"?self:window).bsv.PublicKey});var ar=x((mu,wn)=>{"use strict";f();var ca=ze(),ua=_n(),ha=A(),En=fe(),sr=pe(),E=G(),Ge=sr.scriptNum;function pt(e){return e instanceof ca?e.toPublicKey().toBuffer():e instanceof ua?e.toBuffer():e}function pa(){return{name:"single-key",commit:function(e){return En.sha256ripemd160(pt(e))},emit:function(e){return e.add(E.OP_OVER).add(E.OP_HASH160).add(E.OP_EQUALVERIFY),e.add(E.OP_CHECKSIGVERIFY),e},unlockArgs:function(e,t,r,i,n){var o=sr.signInput(e,n,t,r,i);return[o,n.toPublicKey().toBuffer()]}}}function or(e,t){var r=t.length;if(e<1||e>r||r<1||r>16)throw new Error("multisig requires 1 <= m <= n <= 16");var i=new ha().add(E["OP_"+e]);return t.forEach(function(n){i.add(u.Buffer.from(n))}),i.add(E["OP_"+r]).add(E.OP_CHECKMULTISIG),i.toBuffer()}function la(e,t){if(typeof t!="number"||!Number.isInteger(t))throw new Error("multisig(m, nKeys): nKeys is the NUMBER of keys, not the keys themselves"+(Array.isArray(t)?" \u2014 pass "+t.length+" instead of the array":""));if(typeof e!="number"||!Number.isInteger(e))throw new Error("multisig(m, nKeys): m must be an integer");if(e<1||e>t||t<1||t>16)throw new Error("multisig requires 1 <= m <= n <= 16");return{name:e+"-of-"+t+"-multisig",m:e,n:t,commit:function(r){if(r.length!==t)throw new Error("expected "+t+" public keys");return En.sha256ripemd160(or(e,r.map(pt)))},emit:function(r){r.add(E.OP_OVER).add(E.OP_HASH160).add(E.OP_EQUALVERIFY),r.add(Ge(1)).add(E.OP_SPLIT).add(E.OP_NIP),r.add(E.OP_SIZE).add(Ge(2)).add(E.OP_SUB).add(E.OP_SPLIT).add(E.OP_DROP);for(var i=0;i<this.n;i++)r.add(Ge(34)).add(E.OP_SPLIT),r.add(E.OP_SWAP).add(Ge(1)).add(E.OP_SPLIT).add(E.OP_NIP),r.add(E.OP_TOALTSTACK);for(r.add(E.OP_DROP),r.add(Ge(this.m)),i=0;i<this.n;i++)r.add(E.OP_FROMALTSTACK);return r.add(Ge(this.n)),r.add(E.OP_CHECKMULTISIGVERIFY),r},unlockArgs:function(r,i,n,o,s){var a=s.keys;if(a.length!==t)throw new Error("expected "+t+" public keys in signer.keys");var c=or(e,a.map(pt)),d=a.map(pt).map(function(P){return P.toString("hex")}),g=s.signWith.map(function(P){var O=d.indexOf(P.toPublicKey().toBuffer().toString("hex"));if(O<0)throw new Error("signWith key is not in the committed key set");return{idx:O,priv:P}}).sort(function(P,O){return O.idx-P.idx}).slice(0,e);if(g.length<e)throw new Error("need at least "+e+" signing keys");var y=g.map(function(P){return sr.signInput(r,P.priv,i,n,o)});return[E.OP_0].concat(y).concat([c])}}}function da(e){if(!e||typeof e.emit!="function"||typeof e.unlockArgs!="function"||typeof e.commit!="function")throw new Error("predicate authorizer needs { commit, emit, unlockArgs } functions");return{name:e.name||"predicate",commit:e.commit,emit:e.emit,unlockArgs:e.unlockArgs}}wn.exports={singleKey:pa,multisig:la,predicate:da,redeemScript:or}});var ur=x((Su,Cn)=>{"use strict";f();var fa=D(),je=Xe(),cr=pe(),We=ar(),lt=A(),v=G(),te=cr.scriptNum;function Tn(e,t){var r=u.Buffer.isBuffer(e)?e:t.commit(e);if(r.length!==20)throw new Error("owner commitment must be 20 bytes (HASH160)");return r}function In(e,t){return t.length?e.add(u.Buffer.from(t)):e.add(v.OP_0)}function An(e,t){return e.add(v.OP_DUP),je.pushTxCore(e),e.add(v.OP_VERIFY),je.assertSighashAll(e),e.add(v.OP_DUP).add(te(52)).add(v.OP_RIGHT).add(te(8)).add(v.OP_LEFT).add(v.OP_TOALTSTACK),e.add(v.OP_DUP),je.extractHashOutputs(e),e.add(v.OP_TOALTSTACK),e.add(te(104)).add(v.OP_SPLIT).add(v.OP_NIP).add(v.OP_SIZE).add(te(52)).add(v.OP_SUB).add(v.OP_SPLIT).add(v.OP_DROP),e.add(v.OP_DUP).add(te(4)).add(te(20)).add(v.OP_SUBSTR),e.add(v.OP_SWAP).add(v.OP_TOALTSTACK),t.emit(e),e.add(v.OP_FROMALTSTACK),e}function bn(e){return e.add(te(4)).add(v.OP_SPLIT).add(te(20)).add(v.OP_SPLIT).add(v.OP_NIP),e.add(v.OP_TOALTSTACK),e.add(v.OP_SWAP).add(v.OP_CAT),e.add(v.OP_FROMALTSTACK).add(v.OP_CAT),e}function kn(e){var t=e.toBuffer().length;if(t<=252||t>65535)throw new Error("token script length must use a 3-byte varint (253..65535); got "+t);return e}function ga(e,t,r){r=r||We.singleKey();var i=new lt;return i.add(Tn(t,r)),i.add(v.OP_DROP),An(i,r),bn(i),i.add(v.OP_FROMALTSTACK),i.add(v.OP_SWAP),i.add(v.OP_FROMALTSTACK),i.add(v.OP_BIN2NUM).add(te(e)).add(v.OP_SUB).add(te(8)).add(v.OP_NUM2BIN),i.add(v.OP_SWAP).add(v.OP_CAT),i.add(v.OP_HASH256),i.add(v.OP_EQUAL),kn(i)}function Hn(e,t){t=t||We.singleKey();var r=new lt;return r.add(Tn(e,t)),r.add(v.OP_DROP),An(r,t),bn(r),r.add(v.OP_CAT),r.add(v.OP_SWAP).add(v.OP_CAT),r.add(v.OP_CAT),r.add(v.OP_FROMALTSTACK),r.add(v.OP_FROMALTSTACK).add(v.OP_DROP),r.add(v.OP_SWAP).add(v.OP_HASH256).add(v.OP_EQUAL),kn(r)}function ma(e){return We.singleKey().commit(e)}function ya(e,t,r,i,n,o){o=o||{};var s=o.auth||We.singleKey(),a=o.inputIndex||0;if(t.length!==20)throw new Error("newOwnerHash must be 20 bytes (HASH160)");if(i<=1&&!o.allowLowValue)throw new Error("unlockTransfer: single-output token sets output = input - fee, which burns a "+i+"-sat UTXO (e.g. a 1-sat ordinal). Use Token.transferOrdinal / ownershipTokenMulti to preserve the satoshi.");je.grind(r,a,n,i,o.grind);var c=cr.rawPreimage(r,a,n,i),d=s.unlockArgs(r,a,n,i,e),g=new lt().add(u.Buffer.from(t));return d.forEach(function(y){g.add(y)}),g.add(u.Buffer.from(c)),g}function Fn(e,t,r,i,n,o,s){s=s||{};var a=s.auth||We.singleKey(),c=s.inputIndex||0;if(t.length!==20)throw new Error("newOwnerHash must be 20 bytes (HASH160)");if(!o||o.tokenValue==null||o.tokenValue.length!==8)throw new Error("layout.tokenValue must be the 8-byte LE value of the token output");je.grind(r,c,n,i,s.grind);var d=cr.rawPreimage(r,c,n,i),g=a.unlockArgs(r,c,n,i,e),y=new lt;return In(y,o.before||u.Buffer.alloc(0)),In(y,o.after||u.Buffer.alloc(0)),y.add(u.Buffer.from(o.tokenValue)),y.add(u.Buffer.from(t)),g.forEach(function(P){y.add(P)}),y.add(u.Buffer.from(d)),y}function Sa(e,t){return Hn(e,t)}function va(e,t,r,i,n,o){o=o||{},i==null&&(i=1);var s=o.tokenIndex||0,a=r.outputs||[],c=a[s];if(!c)throw new Error("transferOrdinal: spend has no output at tokenIndex "+s);if(c.satoshis!==i)throw new Error("transferOrdinal: token output value ("+c.satoshis+" sat) must equal the ordinal value ("+i+" sat) to avoid burning the inscription");function d(O){return O.toBufferWriter().toBuffer()}var g=u.Buffer.concat(a.slice(0,s).map(d)),y=u.Buffer.concat(a.slice(s+1).map(d)),P=new fa(i).toBuffer({endian:"little",size:8});return Fn(e,t,r,i,n,{before:g,after:y,tokenValue:P},o)}Cn.exports={ownershipToken:ga,ownershipTokenMulti:Hn,ordinalLock:Sa,ownerId:ma,unlockTransfer:ya,unlockTransferMulti:Fn,transferOrdinal:va}});var gr=x((xu,Ln)=>{"use strict";f();var dt=Xe(),xa=nr(),Oa=ur(),dr=pe(),pr=A(),$=G(),lr=q(),hr=dr.scriptNum;function Pa(e,t){return e instanceof lr.Output?e:e instanceof pr?new lr.Output({script:e,satoshis:t}):dr.p2pkhOutput(e,t)}function _a(e,t,r,i,n,o){o=o||5e4;for(var s=0;s<o;s++){e.nLockTime=n+s;var a=dr.rawPreimage(e,t,r,i);if(dt.sFromPreimage(a))return a}throw new Error("covenant grind failed after "+o+" tries")}function le(){if(!(this instanceof le))return new le;this._outputs=[],this._minLockTime=null}le.prototype.payTo=function(e,t){return this._outputs.push(Pa(e,t)),this};le.prototype.lockUntil=function(e){return this._minLockTime=e,this};le.prototype.outputs=function(){return this._outputs.map(function(e){return new lr.Output(e.toObject())})};le.prototype.describe=function(){var e=[];return this._outputs.forEach(function(t,r){e.push("output["+r+"] = "+t.satoshis+" sat to "+t.script.toASM().slice(0,24)+"...")}),this._minLockTime!==null&&e.push("nLockTime >= "+this._minLockTime),"spend allowed iff: "+e.join(" AND ")};le.prototype.compile=function(){if(this._outputs.length===0&&this._minLockTime===null)throw new Error("empty policy: add at least one constraint (payTo / lockUntil)");var e=this,t=new pr().add($.OP_DUP);if(dt.pushTxCore(t),t.add($.OP_VERIFY),this._outputs.length){var r=dt.hashOutputs(this._outputs);t.add($.OP_DUP),dt.extractHashOutputs(t),t.add(u.Buffer.from(r)).add($.OP_EQUALVERIFY)}return this._minLockTime!==null&&(t.add($.OP_DUP),t.add(hr(8)).add($.OP_RIGHT).add(hr(4)).add($.OP_LEFT),t.add($.OP_BIN2NUM).add(hr(this._minLockTime)).add($.OP_GREATERTHANOREQUAL).add($.OP_VERIFY)),t.add($.OP_DROP).add($.OP_1),{lock:t,outputs:e.outputs(),describe:function(){return e.describe()},unlock:function(i,n,o){o=o||0;var s=e._minLockTime===null?0:e._minLockTime;return e._minLockTime!==null&&(i.inputs[o].sequenceNumber=4294967294),new pr().add(_a(i,o,t,n,s))}}};function fr(){return new le}fr.perpetual=function(e){return xa.pelsCovenant(e)};fr.token=function(e,t){return Oa.ownershipToken(e,t)};Ln.exports={policy:fr,Policy:le}});var qn=x((Pu,Un)=>{"use strict";f();var Ea=ge(),wa=D(),Ia=q(),Ta=G(),Aa=pe();function Bn(e){if(e===0)return"OP_0";if(e>=1&&e<=75)return"PUSH("+e+")";if(e===76)return"OP_PUSHDATA1";if(e===77)return"OP_PUSHDATA2";if(e===78)return"OP_PUSHDATA4";try{return Ta.fromNumber(e).toString()}catch{return"0x"+e.toString(16)}}function Rn(e,t){t=t||16;var r=u.Buffer.from(e).toString("hex");return r.length<=t*2?r||"0":r.slice(0,t*2)+"...("+e.length+"B)"}function ba(e,t,r){r=r||{};var i=new Ea,n=[];i.stepListener=function(s,a,c){n.push({phase:i.script===t?"lock":"unlock",op:Bn(s.opcode&&typeof s.opcode.toNumber=="function"?s.opcode.toNumber():s.opcode.num),stack:a.map(function(d){return Rn(d)}),altstack:c.map(function(d){return Rn(d)})})};var o=i.verify(e,t,r.tx||new Ia,r.inputIndex||0,typeof r.flags=="number"?r.flags:Aa.flags(),new wa(r.satoshis||0));return{ok:o,err:i.errstr||"",steps:n}}function Nn(e){var t=[],r=null;return e.steps.forEach(function(i,n){i.phase!==r&&(t.push("-- "+i.phase+" script --"),r=i.phase);var o=i.stack.length?i.stack.join(" | "):"(empty)",s=i.altstack.length?" alt:["+i.altstack.join(" | ")+"]":"";t.push(String(n).padStart(3)+" "+i.op.padEnd(16)+" -> ["+o+"]"+s)}),t.push((e.ok?"VALID":"INVALID")+(e.err?" ("+e.err+")":"")),t.join(`
|
|
23
|
+
`)}function ka(e){return console.log(Nn(e)),e}Un.exports={trace:ba,format:Nn,print:ka,opLabel:Bn}});var Mn=x((Eu,Dn)=>{"use strict";f();Dn.exports="9.1.0"});var zn=x((Iu,Vn)=>{"use strict";f();var Ha=fe(),Gn=q(),Fa=It(),Ca=A(),p={Covenant:oi(),Preimage:J(),SIGHASH:pi(),Builder:Si(),UTXOGenerator:Ri(),ScriptTester:Di(),CovenantBuilder:Gt().CovenantBuilder,CovenantTemplates:Gt().CovenantTemplates,OpcodeMap:qt(),ScriptUtils:Yi(),StackExaminer:ji(),ScriptInterpreter:en(),CovenantHelpers:pe(),Locks:ln(),PushTx:Xe(),PELS:nr(),Token:ur(),Authorizers:ar(),DSL:gr(),Policy:gr().Policy,Debugger:qn()};p.policy=p.DSL.policy;p.trace=function(e,t,r){return p.Debugger.trace(e,t,r)};p.verifyScript=function(e,t,r){return p.CovenantHelpers.verify(e,t,r)};p.perpetualCovenant=function(e){return p.PELS.pelsCovenant(e)};p.ownershipToken=function(e,t,r){return p.Token.ownershipToken(e,t,r)};p.valueCovenant=function(e){return p.PushTx.valueCovenant(e)};p.ordinalLock=function(e,t){return p.Token.ordinalLock(e,t)};p.transferOrdinal=function(e,t,r,i,n,o){return p.Token.transferOrdinal(e,t,r,i,n,o)};p.createCovenant=function(e,t){return new p.Covenant(e,t)};p.extractPreimage=function(e,t){return new p.Preimage(e,t)};p.analyzeSIGHASH=function(e){return new p.SIGHASH(e)};p.buildCovenant=function(e,t){return new p.Builder(e,t)};p.createUTXOGenerator=function(e){return new p.UTXOGenerator(e)};p.createTestEnvironment=function(e){return p.UTXOGenerator.createTestEnvironment(e)};p.testScript=function(e,t,r){return p.ScriptTester.test(e,t,r)};p.testCovenant=function(e,t,r){return p.ScriptTester.testCovenant(e,t,r)};p.testFieldExtraction=function(e,t,r){return p.ScriptTester.testFieldExtraction(e,t,r)};p.debugScript=function(e,t){var r=new p.ScriptTester(t);return r.debug(e)};p.explainZeroHashes=function(){return p.SIGHASH.explainZeroMystery()};p.getAllSIGHASHTypes=function(){return p.SIGHASH.getAllTypes()};p.demonstrateAllSIGHASH=function(){return p.SIGHASH.generateAllDemonstrations()};p.createCovenantBuilder=function(){return new p.CovenantBuilder};p.createValueLockCovenant=function(e){return p.CovenantTemplates.valueLock(e)};p.createHashLockCovenant=function(e){return p.CovenantTemplates.hashLock(e)};p.createComplexValidationCovenant=function(e){return p.CovenantTemplates.complexValidation(e)};p.getOpcodeMap=function(){return p.OpcodeMap.opcodeMap};p.simulateScript=function(e,t){return p.OpcodeMap.utils.simulate(e,t)};p.createASMFromJS=function(e){return p.OpcodeMap.utils.createASM(e)};p.scriptToASM=function(e){return p.ScriptUtils.scriptToASM(e)};p.asmToScript=function(e){return p.ScriptUtils.asmToScript(e)};p.asmToHex=function(e){return p.ScriptUtils.asmToHex(e)};p.hexToASM=function(e){return p.ScriptUtils.hexToASM(e)};p.scriptToHex=function(e){return p.ScriptUtils.scriptToHex(e)};p.validateASM=function(e){return p.ScriptUtils.validateASM(e)};p.validateScript=function(e){return p.ScriptUtils.validateScript(e)};p.estimateScriptSize=function(e){return p.ScriptUtils.estimateScriptSize(e)};p.optimizeScript=function(e){return p.ScriptUtils.optimizeScript(e)};p.compareScripts=function(e,t){return p.ScriptUtils.compareScripts(e,t)};p.explainScript=function(e){return p.ScriptUtils.explainScript(e)};p.scriptMetrics=function(e){return p.ScriptUtils.scriptMetrics(e)};p.analyzeComplexity=function(e){return p.ScriptUtils.analyzeComplexity(e)};p.findOptimizations=function(e){return p.ScriptUtils.findOptimizations(e)};p.covenantToEnglish=function(e){return p.ScriptUtils.covenantToEnglish(e)};p.batchTestScripts=function(e,t){return p.ScriptUtils.batchTestScripts(e,t)};p.examineStack=function(e,t){return p.StackExaminer.runScript(e,t)};p.debugScriptExecution=function(e,t,r){return r=r||{},r.stepMode?p.ScriptInterpreter.stepThroughScript(p.ScriptInterpreter.parseScript(e+" "+t),new Gn,!0):p.ScriptInterpreter.runFullEvaluation(p.ScriptInterpreter.parseScript(e),p.ScriptInterpreter.parseScript(t),new Gn)};p.parseScript=function(e){return p.ScriptInterpreter.parseScript(e)};p.printStack=function(e,t){return p.ScriptInterpreter.printStack(e,t)};p.createQuickCovenant=function(e,t){let r=p.createCovenantBuilder();switch(e){case"value_lock":return r.comment(`Value lock: minimum ${t.value} satoshis`).extractField("value").push(t.value).greaterThanOrEqual().verify().build();case"hash_lock":return r.comment(`Hash lock: requires preimage of ${t.hash}`).push("secret_placeholder").sha256().push(t.hash).equalVerify().build();case"time_lock":return r.comment(`Time lock: requires nLockTime > ${t.timestamp}`).extractField("nLockTime").push(t.timestamp).greaterThan().verify().build();case"multi_condition":let i=r.comment("Multi-condition covenant");return t.conditions.forEach(n=>{switch(n.type){case"value":i=i.extractField("value").push(n.value).greaterThanOrEqual().verify();break;case"hash":i=i.push("secret_placeholder").sha256().push(n.hash).equalVerify();break;case"time":i=i.extractField("nLockTime").push(n.timestamp).greaterThan().verify();break}}),i.build();default:throw new Error(`Unknown covenant type: ${e}`)}};p.completeCovenantFlow=function(e,t,r){var i=new p.Covenant(e);return i.completeFlow(t,r)};p.getEducationalResources=function(){return{zeroHashMystery:p.SIGHASH.explainZeroMystery(),sighashTypes:p.SIGHASH.getAllTypes(),exampleDemonstrations:p.SIGHASH.generateAllDemonstrations()}};p.utils={};p.utils.reconstructP2pkhScript=function(e){return Ca.buildPublicKeyHashOut(e).toHex()};p.utils.createCovenantAddress=function(e){var t=Ha.sha256ripemd160(e.toBuffer());return Fa.fromScriptHash(t)};p.utils.decodeCompactSize=function(e,t){return p.Preimage.decodeCompactSize(e,t)};p.version=Mn();p.description="Smart Contract Framework for Bitcoin SV";p.features={BIP143_PREIMAGE:!0,COMPACT_SIZE_VARINT:!0,BIDIRECTIONAL_EXTRACTION:!0,SIGHASH_DETECTION:!0,ZERO_HASH_WARNINGS:!0,MULTI_FIELD_VALIDATION:!0,REAL_UTXO_GENERATION:!0,SCRIPT_TESTING:!0,LOCAL_VERIFICATION:!0,JAVASCRIPT_TO_SCRIPT:!0,OPCODE_MAPPING:!0,COVENANT_BUILDER:!0,SCRIPT_ANALYSIS:!0,SCRIPT_OPTIMIZATION:!0,SCRIPT_CONVERSION:!0,BATCH_TESTING:!0,QUICK_COVENANTS:!0,SCRIPT_EXPLANATIONS:!0,STACK_EXAMINATION:!0,SCRIPT_DEBUGGING:!0,STEP_BY_STEP_EXECUTION:!0,INTERACTIVE_DEBUGGING:!0};p.interpretScript=p.debugScriptExecution;p.getScriptMetrics=p.scriptMetrics;Vn.exports=p});var La=x((Au,Kn)=>{f();Kn.exports=zn()});return La();})();
|
|
24
24
|
if(typeof module!=="undefined"&&module.exports){module.exports=bsvSmartContract}else if(typeof define==="function"&&define.amd){define([],function(){return bsvSmartContract})}
|