@smartledger/bsv 8.0.1 → 8.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 +36 -0
- package/README.md +38 -38
- package/bsv-gdaf.min.js +2 -2
- package/bsv-ltp.min.js +1 -1
- package/bsv-smartcontract.min.js +1 -1
- package/bsv.bundle.js +2 -2
- package/bsv.min.js +2 -2
- package/docs/AUDIT_SCOPE.md +9 -9
- package/docs/MODULE_REFERENCE_COMPLETE.md +27 -27
- package/docs/advanced/UTXO_MANAGER_GUIDE.md +1 -1
- package/docs/getting-started/INSTALLATION.md +23 -23
- package/docs/getting-started/QUICK_START.md +7 -7
- package/docs/migration/FROM_BSV_1_5_6.md +5 -5
- package/lib/script/interpreter.js +20 -1
- package/package.json +1 -1
- package/test/script/genesis_limits.js +37 -6
- package/version.js +1 -1
package/bsv-ltp.min.js
CHANGED
|
@@ -66,5 +66,5 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
66
66
|
`))}throw n}};function ZE(e,t,r,n,i){if(!bc(t))throw new ns("regexp","RegExp",t);var o=i==="match";if(typeof e!="string"||_c(t,e)!==o){if(r instanceof Error)throw r;var s=!r;r=r||(typeof e!="string"?'The "string" argument must be of type string. Received type '+"".concat(Fr(e)," (").concat(vc(e),")"):(o?"The input did not match the regular expression ":"The input was expected to not match the regular expression ")+"".concat(vc(t),`. Input:
|
|
67
67
|
|
|
68
68
|
`).concat(vc(e),`
|
|
69
|
-
`));var a=new li({actual:e,expected:t,message:r,operator:i,stackStartFn:n});throw a.generatedMessage=s,a}}Ge.match=function e(t,r,n){ZE(t,r,n,e,"match")};Ge.doesNotMatch=function e(t,r,n){ZE(t,r,n,e,"doesNotMatch")};function XE(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];KE.apply(void 0,[XE,t.length].concat(t))}Ge.strict=f6(XE,Ge,{equal:Ge.strictEqual,deepEqual:Ge.deepStrictEqual,notEqual:Ge.notStrictEqual,notDeepEqual:Ge.notDeepStrictEqual});Ge.strict.strict=Ge.strict});var Qi=P((RF,e1)=>{"use strict";m();var QE=oc(),tt=function e(t){if(!(this instanceof e))return new e(t);this.bufLen=0,t?this.set(t):this.bufs=[]};tt.prototype.set=function(e){return this.bufs=e.bufs||this.bufs||[],this.bufLen=this.bufs.reduce(function(t,r){return t+r.length},0),this};tt.prototype.toBuffer=function(){return this.concat()};tt.prototype.concat=function(){return d.Buffer.concat(this.bufs,this.bufLen)};tt.prototype.write=function(e){return QE(d.Buffer.isBuffer(e)),this.bufs.push(e),this.bufLen+=e.length,this};tt.prototype.writeReverse=function(e){return QE(d.Buffer.isBuffer(e)),this.bufs.push(d.Buffer.from(e).reverse()),this.bufLen+=e.length,this};tt.prototype.writeUInt8=function(e){var t=d.Buffer.alloc(1);return t.writeUInt8(e,0),this.write(t),this};tt.prototype.writeUInt16BE=function(e){var t=d.Buffer.alloc(2);return t.writeUInt16BE(e,0),this.write(t),this};tt.prototype.writeUInt16LE=function(e){var t=d.Buffer.alloc(2);return t.writeUInt16LE(e,0),this.write(t),this};tt.prototype.writeUInt32BE=function(e){var t=d.Buffer.alloc(4);return t.writeUInt32BE(e,0),this.write(t),this};tt.prototype.writeInt32LE=function(e){var t=d.Buffer.alloc(4);return t.writeInt32LE(e,0),this.write(t),this};tt.prototype.writeUInt32LE=function(e){var t=d.Buffer.alloc(4);return t.writeUInt32LE(e,0),this.write(t),this};tt.prototype.writeUInt64BEBN=function(e){var t=e.toBuffer({size:8});return this.write(t),this};tt.prototype.writeUInt64LEBN=function(e){var t=e.toBuffer({size:8});return this.writeReverse(t),this};tt.prototype.writeVarintNum=function(e){var t=tt.varintBufNum(e);return this.write(t),this};tt.prototype.writeVarintBN=function(e){var t=tt.varintBufBN(e);return this.write(t),this};tt.varintBufNum=function(e){var t;return e<253?(t=d.Buffer.alloc(1),t.writeUInt8(e,0)):e<65536?(t=d.Buffer.alloc(3),t.writeUInt8(253,0),t.writeUInt16LE(e,1)):e<4294967296?(t=d.Buffer.alloc(5),t.writeUInt8(254,0),t.writeUInt32LE(e,1)):(t=d.Buffer.alloc(9),t.writeUInt8(255,0),t.writeInt32LE(e&-1,1),t.writeUInt32LE(Math.floor(e/4294967296),5)),t};tt.varintBufBN=function(e){var t,r=e.toNumber();if(r<253)t=d.Buffer.alloc(1),t.writeUInt8(r,0);else if(r<65536)t=d.Buffer.alloc(3),t.writeUInt8(253,0),t.writeUInt16LE(r,1);else if(r<4294967296)t=d.Buffer.alloc(5),t.writeUInt8(254,0),t.writeUInt32LE(r,1);else{var n=new tt;n.writeUInt8(255),n.writeUInt64LEBN(e),t=n.concat()}return t};e1.exports=tt});var sp=P((PF,t1)=>{"use strict";m();var is=Ve(),Na=ke(),l6=pr();function Pe(e){if(!(this instanceof Pe))return new Pe(e);var t;if(is.isNumber(e))t=e;else if(is.isString(e))t=Pe.map[e];else throw new TypeError('Unrecognized num type: "'+typeof e+'" for Opcode');return l6.defineImmutable(this,{num:t}),this}Pe.fromBuffer=function(e){return Na.checkArgument(d.Buffer.isBuffer(e)),new Pe(+("0x"+e.toString("hex")))};Pe.fromNumber=function(e){return Na.checkArgument(is.isNumber(e)),new Pe(e)};Pe.fromString=function(e){Na.checkArgument(is.isString(e));var t=Pe.map[e];if(typeof t>"u")throw new TypeError("Invalid opcodestr");return new Pe(t)};Pe.prototype.toHex=function(){return this.num.toString(16)};Pe.prototype.toBuffer=function(){return d.Buffer.from(this.toHex(),"hex")};Pe.prototype.toNumber=function(){return this.num};Pe.prototype.toString=function(){var e=Pe.reverseMap[this.num];if(typeof e>"u")throw new Error("Opcode does not have a string representation");return e};Pe.smallInt=function(e){return Na.checkArgument(is.isNumber(e),"Invalid Argument: n should be number"),Na.checkArgument(e>=0&&e<=16,"Invalid Argument: n must be between 0 and 16"),e===0?Pe("OP_0"):new Pe(Pe.map.OP_1+e-1)};Pe.map={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SPLIT:127,OP_NUM2BIN:128,OP_BIN2NUM:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_CHECKLOCKTIMEVERIFY:177,OP_CHECKSEQUENCEVERIFY:178,OP_NOP1:176,OP_NOP2:177,OP_NOP3:178,OP_SUBSTR:179,OP_LEFT:180,OP_RIGHT:181,OP_LSHIFTNUM:182,OP_RSHIFTNUM:183,OP_NOP9:184,OP_NOP10:185,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255};Pe.reverseMap=[];for(op in Pe.map)Pe.reverseMap[Pe.map[op]]=op;var op;is.extend(Pe,Pe.map);Pe.isSmallIntOp=function(e){return e instanceof Pe&&(e=e.toNumber()),e===Pe.map.OP_0||e>=Pe.map.OP_1&&e<=Pe.map.OP_16};Pe.prototype.inspect=function(){return"<Opcode: "+this.toString()+", hex: "+this.toHex()+", decimal: "+this.num+">"};t1.exports=Pe});var ir=P((NF,n1)=>{"use strict";m();var eo=Er(),h6=Ve(),nr=ke(),d6=pr(),Ie=function e(t,r){if(!(this instanceof e))return new e(t,r);if(t instanceof eo)this.set({r:t,s:r});else if(t){var n=t;this.set(n)}};Ie.prototype.set=function(e){return this.r=e.r||this.r||void 0,this.s=e.s||this.s||void 0,this.i=typeof e.i<"u"?e.i:this.i,this.compressed=typeof e.compressed<"u"?e.compressed:this.compressed,this.nhashtype=e.nhashtype||this.nhashtype||void 0,this};Ie.fromCompact=function(e){nr.checkArgument(d.Buffer.isBuffer(e),"Argument is expected to be a Buffer");var t=new Ie,r=!0,n=e.slice(0,1)[0]-27-4;n<0&&(r=!1,n=n+4);var i=e.slice(1,33),o=e.slice(33,65);return nr.checkArgument(n===0||n===1||n===2||n===3,new Error("i must be 0, 1, 2, or 3")),nr.checkArgument(i.length===32,new Error("r must be 32 bytes")),nr.checkArgument(o.length===32,new Error("s must be 32 bytes")),t.compressed=r,t.i=n,t.r=eo.fromBuffer(i),t.s=eo.fromBuffer(o),t};Ie.fromDER=Ie.fromBuffer=function(e,t){var r=Ie.parseDER(e,t),n=new Ie;return n.r=r.r,n.s=r.s,n};Ie.fromTxFormat=function(e){var t=e.readUInt8(e.length-1),r=e.slice(0,e.length-1),n=Ie.fromDER(r,!1);return n.nhashtype=t,n};Ie.fromString=function(e){var t=d.Buffer.from(e,"hex");return Ie.fromDER(t)};function r1(e,t){nr.checkArgument(t.length>0,new Error("Length of "+e+" is zero")),nr.checkArgument(!(t[0]&128),new Error("Value of "+e+" is negative")),nr.checkArgument(!(t.length>1&&t[0]===0&&!(t[1]&128)),new Error("Value of "+e+" is excessively padded"))}Ie.parseDER=function(e,t){nr.checkArgument(d.Buffer.isBuffer(e),new Error("DER formatted signature should be a buffer")),h6.isUndefined(t)&&(t=!0);var r=e[0];nr.checkArgument(r===48,new Error("Header byte should be 0x30"));var n=e[1],i=e.slice(2).length;nr.checkArgument(!t||n===i,new Error("Length byte should length of what follows")),n=n<i?n:i;var o=e[2];nr.checkArgument(o===2,new Error("Integer byte for r should be 0x02"));var s=e[3],a=e.slice(4,4+s),c=eo.fromBuffer(a),h=e[4]===0;nr.checkArgument(s===a.length,new Error("Length of r incorrect"));var g=e[4+s+0];nr.checkArgument(g===2,new Error("Integer byte for s should be 0x02"));var y=e[4+s+1],w=e.slice(4+s+2,4+s+2+y),I=eo.fromBuffer(w),T=e[4+s+2]===0;nr.checkArgument(y===w.length,new Error("Length of s incorrect"));var M=4+s+2+y;nr.checkArgument(n===M-2,new Error("Length of signature incorrect")),t&&(r1("r",a),r1("s",w));var L={header:r,length:n,rheader:o,rlength:s,rneg:h,rbuf:a,r:c,sheader:g,slength:y,sneg:T,sbuf:w,s:I};return L};Ie.prototype.toCompact=function(e,t){if(e=typeof e=="number"?e:this.i,t=typeof t=="boolean"?t:this.compressed,!(e===0||e===1||e===2||e===3))throw new Error("i must be equal to 0, 1, 2, or 3");var r=e+27+4;t===!1&&(r=r-4);var n=d.Buffer.from([r]),i=this.r.toBuffer({size:32}),o=this.s.toBuffer({size:32});return d.Buffer.concat([n,i,o])};Ie.prototype.toBuffer=Ie.prototype.toDER=function(){var e=this.r.toBuffer(),t=this.s.toBuffer(),r=!!(e[0]&128),n=!!(t[0]&128),i=r?d.Buffer.concat([d.Buffer.from([0]),e]):e,o=n?d.Buffer.concat([d.Buffer.from([0]),t]):t,s=i.length,a=o.length,c=2+s+2+a,h=2,g=2,y=48,w=d.Buffer.concat([d.Buffer.from([y,c,h,s]),i,d.Buffer.from([g,a]),o]);return w};Ie.prototype.toString=function(){var e=this.toDER();return e.toString("hex")};Ie.isTxDER=function(e){if(e.length<9||e.length>73||e[0]!==48||e[1]!==e.length-3)return!1;var t=e[3];if(5+t>=e.length)return!1;var r=e[5+t];if(t+r+7!==e.length)return!1;var n=e.slice(4);if(e[2]!==2||t===0||n[0]&128||t>1&&n[0]===0&&!(n[1]&128))return!1;var i=e.slice(6+t);return!(e[6+t-2]!==2||r===0||i[0]&128||r>1&&i[0]===0&&!(i[1]&128))};Ie.prototype.hasLowS=function(){return!(this.s.lt(new eo(1))||this.s.gt(new eo("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex")))};Ie.prototype.hasDefinedHashtype=function(){if(!d6.isNaturalNumber(this.nhashtype))return!1;var e=this.nhashtype&31;return!(e<Ie.SIGHASH_ALL||e>Ie.SIGHASH_SINGLE)};Ie.prototype.toTxFormat=function(){var e=this.toDER(),t=d.Buffer.alloc(1);return t.writeUInt8(this.nhashtype,0),d.Buffer.concat([e,t])};Ie.SIGHASH_ALL=1;Ie.SIGHASH_NONE=2;Ie.SIGHASH_SINGLE=3;Ie.SIGHASH_CHRONICLE=32;Ie.SIGHASH_FORKID=64;Ie.SIGHASH_ANYONECANPAY=128;Ie.prototype.isCanonical=function(){var e=ii(),t=e.getN().shrn(1);return this.s.lte(t)};Ie.prototype.toCanonical=function(){if(this.isCanonical())return new Ie({r:this.r,s:this.s,i:this.i,compressed:this.compressed,nhashtype:this.nhashtype});var e=ii(),t=e.getN(),r=t.sub(this.s);return new Ie({r:this.r,s:r,i:this.i,compressed:this.compressed,nhashtype:this.nhashtype})};Ie.prototype.validate=function(){if(!this.r||!this.s)throw new Error("Signature missing r or s component");if(this.r.isZero())throw new Error("Signature r component is zero");if(this.s.isZero())throw new Error("Signature s component is zero");var e=ii(),t=e.getN();if(this.r.gte(t))throw new Error("Signature r component >= curve order");if(this.s.gte(t))throw new Error("Signature s component >= curve order");if(this.r.isNeg())throw new Error("Signature r component is negative");if(this.s.isNeg())throw new Error("Signature s component is negative");return!0};Ie.prototype.isValid=function(){try{return this.validate(),!0}catch{return!1}};Ie.prototype.applySecurityPatches=function(){var e=ii(),t=e.getN(),r=t.shrn(1);if(this.r.isZero()||this.s.isZero())throw new Error("Invalid signature: zero r or s");if(this.r.gte(t)||this.s.gte(t))throw new Error("Invalid signature: out of range");if(this.s.gt(r))throw new Error("Invalid signature: non-canonical (high) s");return this};n1.exports=Ie});var fp=P((kF,s1)=>{"use strict";m();var Hr=no(),p6=va(),g6=Qi(),ap=Qt(),X=sp(),ro=Tr(),to=ir(),i1=ga(),$e=ke(),Ae=Ve(),up=Jn(),o1=Tt(),y6=pr(),D=function e(t){if(!(this instanceof e))return new e(t);if(this.chunks=[],d.Buffer.isBuffer(t))return e.fromBuffer(t);if(t instanceof Hr)return e.fromAddress(t);if(t instanceof e)return e.fromBuffer(t.toBuffer());if(Ae.isString(t))return e.fromString(t);Ae.isObject(t)&&Ae.isArray(t.chunks)&&this.set(t)};D.prototype.set=function(e){return $e.checkArgument(Ae.isObject(e)),$e.checkArgument(Ae.isArray(e.chunks)),this.chunks=e.chunks,this};D.fromBuffer=function(e){var t=new D;t.chunks=[];for(var r=new p6(e);!r.finished();)try{var n=r.readUInt8(),i,o;n>0&&n<X.OP_PUSHDATA1?(i=n,t.chunks.push({buf:r.read(i),len:i,opcodenum:n})):n===X.OP_PUSHDATA1?(i=r.readUInt8(),o=r.read(i),t.chunks.push({buf:o,len:i,opcodenum:n})):n===X.OP_PUSHDATA2?(i=r.readUInt16LE(),o=r.read(i),t.chunks.push({buf:o,len:i,opcodenum:n})):n===X.OP_PUSHDATA4?(i=r.readUInt32LE(),o=r.read(i),t.chunks.push({buf:o,len:i,opcodenum:n})):t.chunks.push({opcodenum:n})}catch(s){throw s instanceof RangeError?new up.Script.InvalidBuffer(e.toString("hex")):s}return t};D.prototype.toBuffer=function(){for(var e=new g6,t=0;t<this.chunks.length;t++){var r=this.chunks[t],n=r.opcodenum;e.writeUInt8(r.opcodenum),r.buf&&(n<X.OP_PUSHDATA1?e.write(r.buf):n===X.OP_PUSHDATA1?(e.writeUInt8(r.len),e.write(r.buf)):n===X.OP_PUSHDATA2?(e.writeUInt16LE(r.len),e.write(r.buf)):n===X.OP_PUSHDATA4&&(e.writeUInt32LE(r.len),e.write(r.buf)))}return e.concat()};D.fromASM=function(e){var t=new D;t.chunks=[];for(var r=e.split(" "),n=0;n<r.length;){var i=r[n],o=X(i),s=o.toNumber();if(i==="0")s=0,t.chunks.push({opcodenum:s}),n=n+1;else if(i==="-1")s=X.OP_1NEGATE,t.chunks.push({opcodenum:s}),n=n+1;else if(Ae.isUndefined(s)){var a=d.Buffer.from(r[n],"hex");if(a.toString("hex")!==r[n])throw new Error("invalid hex string in script");var c=a.length;c>=0&&c<X.OP_PUSHDATA1?s=c:c<Math.pow(2,8)?s=X.OP_PUSHDATA1:c<Math.pow(2,16)?s=X.OP_PUSHDATA2:c<Math.pow(2,32)&&(s=X.OP_PUSHDATA4),t.chunks.push({buf:a,len:a.length,opcodenum:s}),n=n+1}else t.chunks.push({opcodenum:s}),n=n+1}return t};D.fromHex=function(e){return new D(o1.Buffer.from(e,"hex"))};D.fromString=function(e){if(y6.isHexa(e)||e.length===0)return new D(o1.Buffer.from(e,"hex"));var t=new D;t.chunks=[];for(var r=e.split(" "),n=0;n<r.length;){var i=r[n],o=X(i),s=o.toNumber();if(Ae.isUndefined(s))if(s=parseInt(i),s>0&&s<X.OP_PUSHDATA1)t.chunks.push({buf:d.Buffer.from(r[n+1].slice(2),"hex"),len:s,opcodenum:s}),n=n+2;else throw new Error("Invalid script: "+JSON.stringify(e));else if(s===X.OP_PUSHDATA1||s===X.OP_PUSHDATA2||s===X.OP_PUSHDATA4){if(r[n+2].slice(0,2)!=="0x")throw new Error("Pushdata data must start with 0x");t.chunks.push({buf:d.Buffer.from(r[n+2].slice(2),"hex"),len:parseInt(r[n+1]),opcodenum:s}),n=n+3}else t.chunks.push({opcodenum:s}),n=n+1}return t};D.prototype._chunkToString=function(e,t){var r=e.opcodenum,n=t==="asm",i="";if(e.buf)!n&&(r===X.OP_PUSHDATA1||r===X.OP_PUSHDATA2||r===X.OP_PUSHDATA4)&&(i=i+" "+X(r).toString()),e.len>0&&(n?i=i+" "+e.buf.toString("hex"):i=i+" "+e.len+" 0x"+e.buf.toString("hex"));else if(typeof X.reverseMap[r]<"u")n?r===0?i=i+" 0":r===79?i=i+" -1":i=i+" "+X(r).toString():i=i+" "+X(r).toString();else{var o=r.toString(16);o.length%2!==0&&(o="0"+o),n?i=i+" "+o:i=i+" 0x"+o}return i};D.prototype.toASM=function(){for(var e="",t=0;t<this.chunks.length;t++){var r=this.chunks[t];e+=this._chunkToString(r,"asm")}return e.substr(1)};D.prototype.toString=function(){for(var e="",t=0;t<this.chunks.length;t++){var r=this.chunks[t];e+=this._chunkToString(r)}return e.substr(1)};D.prototype.toHex=function(){return this.toBuffer().toString("hex")};D.prototype.inspect=function(){return"<Script: "+this.toString()+">"};D.prototype.isPublicKeyHashOut=function(){return!!(this.chunks.length===5&&this.chunks[0].opcodenum===X.OP_DUP&&this.chunks[1].opcodenum===X.OP_HASH160&&this.chunks[2].buf&&this.chunks[2].buf.length===20&&this.chunks[3].opcodenum===X.OP_EQUALVERIFY&&this.chunks[4].opcodenum===X.OP_CHECKSIG)};D.prototype.isPublicKeyHashOutPrefix=function(){return!!(this.chunks.length>=5&&this.chunks[0].opcodenum===X.OP_DUP&&this.chunks[1].opcodenum===X.OP_HASH160&&this.chunks[2].buf&&this.chunks[2].buf.length===20&&this.chunks[3].opcodenum===X.OP_EQUALVERIFY&&this.chunks[4].opcodenum===X.OP_CHECKSIG)};D.prototype.isPublicKeyHashIn=function(){if(this.chunks.length===2){var e=this.chunks[0].buf,t=this.chunks[1].buf;if(e&&e.length&&e[0]===48&&t&&t.length){var r=t[0];if((r===4||r===6||r===7)&&t.length===65)return!0;if((r===3||r===2)&&t.length===33)return!0}}return!1};D.prototype.getPublicKey=function(){return $e.checkState(this.isPublicKeyOut(),"Can't retrieve PublicKey from a non-PK output"),this.chunks[0].buf};D.prototype.getPublicKeyHash=function(){return $e.checkState(this.isPublicKeyHashOut(),"Can't retrieve PublicKeyHash from a non-PKH output"),this.chunks[2].buf};D.prototype.isPublicKeyOut=function(){if(this.chunks.length===2&&this.chunks[0].buf&&this.chunks[0].buf.length&&this.chunks[1].opcodenum===X.OP_CHECKSIG){var e=this.chunks[0].buf,t=e[0],r=!1;if(((t===4||t===6||t===7)&&e.length===65||(t===3||t===2)&&e.length===33)&&(r=!0),r)return ro.isValid(e)}return!1};D.prototype.isPublicKeyIn=function(){if(this.chunks.length===1){var e=this.chunks[0].buf;if(e&&e.length&&e[0]===48)return!0}return!1};D.prototype.isScriptHashOut=function(){var e=this.toBuffer();return e.length===23&&e[0]===X.OP_HASH160&&e[1]===20&&e[e.length-1]===X.OP_EQUAL};D.prototype.isScriptHashIn=function(){if(this.chunks.length<=1)return!1;var e=this.chunks[this.chunks.length-1],t=e.buf;if(!t)return!1;var r;try{r=D.fromBuffer(t)}catch(i){if(i instanceof up.Script.InvalidBuffer)return!1;throw i}var n=r.classify();return n!==D.types.UNKNOWN};D.prototype.isMultisigOut=function(){return this.chunks.length>3&&X.isSmallIntOp(this.chunks[0].opcodenum)&&this.chunks.slice(1,this.chunks.length-2).every(function(e){return e.buf&&d.Buffer.isBuffer(e.buf)})&&X.isSmallIntOp(this.chunks[this.chunks.length-2].opcodenum)&&this.chunks[this.chunks.length-1].opcodenum===X.OP_CHECKMULTISIG};D.prototype.isMultisigIn=function(){return this.chunks.length>=2&&this.chunks[0].opcodenum===0&&this.chunks.slice(1,this.chunks.length).every(function(e){return e.buf&&d.Buffer.isBuffer(e.buf)&&to.isTxDER(e.buf)})};D.prototype.isDataOut=function(){var e=this.chunks.length>=1&&this.chunks[0].opcodenum===X.OP_RETURN;if(!e)return!1;var t=this.chunks.slice(1),r=new D({chunks:t});return r.isPushOnly()};D.prototype.isSafeDataOut=function(){if(this.chunks.length<2||this.chunks[0].opcodenum!==X.OP_FALSE)return!1;var e=this.chunks.slice(1),t=new D({chunks:e});return t.isDataOut()};D.prototype.getData=function(){if(this.isSafeDataOut()){var e=this.chunks.slice(2),t=e.map(r=>r.buf);return t}if(this.isDataOut()||this.isScriptHashOut())return Ae.isUndefined(this.chunks[1])?d.Buffer.alloc(0):d.Buffer.from(this.chunks[1].buf);if(this.isPublicKeyHashOut())return d.Buffer.from(this.chunks[2].buf);throw new Error("Unrecognized script type to get data from")};D.prototype.isPushOnly=function(){return Ae.every(this.chunks,function(e){return e.opcodenum<=X.OP_16||e.opcodenum===X.OP_PUSHDATA1||e.opcodenum===X.OP_PUSHDATA2||e.opcodenum===X.OP_PUSHDATA4})};D.types={};D.types.UNKNOWN="Unknown";D.types.PUBKEY_OUT="Pay to public key";D.types.PUBKEY_IN="Spend from public key";D.types.PUBKEYHASH_OUT="Pay to public key hash";D.types.PUBKEYHASH_IN="Spend from public key hash";D.types.SCRIPTHASH_OUT="Pay to script hash";D.types.SCRIPTHASH_IN="Spend from script hash";D.types.MULTISIG_OUT="Pay to multisig";D.types.MULTISIG_IN="Spend from multisig";D.types.DATA_OUT="Data push";D.types.SAFE_DATA_OUT="Safe data push";D.OP_RETURN_STANDARD_SIZE=220;D.prototype.classify=function(){if(this._isInput)return this.classifyInput();if(this._isOutput)return this.classifyOutput();var e=this.classifyOutput();return e!==D.types.UNKNOWN?e:this.classifyInput()};D.outputIdentifiers={};D.outputIdentifiers.PUBKEY_OUT=D.prototype.isPublicKeyOut;D.outputIdentifiers.PUBKEYHASH_OUT=D.prototype.isPublicKeyHashOut;D.outputIdentifiers.MULTISIG_OUT=D.prototype.isMultisigOut;D.outputIdentifiers.SCRIPTHASH_OUT=D.prototype.isScriptHashOut;D.outputIdentifiers.DATA_OUT=D.prototype.isDataOut;D.outputIdentifiers.SAFE_DATA_OUT=D.prototype.isSafeDataOut;D.prototype.classifyOutput=function(){for(var e in D.outputIdentifiers)if(D.outputIdentifiers[e].bind(this)())return D.types[e];return D.types.UNKNOWN};D.inputIdentifiers={};D.inputIdentifiers.PUBKEY_IN=D.prototype.isPublicKeyIn;D.inputIdentifiers.PUBKEYHASH_IN=D.prototype.isPublicKeyHashIn;D.inputIdentifiers.MULTISIG_IN=D.prototype.isMultisigIn;D.inputIdentifiers.SCRIPTHASH_IN=D.prototype.isScriptHashIn;D.prototype.classifyInput=function(){for(var e in D.inputIdentifiers)if(D.inputIdentifiers[e].bind(this)())return D.types[e];return D.types.UNKNOWN};D.prototype.isStandard=function(){return this.classify()!==D.types.UNKNOWN};D.prototype.prepend=function(e){return this._addByType(e,!0),this};D.prototype.equals=function(e){if($e.checkState(e instanceof D,"Must provide another script"),this.chunks.length!==e.chunks.length)return!1;var t;for(t=0;t<this.chunks.length;t++){if(d.Buffer.isBuffer(this.chunks[t].buf)&&!d.Buffer.isBuffer(e.chunks[t].buf)||d.Buffer.isBuffer(this.chunks[t].buf)&&!this.chunks[t].buf.equals(e.chunks[t].buf))return!1;if(this.chunks[t].opcodenum!==e.chunks[t].opcodenum)return!1}return!0};D.prototype.add=function(e){return this._addByType(e,!1),this};D.prototype._addByType=function(e,t){if(typeof e=="string")this._addOpcode(e,t);else if(typeof e=="number")this._addOpcode(e,t);else if(e instanceof X)this._addOpcode(e,t);else if(d.Buffer.isBuffer(e))this._addBuffer(e,t);else if(e instanceof D)this.chunks=this.chunks.concat(e.chunks);else if(typeof e=="object")this._insertAtPosition(e,t);else throw new Error("Invalid script chunk")};D.prototype._insertAtPosition=function(e,t){t?this.chunks.unshift(e):this.chunks.push(e)};D.prototype._addOpcode=function(e,t){var r;return typeof e=="number"?r=e:e instanceof X?r=e.toNumber():r=X(e).toNumber(),this._insertAtPosition({opcodenum:r},t),this};D.prototype._addBuffer=function(e,t){var r,n=e.length;if(n>=0&&n<X.OP_PUSHDATA1)r=n;else if(n<Math.pow(2,8))r=X.OP_PUSHDATA1;else if(n<Math.pow(2,16))r=X.OP_PUSHDATA2;else if(n<Math.pow(2,32))r=X.OP_PUSHDATA4;else throw new Error("You can't push that much data");return this._insertAtPosition({buf:e,len:n,opcodenum:r},t),this};D.prototype.removeCodeseparators=function(){for(var e=[],t=0;t<this.chunks.length;t++)this.chunks[t].opcodenum!==X.OP_CODESEPARATOR&&e.push(this.chunks[t]);return this.chunks=e,this};D.buildMultisigOut=function(e,t,r){$e.checkArgument(t<=e.length,"Number of required signatures must be less than or equal to the number of public keys"),r=r||{};var n=new D;n.add(X.smallInt(t)),e=Ae.map(e,ro);var i=e;r.noSorting||(i=e.map(a=>a.toString("hex")).sort().map(a=>new ro(a)));for(var o=0;o<i.length;o++){var s=i[o];n.add(s.toBuffer())}return n.add(X.smallInt(e.length)),n.add(X.OP_CHECKMULTISIG),n};D.buildMultisigIn=function(e,t,r,n){$e.checkArgument(Ae.isArray(e)),$e.checkArgument(Ae.isNumber(t)),$e.checkArgument(Ae.isArray(r)),n=n||{};var i=new D;return i.add(X.OP_0),Ae.each(r,function(o){$e.checkArgument(d.Buffer.isBuffer(o),"Signatures must be an array of Buffers"),i.add(o)}),i};D.buildP2SHMultisigIn=function(e,t,r,n){$e.checkArgument(Ae.isArray(e)),$e.checkArgument(Ae.isNumber(t)),$e.checkArgument(Ae.isArray(r)),n=n||{};var i=new D;return i.add(X.OP_0),Ae.each(r,function(o){$e.checkArgument(d.Buffer.isBuffer(o),"Signatures must be an array of Buffers"),i.add(o)}),i.add((n.cachedMultisig||D.buildMultisigOut(e,t,n)).toBuffer()),i};D.buildPublicKeyHashOut=function(e){$e.checkArgument(!Ae.isUndefined(e)),$e.checkArgument(e instanceof ro||e instanceof Hr||Ae.isString(e)),e instanceof ro?e=e.toAddress():Ae.isString(e)&&(e=new Hr(e));var t=new D;return t.add(X.OP_DUP).add(X.OP_HASH160).add(e.hashBuffer).add(X.OP_EQUALVERIFY).add(X.OP_CHECKSIG),t._network=e.network,t};D.buildPublicKeyOut=function(e){$e.checkArgument(e instanceof ro);var t=new D;return t.add(e.toBuffer()).add(X.OP_CHECKSIG),t};D.buildDataOut=function(e,t){$e.checkArgument(Ae.isUndefined(e)||Ae.isString(e)||Ae.isArray(e)||d.Buffer.isBuffer(e));var r=e;Ae.isArray(r)||(r=[e]);var n=new D;n.add(X.OP_RETURN);for(let i of r)$e.checkArgument(Ae.isUndefined(i)||Ae.isString(i)||d.Buffer.isBuffer(i)),Ae.isString(i)&&(i=d.Buffer.from(i,t)),Ae.isUndefined(i)||n.add(i);return n};D.buildSafeDataOut=function(e,t){var r=D.buildDataOut(e,t),n=new D;return n.add(X.OP_FALSE),n.add(r),n};D.buildScriptHashOut=function(e){$e.checkArgument(e instanceof D||e instanceof Hr&&e.isPayToScriptHash());var t=new D;return t.add(X.OP_HASH160).add(e instanceof Hr?e.hashBuffer:ap.sha256ripemd160(e.toBuffer())).add(X.OP_EQUAL),t._network=e._network||e.network,t};D.buildPublicKeyIn=function(e,t){$e.checkArgument(e instanceof to||d.Buffer.isBuffer(e)),$e.checkArgument(Ae.isUndefined(t)||Ae.isNumber(t)),e instanceof to&&(e=e.toBuffer());var r=new D;return r.add(d.Buffer.concat([e,d.Buffer.from([(t||to.SIGHASH_ALL)&255])])),r};D.buildPublicKeyHashIn=function(e,t,r){$e.checkArgument(t instanceof to||d.Buffer.isBuffer(t)),$e.checkArgument(Ae.isUndefined(r)||Ae.isNumber(r)),t instanceof to&&(t=t.toBuffer());var n=new D().add(d.Buffer.concat([t,d.Buffer.from([(r||to.SIGHASH_ALL)&255])])).add(new ro(e).toBuffer());return n};D.empty=function(){return new D};D.prototype.toScriptHashOut=function(){return D.buildScriptHashOut(this)};D.fromAddress=function(e){if(e=Hr(e),e.isPayToScriptHash())return D.buildScriptHashOut(e);if(e.isPayToPublicKeyHash())return D.buildPublicKeyHashOut(e);throw new up.Script.UnrecognizedAddress(e)};D.prototype.getAddressInfo=function(e){if(this._isInput)return this._getInputAddressInfo();if(this._isOutput)return this._getOutputAddressInfo();var t=this._getOutputAddressInfo();return t||this._getInputAddressInfo()};D.prototype._getOutputAddressInfo=function(){var e={};if(this.isScriptHashOut())e.hashBuffer=this.getData(),e.type=Hr.PayToScriptHash;else if(this.isPublicKeyHashOut())e.hashBuffer=this.getData(),e.type=Hr.PayToPublicKeyHash;else return!1;return e};D.prototype._getInputAddressInfo=function(){var e={};if(this.isPublicKeyHashIn())e.hashBuffer=ap.sha256ripemd160(this.chunks[1].buf),e.type=Hr.PayToPublicKeyHash;else if(this.isScriptHashIn())e.hashBuffer=ap.sha256ripemd160(this.chunks[this.chunks.length-1].buf),e.type=Hr.PayToScriptHash;else return!1;return e};D.prototype.toAddress=function(e){var t=this.getAddressInfo();return t?(t.network=i1.get(e)||this._network||i1.defaultNetwork,new Hr(t)):!1};D.prototype.findAndDelete=function(e){for(var t=e.toBuffer(),r=t.toString("hex"),n=0;n<this.chunks.length;n++){var i=D({chunks:[this.chunks[n]]}),o=i.toBuffer(),s=o.toString("hex");r===s&&this.chunks.splice(n,1)}return this};D.prototype.checkMinimalPush=function(e){var t=this.chunks[e],r=t.buf,n=t.opcodenum;return r?r.length===0?n===X.OP_0:r.length===1&&r[0]>=1&&r[0]<=16?n===X.OP_1+(r[0]-1):r.length===1&&r[0]===129?n===X.OP_1NEGATE:r.length<=75?n===r.length:r.length<=255?n===X.OP_PUSHDATA1:r.length<=65535?n===X.OP_PUSHDATA2:!0:!0};D.prototype._decodeOP_N=function(e){if(e===X.OP_0)return 0;if(e>=X.OP_1&&e<=X.OP_16)return e-(X.OP_1-1);throw new Error("Invalid opcode: "+JSON.stringify(e))};D.prototype.getSignatureOperationsCount=function(e){e=Ae.isUndefined(e)?!0:e;var t=this,r=0,n=X.OP_INVALIDOPCODE;return Ae.each(t.chunks,function(o){var s=o.opcodenum;s===X.OP_CHECKSIG||s===X.OP_CHECKSIGVERIFY?r++:(s===X.OP_CHECKMULTISIG||s===X.OP_CHECKMULTISIGVERIFY)&&(e&&n>=X.OP_1&&n<=X.OP_16?r+=t._decodeOP_N(n):r+=20),n=s}),r};s1.exports=D});var Ma=P((LF,f1)=>{"use strict";m();var a1=Qi(),u1=va(),m6=Er(),jr=function e(t){if(!(this instanceof e))return new e(t);if(d.Buffer.isBuffer(t))this.buf=t;else if(typeof t=="number"){var r=t;this.fromNumber(r)}else if(t instanceof m6){var n=t;this.fromBN(n)}else if(t){var i=t;this.set(i)}};jr.prototype.set=function(e){return this.buf=e.buf||this.buf,this};jr.prototype.fromString=function(e){return this.set({buf:d.Buffer.from(e,"hex")}),this};jr.prototype.toString=function(){return this.buf.toString("hex")};jr.prototype.fromBuffer=function(e){return this.buf=e,this};jr.prototype.fromBufferReader=function(e){return this.buf=e.readVarintBuf(),this};jr.prototype.fromBN=function(e){return this.buf=a1().writeVarintBN(e).concat(),this};jr.prototype.fromNumber=function(e){return this.buf=a1().writeVarintNum(e).concat(),this};jr.prototype.toBuffer=function(){return this.buf};jr.prototype.toBN=function(){return u1(this.buf).readVarintBN()};jr.prototype.toNumber=function(){return u1(this.buf).readVarintNum()};f1.exports=jr});var Dn=P((UF,l1)=>{"use strict";m();var Ec=Ve(),cp=Er(),c1=Tt(),xc=pr(),v6=Qi(),b6=Ma(),lp=Kr(),hp=ke(),_6=Jn(),S6=9007199254740991;function Ut(e){if(!(this instanceof Ut))return new Ut(e);if(Ec.isObject(e))if(this.satoshis=e.satoshis,d.Buffer.isBuffer(e.script))this._scriptBuffer=e.script;else{var t;Ec.isString(e.script)&&xc.isHexa(e.script)?t=c1.Buffer.from(e.script,"hex"):t=e.script,this.setScript(t)}else throw new TypeError("Unrecognized argument for Output")}Object.defineProperty(Ut.prototype,"script",{configurable:!1,enumerable:!0,get:function(){return this._script?this._script:(this.setScriptFromBuffer(this._scriptBuffer),this._script)}});Object.defineProperty(Ut.prototype,"satoshis",{configurable:!1,enumerable:!0,get:function(){return this._satoshis},set:function(e){e instanceof cp?(this._satoshisBN=e,this._satoshis=e.toNumber()):Ec.isString(e)?(this._satoshis=parseInt(e),this._satoshisBN=cp.fromNumber(this._satoshis)):(hp.checkArgument(xc.isNaturalNumber(e),"Output satoshis is not a natural number"),this._satoshisBN=cp.fromNumber(e),this._satoshis=e),hp.checkState(xc.isNaturalNumber(this._satoshis),"Output satoshis is not a natural number")}});Ut.prototype.invalidSatoshis=function(){return this._satoshis>S6?"transaction txout satoshis greater than max safe integer":this._satoshis!==this._satoshisBN.toNumber()?"transaction txout satoshis has corrupted value":this._satoshis<0?"transaction txout negative":!1};Object.defineProperty(Ut.prototype,"satoshisBN",{configurable:!1,enumerable:!0,get:function(){return this._satoshisBN},set:function(e){this._satoshisBN=e,this._satoshis=e.toNumber(),hp.checkState(xc.isNaturalNumber(this._satoshis),"Output satoshis is not a natural number")}});Ut.prototype.toObject=Ut.prototype.toJSON=function(){var t={satoshis:this.satoshis};return t.script=this._scriptBuffer.toString("hex"),t};Ut.fromObject=function(e){return new Ut(e)};Ut.prototype.setScriptFromBuffer=function(e){this._scriptBuffer=e;try{this._script=lp.fromBuffer(this._scriptBuffer),this._script._isOutput=!0}catch(t){if(t instanceof _6.Script.InvalidBuffer)this._script=null;else throw t}};Ut.prototype.setScript=function(e){if(e instanceof lp)this._scriptBuffer=e.toBuffer(),this._script=e,this._script._isOutput=!0;else if(Ec.isString(e))this._script=lp.fromString(e),this._scriptBuffer=this._script.toBuffer(),this._script._isOutput=!0;else if(d.Buffer.isBuffer(e))this.setScriptFromBuffer(e);else throw new TypeError("Invalid argument type: script");return this};Ut.prototype.inspect=function(){var e;return this.script?e=this.script.inspect():e=this._scriptBuffer.toString("hex"),"<Output ("+this.satoshis+" sats) "+e+">"};Ut.fromBufferReader=function(e){var t={};t.satoshis=e.readUInt64LEBN();var r=e.readVarintNum();return r!==0?t.script=e.read(r):t.script=c1.Buffer.from([]),new Ut(t)};Ut.prototype.toBufferWriter=function(e){e||(e=new v6),e.writeUInt64LEBN(this._satoshisBN);var t=this._scriptBuffer;return e.writeVarintNum(t.length),e.write(t),e};Ut.prototype.getSize=function(){var e=this.script.toBuffer().length,t=b6(e).toBuffer().length;return 8+t+e};l1.exports=Ut});var ka=P((qF,h1)=>{"use strict";m();var gr=Er(),cn=ii(),w6=ir(),E6=Tr(),x6=ea(),hi=Qt(),I6=Ve(),dp=ke(),qe=function e(t){if(!(this instanceof e))return new e(t);t&&this.set(t)};Object.defineProperty(qe.prototype,"k",{get:function(){return this._k},set:function(e){this._k=e,this._kFresh=!0},enumerable:!0,configurable:!0});qe.prototype.set=function(e){if(this.hashbuf=e.hashbuf||this.hashbuf,this.endian=e.endian||this.endian,this.privkey=e.privkey||this.privkey,this.pubkey=e.pubkey||(this.privkey?this.privkey.publicKey:this.pubkey),e.sig)if(d.Buffer.isBuffer(e.sig)){var t=ir();this.sig=t.fromDER(e.sig)}else this.sig=e.sig;else this.sig=this.sig;return e.k&&(this.k=e.k),this.verified=e.verified||this.verified,this};qe.prototype.privkey2pubkey=function(){this.pubkey=this.privkey.toPublicKey()};qe.prototype.calci=function(){for(var e=0;e<4;e++){this.sig.i=e;var t;try{t=this.toPublicKey()}catch(r){console.error(r);continue}if(t.point.eq(this.pubkey.point))return this.sig.compressed=this.pubkey.compressed,this}throw this.sig.i=void 0,new Error("Unable to find valid recovery factor")};qe.fromString=function(e){var t=JSON.parse(e);return new qe(t)};qe.prototype.randomK=function(){var e=cn.getN(),t;do t=gr.fromBuffer(x6.getRandomBuffer(32));while(!(t.lt(e)&&t.gt(gr.Zero)));return this.k=t,this};qe.prototype.deterministicK=function(e){I6.isUndefined(e)&&(e=0);var t=d.Buffer.alloc(32);t.fill(1);var r=d.Buffer.alloc(32);r.fill(0);var n=this.privkey.bn.toBuffer({size:32}),i=this.endian==="little"?d.Buffer.from(this.hashbuf).reverse():this.hashbuf;r=hi.sha256hmac(d.Buffer.concat([t,d.Buffer.from([0]),n,i]),r),t=hi.sha256hmac(t,r),r=hi.sha256hmac(d.Buffer.concat([t,d.Buffer.from([1]),n,i]),r),t=hi.sha256hmac(t,r),t=hi.sha256hmac(t,r);for(var o=gr.fromBuffer(t),s=cn.getN(),a=0;a<e||!(o.lt(s)&&o.gt(gr.Zero));a++)r=hi.sha256hmac(d.Buffer.concat([t,d.Buffer.from([0])]),r),t=hi.sha256hmac(t,r),t=hi.sha256hmac(t,r),o=gr.fromBuffer(t);return this.k=o,this};qe.prototype.toPublicKey=function(){var e=this.sig.i;dp.checkArgument(e===0||e===1||e===2||e===3,new Error("i must be equal to 0, 1, 2, or 3"));var t=gr.fromBuffer(this.hashbuf),r=this.sig.r,n=this.sig.s,i=e&1,o=e>>1,s=cn.getN(),a=cn.getG(),c=o?r.add(s):r,h=cn.fromX(i,c),g=h.mul(s);if(!g.isInfinity())throw new Error("nR is not a valid curve point");var y=t.neg().umod(s),w=r.invm(s),I=h.mul(n).add(a.mul(y)).mul(w),T=E6.fromPoint(I,this.sig.compressed);return T};qe.prototype.sigError=function(){if(!d.Buffer.isBuffer(this.hashbuf)||this.hashbuf.length!==32)return"hashbuf must be a 32 byte buffer";var e=this.sig.r,t=this.sig.s,r=cn.getN();try{if(e.lte(gr.Zero)||t.lte(gr.Zero)||e.gte(r)||t.gte(r))return"r and s not in range";var n=gr.fromBuffer(this.hashbuf,this.endian?{endian:this.endian}:void 0),i=t.invm(r),o=i.mul(n).umod(r),s=i.mul(e).umod(r),a=cn.getG().mulAdd(o,this.pubkey.point,s);return a.isInfinity()?"p is infinity":a.getX().umod(r).cmp(e)!==0?"Invalid signature":!1}catch(c){return"Signature security validation failed: "+c.message}};qe.toLowS=function(e){return e.gt(gr.fromBuffer(d.Buffer.from("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex")))&&(e=cn.getN().sub(e)),e};qe.prototype._findSignature=function(e,t){var r=cn.getN(),n=cn.getG(),i=0,o,s,a,c;do(!this.k||!this._kFresh||i>0)&&this.deterministicK(i),i++,o=this.k,s=n.mul(o),a=s.x.umod(r),c=o.invm(r).mul(t.add(e.mul(a))).umod(r);while(a.cmp(gr.Zero)<=0||c.cmp(gr.Zero)<=0);return this._kFresh=!1,c=qe.toLowS(c),{s:c,r:a}};qe.prototype.sign=function(){var e=this.hashbuf,t=this.privkey,r=t.bn;dp.checkState(e&&t&&r,new Error("invalid parameters")),dp.checkState(d.Buffer.isBuffer(e)&&e.length===32,new Error("hashbuf must be a 32 byte buffer"));var n=gr.fromBuffer(e,this.endian?{endian:this.endian}:void 0),i=this._findSignature(r,n);return i.compressed=this.pubkey.compressed,this.sig=new w6(i),this};qe.prototype.signRandomK=function(){return this.randomK(),this.sign()};qe.prototype.toString=function(){var e={};return this.hashbuf&&(e.hashbuf=this.hashbuf.toString("hex")),this.privkey&&(e.privkey=this.privkey.toString()),this.pubkey&&(e.pubkey=this.pubkey.toString()),this.sig&&(e.sig=this.sig.toString()),this.k&&(e.k=this.k.toString()),JSON.stringify(e)};qe.prototype.verify=function(){return this.verified=!this.sigError(),this.verified};qe.prototype.verifyBool=function(){return this.verify()===!0};qe.sign=function(e,t,r){return qe().set({hashbuf:e,endian:r,privkey:t}).sign().sig};qe.signWithCalcI=function(e,t,r){return qe().set({hashbuf:e,endian:r,privkey:t}).sign().calci().sig};qe.signRandomK=function(e,t,r){return qe().set({hashbuf:e,endian:r,privkey:t}).signRandomK().sig};qe.verify=function(e,t,r,n){return qe().set({hashbuf:e,endian:n,sig:t,pubkey:r}).verify()};h1.exports=qe});var os=P((jF,y1)=>{"use strict";m();var di=Ve(),A6=ke(),Ca=Jn(),O6=Qi(),pp=Tt(),p1=pr(),Ic=Kr(),R6=pi(),d1=Dn(),Ac=4294967295,T6=Ac-2,g1=Ac,P6=Ac-1;function He(e){if(!(this instanceof He))return new He(e);if(e)return this._fromObject(e)}He.MAXINT=Ac;He.DEFAULT_SEQNUMBER=g1;He.DEFAULT_LOCKTIME_SEQNUMBER=P6;He.DEFAULT_RBF_SEQNUMBER=T6;He.BASE_SIZE=40;Object.defineProperty(He.prototype,"script",{configurable:!1,enumerable:!0,get:function(){return this.isNull()?null:(this._script||(this._script=new Ic(this._scriptBuffer),this._script._isInput=!0),this._script)}});He.fromObject=function(e){A6.checkArgument(di.isObject(e));var t=new He;return t._fromObject(e)};He.prototype._fromObject=function(e){var t;if(di.isString(e.prevTxId)&&p1.isHexa(e.prevTxId)?t=pp.Buffer.from(e.prevTxId,"hex"):t=e.prevTxId,this.output=e.output?e.output instanceof d1?e.output:new d1(e.output):void 0,this.prevTxId=t||e.txidbuf,this.outputIndex=di.isUndefined(e.outputIndex)?e.txoutnum:e.outputIndex,this.sequenceNumber=di.isUndefined(e.sequenceNumber)?di.isUndefined(e.seqnum)?g1:e.seqnum:e.sequenceNumber,di.isUndefined(e.script)&&di.isUndefined(e.scriptBuffer))throw new Ca.Transaction.Input.MissingScript;return this.setScript(e.scriptBuffer||e.script),this};He.prototype.toObject=He.prototype.toJSON=function(){var t={prevTxId:this.prevTxId.toString("hex"),outputIndex:this.outputIndex,sequenceNumber:this.sequenceNumber,script:this._scriptBuffer.toString("hex")};return this.script&&(t.scriptString=this.script.toString()),this.output&&(t.output=this.output.toObject()),t};He.fromBufferReader=function(e){var t=new He;return t.prevTxId=e.readReverse(32),t.outputIndex=e.readUInt32LE(),t._scriptBuffer=e.readVarLengthBuffer(),t.sequenceNumber=e.readUInt32LE(),t};He.prototype.toBufferWriter=function(e){e||(e=new O6),e.writeReverse(this.prevTxId),e.writeUInt32LE(this.outputIndex);var t=this._scriptBuffer;return e.writeVarintNum(t.length),e.write(t),e.writeUInt32LE(this.sequenceNumber),e};He.prototype.setScript=function(e){if(this._script=null,e instanceof Ic)this._script=e,this._script._isInput=!0,this._scriptBuffer=e.toBuffer();else if(e===null)this._script=Ic.empty(),this._script._isInput=!0,this._scriptBuffer=this._script.toBuffer();else if(p1.isHexa(e))this._scriptBuffer=pp.Buffer.from(e,"hex");else if(di.isString(e))this._script=new Ic(e),this._script._isInput=!0,this._scriptBuffer=this._script.toBuffer();else if(d.Buffer.isBuffer(e))this._scriptBuffer=pp.Buffer.from(e);else throw new TypeError("Invalid argument type: script");return this};He.prototype.getSignatures=function(){throw new Ca.AbstractMethodInvoked("Trying to sign unsupported output type (only P2PKH and P2SH multisig inputs are supported) for input: "+JSON.stringify(this))};He.prototype.isFullySigned=function(){throw new Ca.AbstractMethodInvoked("Input#isFullySigned")};He.prototype.isFinal=function(){return this.sequenceNumber===He.MAXINT};He.prototype.addSignature=function(){throw new Ca.AbstractMethodInvoked("Input#addSignature")};He.prototype.clearSignatures=function(){throw new Ca.AbstractMethodInvoked("Input#clearSignatures")};He.prototype.isValidSignature=function(e,t){return t.signature.nhashtype=t.sigtype,R6.verify(e,t.signature,t.publicKey,t.inputIndex,this.output.script,this.output.satoshisBN)};He.prototype.isNull=function(){return this.prevTxId.toString("hex")==="0000000000000000000000000000000000000000000000000000000000000000"&&this.outputIndex===4294967295};He.prototype._estimateSize=function(){return this.toBufferWriter().toBuffer().length};y1.exports=He});var ss=P((VF,m1)=>{"use strict";m();m1.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}});var us=P((zF,_1)=>{"use strict";m();var as=Ve(),Pr=ke(),B6=ss(),v1=pr(),b1=Tr(),N6=Jn(),La=ir();function Vr(e){if(!(this instanceof Vr))return new Vr(e);if(e instanceof Vr)return e;if(as.isObject(e))return this._fromObject(e);throw new N6.InvalidArgument("TransactionSignatures must be instantiated from an object")}B6(Vr,La);Vr.prototype._fromObject=function(e){return this._checkObjectArgs(e),this.publicKey=new b1(e.publicKey),this.prevTxId=d.Buffer.isBuffer(e.prevTxId)?e.prevTxId:d.Buffer.from(e.prevTxId,"hex"),this.outputIndex=e.outputIndex,this.inputIndex=e.inputIndex,this.signature=e.signature instanceof La?e.signature:d.Buffer.isBuffer(e.signature)?La.fromBuffer(e.signature):La.fromString(e.signature),this.sigtype=e.sigtype,this};Vr.prototype._checkObjectArgs=function(e){Pr.checkArgument(b1(e.publicKey),"publicKey"),Pr.checkArgument(!as.isUndefined(e.inputIndex),"inputIndex"),Pr.checkArgument(!as.isUndefined(e.outputIndex),"outputIndex"),Pr.checkState(as.isNumber(e.inputIndex),"inputIndex must be a number"),Pr.checkState(as.isNumber(e.outputIndex),"outputIndex must be a number"),Pr.checkArgument(e.signature,"signature"),Pr.checkArgument(e.prevTxId,"prevTxId"),Pr.checkState(e.signature instanceof La||d.Buffer.isBuffer(e.signature)||v1.isHexa(e.signature),"signature must be a buffer or hexa value"),Pr.checkState(d.Buffer.isBuffer(e.prevTxId)||v1.isHexa(e.prevTxId),"prevTxId must be a buffer or hexa value"),Pr.checkArgument(e.sigtype,"sigtype"),Pr.checkState(as.isNumber(e.sigtype),"sigtype must be a number")};Vr.prototype.toObject=Vr.prototype.toJSON=function(){return{publicKey:this.publicKey.toString(),prevTxId:this.prevTxId.toString("hex"),outputIndex:this.outputIndex,inputIndex:this.inputIndex,signature:this.signature.toString(),sigtype:this.sigtype}};Vr.fromObject=function(e){return Pr.checkArgument(e),new Vr(e)};_1.exports=Vr});var I1=P((YF,x1)=>{"use strict";m();var M6=ss(),w1=ke(),gp=os(),k6=Dn(),C6=pi(),E1=Kr(),S1=ir(),L6=us();function Un(){gp.apply(this,arguments)}M6(Un,gp);Un.prototype.getSignatures=function(e,t,r,n){w1.checkState(this.output instanceof k6),n=n||S1.SIGHASH_ALL|S1.SIGHASH_FORKID;var i=t.toPublicKey();return i.toString()===this.output.script.getPublicKey().toString("hex")?[new L6({publicKey:i,prevTxId:this.prevTxId,outputIndex:this.outputIndex,inputIndex:r,signature:C6.sign(e,t,n,r,this.output.script,this.output.satoshisBN),sigtype:n})]:[]};Un.prototype.addSignature=function(e,t){return w1.checkState(this.isValidSignature(e,t),"Signature is invalid"),this.setScript(E1.buildPublicKeyIn(t.signature.toDER(),t.sigtype)),this};Un.prototype.clearSignatures=function(){return this.setScript(E1.empty()),this};Un.prototype.isFullySigned=function(){return this.script.isPublicKeyIn()};Un.SCRIPT_MAX_SIZE=74;Un.prototype._estimateSize=function(){return gp.BASE_SIZE+Un.SCRIPT_MAX_SIZE};x1.exports=Un});var P1=P((ZF,T1)=>{"use strict";m();var D6=ss(),O1=ke(),U6=Qt(),yp=os(),F6=Dn(),q6=pi(),R1=Kr(),A1=ir(),H6=us();function Fn(){yp.apply(this,arguments)}D6(Fn,yp);Fn.prototype.getSignatures=function(e,t,r,n,i){O1.checkState(this.output instanceof F6),i=i||U6.sha256ripemd160(t.publicKey.toBuffer()),n=n||A1.SIGHASH_ALL|A1.SIGHASH_FORKID;var o=this.output.script.chunks[2]&&this.output.script.chunks[2].buf;return o&&i.equals(o)?[new H6({publicKey:t.publicKey,prevTxId:this.prevTxId,outputIndex:this.outputIndex,inputIndex:r,signature:q6.sign(e,t,n,r,this.output.script,this.output.satoshisBN),sigtype:n})]:[]};Fn.prototype.addSignature=function(e,t){return O1.checkState(this.isValidSignature(e,t),"Signature is invalid"),this.setScript(R1.buildPublicKeyHashIn(t.publicKey,t.signature.toDER(),t.sigtype)),this};Fn.prototype.clearSignatures=function(){return this.setScript(R1.empty()),this};Fn.prototype.isFullySigned=function(){return this.script.isPublicKeyHashIn()};Fn.SCRIPT_MAX_SIZE=108;Fn.prototype._estimateSize=function(){return yp.BASE_SIZE+Fn.SCRIPT_MAX_SIZE};T1.exports=Fn});var M1=P((JF,N1)=>{"use strict";m();var Gr=Ve(),j6=ss(),Rc=os(),K6=Dn(),Da=ke(),B1=Kr(),Oc=ir(),mp=pi(),vp=us(),V6=Tr(),G6=Ma();function Pt(e,t,r,n){Rc.apply(this,arguments);var i=this;t=t||e.publicKeys,r=r||e.threshold,n=n||e.signatures,this.publicKeys=t.map(o=>o.toString("hex")).sort().map(o=>new V6(o)),Da.checkState(B1.buildMultisigOut(this.publicKeys,r).equals(this.output.script),"Provided public keys don't match to the provided output script"),this.publicKeyIndex={},Gr.each(this.publicKeys,function(o,s){i.publicKeyIndex[o.toString()]=s}),this.threshold=r,this.signatures=n?this._deserializeSignatures(n):new Array(this.publicKeys.length)}j6(Pt,Rc);Pt.prototype.toObject=function(){var e=Rc.prototype.toObject.apply(this,arguments);return e.threshold=this.threshold,e.publicKeys=Gr.map(this.publicKeys,function(t){return t.toString()}),e.signatures=this._serializeSignatures(),e};Pt.prototype._deserializeSignatures=function(e){return Gr.map(e,function(t){if(t)return new vp(t)})};Pt.prototype._serializeSignatures=function(){return Gr.map(this.signatures,function(e){if(e)return e.toObject()})};Pt.prototype.getSignatures=function(e,t,r,n){Da.checkState(this.output instanceof K6),n=n||Oc.SIGHASH_ALL|Oc.SIGHASH_FORKID;var i=this,o=[];return Gr.each(this.publicKeys,function(s){s.toString()===t.publicKey.toString()&&o.push(new vp({publicKey:t.publicKey,prevTxId:i.prevTxId,outputIndex:i.outputIndex,inputIndex:r,signature:mp.sign(e,t,n,r,i.output.script,i.output.satoshisBN),sigtype:n}))}),o};Pt.prototype.addSignature=function(e,t){return Da.checkState(!this.isFullySigned(),"All needed signatures have already been added"),Da.checkArgument(!Gr.isUndefined(this.publicKeyIndex[t.publicKey.toString()]),"Signature has no matching public key"),Da.checkState(this.isValidSignature(e,t)),this.signatures[this.publicKeyIndex[t.publicKey.toString()]]=t,this._updateScript(),this};Pt.prototype._updateScript=function(){return this.setScript(B1.buildMultisigIn(this.publicKeys,this.threshold,this._createSignatures())),this};Pt.prototype._createSignatures=function(){return Gr.map(Gr.filter(this.signatures,function(e){return!Gr.isUndefined(e)}),function(e){return d.Buffer.concat([e.signature.toDER(),d.Buffer.from([e.sigtype&255])])})};Pt.prototype.clearSignatures=function(){this.signatures=new Array(this.publicKeys.length),this._updateScript()};Pt.prototype.isFullySigned=function(){return this.countSignatures()===this.threshold};Pt.prototype.countMissingSignatures=function(){return this.threshold-this.countSignatures()};Pt.prototype.countSignatures=function(){return Gr.reduce(this.signatures,function(e,t){return e+!!t},0)};Pt.prototype.publicKeysWithoutSignature=function(){var e=this;return Gr.filter(this.publicKeys,function(t){return!e.signatures[e.publicKeyIndex[t.toString()]]})};Pt.prototype.isValidSignature=function(e,t){return t.signature.nhashtype=t.sigtype,mp.verify(e,t.signature,t.publicKey,t.inputIndex,this.output.script,this.output.satoshisBN)};Pt.normalizeSignatures=function(e,t,r,n,i){return i.map(function(o){var s=null;return n=n.filter(function(a){if(s)return!0;var c=new vp({signature:Oc.fromTxFormat(a),publicKey:o,prevTxId:t.prevTxId,outputIndex:t.outputIndex,inputIndex:r,sigtype:Oc.SIGHASH_ALL});c.signature.nhashtype=c.sigtype;var h=mp.verify(e,c.signature,c.publicKey,c.inputIndex,t.output.script);return h?(s=c,!1):!0}),s||null})};Pt.SIGNATURE_SIZE=73;Pt.prototype._estimateSize=function(){var e=1+this.threshold*Pt.SIGNATURE_SIZE;return Rc.BASE_SIZE+G6(e).toBuffer().length+e};N1.exports=Pt});var U1=P((e5,D1)=>{"use strict";m();var zr=Ve(),z6=ss(),Tc=os(),W6=Dn(),Ua=ke(),bp=Kr(),k1=ir(),C1=pi(),L1=us(),Y6=Tr(),$6=Ma();function Ot(e,t,r,n){Tc.apply(this,arguments);var i=this;t=t||e.publicKeys,r=r||e.threshold,n=n||e.signatures,this.publicKeys=t.map(o=>o.toString("hex")).sort().map(o=>new Y6(o)),this.redeemScript=bp.buildMultisigOut(this.publicKeys,r),Ua.checkState(bp.buildScriptHashOut(this.redeemScript).equals(this.output.script),"Provided public keys don't hash to the provided output"),this.publicKeyIndex={},zr.each(this.publicKeys,function(o,s){i.publicKeyIndex[o.toString()]=s}),this.threshold=r,this.signatures=n?this._deserializeSignatures(n):new Array(this.publicKeys.length)}z6(Ot,Tc);Ot.prototype.toObject=function(){var e=Tc.prototype.toObject.apply(this,arguments);return e.threshold=this.threshold,e.publicKeys=zr.map(this.publicKeys,function(t){return t.toString()}),e.signatures=this._serializeSignatures(),e};Ot.prototype._deserializeSignatures=function(e){return zr.map(e,function(t){if(t)return new L1(t)})};Ot.prototype._serializeSignatures=function(){return zr.map(this.signatures,function(e){if(e)return e.toObject()})};Ot.prototype.getSignatures=function(e,t,r,n){Ua.checkState(this.output instanceof W6),n=n||k1.SIGHASH_ALL|k1.SIGHASH_FORKID;var i=this,o=[];return zr.each(this.publicKeys,function(s){s.toString()===t.publicKey.toString()&&o.push(new L1({publicKey:t.publicKey,prevTxId:i.prevTxId,outputIndex:i.outputIndex,inputIndex:r,signature:C1.sign(e,t,n,r,i.redeemScript,i.output.satoshisBN),sigtype:n}))}),o};Ot.prototype.addSignature=function(e,t){return Ua.checkState(!this.isFullySigned(),"All needed signatures have already been added"),Ua.checkArgument(!zr.isUndefined(this.publicKeyIndex[t.publicKey.toString()]),"Signature has no matching public key"),Ua.checkState(this.isValidSignature(e,t)),this.signatures[this.publicKeyIndex[t.publicKey.toString()]]=t,this._updateScript(),this};Ot.prototype._updateScript=function(){return this.setScript(bp.buildP2SHMultisigIn(this.publicKeys,this.threshold,this._createSignatures(),{cachedMultisig:this.redeemScript})),this};Ot.prototype._createSignatures=function(){return zr.map(zr.filter(this.signatures,function(e){return!zr.isUndefined(e)}),function(e){return d.Buffer.concat([e.signature.toDER(),d.Buffer.from([e.sigtype&255])])})};Ot.prototype.clearSignatures=function(){this.signatures=new Array(this.publicKeys.length),this._updateScript()};Ot.prototype.isFullySigned=function(){return this.countSignatures()===this.threshold};Ot.prototype.countMissingSignatures=function(){return this.threshold-this.countSignatures()};Ot.prototype.countSignatures=function(){return zr.reduce(this.signatures,function(e,t){return e+!!t},0)};Ot.prototype.publicKeysWithoutSignature=function(){var e=this;return zr.filter(this.publicKeys,function(t){return!e.signatures[e.publicKeyIndex[t.toString()]]})};Ot.prototype.isValidSignature=function(e,t){return t.signature.nhashtype=t.sigtype,C1.verify(e,t.signature,t.publicKey,t.inputIndex,this.redeemScript,this.output.satoshisBN)};Ot.SIGNATURE_SIZE=73;Ot.PUBKEY_SIZE=34;Ot.prototype._estimateSize=function(){var e=this.publicKeys.length*Ot.PUBKEY_SIZE,t=this.threshold*Ot.SIGNATURE_SIZE,r=3+e,n=r<=75?1:r<=255?2:3,i=t+1+n+r;return Tc.BASE_SIZE+$6(i).toBuffer().length+i};D1.exports=Ot});var Pc=P((r5,fs)=>{m();fs.exports=os();fs.exports.PublicKey=I1();fs.exports.PublicKeyHash=P1();fs.exports.MultiSig=M1();fs.exports.MultiSigScriptHash=U1()});var pi=P((i5,K1)=>{"use strict";m();var Z6=Tt(),fr=ir(),_p=Kr(),X6=Dn(),J6=va(),Fa=Qi(),F1=Er(),Bc=Qt(),q1=ka(),Sp=ke(),wp=Nc(),gi=Ve(),H1=d.Buffer.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),Q6="ffffffffffffffff",ek=wp.SCRIPT_ENABLE_SIGHASH_FORKID,tk=function(e,t,r,n,i){var o=e.inputs[r];Sp.checkArgument(i instanceof F1,"For ForkId=0 signatures, satoshis or complete input must be provided");function s(M){var L=new Fa;gi.each(M.inputs,function(q){L.writeReverse(q.prevTxId),L.writeUInt32LE(q.outputIndex)});var j=L.toBuffer(),G=Bc.sha256sha256(j);return G}function a(M){var L=new Fa;gi.each(M.inputs,function(q){L.writeUInt32LE(q.sequenceNumber)});var j=L.toBuffer(),G=Bc.sha256sha256(j);return G}function c(M,L){var j=new Fa;gi.isUndefined(L)?gi.each(M.outputs,function(W){W.toBufferWriter(j)}):M.outputs[L].toBufferWriter(j);var G=j.toBuffer(),q=Bc.sha256sha256(G);return q}var h=d.Buffer.alloc(32),g=d.Buffer.alloc(32),y=d.Buffer.alloc(32);t&fr.SIGHASH_ANYONECANPAY||(h=s(e)),!(t&fr.SIGHASH_ANYONECANPAY)&&(t&31)!==fr.SIGHASH_SINGLE&&(t&31)!==fr.SIGHASH_NONE&&(g=a(e)),(t&31)!==fr.SIGHASH_SINGLE&&(t&31)!==fr.SIGHASH_NONE?y=c(e):(t&31)===fr.SIGHASH_SINGLE&&r<e.outputs.length&&(y=c(e,r));var w=new Fa;w.writeInt32LE(e.version),w.write(h),w.write(g),w.writeReverse(o.prevTxId),w.writeUInt32LE(o.outputIndex),w.writeVarintNum(n.toBuffer().length),w.write(n.toBuffer()),w.writeUInt64LEBN(i);var I=o.sequenceNumber;w.writeUInt32LE(I),w.write(y),w.writeUInt32LE(e.nLockTime),w.writeUInt32LE(t>>>0);var T=w.toBuffer();return T},j1=function(t,r,n,i,o,s){var a=xp(),c=Pc();gi.isUndefined(s)&&(s=ek);var h=a.shallowCopy(t);if(i=new _p(i),s&wp.SCRIPT_ENABLE_REPLAY_PROTECTION){var g=r>>8,y=16711680|g^57005;r=y<<8|r&255}if(r&fr.SIGHASH_FORKID&&!(r&fr.SIGHASH_CHRONICLE)&&s&wp.SCRIPT_ENABLE_SIGHASH_FORKID)return tk(h,r,n,i,o);i.removeCodeseparators();var w;for(w=0;w<h.inputs.length;w++)h.inputs[w]=new c(h.inputs[w]).setScript(_p.empty());if(h.inputs[n]=new c(h.inputs[n]).setScript(i),(r&31)===fr.SIGHASH_NONE||(r&31)===fr.SIGHASH_SINGLE)for(w=0;w<h.inputs.length;w++)w!==n&&(h.inputs[w].sequenceNumber=0);if((r&31)===fr.SIGHASH_NONE)h.outputs=[];else if((r&31)===fr.SIGHASH_SINGLE){if(n>=h.outputs.length)return H1;for(h.outputs.length=n+1,w=0;w<n;w++)h.outputs[w]=new X6({satoshis:F1.fromBuffer(Z6.Buffer.from(Q6,"hex")),script:_p.empty()})}r&fr.SIGHASH_ANYONECANPAY&&(h.inputs=[h.inputs[n]]);var I=new Fa().write(h.toBuffer()).writeInt32LE(r).toBuffer();return I},Ep=function(t,r,n,i,o,s){var a=j1(t,r,n,i,o,s);if(a.compare(H1)===0)return a;var c=Bc.sha256sha256(a);return c=new J6(c).readReverse(),c};function rk(e,t,r,n,i,o,s){var a=Ep(e,r,n,i,o,s),c=q1.sign(a,t,"little").set({nhashtype:r});return c}function nk(e,t,r,n,i,o,s){Sp.checkArgument(!gi.isUndefined(e)),Sp.checkArgument(!gi.isUndefined(t)&&!gi.isUndefined(t.nhashtype));var a=Ep(e,t.nhashtype,n,i,o,s);return q1.verify(a,t,r,"little")}K1.exports={sighashPreimage:j1,sighash:Ep,sign:rk,verify:nk}});var Ip=P((s5,G1)=>{"use strict";m();var qn=Ve(),Mc=ke(),V1=pr(),ik=Kr(),ok=no();function Hn(e){if(!(this instanceof Hn))return new Hn(e);Mc.checkArgument(qn.isObject(e),"Must provide an object from where to extract data");var t=e.address?new ok(e.address):void 0,r=e.txid?e.txid:e.txId;if(!r||!V1.isHexaString(r)||r.length>64)throw new Error("Invalid TXID in object",e);var n=qn.isUndefined(e.vout)?e.outputIndex:e.vout;if(!qn.isNumber(n))throw new Error("Invalid outputIndex, received "+n);Mc.checkArgument(!qn.isUndefined(e.scriptPubKey)||!qn.isUndefined(e.script),"Must provide the scriptPubKey for that output!");var i=new ik(e.scriptPubKey||e.script);Mc.checkArgument(!qn.isUndefined(e.amount)||!qn.isUndefined(e.satoshis),"Must provide an amount for the output");var o=qn.isUndefined(e.amount)?e.satoshis:Math.round(e.amount*1e8);Mc.checkArgument(qn.isNumber(o),"Amount must be a number"),V1.defineImmutable(this,{address:t,txId:r,outputIndex:n,script:i,satoshis:o})}Hn.prototype.inspect=function(){return"<UnspentOutput: "+this.txId+":"+this.outputIndex+", satoshis: "+this.satoshis+", address: "+this.address+">"};Hn.prototype.toString=function(){return this.txId+":"+this.outputIndex};Hn.fromObject=function(e){return new Hn(e)};Hn.prototype.toObject=Hn.prototype.toJSON=function(){return{address:this.address?this.address.toString():void 0,txid:this.txId,vout:this.outputIndex,scriptPubKey:this.script.toBuffer().toString("hex"),amount:Number.parseFloat((this.satoshis/1e8).toFixed(8))}};G1.exports=Hn});var xp=P((u5,Q1)=>{"use strict";m();var pe=Ve(),Ft=ke(),sk=Tt(),Nt=Jn(),W1=pr(),Y1=va(),ak=Qi(),z1=Ma(),$1=Qt(),Cc=ir(),Z1=pi(),uk=no(),X1=Ip(),Bt=Pc(),fk=Bt.PublicKeyHash,ck=Bt.PublicKey,lk=Bt.MultiSigScriptHash,hk=Bt.MultiSig,Wr=Dn(),ln=Kr(),dk=io(),kc=Er(),pk=Nc(),gk=pk.SCRIPT_ENABLE_SIGHASH_FORKID;function z(e){if(!(this instanceof z))return new z(e);if(this.inputs=[],this.outputs=[],this._inputAmount=void 0,this._outputAmount=void 0,e){if(e instanceof z)return z.shallowCopy(e);if(W1.isHexa(e))this.fromString(e);else if(d.Buffer.isBuffer(e))this.fromBuffer(e);else if(pe.isObject(e))this.fromObject(e);else throw new Nt.InvalidArgument("Must provide an object or string to deserialize a transaction")}else this._newTransaction()}var yk=1,mk=0,vk=1e6;z.DUST_AMOUNT=546;z.FEE_SECURITY_MARGIN=150;z.MAX_MONEY=21e6*1e8;z.NLOCKTIME_BLOCKHEIGHT_LIMIT=5e8;z.NLOCKTIME_MAX_VALUE=4294967295;z.FEE_PER_KB=500;z.CHANGE_OUTPUT_MAX_SIZE=62;z.shallowCopy=function(e){var t=new z(e.toBuffer());return t};var J1={configurable:!1,enumerable:!0,get:function(){return this._hash=new Y1(this._getHash()).readReverse().toString("hex"),this._hash}};Object.defineProperty(z.prototype,"hash",J1);Object.defineProperty(z.prototype,"id",J1);var Ap={configurable:!1,enumerable:!0,get:function(){return this._getInputAmount()}};Object.defineProperty(z.prototype,"inputAmount",Ap);Ap.get=function(){return this._getOutputAmount()};Object.defineProperty(z.prototype,"outputAmount",Ap);z.prototype._getHash=function(){return $1.sha256sha256(this.toBuffer())};z.prototype.serialize=function(e){return e===!0||e&&e.disableAll?this.uncheckedSerialize():this.checkedSerialize(e)};z.prototype.uncheckedSerialize=z.prototype.toString=function(){return this.toBuffer().toString("hex")};z.prototype.checkedSerialize=function(e){var t=this.getSerializationError(e);if(t)throw t.message+=" - For more information please see: https://bsv.io/api/lib/transaction#serialization-checks",t;return this.uncheckedSerialize()};z.prototype.invalidSatoshis=function(){for(var e=!1,t=0;t<this.outputs.length;t++)this.outputs[t].invalidSatoshis()&&(e=!0);return e};z.prototype.getSerializationError=function(e){if(e=e||{},this.invalidSatoshis())return new Nt.Transaction.InvalidSatoshis;var t=this._getUnspentValue(),r;return t<0?e.disableMoreOutputThanInput||(r=new Nt.Transaction.InvalidOutputAmountSum):r=this._hasFeeError(e,t),r||this._hasDustOutputs(e)||this._isMissingSignatures(e)};z.prototype._hasFeeError=function(e,t){if(!pe.isUndefined(this._fee)&&this._fee!==t)return new Nt.Transaction.FeeError.Different("Unspent value is "+t+" but specified fee is "+this._fee);if(!e.disableLargeFees){var r=Math.floor(z.FEE_SECURITY_MARGIN*this._estimateFee());if(t>r)return this._missingChange()?new Nt.Transaction.ChangeAddressMissing("Fee is too large and no change address was provided"):new Nt.Transaction.FeeError.TooLarge("expected less than "+r+" but got "+t)}};z.prototype._missingChange=function(){return!this._changeScript};z.prototype._hasDustOutputs=function(e){if(!e.disableDustOutputs){var t,r;for(t in this.outputs)if(r=this.outputs[t],r.satoshis<z.DUST_AMOUNT&&!r.script.isDataOut()&&!r.script.isSafeDataOut())return new Nt.Transaction.DustOutputs}};z.prototype._isMissingSignatures=function(e){if(!e.disableIsFullySigned&&!this.isFullySigned())return new Nt.Transaction.MissingSignatures};z.prototype.inspect=function(){return"<Transaction: "+this.uncheckedSerialize()+">"};z.prototype.toBuffer=function(){var e=new ak;return this.toBufferWriter(e).toBuffer()};z.prototype.toBufferWriter=function(e){return e.writeInt32LE(this.version),e.writeVarintNum(this.inputs.length),pe.each(this.inputs,function(t){t.toBufferWriter(e)}),e.writeVarintNum(this.outputs.length),pe.each(this.outputs,function(t){t.toBufferWriter(e)}),e.writeUInt32LE(this.nLockTime),e};z.prototype.fromBuffer=function(e){var t=new Y1(e);return this.fromBufferReader(t)};z.prototype.fromBufferReader=function(e){Ft.checkArgument(!e.finished(),"No transaction data received");var t,r,n;for(this.version=e.readInt32LE(),r=e.readVarintNum(),t=0;t<r;t++){var i=Bt.fromBufferReader(e);this.inputs.push(i)}for(n=e.readVarintNum(),t=0;t<n;t++)this.outputs.push(Wr.fromBufferReader(e));return this.nLockTime=e.readUInt32LE(),this};z.prototype.toObject=z.prototype.toJSON=function(){var t=[];this.inputs.forEach(function(i){t.push(i.toObject())});var r=[];this.outputs.forEach(function(i){r.push(i.toObject())});var n={hash:this.hash,version:this.version,inputs:t,outputs:r,nLockTime:this.nLockTime};return this._changeScript&&(n.changeScript=this._changeScript.toString()),pe.isUndefined(this._changeIndex)||(n.changeIndex=this._changeIndex),pe.isUndefined(this._fee)||(n.fee=this._fee),n};z.prototype.fromObject=function(t){Ft.checkArgument(pe.isObject(t)||t instanceof z);var r=this,n;return t instanceof z?n=t.toObject():n=t,pe.each(n.inputs,function(i){if(!i.output||!i.output.script){r.uncheckedAddInput(new Bt(i));return}var o=new ln(i.output.script),s;if(o.isPublicKeyHashOut())s=new Bt.PublicKeyHash(i);else if(o.isScriptHashOut()&&i.publicKeys&&i.threshold)s=new Bt.MultiSigScriptHash(i,i.publicKeys,i.threshold,i.signatures);else if(o.isPublicKeyOut())s=new Bt.PublicKey(i);else throw new Nt.Transaction.Input.UnsupportedScript(i.output.script);r.addInput(s)}),pe.each(n.outputs,function(i){r.addOutput(new Wr(i))}),n.changeIndex&&(this._changeIndex=n.changeIndex),n.changeScript&&(this._changeScript=new ln(n.changeScript)),n.fee&&(this._fee=n.fee),this.nLockTime=n.nLockTime,this.version=n.version,this._checkConsistency(t),this};z.prototype._checkConsistency=function(e){pe.isUndefined(this._changeIndex)||(Ft.checkState(this._changeScript,"Change script is expected."),Ft.checkState(this.outputs[this._changeIndex],"Change index points to undefined output."),Ft.checkState(this.outputs[this._changeIndex].script.toString()===this._changeScript.toString(),"Change output has an unexpected script.")),e&&e.hash&&Ft.checkState(e.hash===this.hash,"Hash in object does not match transaction hash.")};z.prototype.lockUntilDate=function(e){if(Ft.checkArgument(e),pe.isNumber(e)&&e<z.NLOCKTIME_BLOCKHEIGHT_LIMIT)throw new Nt.Transaction.LockTimeTooEarly;pe.isDate(e)&&(e=e.getTime()/1e3);for(var t=0;t<this.inputs.length;t++)this.inputs[t].sequenceNumber===Bt.DEFAULT_SEQNUMBER&&(this.inputs[t].sequenceNumber=Bt.DEFAULT_LOCKTIME_SEQNUMBER);return this.nLockTime=e,this};z.prototype.lockUntilBlockHeight=function(e){if(Ft.checkArgument(pe.isNumber(e)),e>=z.NLOCKTIME_BLOCKHEIGHT_LIMIT)throw new Nt.Transaction.BlockHeightTooHigh;if(e<0)throw new Nt.Transaction.NLockTimeOutOfRange;for(var t=0;t<this.inputs.length;t++)this.inputs[t].sequenceNumber===Bt.DEFAULT_SEQNUMBER&&(this.inputs[t].sequenceNumber=Bt.DEFAULT_LOCKTIME_SEQNUMBER);return this.nLockTime=e,this};z.prototype.getLockTime=function(){return this.nLockTime?this.nLockTime<z.NLOCKTIME_BLOCKHEIGHT_LIMIT?this.nLockTime:new Date(1e3*this.nLockTime):null};z.prototype.fromString=function(e){this.fromBuffer(sk.Buffer.from(e,"hex"))};z.prototype._newTransaction=function(){this.version=yk,this.nLockTime=mk};z.prototype.from=function(e,t,r){if(pe.isArray(e)){var n=this;return pe.each(e,function(o){n.from(o,t,r)}),this}var i=pe.some(this.inputs,function(o){return o.prevTxId.toString("hex")===e.txId&&o.outputIndex===e.outputIndex});return i?this:(t&&r?this._fromMultisigUtxo(e,t,r):this._fromNonP2SH(e),this)};z.prototype._fromNonP2SH=function(e){var t;e=new X1(e),e.script.isPublicKeyHashOutPrefix()?t=fk:e.script.isPublicKeyOut()?t=ck:t=Bt,this.addInput(new t({output:new Wr({script:e.script,satoshis:e.satoshis}),prevTxId:e.txId,outputIndex:e.outputIndex,script:ln.empty()}))};z.prototype._fromMultisigUtxo=function(e,t,r){Ft.checkArgument(r<=t.length,"Number of required signatures must be greater than the number of public keys");var n;if(e=new X1(e),e.script.isMultisigOut())n=hk;else if(e.script.isScriptHashOut())n=lk;else throw new Nt.Transaction.Input.UnsupportedScript(e.script.toString());this.addInput(new n({output:new Wr({script:e.script,satoshis:e.satoshis}),prevTxId:e.txId,outputIndex:e.outputIndex,script:ln.empty()},t,r))};z.prototype.addInput=function(e,t,r){if(Ft.checkArgumentType(e,Bt,"input"),!e.output&&(pe.isUndefined(t)||pe.isUndefined(r)))throw new Nt.Transaction.NeedMoreInfo("Need information about the UTXO script and satoshis");return!e.output&&t&&!pe.isUndefined(r)&&(t=t instanceof ln?t:new ln(t),Ft.checkArgumentType(r,"number","satoshis"),e.output=new Wr({script:t,satoshis:r})),this.uncheckedAddInput(e)};z.prototype.uncheckedAddInput=function(e){return Ft.checkArgumentType(e,Bt,"input"),this.inputs.push(e),this._inputAmount=void 0,this._updateChangeOutput(),this};z.prototype.hasAllUtxoInfo=function(){return pe.every(this.inputs.map(function(e){return!!e.output}))};z.prototype.fee=function(e){return Ft.checkArgument(pe.isNumber(e),"amount must be a number"),this._fee=e,this._updateChangeOutput(),this};z.prototype.feePerKb=function(e){return Ft.checkArgument(pe.isNumber(e),"amount must be a number"),this._feePerKb=e,this._updateChangeOutput(),this};z.prototype.change=function(e){return Ft.checkArgument(e,"address is required"),this._changeScript=ln.fromAddress(e),this._updateChangeOutput(),this};z.prototype.getChangeOutput=function(){return pe.isUndefined(this._changeIndex)?null:this.outputs[this._changeIndex]};z.prototype.to=function(e,t){if(pe.isArray(e)){var r=this;return pe.each(e,function(n){r.to(n.address,n.satoshis)}),this}return Ft.checkArgument(W1.isNaturalNumber(t),"Amount is expected to be a positive integer"),this.addOutput(new Wr({script:ln(new uk(e)),satoshis:t})),this};z.prototype.addData=function(e){return this.addOutput(new Wr({script:ln.buildDataOut(e),satoshis:0})),this};z.prototype.addSafeData=function(e){return this.addOutput(new Wr({script:ln.buildSafeDataOut(e),satoshis:0})),this};z.prototype.addOutput=function(e){return Ft.checkArgumentType(e,Wr,"output"),this._addOutput(e),this._updateChangeOutput(),this};z.prototype.clearOutputs=function(){return this.outputs=[],this._clearSignatures(),this._outputAmount=void 0,this._changeIndex=void 0,this._updateChangeOutput(),this};z.prototype._addOutput=function(e){this.outputs.push(e),this._outputAmount=void 0};z.prototype._getOutputAmount=function(){if(pe.isUndefined(this._outputAmount)){var e=this;this._outputAmount=0,pe.each(this.outputs,function(t){e._outputAmount+=t.satoshis})}return this._outputAmount};z.prototype._getInputAmount=function(){if(pe.isUndefined(this._inputAmount)){var e=this;this._inputAmount=0,pe.each(this.inputs,function(t){if(pe.isUndefined(t.output))throw new Nt.Transaction.Input.MissingPreviousOutput;e._inputAmount+=t.output.satoshis})}return this._inputAmount};z.prototype._updateChangeOutput=function(){if(this._changeScript){this._clearSignatures(),pe.isUndefined(this._changeIndex)||this._removeOutput(this._changeIndex),this._changeIndex=this.outputs.length,this._addOutput(new Wr({script:this._changeScript,satoshis:0}));var e=this._getUnspentValue(),t=this.getFee(),r=e-t;this._removeOutput(this._changeIndex),this._changeIndex=void 0,r>=z.DUST_AMOUNT&&(this._changeIndex=this.outputs.length,this._addOutput(new Wr({script:this._changeScript,satoshis:r})))}};z.prototype.getFee=function(){return this.isCoinbase()?0:pe.isUndefined(this._fee)?this._changeScript?this._estimateFee():this._getUnspentValue():this._fee};z.prototype._estimateFee=function(){var e=this._estimateSize();return Math.ceil(e/1e3*(this._feePerKb||z.FEE_PER_KB))};z.prototype._getUnspentValue=function(){return this._getInputAmount()-this._getOutputAmount()};z.prototype._clearSignatures=function(){pe.each(this.inputs,function(e){e.clearSignatures!==Bt.prototype.clearSignatures&&e.clearSignatures()})};z.prototype._estimateSize=function(){var e=8;return e+=z1(this.inputs.length).toBuffer().length,e+=z1(this.outputs.length).toBuffer().length,pe.each(this.inputs,function(t){e+=t._estimateSize()}),pe.each(this.outputs,function(t){e+=t.getSize()}),e};z.prototype._removeOutput=function(e){var t=this.outputs[e];this.outputs=pe.without(this.outputs,t),this._outputAmount=void 0};z.prototype.removeOutput=function(e){this._removeOutput(e),this._updateChangeOutput()};z.prototype.sort=function(){return this.sortInputs(function(e){var t=Array.prototype.concat.apply([],e);return t.sort(function(r,n){return r.prevTxId.compare(n.prevTxId)||r.outputIndex-n.outputIndex}),t}),this.sortOutputs(function(e){var t=Array.prototype.concat.apply([],e);return t.sort(function(r,n){return r.satoshis-n.satoshis||r.script.toBuffer().compare(n.script.toBuffer())}),t}),this};z.prototype.shuffleOutputs=function(){return this.sortOutputs(pe.shuffle)};z.prototype.sortOutputs=function(e){var t=e(this.outputs);return this._newOutputOrder(t)};z.prototype.sortInputs=function(e){return this.inputs=e(this.inputs),this._clearSignatures(),this};z.prototype._newOutputOrder=function(e){var t=this.outputs.length!==e.length||pe.difference(this.outputs,e).length!==0;if(t)throw new Nt.Transaction.InvalidSorting;if(!pe.isUndefined(this._changeIndex)){var r=this.outputs[this._changeIndex];this._changeIndex=e.indexOf(r)}return this.outputs=e,this};z.prototype.removeInput=function(e,t){var r;if(!t&&pe.isNumber(e)?r=e:r=pe.findIndex(this.inputs,function(i){return i.prevTxId.toString("hex")===e&&i.outputIndex===t}),r<0||r>=this.inputs.length)throw new Nt.Transaction.InvalidIndex(r,this.inputs.length);var n=this.inputs[r];this.inputs=pe.without(this.inputs,n),this._inputAmount=void 0,this._updateChangeOutput()};z.prototype.sign=function(e,t){Ft.checkState(this.hasAllUtxoInfo(),"Not all utxo information is available to sign the transaction.");var r=this;return pe.isArray(e)?(pe.each(e,function(n){r.sign(n,t)}),this):(pe.each(this.getSignatures(e,t),function(n){r.applySignature(n)}),this)};z.prototype.getSignatures=function(e,t){e=new dk(e),t=t||Cc.SIGHASH_ALL|Cc.SIGHASH_FORKID;var r=this,n=[],i=$1.sha256ripemd160(e.publicKey.toBuffer());return pe.each(this.inputs,function(s,a){pe.each(s.getSignatures(r,e,a,t,i),function(c){n.push(c)})}),n};z.prototype.applySignature=function(e){return this.inputs[e.inputIndex].addSignature(this,e),this};z.prototype.isFullySigned=function(){return pe.each(this.inputs,function(e){if(e.isFullySigned===Bt.prototype.isFullySigned)throw new Nt.Transaction.UnableToVerifySignature("Unrecognized script kind, or not enough information to execute script.This usually happens when creating a transaction from a serialized transaction")}),pe.every(pe.map(this.inputs,function(e){return e.isFullySigned()}))};z.prototype.isValidSignature=function(e){var t=this;if(this.inputs[e.inputIndex].isValidSignature===Bt.prototype.isValidSignature)throw new Nt.Transaction.UnableToVerifySignature("Unrecognized script kind, or not enough information to execute script.This usually happens when creating a transaction from a serialized transaction");return this.inputs[e.inputIndex].isValidSignature(t,e)};z.prototype.verifySignature=function(e,t,r,n,i,o){return Z1.verify(this,e,t,r,n,i,o)};z.prototype.verify=function(){if(this.inputs.length===0)return"transaction txins empty";if(this.outputs.length===0)return"transaction txouts empty";for(var e=new kc(0),t=0;t<this.outputs.length;t++){var r=this.outputs[t];if(r.invalidSatoshis())return"transaction txout "+t+" satoshis is invalid";if(r._satoshisBN.gt(new kc(z.MAX_MONEY,10)))return"transaction txout "+t+" greater than MAX_MONEY";if(e=e.add(r._satoshisBN),e.gt(new kc(z.MAX_MONEY)))return"transaction txout "+t+" total output greater than MAX_MONEY"}if(this.toBuffer().length>vk)return"transaction over the maximum block size";var n={};for(t=0;t<this.inputs.length;t++){var i=this.inputs[t],o=i.prevTxId+":"+i.outputIndex;if(!pe.isUndefined(n[o]))return"transaction input "+t+" duplicate input";n[o]=!0}var s=this.isCoinbase();if(s){var a=this.inputs[0]._scriptBuffer;if(a.length<2||a.length>100)return"coinbase transaction script size invalid"}else for(t=0;t<this.inputs.length;t++)if(this.inputs[t].isNull())return"transaction input "+t+" has null input";return!0};z.prototype.isCoinbase=function(){return this.inputs.length===1&&this.inputs[0].isNull()};z.prototype.sighash=function(e,t,r,n,i){t=t||Cc.SIGHASH_ALL|Cc.SIGHASH_FORKID;var o=this.inputs[e];if(!o)throw new Error("Input index "+e+" does not exist");return!r&&o.output&&(r=o.output.script),!n&&o.output&&(n=new kc(o.output.satoshis)),i=i||gk,Z1.sighash(this,t,e,r,n,i)};Q1.exports=z});var Op=P((c5,oo)=>{m();oo.exports=xp();oo.exports.Input=Pc();oo.exports.Output=Dn();oo.exports.UnspentOutput=Ip();oo.exports.Signature=us();oo.exports.Sighash=pi()});var Nc=P((h5,rx)=>{"use strict";m();var Lc=Ve(),Ha=fp(),N=sp(),fe=Er(),qa=Qt(),yi=ir(),Rp=Tr();function ex(e){return e.map(function(t){return d.Buffer.isBuffer(t)?d.Buffer.from(t):t})}var B=function e(t){if(!(this instanceof e))return new e(t);t?(this.initialize(),this.set(t)):this.initialize()};B.prototype.verify=function(e,t,r,n,i,o){var s=Op();if(Lc.isUndefined(r)&&(r=new s),Lc.isUndefined(n)&&(n=0),Lc.isUndefined(i)&&(i=B.currentConsensusFlags(),o||(i&=~B.SCRIPT_ENABLE_SIGHASH_FORKID)),i&B.SCRIPT_ENABLE_SIGHASH_FORKID&&(i|=B.SCRIPT_VERIFY_STRICTENC,!o))throw new Error("internal error - need satoshisBN to verify FORKID transactions");this.set({script:e,tx:r,nin:n,flags:i,satoshisBN:o});var a;if((i&B.SCRIPT_VERIFY_SIGPUSHONLY)!==0&&!e.isPushOnly())return this.errstr="SCRIPT_ERR_SIG_PUSHONLY",!1;if(!this.evaluate())return!1;var c=(i&B.SCRIPT_VERIFY_P2SH)!==0&&(i&B.SCRIPT_UTXO_AFTER_GENESIS)===0;c&&(a=this.stack.slice());var h=this.stack;if(this.initialize(),this.set({script:t,stack:h,tx:r,nin:n,flags:i,satoshisBN:o}),!this.evaluate())return!1;if(this.stack.length===0)return this.errstr="SCRIPT_ERR_EVAL_FALSE_NO_RESULT",!1;var g=this.stack[this.stack.length-1];if(!B.castToBool(g))return this.errstr="SCRIPT_ERR_EVAL_FALSE_IN_STACK",!1;if(c&&t.isScriptHashOut()){if(!e.isPushOnly())return this.errstr="SCRIPT_ERR_SIG_PUSHONLY",!1;if(a.length===0)throw new Error("internal error - stack copy empty");var y=a[a.length-1],w=Ha.fromBuffer(y);if(a.pop(),this.initialize(),this.set({script:w,stack:a,tx:r,nin:n,flags:i,satoshisBN:o}),!this.evaluate())return!1;if(a.length===0)return this.errstr="SCRIPT_ERR_EVAL_FALSE_NO_P2SH_STACK",!1;if(!B.castToBool(a[a.length-1]))return this.errstr="SCRIPT_ERR_EVAL_FALSE_IN_P2SH_STACK",!1}if((i&B.SCRIPT_VERIFY_CLEANSTACK)!==0){if((i&B.SCRIPT_VERIFY_P2SH)===0&&(i&B.SCRIPT_UTXO_AFTER_GENESIS)===0)throw new Error("internal error - CLEANSTACK without P2SH");if(this.stack.length!==1)return this.errstr="SCRIPT_ERR_CLEANSTACK",!1}return!0};rx.exports=B;B.prototype.initialize=function(e){this.stack=[],this.altstack=[],this.pc=0,this.pbegincodehash=0,this.nOpCount=0,this.returned=!1,this.nonTopLevelReturnAfterGenesis=!1,this.vfExec=[],this.vfElse=[],this.errstr="",this.flags=0};B.prototype.set=function(e){this.script=e.script||this.script,this.tx=e.tx||this.tx,this.nin=typeof e.nin<"u"?e.nin:this.nin,this.satoshisBN=e.satoshisBN||this.satoshisBN,this.stack=e.stack||this.stack,this.altstack=e.altstack||this.altstack,this.pc=typeof e.pc<"u"?e.pc:this.pc,this.pbegincodehash=typeof e.pbegincodehash<"u"?e.pbegincodehash:this.pbegincodehash,this.nOpCount=typeof e.nOpCount<"u"?e.nOpCount:this.nOpCount,this.returned=typeof e.returned<"u"?e.returned:this.returned,this.nonTopLevelReturnAfterGenesis=typeof e.nonTopLevelReturnAfterGenesis<"u"?e.nonTopLevelReturnAfterGenesis:this.nonTopLevelReturnAfterGenesis,this.vfExec=e.vfExec||this.vfExec,this.vfElse=e.vfElse||this.vfElse,this.errstr=e.errstr||this.errstr,this.flags=typeof e.flags<"u"?e.flags:this.flags};B.true=d.Buffer.from([1]);B.false=d.Buffer.from([]);B.MAX_SCRIPT_ELEMENT_SIZE=520;B.MAXIMUM_ELEMENT_SIZE=4;B.MAX_OPS_PER_SCRIPT=500;B.MAX_SCRIPT_SIZE=1e4;B.UNLIMITED=Number.MAX_SAFE_INTEGER;B.MAX_SCRIPT_NUM_LENGTH_AFTER_GENESIS=75e4;B.MAX_SCRIPT_NUM_LENGTH_AFTER_CHRONICLE=32e6;B.MAX_PUBKEYS_PER_MULTISIG_AFTER_GENESIS=4294967295;B.LOCKTIME_THRESHOLD=5e8;B.LOCKTIME_THRESHOLD_BN=new fe(B.LOCKTIME_THRESHOLD);B.useGenesisLimits=function(e){return e=e||2147483647,B.MAX_SCRIPT_ELEMENT_SIZE=e,B.MAXIMUM_ELEMENT_SIZE=e,B.MAX_OPS_PER_SCRIPT=e,B.MAX_SCRIPT_SIZE=e,B};B.getLimits=function(){return{maxScriptElementSize:B.MAX_SCRIPT_ELEMENT_SIZE,maximumElementSize:B.MAXIMUM_ELEMENT_SIZE,maxOpsPerScript:B.MAX_OPS_PER_SCRIPT,maxScriptSize:B.MAX_SCRIPT_SIZE}};B.setLimits=function(e){return e=e||{},e.maxScriptElementSize!=null&&(B.MAX_SCRIPT_ELEMENT_SIZE=e.maxScriptElementSize),e.maximumElementSize!=null&&(B.MAXIMUM_ELEMENT_SIZE=e.maximumElementSize),e.maxOpsPerScript!=null&&(B.MAX_OPS_PER_SCRIPT=e.maxOpsPerScript),e.maxScriptSize!=null&&(B.MAX_SCRIPT_SIZE=e.maxScriptSize),B};B.SCRIPT_VERIFY_NONE=0;B.SCRIPT_VERIFY_P2SH=1;B.SCRIPT_VERIFY_STRICTENC=2;B.SCRIPT_VERIFY_DERSIG=4;B.SCRIPT_VERIFY_LOW_S=8;B.SCRIPT_VERIFY_NULLDUMMY=16;B.SCRIPT_VERIFY_SIGPUSHONLY=32;B.SCRIPT_VERIFY_MINIMALDATA=64;B.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS=128;B.SCRIPT_VERIFY_CLEANSTACK=256;B.SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY=512;B.SCRIPT_VERIFY_CHECKSEQUENCEVERIFY=1024;B.SCRIPT_VERIFY_MINIMALIF=8192;B.SCRIPT_VERIFY_NULLFAIL=16384;B.SCRIPT_VERIFY_COMPRESSED_PUBKEYTYPE=32768;B.SCRIPT_ENABLE_SIGHASH_FORKID=65536;B.SCRIPT_ENABLE_REPLAY_PROTECTION=1<<17;B.SCRIPT_ENABLE_MONOLITH_OPCODES=2048;B.SCRIPT_ENABLE_MAGNETIC_OPCODES=4096;B.SCRIPT_GENESIS=1<<18;B.SCRIPT_UTXO_AFTER_GENESIS=1<<19;B.SCRIPT_ENABLE_CHRONICLE=1<<20;B.SCRIPT_CHRONICLE=B.SCRIPT_ENABLE_CHRONICLE;B.SCRIPT_UTXO_AFTER_CHRONICLE=1<<21;B.CHRONICLE_ACTIVATION_HEIGHT=943816;B.mainnetFlags=function(e){e=e||{};var t=B.SCRIPT_VERIFY_P2SH|B.SCRIPT_VERIFY_STRICTENC|B.SCRIPT_VERIFY_DERSIG|B.SCRIPT_VERIFY_LOW_S|B.SCRIPT_VERIFY_NULLFAIL|B.SCRIPT_VERIFY_MINIMALDATA|B.SCRIPT_ENABLE_SIGHASH_FORKID|B.SCRIPT_ENABLE_MAGNETIC_OPCODES|B.SCRIPT_ENABLE_MONOLITH_OPCODES|B.SCRIPT_GENESIS|B.SCRIPT_UTXO_AFTER_GENESIS;return e.afterChronicle!==!1&&(t|=B.SCRIPT_ENABLE_CHRONICLE|B.SCRIPT_UTXO_AFTER_CHRONICLE),t};B.currentConsensusFlags=function(){return B.SCRIPT_ENABLE_MONOLITH_OPCODES|B.SCRIPT_ENABLE_MAGNETIC_OPCODES|B.SCRIPT_GENESIS|B.SCRIPT_UTXO_AFTER_GENESIS|B.SCRIPT_ENABLE_CHRONICLE|B.SCRIPT_UTXO_AFTER_CHRONICLE|B.SCRIPT_ENABLE_SIGHASH_FORKID};B.useMainnetConsensus=function(e){return e=e||{},B.useGenesisLimits(e.max),B.mainnetFlags(e)};B.SEQUENCE_LOCKTIME_DISABLE_FLAG=1<<31;B.SEQUENCE_LOCKTIME_TYPE_FLAG=1<<22;B.SEQUENCE_LOCKTIME_MASK=65535;B.castToBool=function(e){for(var t=0;t<e.length;t++)if(e[t]!==0)return!(t===e.length-1&&e[t]===128);return!1};B.prototype.checkSignatureEncoding=function(e){var t;if(e.length===0)return!0;if((this.flags&(B.SCRIPT_VERIFY_DERSIG|B.SCRIPT_VERIFY_LOW_S|B.SCRIPT_VERIFY_STRICTENC))!==0&&!yi.isTxDER(e))return this.errstr="SCRIPT_ERR_SIG_DER_INVALID_FORMAT",!1;if((this.flags&B.SCRIPT_VERIFY_LOW_S)!==0){if(t=yi.fromTxFormat(e),!t.hasLowS())return this.errstr="SCRIPT_ERR_SIG_DER_HIGH_S",!1}else if((this.flags&B.SCRIPT_VERIFY_STRICTENC)!==0){if(t=yi.fromTxFormat(e),!t.hasDefinedHashtype())return this.errstr="SCRIPT_ERR_SIG_HASHTYPE",!1;if(!(this.flags&B.SCRIPT_ENABLE_SIGHASH_FORKID)&&t.nhashtype&yi.SIGHASH_FORKID)return this.errstr="SCRIPT_ERR_ILLEGAL_FORKID",!1;if(!(this.flags&B.SCRIPT_CHRONICLE)&&t.nhashtype&yi.SIGHASH_CHRONICLE)return this.errstr="SCRIPT_ERR_ILLEGAL_CHRONICLE",!1;if(this.flags&B.SCRIPT_ENABLE_SIGHASH_FORKID&&!(t.nhashtype&yi.SIGHASH_FORKID))return this.errstr="SCRIPT_ERR_MUST_USE_FORKID",!1}return!0};B.prototype.checkPubkeyEncoding=function(e){return(this.flags&B.SCRIPT_VERIFY_STRICTENC)!==0&&!Rp.isValid(e)?(this.errstr="SCRIPT_ERR_PUBKEYTYPE",!1):!0};B.prototype.isAfterGenesis=function(){return(this.flags&B.SCRIPT_UTXO_AFTER_GENESIS)!==0};B.prototype.isAfterChronicle=function(){return(this.flags&(B.SCRIPT_UTXO_AFTER_CHRONICLE|B.SCRIPT_ENABLE_CHRONICLE))!==0};B.prototype.maxScriptElementSize=function(){return this.isAfterGenesis()?B.UNLIMITED:B.MAX_SCRIPT_ELEMENT_SIZE};B.prototype.maxScriptSize=function(){return this.isAfterGenesis()?B.UNLIMITED:B.MAX_SCRIPT_SIZE};B.prototype.maxOpsPerScript=function(){return this.isAfterGenesis()?B.UNLIMITED:B.MAX_OPS_PER_SCRIPT};B.prototype.maxScriptNumLength=function(){return this.isAfterChronicle()?B.MAX_SCRIPT_NUM_LENGTH_AFTER_CHRONICLE:this.isAfterGenesis()?B.MAX_SCRIPT_NUM_LENGTH_AFTER_GENESIS:B.MAXIMUM_ELEMENT_SIZE};B.prototype.maxPubKeysPerMultisig=function(){return this.isAfterGenesis()?B.MAX_PUBKEYS_PER_MULTISIG_AFTER_GENESIS:20};B._isMinimallyEncoded=function(e,t){return t=t||B.MAXIMUM_ELEMENT_SIZE,!(e.length>t||e.length>0&&(e[e.length-1]&127)===0&&(e.length<=1||(e[e.length-2]&128)===0))};B._minimallyEncode=function(e){if(e.length===0)return e;var t=e[e.length-1];if(t&127)return e;if(e.length===1)return d.Buffer.from("");if(e[e.length-2]&128)return e;for(var r=e.length-1;r>0;r--)if(e[r-1]!==0)return e[r-1]&128?e[r++]=t:e[r-1]|=t,e.slice(0,r);return d.Buffer.from("")};B.prototype.evaluate=function(){if(this.script.toBuffer().length>this.maxScriptSize())return this.errstr="SCRIPT_ERR_SCRIPT_SIZE",!1;try{for(;this.pc<this.script.chunks.length;){let t={pc:this.pc,opcode:N.fromNumber(this.script.chunks[this.pc].opcodenum)};var e=this.step();if(!e)return!1;if(this._callbackStep(t),this.returned)return!0}if(this.stack.length+this.altstack.length>1e3)return this.errstr="SCRIPT_ERR_STACK_SIZE",!1}catch(t){return this.errstr=t.scriptErr||"SCRIPT_ERR_UNKNOWN_ERROR: "+t,!1}return this.vfExec.length>0?(this.errstr="SCRIPT_ERR_UNBALANCED_CONDITIONAL",!1):!0};B.prototype._callbackStep=function(e){if(typeof this.stepListener=="function")try{this.stepListener(e,ex(this.stack),ex(this.altstack))}catch(t){console.log(`Error in Step callback:${t}`)}};B.prototype.checkLockTime=function(e){if(!(this.tx.nLockTime<B.LOCKTIME_THRESHOLD&&e.lt(B.LOCKTIME_THRESHOLD_BN)||this.tx.nLockTime>=B.LOCKTIME_THRESHOLD&&e.gte(B.LOCKTIME_THRESHOLD_BN))||e.gt(new fe(this.tx.nLockTime)))return!1;var t=this.tx.inputs[this.nin];return!(!t||t.isFinal())};B.prototype.checkSequence=function(e){var t=this.tx.inputs[this.nin];if(!t)return!1;var r=t.sequenceNumber;if(this.tx.version<2||r&B.SEQUENCE_LOCKTIME_DISABLE_FLAG)return!1;var n=B.SEQUENCE_LOCKTIME_TYPE_FLAG|B.SEQUENCE_LOCKTIME_MASK,i=new fe(r&n),o=e.and(new fe(n)),s=new fe(B.SEQUENCE_LOCKTIME_TYPE_FLAG);return!(!(i.lt(s)&&o.lt(s)||i.gte(s)&&o.gte(s))||o.gt(i))};function bk(e,t){let r=e;for(;r.length<t;)r=d.Buffer.concat([d.Buffer.from([0]),r]);return r}function tx(e){var t=d.Buffer.alloc(4);return t.writeInt32LE(e|0,0),t}B.prototype.step=function(){var e=this;function t(re){return e.stack[e.stack.length+re]}function r(re){switch(re){case N.OP_2MUL:case N.OP_2DIV:if(!e.isAfterChronicle())return!0;break;case N.OP_INVERT:case N.OP_MUL:case N.OP_LSHIFT:case N.OP_RSHIFT:if((e.flags&B.SCRIPT_ENABLE_MAGNETIC_OPCODES)===0)return!0;break;case N.OP_DIV:case N.OP_MOD:case N.OP_SPLIT:case N.OP_CAT:case N.OP_AND:case N.OP_OR:case N.OP_XOR:case N.OP_BIN2NUM:case N.OP_NUM2BIN:return!1;default:break}return!1}var n=(this.flags&B.SCRIPT_VERIFY_MINIMALDATA)!==0,i,o,s,a,c,h,g,y,w,I,T,M,L,j,G,q,W,J=this.script.chunks[this.pc];this.pc++;var Y=J.opcodenum,be=this.vfExec.indexOf(!1)===-1&&(!this.nonTopLevelReturnAfterGenesis||Y===N.OP_RETURN);if(Lc.isUndefined(Y))return this.errstr="SCRIPT_ERR_UNDEFINED_OPCODE",!1;if(J.buf&&J.buf.length>this.maxScriptElementSize())return this.errstr="SCRIPT_ERR_PUSH_SIZE",!1;if(Y>N.OP_16&&++this.nOpCount>this.maxOpsPerScript())return this.errstr="SCRIPT_ERR_OP_COUNT",!1;if(r(Y)&&(!this.isAfterGenesis()||be))return this.errstr="SCRIPT_ERR_DISABLED_OPCODE",!1;if(be&&Y>=0&&Y<=N.OP_PUSHDATA4){if(n&&!this.script.checkMinimalPush(this.pc-1))return this.errstr="SCRIPT_ERR_MINIMALDATA",!1;if(!J.buf)this.stack.push(B.false);else{if(J.len!==J.buf.length)return this.errstr="SCRIPT_ERR_BAD_OPCODE",!1;this.stack.push(J.buf)}}else if(be||N.OP_IF<=Y&&Y<=N.OP_ENDIF)switch(Y){case N.OP_1NEGATE:case N.OP_1:case N.OP_2:case N.OP_3:case N.OP_4:case N.OP_5:case N.OP_6:case N.OP_7:case N.OP_8:case N.OP_9:case N.OP_10:case N.OP_11:case N.OP_12:case N.OP_13:case N.OP_14:case N.OP_15:case N.OP_16:c=Y-(N.OP_1-1),i=new fe(c).toScriptNumBuffer(),this.stack.push(i);break;case N.OP_NOP:break;case N.OP_NOP2:case N.OP_CHECKLOCKTIMEVERIFY:if(!(this.flags&B.SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)||this.isAfterGenesis()){if(this.flags&B.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)return this.errstr="SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS",!1;break}if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;var se=fe.fromScriptNumBuffer(this.stack[this.stack.length-1],n,5);if(se.lt(new fe(0)))return this.errstr="SCRIPT_ERR_NEGATIVE_LOCKTIME",!1;if(!this.checkLockTime(se))return this.errstr="SCRIPT_ERR_UNSATISFIED_LOCKTIME",!1;break;case N.OP_NOP3:case N.OP_CHECKSEQUENCEVERIFY:if(!(this.flags&B.SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)||this.isAfterGenesis()){if(this.flags&B.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)return this.errstr="SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS",!1;break}if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;var de=fe.fromScriptNumBuffer(t(-1),n,5);if(de.lt(new fe(0)))return this.errstr="SCRIPT_ERR_NEGATIVE_LOCKTIME",!1;if((de&B.SEQUENCE_LOCKTIME_DISABLE_FLAG)!==0)break;if(!this.checkSequence(de))return this.errstr="SCRIPT_ERR_UNSATISFIED_LOCKTIME",!1;break;case N.OP_NOP1:case N.OP_NOP9:case N.OP_NOP10:if(this.flags&B.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)return this.errstr="SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS",!1;break;case N.OP_LSHIFTNUM:case N.OP_RSHIFTNUM:if(!this.isAfterChronicle()){if(this.flags&B.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)return this.errstr="SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS",!1;break}if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;var A=this.maxScriptNumLength(),u=fe.fromScriptNumBuffer(t(-1),n,A);if(u.isNeg())return this.errstr="SCRIPT_ERR_INVALID_NUMBER_RANGE",!1;this.stack.pop();var l=fe.fromScriptNumBuffer(t(-1),n,A);this.stack.pop();var p=u.toNumber(),v=l.isNeg(),b=l.abs(),E;if(Y===N.OP_LSHIFTNUM){var O=l.toScriptNumBuffer().length;if(O+Math.floor(p/8)>A)return this.errstr="SCRIPT_ERR_SCRIPTNUM_OVERFLOW",!1;E=b.shln(p)}else E=p>=b.bitLength()?new fe(0):b.shrn(p);if(v&&!E.isZero()&&(E=E.neg()),E.toScriptNumBuffer().length>A)return this.errstr="SCRIPT_ERR_SCRIPTNUM_OVERFLOW",!1;this.stack.push(E.toScriptNumBuffer());break;case N.OP_VER:if(!this.isAfterChronicle())return this.errstr="SCRIPT_ERR_BAD_OPCODE",!1;if(this.tx==null)return this.errstr="SCRIPT_ERR_UNKNOWN_ERROR",!1;this.stack.push(tx(this.tx.version));break;case N.OP_VERIF:case N.OP_VERNOTIF:if(!this.isAfterChronicle()){if(this.isAfterGenesis()&&!be)break;return this.errstr="SCRIPT_ERR_BAD_OPCODE",!1}if(q=!1,be){if(this.stack.length<1)return this.errstr="SCRIPT_ERR_UNBALANCED_CONDITIONAL",!1;if(this.tx==null)return this.errstr="SCRIPT_ERR_UNKNOWN_ERROR",!1;i=t(-1),q=i.length===4&&i.equals(tx(this.tx.version)),Y===N.OP_VERNOTIF&&(q=!q),this.stack.pop()}this.vfExec.push(q),this.vfElse.push(!1);break;case N.OP_IF:case N.OP_NOTIF:if(q=!1,be){if(this.stack.length<1)return this.errstr="SCRIPT_ERR_UNBALANCED_CONDITIONAL",!1;if(i=t(-1),this.flags&B.SCRIPT_VERIFY_MINIMALIF){if(i.length>1)return this.errstr="SCRIPT_ERR_MINIMALIF",!1;if(i.length===1&&i[0]!==1)return this.errstr="SCRIPT_ERR_MINIMALIF",!1}q=B.castToBool(i),Y===N.OP_NOTIF&&(q=!q),this.stack.pop()}this.vfExec.push(q),this.vfElse.push(!1);break;case N.OP_ELSE:if(this.vfExec.length===0||this.vfElse[this.vfElse.length-1]&&this.isAfterGenesis())return this.errstr="SCRIPT_ERR_UNBALANCED_CONDITIONAL",!1;this.vfExec[this.vfExec.length-1]=!this.vfExec[this.vfExec.length-1],this.vfElse[this.vfElse.length-1]=!0;break;case N.OP_ENDIF:if(this.vfExec.length===0)return this.errstr="SCRIPT_ERR_UNBALANCED_CONDITIONAL",!1;this.vfExec.pop(),this.vfElse.pop();break;case N.OP_VERIFY:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(i=t(-1),q=B.castToBool(i),q)this.stack.pop();else return this.errstr="SCRIPT_ERR_VERIFY",!1;break;case N.OP_RETURN:if(this.isAfterGenesis()){if(this.vfExec.length===0){this.returned=!0;break}this.nonTopLevelReturnAfterGenesis=!0;break}return this.errstr="SCRIPT_ERR_OP_RETURN",!1;case N.OP_TOALTSTACK:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.altstack.push(this.stack.pop());break;case N.OP_FROMALTSTACK:if(this.altstack.length<1)return this.errstr="SCRIPT_ERR_INVALID_ALTSTACK_OPERATION",!1;this.stack.push(this.altstack.pop());break;case N.OP_2DROP:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.stack.pop(),this.stack.pop();break;case N.OP_2DUP:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;o=t(-2),s=t(-1),this.stack.push(d.Buffer.from(o)),this.stack.push(d.Buffer.from(s));break;case N.OP_3DUP:if(this.stack.length<3)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;o=t(-3),s=t(-2);var _=t(-1);this.stack.push(d.Buffer.from(o)),this.stack.push(d.Buffer.from(s)),this.stack.push(d.Buffer.from(_));break;case N.OP_2OVER:if(this.stack.length<4)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;o=t(-4),s=t(-3),this.stack.push(d.Buffer.from(o)),this.stack.push(d.Buffer.from(s));break;case N.OP_2ROT:if(this.stack.length<6)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;a=this.stack.splice(this.stack.length-6,2),this.stack.push(a[0]),this.stack.push(a[1]);break;case N.OP_2SWAP:if(this.stack.length<4)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;a=this.stack.splice(this.stack.length-4,2),this.stack.push(a[0]),this.stack.push(a[1]);break;case N.OP_IFDUP:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;i=t(-1),q=B.castToBool(i),q&&this.stack.push(d.Buffer.from(i));break;case N.OP_DEPTH:i=new fe(this.stack.length).toScriptNumBuffer(),this.stack.push(i);break;case N.OP_DROP:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.stack.pop();break;case N.OP_DUP:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.stack.push(d.Buffer.from(t(-1)));break;case N.OP_NIP:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.stack.splice(this.stack.length-2,1);break;case N.OP_OVER:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.stack.push(d.Buffer.from(t(-2)));break;case N.OP_PICK:case N.OP_ROLL:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(i=t(-1),y=fe.fromScriptNumBuffer(i,n,this.maxScriptNumLength()),c=y.toNumber(),this.stack.pop(),c<0||c>=this.stack.length)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;i=t(-c-1),Y===N.OP_ROLL&&this.stack.splice(this.stack.length-c-1,1),this.stack.push(d.Buffer.from(i));break;case N.OP_ROT:if(this.stack.length<3)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;h=t(-3),g=t(-2);var f=t(-1);this.stack[this.stack.length-3]=g,this.stack[this.stack.length-2]=f,this.stack[this.stack.length-1]=h;break;case N.OP_SWAP:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;h=t(-2),g=t(-1),this.stack[this.stack.length-2]=g,this.stack[this.stack.length-1]=h;break;case N.OP_TUCK:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.stack.splice(this.stack.length-2,0,d.Buffer.from(t(-1)));break;case N.OP_SIZE:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;y=new fe(t(-1).length),this.stack.push(y.toScriptNumBuffer());break;case N.OP_AND:case N.OP_OR:case N.OP_XOR:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(o=t(-2),s=t(-1),o.length!==s.length)return this.errstr="SCRIPT_ERR_INVALID_OPERAND_SIZE",!1;switch(Y){case N.OP_AND:for(let re=0;re<o.length;re++)o[re]&=s[re];break;case N.OP_OR:for(let re=0;re<o.length;re++)o[re]|=s[re];break;case N.OP_XOR:for(let re=0;re<o.length;re++)o[re]^=s[re];break;default:break}this.stack.pop();break;case N.OP_INVERT:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;i=t(-1);for(let re=0;re<i.length;re++)i[re]=~i[re];break;case N.OP_LSHIFT:case N.OP_RSHIFT:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(o=t(-2),o.length===0)this.stack.pop();else{if(w=new fe(o),I=fe.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength()),c=I.toNumber(),c<0)return this.errstr="SCRIPT_ERR_INVALID_NUMBER_RANGE",!1;this.stack.pop(),this.stack.pop();let re;Y===N.OP_LSHIFT&&(re=w.ushln(c)),Y===N.OP_RSHIFT&&(re=w.ushrn(c));let me=bk(d.Buffer.from(re.toArray().slice(o.length*-1)),o.length);this.stack.push(me)}break;case N.OP_EQUAL:case N.OP_EQUALVERIFY:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;o=t(-2),s=t(-1);var S=o.toString("hex")===s.toString("hex");if(this.stack.pop(),this.stack.pop(),this.stack.push(S?B.true:B.false),Y===N.OP_EQUALVERIFY)if(S)this.stack.pop();else return this.errstr="SCRIPT_ERR_EQUALVERIFY",!1;break;case N.OP_2MUL:case N.OP_2DIV:case N.OP_1ADD:case N.OP_1SUB:case N.OP_NEGATE:case N.OP_ABS:case N.OP_NOT:case N.OP_0NOTEQUAL:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;switch(i=t(-1),y=fe.fromScriptNumBuffer(i,n,this.maxScriptNumLength()),Y){case N.OP_2MUL:y=y.mul(new fe(2));break;case N.OP_2DIV:y=y.div(new fe(2));break;case N.OP_1ADD:y=y.add(fe.One);break;case N.OP_1SUB:y=y.sub(fe.One);break;case N.OP_NEGATE:y=y.neg();break;case N.OP_ABS:y.cmp(fe.Zero)<0&&(y=y.neg());break;case N.OP_NOT:y=new fe((y.cmp(fe.Zero)===0)+0);break;case N.OP_0NOTEQUAL:y=new fe((y.cmp(fe.Zero)!==0)+0);break}this.stack.pop(),this.stack.push(y.toScriptNumBuffer());break;case N.OP_ADD:case N.OP_SUB:case N.OP_MUL:case N.OP_MOD:case N.OP_DIV:case N.OP_BOOLAND:case N.OP_BOOLOR:case N.OP_NUMEQUAL:case N.OP_NUMEQUALVERIFY:case N.OP_NUMNOTEQUAL:case N.OP_LESSTHAN:case N.OP_GREATERTHAN:case N.OP_LESSTHANOREQUAL:case N.OP_GREATERTHANOREQUAL:case N.OP_MIN:case N.OP_MAX:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;switch(w=fe.fromScriptNumBuffer(t(-2),n,this.maxScriptNumLength()),I=fe.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength()),y=new fe(0),Y){case N.OP_ADD:y=w.add(I);break;case N.OP_SUB:y=w.sub(I);break;case N.OP_MUL:y=w.mul(I);break;case N.OP_DIV:if(I.cmp(fe.Zero)===0)return this.errstr="SCRIPT_ERR_DIV_BY_ZERO",!1;y=w.div(I);break;case N.OP_MOD:if(I.cmp(fe.Zero)===0)return this.errstr="SCRIPT_ERR_MOD_BY_ZERO",!1;y=w.mod(I);break;case N.OP_BOOLAND:y=new fe((w.cmp(fe.Zero)!==0&&I.cmp(fe.Zero)!==0)+0);break;case N.OP_BOOLOR:y=new fe((w.cmp(fe.Zero)!==0||I.cmp(fe.Zero)!==0)+0);break;case N.OP_NUMEQUAL:y=new fe((w.cmp(I)===0)+0);break;case N.OP_NUMEQUALVERIFY:y=new fe((w.cmp(I)===0)+0);break;case N.OP_NUMNOTEQUAL:y=new fe((w.cmp(I)!==0)+0);break;case N.OP_LESSTHAN:y=new fe((w.cmp(I)<0)+0);break;case N.OP_GREATERTHAN:y=new fe((w.cmp(I)>0)+0);break;case N.OP_LESSTHANOREQUAL:y=new fe((w.cmp(I)<=0)+0);break;case N.OP_GREATERTHANOREQUAL:y=new fe((w.cmp(I)>=0)+0);break;case N.OP_MIN:y=w.cmp(I)<0?w:I;break;case N.OP_MAX:y=w.cmp(I)>0?w:I;break}if(this.stack.pop(),this.stack.pop(),this.stack.push(y.toScriptNumBuffer()),Y===N.OP_NUMEQUALVERIFY)if(B.castToBool(t(-1)))this.stack.pop();else return this.errstr="SCRIPT_ERR_NUMEQUALVERIFY",!1;break;case N.OP_WITHIN:if(this.stack.length<3)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;w=fe.fromScriptNumBuffer(t(-3),n,this.maxScriptNumLength()),I=fe.fromScriptNumBuffer(t(-2),n,this.maxScriptNumLength());var K=fe.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength());q=I.cmp(w)<=0&&w.cmp(K)<0,this.stack.pop(),this.stack.pop(),this.stack.pop(),this.stack.push(q?B.true:B.false);break;case N.OP_RIPEMD160:case N.OP_SHA1:case N.OP_SHA256:case N.OP_HASH160:case N.OP_HASH256:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;i=t(-1);var F;Y===N.OP_RIPEMD160?F=qa.ripemd160(i):Y===N.OP_SHA1?F=qa.sha1(i):Y===N.OP_SHA256?F=qa.sha256(i):Y===N.OP_HASH160?F=qa.sha256ripemd160(i):Y===N.OP_HASH256&&(F=qa.sha256sha256(i)),this.stack.pop(),this.stack.push(F);break;case N.OP_CODESEPARATOR:this.pbegincodehash=this.pc;break;case N.OP_CHECKSIG:case N.OP_CHECKSIGVERIFY:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(T=t(-2),M=t(-1),!this.checkSignatureEncoding(T)||!this.checkPubkeyEncoding(M))return!1;L=new Ha().set({chunks:this.script.chunks.slice(this.pbegincodehash)});var $=new Ha().add(T);L.findAndDelete($);try{j=yi.fromTxFormat(T),G=Rp.fromBuffer(M,!1),W=this.tx.verifySignature(j,G,this.nin,L,this.satoshisBN,this.flags)}catch{W=!1}if(!W&&this.flags&B.SCRIPT_VERIFY_NULLFAIL&&T.length)return this.errstr="SCRIPT_ERR_NULLFAIL",!1;if(this.stack.pop(),this.stack.pop(),this.stack.push(W?B.true:B.false),Y===N.OP_CHECKSIGVERIFY)if(W)this.stack.pop();else return this.errstr="SCRIPT_ERR_CHECKSIGVERIFY",!1;break;case N.OP_CHECKMULTISIG:case N.OP_CHECKMULTISIGVERIFY:var Z=1;if(this.stack.length<Z)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;var Q=fe.fromScriptNumBuffer(t(-Z),n,this.maxScriptNumLength()).toNumber();if(Q<0||Q>this.maxPubKeysPerMultisig())return this.errstr="SCRIPT_ERR_PUBKEY_COUNT",!1;if(this.nOpCount+=Q,this.nOpCount>B.MAX_OPS_PER_SCRIPT)return this.errstr="SCRIPT_ERR_OP_COUNT",!1;var ae=++Z;Z+=Q;var ge=Q+2;if(this.stack.length<Z)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;var le=fe.fromScriptNumBuffer(t(-Z),n,this.maxScriptNumLength()).toNumber();if(le<0||le>Q)return this.errstr="SCRIPT_ERR_SIG_COUNT",!1;var R=++Z;if(Z+=le,this.stack.length<Z)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;L=new Ha().set({chunks:this.script.chunks.slice(this.pbegincodehash)});for(var k=0;k<le;k++)T=t(-R-k),L.findAndDelete(new Ha().add(T));for(W=!0;W&&le>0;){if(T=t(-R),M=t(-ae),!this.checkSignatureEncoding(T)||!this.checkPubkeyEncoding(M))return!1;var H;try{j=yi.fromTxFormat(T),G=Rp.fromBuffer(M,!1),H=this.tx.verifySignature(j,G,this.nin,L,this.satoshisBN,this.flags)}catch{H=!1}H&&(R++,le--),ae++,Q--,le>Q&&(W=!1)}for(;Z-- >1;){if(!W&&this.flags&B.SCRIPT_VERIFY_NULLFAIL&&!ge&&t(-1).length)return this.errstr="SCRIPT_ERR_NULLFAIL",!1;ge>0&&ge--,this.stack.pop()}if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(this.flags&B.SCRIPT_VERIFY_NULLDUMMY&&t(-1).length)return this.errstr="SCRIPT_ERR_SIG_NULLDUMMY",!1;if(this.stack.pop(),this.stack.push(W?B.true:B.false),Y===N.OP_CHECKMULTISIGVERIFY)if(W)this.stack.pop();else return this.errstr="SCRIPT_ERR_CHECKMULTISIGVERIFY",!1;break;case N.OP_CAT:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(o=t(-2),s=t(-1),o.length+s.length>this.maxScriptElementSize())return this.errstr="SCRIPT_ERR_PUSH_SIZE",!1;this.stack[this.stack.length-2]=d.Buffer.concat([o,s]),this.stack.pop();break;case N.OP_SPLIT:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;o=t(-2);var V=fe.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength()).toNumber();if(V<0||V>o.length)return this.errstr="SCRIPT_ERR_INVALID_SPLIT_RANGE",!1;var ie=d.Buffer.from(o);this.stack[this.stack.length-2]=ie.slice(0,V),this.stack[this.stack.length-1]=ie.slice(V);break;case N.OP_LEFT:case N.OP_RIGHT:if(!this.isAfterChronicle()){if(this.flags&B.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)return this.errstr="SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS",!1;break}if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(o=t(-2),c=fe.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength()).toNumber(),c<0||c>o.length)return this.errstr="SCRIPT_ERR_INVALID_NUMBER_RANGE",!1;this.stack.pop(),Y===N.OP_LEFT?this.stack[this.stack.length-1]=d.Buffer.from(o).slice(0,c):this.stack[this.stack.length-1]=d.Buffer.from(o).slice(o.length-c);break;case N.OP_SUBSTR:if(!this.isAfterChronicle()){if(this.flags&B.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)return this.errstr="SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS",!1;break}if(this.stack.length<3)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;o=t(-3);var ee=fe.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength()).toNumber(),te=fe.fromScriptNumBuffer(t(-2),n,this.maxScriptNumLength()).toNumber();if(te<0||te>=o.length||ee<0||ee>o.length-te)return this.errstr="SCRIPT_ERR_INVALID_NUMBER_RANGE",!1;this.stack.pop(),this.stack.pop(),this.stack[this.stack.length-1]=d.Buffer.from(o).slice(te,te+ee);break;case N.OP_NUM2BIN:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;var he=fe.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength()).toNumber();if(he<0||he>this.maxScriptElementSize())return this.errstr="SCRIPT_ERR_PUSH_SIZE",!1;this.stack.pop();var oe=t(-1);if(oe=B._minimallyEncode(oe),oe.length>he)return this.errstr="SCRIPT_ERR_IMPOSSIBLE_ENCODING",!1;if(oe.length===he){this.stack[this.stack.length-1]=oe;break}var ue=0;oe.length>0&&(ue=oe[oe.length-1]&128,oe[oe.length-1]&=127);var We=d.Buffer.alloc(he);oe.copy(We,0);for(var Oe=oe.length-1;Oe++<he-2;)We[Oe]=0;We[Oe]=ue,this.stack[this.stack.length-1]=We;break;case N.OP_BIN2NUM:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(o=t(-1),s=B._minimallyEncode(o),this.stack[this.stack.length-1]=s,!B._isMinimallyEncoded(s))return this.errstr="SCRIPT_ERR_INVALID_NUMBER_RANGE",!1;break;default:return this.errstr="SCRIPT_ERR_BAD_OPCODE",!1}return!0}});var Kr=P((p5,Tp)=>{m();Tp.exports=fp();Tp.exports.Interpreter=Nc()});var no=P((y5,sx)=>{"use strict";m();var Pp=Ve(),jn=ke(),_k=Jn(),nx=Fd(),Br=ga(),ix=Qt(),ox=pr(),Bp=Tr();function ne(e,t,r){if(!(this instanceof ne))return new ne(e,t,r);if(Pp.isArray(e)&&Pp.isNumber(t))return ne.createMultisig(e,t,r);if(e instanceof ne)return e;if(jn.checkArgument(e,"First argument is required, please include address data.","guide/address.html"),t&&!Br.get(t))throw new TypeError('Second argument must be "livenet", "testnet", or "regtest".');if(r&&r!==ne.PayToPublicKeyHash&&r!==ne.PayToScriptHash)throw new TypeError('Third argument must be "pubkeyhash" or "scripthash".');var n=this._classifyArguments(e,t,r);return n.network=n.network||Br.get(t)||Br.defaultNetwork,n.type=n.type||r||ne.PayToPublicKeyHash,ox.defineImmutable(this,{hashBuffer:n.hashBuffer,network:n.network,type:n.type}),this}ne.prototype._classifyArguments=function(e,t,r){if((e instanceof d.Buffer||e instanceof Uint8Array)&&e.length===20)return ne._transformHash(e);if((e instanceof d.Buffer||e instanceof Uint8Array)&&e.length===21)return ne._transformBuffer(e,t,r);if(e instanceof Bp)return ne._transformPublicKey(e);if(e instanceof ja())return ne._transformScript(e,t);if(typeof e=="string")return ne._transformString(e,t,r);if(Pp.isObject(e))return ne._transformObject(e);throw new TypeError("First argument is an unrecognized data format.")};ne.PayToPublicKeyHash="pubkeyhash";ne.PayToScriptHash="scripthash";ne._transformHash=function(e){var t={};if(!(e instanceof d.Buffer)&&!(e instanceof Uint8Array))throw new TypeError("Address supplied is not a buffer.");if(e.length!==20)throw new TypeError("Address hashbuffers must be exactly 20 bytes.");return t.hashBuffer=e,t};ne._transformObject=function(e){return jn.checkArgument(e.hash||e.hashBuffer,"Must provide a `hash` or `hashBuffer` property"),jn.checkArgument(e.type,"Must provide a `type` property"),{hashBuffer:e.hash?d.Buffer.from(e.hash,"hex"):e.hashBuffer,network:Br.get(e.network)||Br.defaultNetwork,type:e.type}};ne._classifyFromVersion=function(e){var t={},r=Br.get(e[0],"pubkeyhash"),n=Br.get(e[0],"scripthash");return r?(t.network=r,t.type=ne.PayToPublicKeyHash):n&&(t.network=n,t.type=ne.PayToScriptHash),t};ne._transformBuffer=function(e,t,r){var n={};if(!(e instanceof d.Buffer)&&!(e instanceof Uint8Array))throw new TypeError("Address supplied is not a buffer.");if(e.length!==21)throw new TypeError("Address buffers must be exactly 21 bytes.");var i=Br.get(t),o=ne._classifyFromVersion(e);if(t&&!i)throw new TypeError("Unknown network");if(!o.network||i&&i!==o.network)throw new TypeError("Address has mismatched network type.");if(!o.type||r&&r!==o.type)throw new TypeError("Address has mismatched type.");return n.hashBuffer=e.slice(1),n.network=o.network,n.type=o.type,n};ne._transformPublicKey=function(e){var t={};if(!(e instanceof Bp))throw new TypeError("Address must be an instance of PublicKey.");return t.hashBuffer=ix.sha256ripemd160(e.toBuffer()),t.type=ne.PayToPublicKeyHash,t};ne._transformScript=function(e,t){jn.checkArgument(e instanceof ja(),"script must be a Script instance");var r=e.getAddressInfo(t);if(!r)throw new _k.Script.CantDeriveAddress(e);return r};ne.createMultisig=function(e,t,r){return r=r||e[0].network||Br.defaultNetwork,ne.payingTo(ja().buildMultisigOut(e,t),r)};ne._transformString=function(e,t,r){if(typeof e!="string")throw new TypeError("data parameter supplied is not a string.");if(e.length<27)throw new Error("Invalid Address string provided");e=e.trim();var n=Br.get(t);if(t&&!n)throw new TypeError("Unknown network");var i=nx.decode(e);return ne._transformBuffer(i,t,r)};ne.fromPublicKey=function(e,t){var r=ne._transformPublicKey(e);return t=t||Br.defaultNetwork,new ne(r.hashBuffer,t,r.type)};ne.fromPrivateKey=function(e,t){let r=Bp.fromPrivateKey(e);return t=t||e.network||Br.defaultNetwork,ne.fromPublicKey(r,t)};ne.fromPublicKeyHash=function(e,t){var r=ne._transformHash(e);return new ne(r.hashBuffer,t,ne.PayToPublicKeyHash)};ne.fromScriptHash=function(e,t){jn.checkArgument(e,"hash parameter is required");var r=ne._transformHash(e);return new ne(r.hashBuffer,t,ne.PayToScriptHash)};ne.payingTo=function(e,t){return jn.checkArgument(e,"script is required"),jn.checkArgument(e instanceof ja(),"script must be instance of Script"),ne.fromScriptHash(ix.sha256ripemd160(e.toBuffer()),t)};ne.fromScript=function(e,t){jn.checkArgument(e instanceof ja(),"script must be a Script instance");var r=ne._transformScript(e,t);return new ne(r.hashBuffer,t,r.type)};ne.fromBuffer=function(e,t,r){var n=ne._transformBuffer(e,t,r);return new ne(n.hashBuffer,n.network,n.type)};ne.fromHex=function(e,t,r){return ne.fromBuffer(d.Buffer.from(e,"hex"),t,r)};ne.fromString=function(e,t,r){var n=ne._transformString(e,t,r);return new ne(n.hashBuffer,n.network,n.type)};ne.fromObject=function(t){jn.checkState(ox.isHexa(t.hash),'Unexpected hash property, "'+t.hash+'", expected to be hex.');var r=d.Buffer.from(t.hash,"hex");return new ne(r,t.network,t.type)};ne.getValidationError=function(e,t,r){var n;try{new ne(e,t,r)}catch(i){n=i}return n};ne.isValid=function(e,t,r){return!ne.getValidationError(e,t,r)};ne.prototype.isPayToPublicKeyHash=function(){return this.type===ne.PayToPublicKeyHash};ne.prototype.isPayToScriptHash=function(){return this.type===ne.PayToScriptHash};ne.prototype.toBuffer=function(){var e=d.Buffer.from([this.network[this.type]]),t=d.Buffer.concat([e,this.hashBuffer]);return t};ne.prototype.toHex=function(){return this.toBuffer().toString("hex")};ne.prototype.toObject=ne.prototype.toJSON=function(){return{hash:this.hashBuffer.toString("hex"),type:this.type,network:this.network.toString()}};ne.prototype.inspect=function(){return"<Address: "+this.toString()+", type: "+this.type+", network: "+this.network+">"};ne.prototype.toString=function(){return nx.encode(this.toBuffer())};sx.exports=ne;function ja(){return Kr()}});var io=P((v5,cx)=>{"use strict";m();var Dc=Ve(),Sk=no(),ax=Fd(),mi=Er(),ux=pr(),hn=ga(),Mp=ii(),wk=Tr(),Ek=ea(),fx=ke(),Np="[REDACTED]";function ye(e,t){if(!(this instanceof ye))return new ye(e,t);if(e instanceof ye)return e;var r=this._classifyArguments(e,t);if(!r.bn||r.bn.cmp(new mi(0))===0)throw new TypeError("Number can not be equal to zero, undefined, null or false");if(!r.bn.lt(Mp.getN()))throw new TypeError("Number must be less than N");if(typeof r.network>"u")throw new TypeError('Must specify the network ("livenet" or "testnet")');return ux.defineImmutable(this,{bn:r.bn,compressed:r.compressed,network:r.network}),Object.defineProperty(this,"publicKey",{configurable:!1,enumerable:!0,get:this.toPublicKey.bind(this)}),this}ye.prototype._classifyArguments=function(e,t){var r={compressed:!0,network:t?hn.get(t):hn.defaultNetwork};if(Dc.isUndefined(e)||Dc.isNull(e))r.bn=ye._getRandomBN();else if(e instanceof mi)r.bn=e;else if(e instanceof d.Buffer||e instanceof Uint8Array)r=ye._transformBuffer(e,t);else if(e.bn&&e.network)r=ye._transformObject(e);else if(!t&&hn.get(e))r.bn=ye._getRandomBN(),r.network=hn.get(e);else if(typeof e=="string")ux.isHexa(e)?r.bn=new mi(d.Buffer.from(e,"hex")):r=ye._transformWIF(e,t);else throw new TypeError("First argument is an unrecognized data type.");return r};ye._getRandomBN=function(){var e,t;do{var r=Ek.getRandomBuffer(32);t=mi.fromBuffer(r),e=t.lt(Mp.getN())}while(!e);return t};ye._transformBuffer=function(e,t){var r={};if(e.length===32)return ye._transformBNBuffer(e,t);if(r.network=hn.get(e[0],"privatekey"),!r.network)throw new Error("Invalid network");if(t&&r.network!==hn.get(t))throw new TypeError("Private key network mismatch");if(e.length===34&&e[33]===1)r.compressed=!0;else if(e.length===33)r.compressed=!1;else throw new Error("Length of buffer must be 33 (uncompressed) or 34 (compressed)");return r.bn=mi.fromBuffer(e.slice(1,33)),r};ye._transformBNBuffer=function(e,t,r){var n={};return n.network=hn.get(t)||hn.defaultNetwork,n.bn=mi.fromBuffer(e),n.compressed=r===void 0?!0:!!r,n};ye._transformWIF=function(e,t){return ye._transformBuffer(ax.decode(e),t)};ye.fromBuffer=function(e,t,r){return r!==void 0&&e&&e.length===32?new ye(ye._transformBNBuffer(e,t,r)):new ye(e,t)};ye.fromHex=function(e,t,r){return ye.fromBuffer(d.Buffer.from(e,"hex"),t,r)};ye._transformObject=function(e){if(e.bn instanceof mi)return{bn:e.bn,network:hn.get(e.network),compressed:e.compressed};if(typeof e.bn!="string"||!e.bn.length)throw new TypeError("Invalid private key: `bn` must be a hex string");if(e.bn===Np)throw new TypeError('Invalid private key: `bn` is "'+Np+'". JSON.stringify() redacts the secret on purpose \u2014 use toObject() for a round-trippable export, or toWIF().');if(!/^[0-9a-fA-F]+$/.test(e.bn))throw new TypeError("Invalid private key: `bn` is not hexadecimal");var t=new mi(e.bn,"hex");if(t.isZero()||t.gte(Mp.getN()))throw new TypeError("Invalid private key: outside the range of valid keys");var r=hn.get(e.network);return{bn:t,network:r,compressed:e.compressed}};ye.fromString=ye.fromWIF=function(e,t){return fx.checkArgument(Dc.isString(e),"First argument is expected to be a string."),new ye(e,t)};ye.fromObject=ye.fromJSON=function(e){return fx.checkArgument(Dc.isObject(e),"First argument is expected to be an object."),new ye(e)};ye.fromRandom=function(e){var t=ye._getRandomBN();return new ye(t,e)};ye.getValidationError=function(e,t){var r;try{new ye(e,t)}catch(n){r=n}return r};ye.isValid=function(e,t){return e?!ye.getValidationError(e,t):!1};ye.prototype.toString=function(){return this.toWIF()};ye.prototype.toWIF=function(){var e=this.network,t=this.compressed,r;return t?r=d.Buffer.concat([d.Buffer.from([e.privatekey]),this.bn.toBuffer({size:32}),d.Buffer.from([1])]):r=d.Buffer.concat([d.Buffer.from([e.privatekey]),this.bn.toBuffer({size:32})]),ax.encode(r)};ye.prototype.toBigNumber=function(){return this.bn};ye.prototype.toBuffer=function(){return this.bn.toBuffer({size:32})};ye.prototype.toHex=function(){return this.toBuffer().toString("hex")};ye.prototype.toPublicKey=function(){return this._pubkey||(this._pubkey=wk.fromPrivateKey(this)),this._pubkey};ye.prototype.toAddress=function(e){var t=this.toPublicKey();return Sk.fromPublicKey(t,e||this.network)};ye.prototype.toObject=function(){return{bn:this.bn.toString("hex"),compressed:this.compressed,network:this.network.toString()}};ye.prototype.toJSON=function(){return{bn:Np,compressed:this.compressed,network:this.network.toString()}};ye.prototype.inspect=function(){var e=this.compressed?"":", uncompressed";return"<PrivateKey: "+this.toHex()+", network: "+this.network+e+">"};cx.exports=ye});var Tr=P((_5,hx)=>{"use strict";m();var cs=Er(),ls=ii(),xk=Qt(),Ik=pr(),lx=ga(),kp=Ve(),so=ke();function ce(e,t){if(!(this instanceof ce))return new ce(e,t);if(so.checkArgument(e,"First argument is required, please include public key data."),e instanceof ce)return e;t=t||{};var r=this._classifyArgs(e,t);return r.point.validate(),Ik.defineImmutable(this,{point:r.point,compressed:r.compressed,network:r.network||lx.defaultNetwork}),this}ce.prototype._classifyArgs=function(e,t){var r={compressed:kp.isUndefined(t.compressed)||t.compressed};if(e instanceof ls)r.point=e;else if(e.x&&e.y)r=ce._transformObject(e);else if(typeof e=="string")r=ce._transformDER(d.Buffer.from(e,"hex"));else if(ce._isBuffer(e))r=ce._transformDER(e);else if(ce._isPrivateKey(e))r=ce._transformPrivateKey(e);else throw new TypeError("First argument is an unrecognized data format.");return r.network||(r.network=kp.isUndefined(t.network)?void 0:lx.get(t.network)),r};ce._isPrivateKey=function(e){var t=io();return e instanceof t};ce._isBuffer=function(e){return e instanceof d.Buffer||e instanceof Uint8Array};ce._transformPrivateKey=function(e){so.checkArgument(ce._isPrivateKey(e),"Must be an instance of PrivateKey");var t={};return t.point=ls.getG().mul(e.bn),t.compressed=e.compressed,t.network=e.network,t};ce._transformDER=function(e,t){so.checkArgument(ce._isBuffer(e),"Must be a buffer of DER encoded public key");var r={};t=kp.isUndefined(t)?!0:t;var n,i,o,s;if(e[0]===4||!t&&(e[0]===6||e[0]===7)){if(o=e.slice(1,33),s=e.slice(33,65),o.length!==32||s.length!==32||e.length!==65)throw new TypeError("Length of x and y must be 32 bytes");n=new cs(o),i=new cs(s),r.point=new ls(n,i),r.compressed=!1}else if(e[0]===3)o=e.slice(1),n=new cs(o),r=ce._transformX(!0,n),r.compressed=!0;else if(e[0]===2)o=e.slice(1),n=new cs(o),r=ce._transformX(!1,n),r.compressed=!0;else throw new TypeError("Invalid DER format public key");return r};ce._transformX=function(e,t){so.checkArgument(typeof e=="boolean","Must specify whether y is odd or not (true or false)");var r={};return r.point=ls.fromX(e,t),r};ce._transformObject=function(e){var t=new cs(e.x,"hex"),r=new cs(e.y,"hex"),n=new ls(t,r);return new ce(n,{compressed:e.compressed})};ce.fromPrivateKey=function(e){so.checkArgument(ce._isPrivateKey(e),"Must be an instance of PrivateKey");var t=ce._transformPrivateKey(e);return new ce(t.point,{compressed:t.compressed,network:t.network})};ce.fromDER=ce.fromBuffer=function(e,t){so.checkArgument(ce._isBuffer(e),"Must be a buffer of DER encoded public key");var r=ce._transformDER(e,t);return new ce(r.point,{compressed:r.compressed})};ce.fromPoint=function(e,t){return so.checkArgument(e instanceof ls,"First argument must be an instance of Point."),new ce(e,{compressed:t})};ce.fromHex=ce.fromString=function(e,t){var r=d.Buffer.from(e,t||"hex"),n=ce._transformDER(r);return new ce(n.point,{compressed:n.compressed})};ce.fromX=function(e,t){var r=ce._transformX(e,t);return new ce(r.point,{compressed:r.compressed})};ce.getValidationError=function(e){var t;try{new ce(e)}catch(r){t=r}return t};ce.isValid=function(e){return!ce.getValidationError(e)};ce.prototype.toObject=ce.prototype.toJSON=function(){return{x:this.point.getX().toString("hex",2),y:this.point.getY().toString("hex",2),compressed:this.compressed}};ce.prototype.toBuffer=ce.prototype.toDER=function(){var e=this.point.getX(),t=this.point.getY(),r=e.toBuffer({size:32}),n=t.toBuffer({size:32}),i;if(this.compressed){var o=n[n.length-1]%2;return o?i=d.Buffer.from([3]):i=d.Buffer.from([2]),d.Buffer.concat([i,r])}else return i=d.Buffer.from([4]),d.Buffer.concat([i,r,n])};ce.prototype._getID=function(){return xk.sha256ripemd160(this.toBuffer())};ce.prototype.toAddress=function(e){var t=no();return t.fromPublicKey(this,e||this.network)};ce.prototype.toString=ce.prototype.toHex=function(){return this.toDER().toString("hex")};ce.prototype.inspect=function(){return"<PublicKey: "+this.toHex()+(this.compressed?"":", uncompressed")+">"};hx.exports=ce});var Ka=P((w5,px)=>{"use strict";m();var dx=ea();function Ak(){var e=dx.getRandomBuffer(16);e[6]=e[6]&15|64,e[8]=e[8]&63|128;var t=e.toString("hex");return[t.substring(0,8),t.substring(8,12),t.substring(12,16),t.substring(16,20),t.substring(20,32)].join("-")}function Ok(e){return dx.getRandomBuffer(Math.ceil(e/2)).toString("hex").substring(0,e)}px.exports={uuid4:Ak,randomHex:Ok}});var bx=P((I5,vx)=>{"use strict";m();var Va=Tr(),Cp=Qt(),Lp=ka(),gx=ir(),Dp=io(),Rt=ke(),x5=Ve(),Rk=Ka();function yx(e,t){if(t=t||{},t.issuerPublicKey)return t.issuerPublicKey instanceof Va?t.issuerPublicKey:Va.fromString(t.issuerPublicKey);var r=e&&e.issuer;if(typeof r!="string")return null;try{var n=r.split("#")[0].split(":")[2];return n?Va.fromString(n):null}catch{return null}}var hs={PROPERTY_TITLE:"PropertyTitle",VEHICLE_TITLE:"VehicleTitle",INTELLECTUAL_PROPERTY:"IntellectualProperty",MUSIC_LICENSE:"MusicLicense",SOFTWARE_LICENSE:"SoftwareLicense",FINANCIAL_INSTRUMENT:"FinancialInstrument",PROMISSORY_NOTE:"PromissoryNote",BOND:"Bond",EQUITY_SHARE:"EquityShare",PROFESSIONAL_LICENSE:"ProfessionalLicense",REGULATORY_PERMIT:"RegulatoryPermit",ACCESS_RIGHT:"AccessRight",VOTING_RIGHT:"VotingRight",ROYALTY_RIGHT:"RoyaltyRight",USAGE_RIGHT:"UsageRight"},mx={create:function(e,t,r,n,i,o){o=o||{},Rt.checkArgument(typeof e=="string","Right type must be string"),Rt.checkArgument(typeof t=="string","Issuer DID must be string"),Rt.checkArgument(typeof r=="string","Subject DID must be string"),Rt.checkArgument(n&&typeof n=="object","Claim must be object");var s=Object.values(hs);Rt.checkArgument(s.includes(e),"Invalid right type: "+e);var a={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","LegalRightToken",e],issuer:t,issuanceDate:new Date().toISOString(),credentialSubject:{id:r,rightType:e,claim:n,jurisdiction:o.jurisdiction||"US",purpose:o.purpose||"legal_right",validFrom:o.validFrom||new Date().toISOString(),validUntil:o.validUntil||null,transferable:o.transferable!==!1,revocable:o.revocable!==!1}};return o.metadata&&(a.credentialSubject.metadata=o.metadata),a},prepareRightToken:function(e,t,r,n,i,o){o=o||{},Rt.checkArgument(typeof e=="string","Right type must be string"),Rt.checkArgument(typeof t=="string","Issuer DID must be string"),Rt.checkArgument(typeof r=="string","Subject DID must be string"),Rt.checkArgument(n&&typeof n=="object","Claim must be object"),Rt.checkArgument(i instanceof Dp,"Invalid issuer private key");var s=Object.values(hs);Rt.checkArgument(s.includes(e),"Invalid right type: "+e);try{var a=this.create(e,t,r,n,i,o),c=this._signToken(a,i);return{success:!0,rightToken:c,tokenHash:c.tokenHash,metadata:{type:e,issuer:t,subject:r,transferable:a.credentialSubject.transferable,revocable:a.credentialSubject.revocable,jurisdiction:a.credentialSubject.jurisdiction},externalOperations:{storeToken:{endpoint:"POST /rights/tokens",data:{token:c,metadata:{type:e,issuer:t,subject:r,transferable:a.credentialSubject.transferable,revocable:a.credentialSubject.revocable,jurisdiction:a.credentialSubject.jurisdiction}}},indexToken:{endpoint:"POST /rights/index",data:{tokenId:c.id,tokenHash:c.tokenHash,type:e,issuer:t,subject:r,issuedAt:c.issuanceDate}},notifyParties:{endpoint:"POST /notifications/right-issued",data:{tokenId:c.id,issuer:t,subject:r,rightType:e}}}}}catch(h){return{success:!1,error:h.message}}},prepareRightTokenVerification:function(e,t){t=t||{};try{var r=[],n=[];this._validateTokenStructure(e,r),this._verifyTokenSignature(e,r,t),this._validateTokenTemporal(e,r,n),this._validateRightType(e,r),t.requireJurisdiction&&this._validateJurisdiction(e,t.allowedJurisdictions,r);var i={valid:r.length===0,errors:r,warnings:n,issuerDID:e.issuer,subjectDID:e.credentialSubject?e.credentialSubject.id:null,rightType:e.credentialSubject?e.credentialSubject.rightType:null,transferable:e.credentialSubject?e.credentialSubject.transferable:null,revocable:e.credentialSubject?e.credentialSubject.revocable:null,verifiedAt:new Date().toISOString()};return{success:!0,verification:i,externalOperations:{recordVerification:{endpoint:"POST /rights/verification-record",data:{tokenId:e.id,result:i.valid,errors:r,warnings:n,verifiedAt:i.verifiedAt}},auditVerification:{endpoint:"POST /audit/right-verification",data:{tokenId:e.id,rightType:i.rightType,issuer:i.issuerDID,subject:i.subjectDID,result:i.valid,verifiedAt:i.verifiedAt}},updateTokenStatus:i.valid?{endpoint:"PUT /rights/tokens/"+e.id+"/status",data:{status:"VERIFIED",verifiedAt:i.verifiedAt}}:null}}}catch(o){return{success:!1,error:"Verification preparation failed: "+o.message}}},prepareRightTokenTransfer:function(e,t,r,n){n=n||{},Rt.checkArgument(e&&typeof e=="object","Invalid token"),Rt.checkArgument(typeof t=="string","New owner DID must be string"),Rt.checkArgument(r instanceof Dp,"Invalid current owner key");try{var i=this.prepareRightTokenVerification(e,{});if(!i.success||!i.verification.valid)return{success:!1,error:"Cannot transfer invalid token: "+i.verification.errors.join(", ")};if(!e.credentialSubject.transferable)return{success:!1,error:"Token is not transferable"};var o=e.credentialSubject&&e.credentialSubject.id,s=yx({issuer:o},{issuerPublicKey:n.currentOwnerPublicKey});if(!s)return{success:!1,error:"Cannot resolve current owner public key from token.credentialSubject.id; pass options.currentOwnerPublicKey"};if(r.toPublicKey().toString()!==s.toString())return{success:!1,error:"Unauthorized transfer: signing key does not match the current owner"};var a={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","LegalRightTransfer"],issuer:e.credentialSubject.id,issuanceDate:new Date().toISOString(),credentialSubject:{id:t,originalToken:e.id,transferFrom:e.credentialSubject.id,transferTo:t,transferDate:new Date().toISOString(),transferReason:n.reason||"ownership_transfer",consideration:n.consideration||null}},c=this._signToken(a,r),h=JSON.parse(JSON.stringify(e));h.id="urn:uuid:"+this._generateUUID(),h.issuanceDate=new Date().toISOString(),h.credentialSubject.id=t,h.credentialSubject.transferHistory=h.credentialSubject.transferHistory||[],h.credentialSubject.transferHistory.push({transferId:c.id,transferDate:c.issuanceDate,from:e.credentialSubject.id,to:t}),delete h.proof;var g=this._signToken(h,r);return{success:!0,newToken:g,transferProof:c,transferId:c.id,externalOperations:{recordTransfer:{endpoint:"POST /rights/transfers",data:{originalTokenId:e.id,newTokenId:g.id,transferProof:c,fromOwner:e.credentialSubject.id,toOwner:t,transferDate:c.issuanceDate}},updateOwnership:{endpoint:"PUT /rights/tokens/"+e.id+"/ownership",data:{newOwner:t,transferId:c.id,transferDate:c.issuanceDate,previousOwner:e.credentialSubject.id}},notifyParties:{endpoint:"POST /notifications/right-transferred",data:{originalTokenId:e.id,newTokenId:g.id,fromOwner:e.credentialSubject.id,toOwner:t,rightType:e.credentialSubject.rightType}},auditTransfer:{endpoint:"POST /audit/right-transfer",data:{originalTokenId:e.id,newTokenId:g.id,transferId:c.id,fromOwner:e.credentialSubject.id,toOwner:t,transferredAt:c.issuanceDate}}}}}catch(y){return{success:!1,error:y.message}}},prepareObligationToken:function(e,t,r,n){Rt.checkArgument(e&&typeof e=="object","Invalid right token"),Rt.checkArgument(typeof t=="string","Obligor DID must be string"),Rt.checkArgument(r&&typeof r=="object","Obligation must be object"),Rt.checkArgument(n instanceof Dp,"Invalid issuer key");try{var i={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","LegalObligationToken"],issuer:e.issuer,issuanceDate:new Date().toISOString(),credentialSubject:{id:t,obligationType:"correlative_obligation",correlativeRight:e.id,rightHolder:e.credentialSubject.id,obligation:r,jurisdiction:e.credentialSubject.jurisdiction,purpose:e.credentialSubject.purpose}},o=this._signToken(i,n);return{success:!0,obligationToken:o,correlativeRight:e.id,externalOperations:{storeObligation:{endpoint:"POST /obligations/tokens",data:{obligationToken:o,correlativeRightId:e.id,obligor:t,rightHolder:e.credentialSubject.id}},linkToRight:{endpoint:"POST /rights/tokens/"+e.id+"/obligations",data:{obligationId:o.id,obligor:t,obligationType:"correlative_obligation"}},notifyObligor:{endpoint:"POST /notifications/obligation-created",data:{obligationId:o.id,obligor:t,rightHolder:e.credentialSubject.id,correlativeRight:e.id}}}}}catch(s){return{success:!1,error:s.message}}},prepareRightTypeValidation:function(e){Rt.checkArgument(typeof e=="string","Right type must be string");var t=Object.values(hs),r=t.includes(e);return{success:!0,validation:{type:e,valid:r,availableTypes:t,category:this._categorizeRightType(e),description:this._getRightTypeDescription(e)},externalOperations:{validateType:{endpoint:"POST /rights/validate-type",data:{type:e,valid:r}}}}},_categorizeRightType:function(e){var t={PropertyTitle:"PROPERTY_RIGHT",VehicleTitle:"PROPERTY_RIGHT",IntellectualProperty:"IP_RIGHT",MusicLicense:"IP_RIGHT",SoftwareLicense:"IP_RIGHT",FinancialInstrument:"FINANCIAL_RIGHT",PromissoryNote:"FINANCIAL_RIGHT",Bond:"FINANCIAL_RIGHT",EquityShare:"FINANCIAL_RIGHT",ProfessionalLicense:"LICENSE_RIGHT",RegulatoryPermit:"LICENSE_RIGHT",AccessRight:"ACCESS_RIGHT",VotingRight:"GOVERNANCE_RIGHT",RoyaltyRight:"IP_RIGHT",UsageRight:"ACCESS_RIGHT"};return t[e]||"UNKNOWN"},_getRightTypeDescription:function(e){var t={PropertyTitle:"Legal ownership of real estate property",VehicleTitle:"Legal ownership of motor vehicle",IntellectualProperty:"Rights to intellectual property assets",MusicLicense:"License for music performance and usage",SoftwareLicense:"License for software usage and distribution",FinancialInstrument:"Rights related to financial instruments",PromissoryNote:"Promise to pay a specified amount",Bond:"Debt security representing loan",EquityShare:"Ownership stake in company",ProfessionalLicense:"License for professional practice",RegulatoryPermit:"Permit for regulated activities",AccessRight:"Right to access resources or locations",VotingRight:"Right to participate in governance",RoyaltyRight:"Right to receive royalty payments",UsageRight:"Right to use specific assets or services"};return t[e]||"Unknown right type"},getRightTypes:function(){return hs},verifyToken:function(e,t){var r=[];try{if(Rt.checkArgument(e&&typeof e=="object","Invalid token"),!e.proof||!e.proof.jws)return r.push("Missing signature proof"),{valid:!1,errors:r};var n=t instanceof Va?t:Va.fromString(t),i=this._canonicalizeToken(e),o=Cp.sha256(d.Buffer.from(i));if(e.tokenHash&&e.tokenHash!==o.toString("hex"))return r.push("Token hash mismatch"),{valid:!1,errors:r};var s=e.proof.jws.split(".");if(s.length!==3||!s[2])return r.push("Malformed JWS"),{valid:!1,errors:r};var a=gx.fromDER(d.Buffer.from(s[2],"base64url")),c=new Lp;return c.hashbuf=o,c.sig=a,c.pubkey=n,c.verify()||r.push("Signature verification failed"),{valid:r.length===0,errors:r,tokenHash:o.toString("hex"),verifiedAt:new Date().toISOString()}}catch(h){return r.push(h.message),{valid:!1,errors:r}}},_signToken:function(e,t){var r=this._canonicalizeToken(e),n=Cp.sha256(d.Buffer.from(r)),i=new Lp;i.hashbuf=n,i.privkey=t,i.pubkey=t.toPublicKey(),i.sign();var o=i.sig,s={type:"EcdsaSecp256k1Signature2019",created:new Date().toISOString(),verificationMethod:"did:smartledger:"+t.toPublicKey().toString()+"#keys-1",proofPurpose:"assertionMethod",jws:this._createJWS(n,o)},a=JSON.parse(JSON.stringify(e));return a.proof=s,a.tokenHash=n.toString("hex"),a},_createJWS:function(e,t){var r={alg:"ES256K",typ:"JWT"},n=d.Buffer.from(JSON.stringify(r)).toString("base64url"),i=t.toDER().toString("base64url");return n+".."+i},_canonicalizeToken:function(e){var t=JSON.parse(JSON.stringify(e));return delete t.proof,delete t.tokenHash,JSON.stringify(this._sortObjectKeys(t))},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e},_validateTokenStructure:function(e,t){e["@context"]||t.push("Missing @context"),e.id||t.push("Missing id"),(!e.type||!Array.isArray(e.type))&&t.push("Missing or invalid type"),e.issuer||t.push("Missing issuer"),e.issuanceDate||t.push("Missing issuanceDate"),e.credentialSubject||t.push("Missing credentialSubject"),e.proof||t.push("Missing proof")},_verifyTokenSignature:function(e,t,r){try{if(!e.proof||!e.proof.jws){t.push("Missing signature proof");return}var n=this._canonicalizeToken(e),i=Cp.sha256(d.Buffer.from(n));if(e.tokenHash&&e.tokenHash!==i.toString("hex")){t.push("Token hash mismatch");return}var o=yx(e,r);if(!o){t.push("Signature not verified: issuer public key could not be resolved from token.issuer; pass options.issuerPublicKey");return}var s=e.proof.jws.split(".");if(s.length!==3||!s[2]){t.push("Malformed JWS");return}var a=gx.fromDER(d.Buffer.from(s[2],"base64url")),c=new Lp;c.hashbuf=i,c.sig=a,c.pubkey=o,c.verify()!==!0&&t.push("Signature verification failed")}catch(h){t.push("Signature verification failed: "+h.message)}},_validateTokenTemporal:function(e,t,r){var n=new Date,i=new Date(e.issuanceDate);if(i>n&&t.push("Token issued in the future"),e.credentialSubject.validFrom){var o=new Date(e.credentialSubject.validFrom);n<o&&r.push("Token not yet valid")}if(e.credentialSubject.validUntil){var s=new Date(e.credentialSubject.validUntil);n>s&&t.push("Token expired")}},_validateRightType:function(e,t){if(!e.credentialSubject.rightType){t.push("Missing rightType");return}var r=Object.values(hs);r.includes(e.credentialSubject.rightType)||t.push("Invalid right type: "+e.credentialSubject.rightType)},_validateJurisdiction:function(e,t,r){if(!e.credentialSubject.jurisdiction){r.push("Missing jurisdiction");return}t&&Array.isArray(t)&&(t.includes(e.credentialSubject.jurisdiction)||r.push("Jurisdiction not allowed: "+e.credentialSubject.jurisdiction))},_generateUUID:function(){return Rk.uuid4()}};mx.RightTypes=hs;vx.exports=mx});var Sx=P((O5,_x)=>{"use strict";m();var Ga=Qt(),yr=ke(),Tk=Ka(),ao={PropertyTitle:{title:"Property Title",description:"Real estate property ownership title",type:"object",required:["propertyId","address","ownershipType"],properties:{propertyId:{type:"string",description:"Unique property identifier"},address:{type:"object",required:["street","city","state","country"],properties:{street:{type:"string"},city:{type:"string"},state:{type:"string"},country:{type:"string"},postalCode:{type:"string"}}},ownershipType:{type:"string",enum:["fee_simple","leasehold","joint_tenancy","tenancy_in_common"]},titleNumber:{type:"string"},registeredDate:{type:"string",format:"date-time"},legalDescription:{type:"string"},encumbrances:{type:"array",items:{type:"object",properties:{type:{type:"string"},amount:{type:"number"},description:{type:"string"}}}}}},VehicleTitle:{title:"Vehicle Title",description:"Motor vehicle ownership title",type:"object",required:["vin","make","model","year"],properties:{vin:{type:"string",pattern:"^[A-HJ-NPR-Z0-9]{17}$",description:"Vehicle Identification Number"},make:{type:"string"},model:{type:"string"},year:{type:"integer",minimum:1900,maximum:2030},titleNumber:{type:"string"},registeredState:{type:"string"},mileage:{type:"integer",minimum:0},color:{type:"string"},fuelType:{type:"string",enum:["gasoline","diesel","electric","hybrid","other"]},liens:{type:"array",items:{type:"object",properties:{lienholderName:{type:"string"},lienAmount:{type:"number"},lienDate:{type:"string",format:"date"}}}}}},PromissoryNote:{title:"Promissory Note",description:"Legal promise to pay a specified amount",type:"object",required:["principal","interestRate","maturityDate","borrower","lender"],properties:{principalAmount:{type:"number",minimum:0,description:"Principal amount in base currency units"},currency:{type:"string",default:"USD"},interestRate:{type:"number",minimum:0,maximum:100,description:"Annual interest rate percentage"},maturityDate:{type:"string",format:"date",description:"Date when principal and interest are due"},payee:{type:"string",description:"DID of the payee (creditor)"},payor:{type:"string",description:"DID of the payor (debtor)"},paymentSchedule:{type:"string",enum:["lump_sum","monthly","quarterly","annually"]},collateral:{type:"array",items:{type:"object",properties:{description:{type:"string"},value:{type:"number"},type:{type:"string"}}}},defaultProvisions:{type:"string"},governingLaw:{type:"string"}}},IntellectualProperty:{title:"Intellectual Property",description:"Intellectual property rights and licensing",type:"object",required:["ipType","title","registrationNumber"],properties:{ipType:{type:"string",enum:["patent","trademark","copyright","trade_secret"]},title:{type:"string"},creator:{type:"string",description:"Creator DID"},registrationNumber:{type:"string"},registrationDate:{type:"string",format:"date"},expirationDate:{type:"string",format:"date"},jurisdiction:{type:"string"},description:{type:"string"},claims:{type:"array",items:{type:"string"}},priorArt:{type:"array",items:{type:"object",properties:{reference:{type:"string"},date:{type:"string",format:"date"},relevance:{type:"string"}}}}}},ProfessionalLicense:{title:"Professional License",description:"Professional practice license or certification",type:"object",required:["licenseType","licenseNumber","issuingAuthority","expirationDate"],properties:{licenseType:{type:"string"},licenseNumber:{type:"string"},issuingAuthority:{type:"string"},licensee:{type:"string",description:"Licensee DID"},issueDate:{type:"string",format:"date"},expirationDate:{type:"string",format:"date"},renewalDate:{type:"string",format:"date"},jurisdiction:{type:"string"},scope:{type:"string"},restrictions:{type:"array",items:{type:"string"}},continuing_education:{type:"object",properties:{hours_required:{type:"integer"},deadline:{type:"string",format:"date"},completed_hours:{type:"integer"}}}}},MusicLicense:{title:"Music License",description:"Music performance and usage licensing",type:"object",required:["songTitle","artist","licenseType","royaltyRate"],properties:{workTitle:{type:"string"},composer:{type:"string",description:"Composer DID"},performer:{type:"string",description:"Performer DID"},licenseType:{type:"string",enum:["mechanical","performance","synchronization","master_use"]},territory:{type:"string"},duration:{type:"string"},royaltyRate:{type:"number",minimum:0,maximum:100},advancePayment:{type:"number",minimum:0},exclusivity:{type:"boolean"},mediaTypes:{type:"array",items:{type:"string",enum:["cd","vinyl","digital","streaming","broadcast","film","tv"]}},usage_restrictions:{type:"string"},copyrightNotice:{type:"string"}}}},Pk={prepareClaimValidation:function(e,t){try{yr.checkArgument(e&&typeof e=="object","Invalid claim"),yr.checkArgument(typeof t=="string","Schema name must be string");var r=ao[t];if(!r)return{success:!1,error:"Unknown schema: "+t};var n=[],i=[];this._validateObject(e,r,"",n,i);var o={valid:n.length===0,errors:n,warnings:i,schema:t,claimHash:this.hash(e),canonical:this.canonicalize(e)};return{success:!0,validation:o,claim:e,schema:r,externalOperations:{store:{endpoint:"POST /claims/validate",data:{claim:e,validation:o,schema:t}},index:{endpoint:"POST /claims/index",data:{claimHash:o.claimHash,schemaName:t,valid:o.valid}}}}}catch(s){return{success:!1,error:"Validation preparation failed: "+s.message}}},prepareClaimAttestation:function(e,t,r){try{yr.checkArgument(e&&typeof e=="object","Invalid claim"),yr.checkArgument(typeof t=="string","Schema name must be string"),yr.checkArgument(r&&typeof r=="object","Invalid attestor");var n=this.prepareClaimValidation(e,t);if(!n.success||!n.validation.valid)return{success:!1,error:"Cannot attest invalid claim",validation:n};var i={type:"LTP_CLAIM_ATTESTATION",claimHash:n.validation.claimHash,schemaName:t,attestor:{did:r.did||r.id,name:r.name||"Unknown",authority:r.authority||null,jurisdiction:r.jurisdiction||null},attestedAt:new Date().toISOString(),confidence:r.confidence||100,evidence:r.evidence||null,notes:r.notes||null},o=Ga.sha256(d.Buffer.from(this.canonicalize(i))).toString("hex");return i.attestationHash=o,{success:!0,attestation:i,claim:e,validation:n.validation,externalOperations:{storeAttestation:{endpoint:"POST /claims/"+n.validation.claimHash+"/attestations",data:i},notifyStakeholders:{endpoint:"POST /notifications/claim-attested",data:{claimHash:n.validation.claimHash,attestorDid:i.attestor.did,attestationHash:o}}}}}catch(s){return{success:!1,error:"Attestation preparation failed: "+s.message}}},prepareClaimDispute:function(e,t,r){try{yr.checkArgument(typeof e=="string","Claim hash must be string"),yr.checkArgument(t&&typeof t=="object","Invalid disputant"),yr.checkArgument(r&&typeof r=="object","Invalid dispute");var n={type:"LTP_CLAIM_DISPUTE",claimHash:e,disputant:{did:t.did||t.id,name:t.name||"Unknown",jurisdiction:t.jurisdiction||null},dispute:{reason:r.reason||"UNSPECIFIED",category:r.category||"ACCURACY",description:r.description||"",evidence:r.evidence||null,requestedAction:r.requestedAction||"REVIEW"},disputedAt:new Date().toISOString(),status:"FILED",priority:r.priority||"NORMAL"},i=Ga.sha256(d.Buffer.from(this.canonicalize(n))).toString("hex");return n.disputeHash=i,{success:!0,dispute:n,disputeId:this._generateDisputeId(e),externalOperations:{fileDispute:{endpoint:"POST /claims/"+e+"/disputes",data:n},notifyStakeholders:{endpoint:"POST /notifications/claim-disputed",data:{claimHash:e,disputantDid:n.disputant.did,disputeHash:i}},escalate:{endpoint:"POST /disputes/escalate",data:{disputeHash:i,priority:n.priority}}}}}catch(o){return{success:!1,error:"Dispute preparation failed: "+o.message}}},prepareBulkClaimValidation:function(e,t){try{yr.checkArgument(Array.isArray(e),"Claims must be array"),yr.checkArgument(typeof t=="string","Schema name must be string");var r=[],n=[],i=0;e.forEach(function(a,c){try{var h=this.prepareClaimValidation(a,t);h.success&&h.validation.valid&&i++,r.push({index:c,result:h})}catch(g){n.push({index:c,error:g.message})}}.bind(this));var o=this._generateBatchId(),s=Ga.sha256(d.Buffer.from(JSON.stringify(r.map(a=>a.result.validation.claimHash)))).toString("hex");return{success:!0,batchId:o,batchHash:s,totalClaims:e.length,validClaims:i,invalidClaims:e.length-i,validations:r,errors:n,externalOperations:{storeBatch:{endpoint:"POST /claims/batch-validate",data:{batchId:o,batchHash:s,schemaName:t,validations:r}},generateReport:{endpoint:"POST /reports/bulk-validation",data:{batchId:o,summary:{total:e.length,valid:i,invalid:e.length-i}}}}}}catch(a){return{success:!1,error:"Bulk validation preparation failed: "+a.message}}},canonicalize:function(e){yr.checkArgument(e&&typeof e=="object","Invalid claim");var t=this._sortObjectKeys(e);return JSON.stringify(t)},hash:function(e){var t=this.canonicalize(e);return Ga.sha256(d.Buffer.from(t)).toString("hex")},prepareClaimTemplate:function(e,t){t=t||{};try{var r=ao[e];if(!r)return{success:!1,error:"Unknown schema: "+e};var n=this._createTemplateFromSchema(r),i=this._generateFormStructure(r);return{success:!0,schemaName:e,template:n,schema:r,formStructure:i,validation:{required:r.required||[],patterns:this._extractPatterns(r),enums:this._extractEnums(r)},externalOperations:{generateForm:{endpoint:"POST /forms/generate",data:{schemaName:e,formStructure:i,template:n}},saveTemplate:{endpoint:"POST /templates/claim",data:{schemaName:e,template:n,customizations:t.customizations||{}}}}}}catch(o){return{success:!1,error:"Template preparation failed: "+o.message}}},getSchemas:function(){return ao},getSchemaNames:function(){return Object.keys(ao)},getSchema:function(e){return ao[e]||null},addSchema:function(e,t){yr.checkArgument(typeof e=="string","Schema name must be string"),yr.checkArgument(t&&typeof t=="object","Invalid schema"),ao[e]=t},createTemplate:function(e){var t=ao[e];if(!t)throw new Error("Unknown schema: "+e);return this._createTemplateFromSchema(t)},_generateDisputeId:function(e){var t="dispute_"+e+"_"+Date.now();return Ga.sha256(d.Buffer.from(t)).toString("hex").substring(0,16)},_generateBatchId:function(){return Tk.randomHex(16)},_generateFormStructure:function(e){var t={type:"form",title:e.title||"Legal Claim Form",description:e.description||"",fields:[]};return e.properties&&Object.keys(e.properties).forEach(function(r){var n=e.properties[r],i={name:r,label:this._humanizeFieldName(r),type:this._mapSchemaTypeToFormType(n),required:e.required&&e.required.includes(r),validation:this._extractFieldValidation(n)};n.enum&&(i.options=n.enum.map(function(o){return{value:o,label:this._humanizeValue(o)}}.bind(this))),t.fields.push(i)}.bind(this)),t},_extractPatterns:function(e){var t={};return e.properties&&Object.keys(e.properties).forEach(function(r){var n=e.properties[r];n.pattern&&(t[r]=n.pattern)}),t},_extractEnums:function(e){var t={};return e.properties&&Object.keys(e.properties).forEach(function(r){var n=e.properties[r];n.enum&&(t[r]=n.enum)}),t},_mapSchemaTypeToFormType:function(e){switch(e.type){case"string":return e.enum?"select":e.format==="date"?"date":e.format==="date-time"?"datetime":"text";case"number":case"integer":return"number";case"boolean":return"checkbox";case"array":return"list";case"object":return"fieldset";default:return"text"}},_extractFieldValidation:function(e){var t={};return e.pattern&&(t.pattern=e.pattern),e.minimum!==void 0&&(t.min=e.minimum),e.maximum!==void 0&&(t.max=e.maximum),e.format&&(t.format=e.format),t},_humanizeFieldName:function(e){return e.replace(/([A-Z])/g," $1").replace(/^./,function(t){return t.toUpperCase()}).replace(/_/g," ")},_humanizeValue:function(e){return e.replace(/_/g," ").replace(/\b\w/g,function(t){return t.toUpperCase()})},_validateObject:function(e,t,r,n,i){t.type==="object"?(t.required&&Array.isArray(t.required)&&t.required.forEach(function(o){e.hasOwnProperty(o)||n.push("Missing required field: "+this._getFieldPath(r,o))}.bind(this)),t.properties&&Object.keys(e).forEach(function(o){var s=this._getFieldPath(r,o),a=t.properties[o];a?this._validateValue(e[o],a,s,n,i):i.push("Unknown field: "+s)}.bind(this))):this._validateValue(e,t,r,n,i)},_validateValue:function(e,t,r,n,i){if(t.type){var o=Array.isArray(e)?"array":typeof e;if(o!==t.type){n.push("Invalid type for "+r+": expected "+t.type+", got "+o);return}}if(t.type==="string"&&(t.pattern&&!new RegExp(t.pattern).test(e)&&n.push("Value does not match pattern for "+r),t.enum&&!t.enum.includes(e)&&n.push("Invalid enum value for "+r+": "+e),t.format==="date"&&!this._isValidDate(e)&&n.push("Invalid date format for "+r),t.format==="date-time"&&!this._isValidDateTime(e)&&n.push("Invalid date-time format for "+r)),(t.type==="number"||t.type==="integer")&&(t.minimum!==void 0&&e<t.minimum&&n.push("Value below minimum for "+r+": "+e+" < "+t.minimum),t.maximum!==void 0&&e>t.maximum&&n.push("Value above maximum for "+r+": "+e+" > "+t.maximum),t.type==="integer"&&!Number.isInteger(e)&&n.push("Value must be integer for "+r)),t.type==="array"&&t.items)for(var s=0;s<e.length;s++)this._validateValue(e[s],t.items,r+"["+s+"]",n,i);t.type==="object"&&this._validateObject(e,t,r,n,i)},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e},_createTemplateFromSchema:function(e){if(e.type==="object"){var t={};return e.properties&&Object.keys(e.properties).forEach(function(r){var n=e.properties[r];t[r]=this._getDefaultValue(n)}.bind(this)),t}return this._getDefaultValue(e)},_getDefaultValue:function(e){if(e.default!==void 0)return e.default;switch(e.type){case"string":return e.enum?e.enum[0]:e.format==="date"?"2023-01-01":e.format==="date-time"?new Date().toISOString():"PLACEHOLDER_STRING";case"number":case"integer":return e.minimum||0;case"boolean":return!1;case"array":return[];case"object":return this._createTemplateFromSchema(e);default:return null}},_getFieldPath:function(e,t){return e?e+"."+t:t},_isValidDate:function(e){var t=new Date(e);return!isNaN(t.getTime())&&e.match(/^\d{4}-\d{2}-\d{2}$/)},_isValidDateTime:function(e){var t=new Date(e);return!isNaN(t.getTime())}};_x.exports=Pk});var Ex=P((T5,wx)=>{"use strict";m();var za=Qt(),ds=ke(),Bk={prepareTokenCommitment:function(e,t){t=t||{},ds.checkArgument(e&&typeof e=="object","Invalid token");try{var r=this._createCommitment(e,t),n=this._formatOpReturn(r,t),i=this._createTxTemplate(n,t);return{success:!0,commitment:r,opReturnData:n,txTemplate:i,preparedAt:new Date().toISOString(),metadata:{tokenId:e.id,purpose:t.purpose||"legal_token_anchor",version:"LTP.v1"}}}catch(o){return{success:!1,error:o.message}}},prepareBatchCommitment:function(e,t){t=t||{},ds.checkArgument(Array.isArray(e),"Tokens must be array");try{var r=this._createBatchCommitment(e,t),n=this._formatOpReturn(r,t),i=this._createTxTemplate(n,t);return{success:!0,batchCommitment:r,opReturnData:n,txTemplate:i,tokenCount:e.length,preparedAt:new Date().toISOString(),metadata:{purpose:t.purpose||"legal_token_batch_anchor",version:"LTP.v1"}}}catch(o){return{success:!1,error:o.message}}},verifyTokenAnchor:function(e,t,r){ds.checkArgument(e&&typeof e=="object","Invalid token"),ds.checkArgument(typeof t=="string","Transaction ID must be string");try{var n=this._createCommitment(e,{}),i=this._extractOpReturn(r);if(!i)return{valid:!1,error:"No OP_RETURN data found in transaction"};var o=this._verifyCommitment(n,i);return{valid:o,chainVerified:!1,txid:t,commitment:n,anchorData:i,verifiedAt:new Date().toISOString()}}catch(s){return{valid:!1,error:s.message}}},formatRevocation:function(e,t){ds.checkArgument(typeof e=="string","Token ID must be string"),ds.checkArgument(t&&typeof t=="object","Invalid revocation data");try{var r={type:"LTP_REVOCATION",tokenId:e,reason:t.reason||"UNSPECIFIED",revokedBy:t.revokedBy||"UNKNOWN",revokedAt:new Date().toISOString(),effectiveDate:t.effectiveDate||new Date().toISOString(),legalBasis:t.legalBasis||null,evidence:t.evidence||null},n=za.sha256(d.Buffer.from(JSON.stringify(r))).toString("hex");return{success:!0,revocation:r,revocationHash:n,opReturnData:this._formatOpReturn({hash:n,type:"REVOCATION"},{})}}catch(i){return{success:!1,error:i.message}}},_createCommitment:function(e,t){var r=this._canonicalizeToken(e),n={type:"LTP_TOKEN",tokenHash:za.sha256(d.Buffer.from(r)).toString("hex"),tokenId:e.id,timestamp:new Date().toISOString(),purpose:t.purpose||"legal_token"},i=za.sha256(d.Buffer.from(JSON.stringify(n))).toString("hex");return{hash:i,data:n,canonical:r}},_createBatchCommitment:function(e,t){var r=[],n=[];e.forEach(function(a){var c=this._createCommitment(a,t);r.push(c.hash),n.push(a.id)}.bind(this));var i=this._createMerkleRoot(r),o={type:"LTP_BATCH",merkleRoot:i,tokenCount:e.length,tokenIds:n,timestamp:new Date().toISOString(),purpose:t.purpose||"batch_anchor"},s=za.sha256(d.Buffer.from(JSON.stringify(o))).toString("hex");return{hash:s,data:o,merkleRoot:i,tokenHashes:r}},_formatOpReturn:function(e,t){var r=t.prefix||"LTP.v1",n=e.hash;return{prefix:r,data:n,full:r+"."+n,bytes:d.Buffer.from(r+"."+n,"utf8"),size:d.Buffer.from(r+"."+n,"utf8").length}},_createTxTemplate:function(e,t){try{var r={version:1,inputs:[],outputs:[{satoshis:0,script:"OP_RETURN "+e.data}],locktime:0};return t.feeOutput&&r.outputs.push(t.feeOutput),{template:r,opReturn:e,estimatedSize:this._estimateSize(r),instructions:{step1:"Add input UTXOs to cover fees",step2:"Add change output if needed",step3:"Sign transaction with appropriate keys",step4:"Broadcast to BSV network"}}}catch(n){throw new Error("Failed to create transaction template: "+n.message)}},_extractOpReturn:function(e){try{if(!e||!e.outputs)return null;for(var t=0;t<e.outputs.length;t++){var r=e.outputs[t];if(r.script&&r.script.startsWith("OP_RETURN")){var n=r.script.replace("OP_RETURN ","");return{raw:n,decoded:d.Buffer.from(n,"hex").toString("utf8")}}}return null}catch{return null}},_verifyCommitment:function(e,t){try{return!t||!t.decoded?!1:t.decoded.includes(e.hash)}catch{return!1}},_canonicalizeToken:function(e){var t=JSON.parse(JSON.stringify(e));return delete t.proof,delete t.tokenHash,delete t.anchorTx,delete t.anchorBlock,JSON.stringify(this._sortObjectKeys(t))},_createMerkleRoot:function(e){if(e.length===0)return null;if(e.length===1)return e[0];for(var t=e.slice();t.length>1;){for(var r=[],n=0;n<t.length;n+=2){var i=t[n],o=t[n+1]||i,s=d.Buffer.concat([d.Buffer.from(i,"hex"),d.Buffer.from(o,"hex")]),a=za.sha256(s).toString("hex");r.push(a)}t=r}return t[0]},_estimateSize:function(e){var t=10,r=e.outputs.length*34,n=148;return{base:t+r,withOneInput:t+r+n,bytesPerInput:n}},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e}};wx.exports=Bk});var Ax=P((B5,Ix)=>{"use strict";m();var Nk=Tr(),Yr=Qt(),xx=ka(),Mk=ir(),kk=io(),or=ke(),Ck={prepareSignatureProof:function(e,t,r){r=r||{},or.checkArgument(e&&typeof e=="object","Invalid token"),or.checkArgument(t instanceof kk,"Invalid private key");try{var n=this._canonicalizeForSigning(e),i=Yr.sha256(d.Buffer.from(n)),o=new xx;o.hashbuf=i,o.privkey=t,o.pubkey=t.toPublicKey(),o.sign();var s=o.sig,a={type:"EcdsaSecp256k1Signature2019",created:new Date().toISOString(),verificationMethod:"did:smartledger:"+t.toPublicKey().toString()+"#keys-1",proofPurpose:r.purpose||"assertionMethod",jws:this._createJWS(i,s),proofValue:s.toDER().toString("hex")};return{success:!0,proof:a,tokenHash:i.toString("hex"),canonical:n,signingKey:{publicKey:t.toPublicKey().toString(),keyId:"did:smartledger:"+t.toPublicKey().toString()+"#keys-1"},externalOperations:{storeProof:{endpoint:"POST /proofs/signature",data:{tokenHash:i.toString("hex"),proof:a,signingKey:t.toPublicKey().toString()}},verifyProof:{endpoint:"POST /proofs/verify-signature",data:{tokenHash:i.toString("hex"),signature:s.toDER().toString("hex"),publicKey:t.toPublicKey().toString()}}}}}catch(c){return{success:!1,error:c.message}}},prepareSignatureVerification:function(e,t){try{if(or.checkArgument(e&&typeof e=="object","Invalid token"),or.checkArgument(typeof t=="string","Public key must be string"),!e.proof)return{success:!1,error:"No proof found in token"};var r=this._canonicalizeForSigning(e),n=Yr.sha256(d.Buffer.from(r)),i=Mk.fromDER(d.Buffer.from(e.proof.proofValue,"hex")),o={tokenHash:n.toString("hex"),signature:i.toDER().toString("hex"),publicKey:t,proof:e.proof,canonical:r},s=new xx;s.hashbuf=n,s.sig=i,s.pubkey=Nk.fromString(t);var a=s.verify()===!0;return{success:!0,verification:{valid:a,tokenHash:n.toString("hex"),signatureValid:a,publicKey:t,verifiedAt:new Date().toISOString()},verificationData:o,externalOperations:{recordVerification:{endpoint:"POST /proofs/verification-record",data:{tokenHash:n.toString("hex"),result:a,publicKey:t,verifiedAt:new Date().toISOString()}},auditVerification:{endpoint:"POST /audit/proof-verification",data:{tokenId:e.id,proofType:e.proof.type,result:a,verifier:t}}}}}catch(c){return{success:!1,error:c.message}}},prepareSelectiveDisclosure:function(e,t,r){or.checkArgument(e&&typeof e=="object","Invalid token"),or.checkArgument(Array.isArray(t),"Revealed fields must be array"),or.checkArgument(typeof r=="string","Nonce must be string");try{var n=this._createFieldCommitments(e,r),i=this._createMerkleTree(n),o=[],s=[];t.forEach(function(c){var h=this._getNestedValue(e,c),g=this._findFieldCommitment(n,c);if(g){o.push({path:c,value:h,commitment:g.hash,salt:g.salt});var y=this._generateMerkleProof(i,g.index);s.push({path:c,leafIndex:g.index,proof:y})}}.bind(this));var a={type:"LegalTokenSelectiveDisclosure",created:new Date().toISOString(),proofPurpose:"selectiveDisclosure",verificationMethod:e.proof?e.proof.verificationMethod:null,nonce:r,merkleRoot:i.root,disclosures:o,merkleProofs:s,totalFields:n.length};return{success:!0,proof:a,hiddenFieldCount:n.length-o.length,revealedFieldCount:o.length,externalOperations:{storeDisclosure:{endpoint:"POST /proofs/selective-disclosure",data:{tokenId:e.id,proof:a,merkleRoot:i.root}},verifyDisclosure:{endpoint:"POST /proofs/verify-disclosure",data:{proof:a,expectedNonce:r}},auditDisclosure:{endpoint:"POST /audit/selective-disclosure",data:{tokenId:e.id,revealedFields:t,totalFields:n.length,disclosedAt:new Date().toISOString()}}}}}catch(c){return{success:!1,error:c.message}}},prepareSelectiveDisclosureVerification:function(e,t){try{if(or.checkArgument(e&&typeof e=="object","Invalid proof"),or.checkArgument(typeof t=="string","Expected nonce must be string"),e.nonce!==t)return{success:!1,error:"Nonce mismatch"};var r=[],n=[];e.disclosures.forEach(function(o,s){var a=e.merkleProofs[s],c=this._hashField(o.path,o.value,o.salt);if(c!==o.commitment){n.push("Invalid commitment for field: "+o.path);return}var h=this._verifyMerkleProof(o.commitment,a.leafIndex,a.proof,e.merkleRoot);h?r.push({path:o.path,value:o.value,verified:!0}):n.push("Invalid Merkle proof for field: "+o.path)}.bind(this));var i={valid:n.length===0,errors:n,disclosures:r,merkleRoot:e.merkleRoot,totalFields:e.totalFields,verifiedAt:new Date().toISOString()};return{success:!0,verification:i,externalOperations:{recordVerification:{endpoint:"POST /proofs/disclosure-verification",data:{proofId:e.id||"unknown",result:i.valid,verifiedFields:r.length,totalFields:e.totalFields,verifiedAt:i.verifiedAt}},auditVerification:{endpoint:"POST /audit/disclosure-verification",data:{merkleRoot:e.merkleRoot,disclosuresVerified:r.length,errors:n.length,result:i.valid}}}}}catch(o){return{success:!1,error:o.message}}},prepareLegalValidityProof:function(e,t,r){or.checkArgument(e&&typeof e=="object","Invalid token"),or.checkArgument(t&&typeof t=="object","Invalid jurisdiction"),or.checkArgument(typeof r=="string","Nonce must be string");try{var n=t.requirements||[],i=[],o=!0;n.forEach(function(a){var c=this._checkLegalRequirement(e,a);i.push(c),c.satisfied||(o=!1)}.bind(this));var s={type:"LegalValidityProof",created:new Date().toISOString(),proofPurpose:"legalValidity",jurisdiction:t.code,nonce:r,valid:o,checks:i,complianceHash:this._hashCompliance(e,t,r)};return{success:!0,proof:s,valid:o,complianceReport:{jurisdiction:t.code,totalRequirements:n.length,satisfiedRequirements:i.filter(a=>a.satisfied).length,failedRequirements:i.filter(a=>!a.satisfied).length,overallCompliance:o},externalOperations:{submitCompliance:{endpoint:"POST /compliance/legal-validity",data:{tokenId:e.id,jurisdiction:t.code,proof:s,complianceReport:{jurisdiction:t.code,totalRequirements:n.length,satisfiedRequirements:i.filter(a=>a.satisfied).length,failedRequirements:i.filter(a=>!a.satisfied).length,overallCompliance:o}}},auditCompliance:{endpoint:"POST /audit/compliance-check",data:{tokenId:e.id,jurisdiction:t.code,result:o,checkedAt:new Date().toISOString(),requirements:i}},notifyRegulator:o?null:{endpoint:"POST /notifications/compliance-failure",data:{tokenId:e.id,jurisdiction:t.code,failedRequirements:i.filter(a=>!a.satisfied)}}}}}catch(a){return{success:!1,error:a.message}}},prepareZeroKnowledgeProof:function(e,t,r){or.checkArgument(e&&typeof e=="object","Invalid token"),or.checkArgument(t&&typeof t=="object","Invalid statement"),or.checkArgument(typeof r=="string","Nonce must be string");try{var n=Yr.sha256(d.Buffer.from(this._canonicalizeForSigning(e)+r)).toString("hex"),i={type:"LegalTokenZKProof",created:new Date().toISOString(),proofPurpose:"zeroKnowledge",statement:{claim:t.claim||"UNSPECIFIED",predicate:t.predicate||"SATISFIES",threshold:t.threshold||null},commitment:n,nonce:r,proofData:this._generateZKProofData(e,t,r)};return{success:!0,proof:i,commitment:n,externalOperations:{storeZKProof:{endpoint:"POST /proofs/zero-knowledge",data:{tokenId:e.id,proof:i,statement:t}},verifyZKProof:{endpoint:"POST /proofs/verify-zk",data:{proof:i,expectedNonce:r}},auditZKProof:{endpoint:"POST /audit/zk-proof",data:{tokenId:e.id,statement:t.claim,proofGenerated:new Date().toISOString()}}}}}catch(o){return{success:!1,error:o.message}}},_generateZKProofData:function(e,t,r){var n={challenge:Yr.sha256(d.Buffer.from(t.claim+r)).toString("hex"),response:Yr.sha256(d.Buffer.from(this._canonicalizeForSigning(e)+t.claim)).toString("hex"),witness:Yr.sha256(d.Buffer.from(r+e.id+t.predicate)).toString("hex")};return n},_createJWS:function(e,t){var r={alg:"ES256K",typ:"JWT"},n=d.Buffer.from(JSON.stringify(r)).toString("base64url"),i=e.toString("base64url"),o=t.toDER().toString("base64url");return n+".."+o},_canonicalizeForSigning:function(e){var t=JSON.parse(JSON.stringify(e));delete t.proof,delete t.tokenHash;var r=this._sortObjectKeys(t);return JSON.stringify(r)},_createFieldCommitments:function(e,t){var r=[],n=0;return this._traverseObject(e,"",function(i,o){if(i!=="proof"&&i!=="tokenHash"){var s=Yr.sha256(d.Buffer.from(t+i+n)).toString("hex"),a=this._hashField(i,o,s);r.push({path:i,value:o,salt:s,hash:a,index:n}),n++}}.bind(this)),r},_hashField:function(e,t,r){var n=e+":"+JSON.stringify(t)+":"+r;return Yr.sha256(d.Buffer.from(n)).toString("hex")},_createMerkleTree:function(e){var t=e.map(function(g){return g.hash});if(t.length===0)return{root:null,levels:[]};for(var r=[t],n=t;n.length>1;){for(var i=[],o=0;o<n.length;o+=2){var s=n[o],a=n[o+1]||s,c=d.Buffer.concat([d.Buffer.from(s,"hex"),d.Buffer.from(a,"hex")]),h=Yr.sha256(c).toString("hex");i.push(h)}r.push(i),n=i}return{root:n[0],levels:r}},_generateMerkleProof:function(e,t){for(var r=[],n=t,i=0;i<e.levels.length-1;i++){var o=e.levels[i],s=n%2===0,a=s?n+1:n-1;a<o.length&&r.push({hash:o[a],isLeft:!s}),n=Math.floor(n/2)}return r},_verifyMerkleProof:function(e,t,r,n){for(var i=e,o=t,s=0;s<r.length;s++){var a=r[s],c=o%2===0,h;a.isLeft?h=d.Buffer.concat([d.Buffer.from(a.hash,"hex"),d.Buffer.from(i,"hex")]):h=d.Buffer.concat([d.Buffer.from(i,"hex"),d.Buffer.from(a.hash,"hex")]),i=Yr.sha256(h).toString("hex"),o=Math.floor(o/2)}return i===n},_traverseObject:function(e,t,r){Array.isArray(e)?e.forEach(function(n,i){var o=t+"["+i+"]";this._traverseObject(n,o,r)}.bind(this)):e!==null&&typeof e=="object"?Object.keys(e).forEach(function(n){var i=t?t+"."+n:n;this._traverseObject(e[n],i,r)}.bind(this)):r(t,e)},_getNestedValue:function(e,t){return t.split(".").reduce(function(r,n){return r&&r[n]},e)},_findFieldCommitment:function(e,t){return e.find(function(r){return r.path===t})},_checkLegalRequirement:function(e,t){switch(t.type){case"field_present":var r=this._getNestedValue(e,t.field);return{requirement:t.type,field:t.field,satisfied:r!=null};case"field_value":var r=this._getNestedValue(e,t.field);return{requirement:t.type,field:t.field,satisfied:r===t.expectedValue};case"temporal_validity":var n=new Date,i=new Date(e.issuanceDate);return{requirement:t.type,satisfied:i<=n};default:return{requirement:t.type,satisfied:!1,error:"Unknown requirement type"}}},_hashCompliance:function(e,t,r){var n={tokenId:e.id,jurisdiction:t.code,nonce:r,timestamp:new Date().toISOString()};return Yr.sha256(d.Buffer.from(JSON.stringify(n))).toString("hex")},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e}};Ix.exports=Ck});var Tx=P((C5,Rx)=>{"use strict";m();var Wa=Qt(),M5=no(),k5=Op(),cr=ke(),Ox=Ka(),Lk={prepareRegistry:function(e){e=e||{},cr.checkArgument(typeof e=="object","Config must be object");var t={id:e.id||this._generateRegistryId(),name:e.name||"Legal Token Registry",jurisdiction:e.jurisdiction||"GLOBAL",authority:e.authority||null,created:new Date().toISOString(),version:"1.0.0",config:{allowPublicRegistration:e.allowPublicRegistration||!1,requireApproval:e.requireApproval||!0,enableRevocation:e.enableRevocation!==!1,enableAuditTrail:e.enableAuditTrail!==!1,retentionPeriod:e.retentionPeriod||"7Y",complianceLevel:e.complianceLevel||"STANDARD"},dataStructure:{tokens:"Map<tokenId, registrationRecord>",revocations:"Map<tokenId, revocationRecord>",auditLog:"Array<auditEntry>",statistics:{totalTokens:0,activeTokens:0,revokedTokens:0,registrations:0}},externalStorage:{required:!0,type:"database_or_blockchain",endpoints:{store:"POST /registry/{id}/tokens",retrieve:"GET /registry/{id}/tokens/{tokenId}",search:"GET /registry/{id}/search",revoke:"POST /registry/{id}/revocations"}}},r=this._prepareAuditEntry({action:"REGISTRY_CREATED",actor:e.authority,timestamp:t.created,metadata:{jurisdiction:t.jurisdiction,config:t.config}});return{success:!0,registry:t,initialAudit:r,instructions:{step1:"Store registry configuration in external system",step2:"Initialize token storage with provided data structure",step3:"Set up audit logging with provided templates",step4:"Configure external endpoints for registry operations"}}},prepareTokenRegistration:function(e,t,r){r=r||{},cr.checkArgument(e&&typeof e=="object","Invalid token"),cr.checkArgument(t&&typeof t=="object","Invalid registry config");try{var n=this._validateTokenForRegistration(e,t);if(!n.valid)return{success:!1,error:"Token validation failed: "+n.error};var i={tokenId:e.id,tokenHash:this._hashToken(e),token:e,status:t.requireApproval?"PENDING":"ACTIVE",registeredBy:r.registeredBy||"UNKNOWN",registeredAt:new Date().toISOString(),approvedBy:null,approvedAt:null,metadata:r.metadata||{},compliance:{jurisdiction:e.jurisdiction||t.jurisdiction,level:this._calculateComplianceLevel(e),checks:n.checks||[]}},o=this._prepareAuditEntry({action:"TOKEN_REGISTERED",actor:r.registeredBy,tokenId:e.id,timestamp:i.registeredAt,metadata:{status:i.status,tokenType:e.type,compliance:i.compliance}});return{success:!0,registrationRecord:i,auditEntry:o,registrationId:this._generateRegistrationId(e.id),validation:n,externalOperations:{store:{endpoint:"POST /registry/"+t.id+"/tokens",data:i},audit:{endpoint:"POST /registry/"+t.id+"/audit",data:o}}}}catch(s){return{success:!1,error:s.message}}},prepareTokenApproval:function(e,t,r){try{cr.checkArgument(typeof e=="string","Token ID must be string"),cr.checkArgument(typeof t=="string","Approver must be string"),cr.checkArgument(r&&typeof r=="object","Invalid registry config");var n={tokenId:e,status:"ACTIVE",approvedBy:t,approvedAt:new Date().toISOString()},i=this._prepareAuditEntry({action:"TOKEN_APPROVED",actor:t,tokenId:e,timestamp:n.approvedAt});return{success:!0,approvalData:n,auditEntry:i,externalOperations:{update:{endpoint:"PUT /registry/"+r.id+"/tokens/"+e+"/status",data:n},audit:{endpoint:"POST /registry/"+r.id+"/audit",data:i}}}}catch(o){return{success:!1,error:o.message}}},prepareTokenRevocation:function(e,t,r){try{if(cr.checkArgument(typeof e=="string","Token ID must be string"),cr.checkArgument(t&&typeof t=="object","Invalid revocation"),cr.checkArgument(r&&typeof r=="object","Invalid registry config"),!r.enableRevocation)return{success:!1,error:"Revocation is disabled for this registry"};var n={tokenId:e,reason:t.reason||"UNSPECIFIED",revokedBy:t.revokedBy||"UNKNOWN",revokedAt:new Date().toISOString(),effectiveDate:t.effectiveDate||new Date().toISOString(),legalBasis:t.legalBasis||null,evidence:t.evidence||null,revocationHash:this._generateRevocationHash(e,t)},i={tokenId:e,status:"REVOKED",revokedAt:n.revokedAt,revocationReason:n.reason},o=this._prepareAuditEntry({action:"TOKEN_REVOKED",actor:t.revokedBy,tokenId:e,timestamp:n.revokedAt,metadata:{reason:n.reason,legalBasis:n.legalBasis}});return{success:!0,revocationRecord:n,statusUpdate:i,auditEntry:o,revocationId:this._generateRevocationId(e),externalOperations:{storeRevocation:{endpoint:"POST /registry/"+r.id+"/revocations",data:n},updateStatus:{endpoint:"PUT /registry/"+r.id+"/tokens/"+e+"/status",data:i},audit:{endpoint:"POST /registry/"+r.id+"/audit",data:o}}}}catch(s){return{success:!1,error:s.message}}},prepareTokenStatusQuery:function(e,t){try{return cr.checkArgument(typeof e=="string","Token ID must be string"),cr.checkArgument(t&&typeof t=="object","Invalid registry config"),{success:!0,query:{tokenId:e,registryId:t.id},externalOperations:{retrieve:{endpoint:"GET /registry/"+t.id+"/tokens/"+e,method:"GET"},checkRevocation:{endpoint:"GET /registry/"+t.id+"/revocations/"+e,method:"GET"}},expectedResponse:{found:"boolean",status:"string (PENDING|ACTIVE|REVOKED)",registeredAt:"ISO datetime",registeredBy:"string",approvedAt:"ISO datetime or null",approvedBy:"string or null",revokedAt:"ISO datetime or null",revocationReason:"string or null",compliance:"object",revocation:"object or null"}}}catch(r){return{success:!1,error:r.message}}},prepareTokenSearch:function(e,t){e=e||{};try{cr.checkArgument(t&&typeof t=="object","Invalid registry config");var r=[];e.status&&r.push("status="+encodeURIComponent(e.status)),e.type&&r.push("type="+encodeURIComponent(e.type)),e.registeredBy&&r.push("registeredBy="+encodeURIComponent(e.registeredBy)),e.jurisdiction&&r.push("jurisdiction="+encodeURIComponent(e.jurisdiction)),e.dateFrom&&r.push("dateFrom="+encodeURIComponent(e.dateFrom)),e.dateTo&&r.push("dateTo="+encodeURIComponent(e.dateTo)),e.includeTokens&&r.push("includeTokens=true"),e.sortBy&&r.push("sortBy="+encodeURIComponent(e.sortBy)),e.sortOrder&&r.push("sortOrder="+encodeURIComponent(e.sortOrder));var n=e.offset||0,i=e.limit||100;r.push("offset="+n),r.push("limit="+i);var o=r.length>0?"?"+r.join("&"):"";return{success:!0,searchCriteria:e,externalOperations:{search:{endpoint:"GET /registry/"+t.id+"/search"+o,method:"GET"}},expectedResponse:{success:"boolean",results:"Array<tokenRecord>",totalCount:"number",totalRegistrations:"number",offset:"number",limit:"number",hasMore:"boolean"}}}catch(s){return{success:!1,error:s.message}}},prepareStatisticsQuery:function(e){return cr.checkArgument(e&&typeof e=="object","Invalid registry config"),{success:!0,query:{registryId:e.id},externalOperations:{getStatistics:{endpoint:"GET /registry/"+e.id+"/statistics",method:"GET"}},expectedResponse:{id:"string",name:"string",jurisdiction:"string",created:"ISO datetime",statistics:{totalTokens:"number",activeTokens:"number",revokedTokens:"number",registrations:"number"},auditEntries:"number",lastActivity:"ISO datetime"}}},prepareAuditLogQuery:function(e,t){if(t=t||{},cr.checkArgument(e&&typeof e=="object","Invalid registry config"),!e.enableAuditTrail)return{success:!1,error:"Audit trail is disabled"};var r=[];t.action&&r.push("action="+encodeURIComponent(t.action)),t.actor&&r.push("actor="+encodeURIComponent(t.actor)),t.tokenId&&r.push("tokenId="+encodeURIComponent(t.tokenId)),t.dateFrom&&r.push("dateFrom="+encodeURIComponent(t.dateFrom)),t.dateTo&&r.push("dateTo="+encodeURIComponent(t.dateTo));var n=t.offset||0,i=t.limit||100;r.push("offset="+n),r.push("limit="+i);var o=r.length>0?"?"+r.join("&"):"";return{success:!0,auditOptions:t,externalOperations:{getAuditLog:{endpoint:"GET /registry/"+e.id+"/audit"+o,method:"GET"}},expectedResponse:{success:"boolean",entries:"Array<auditEntry>",totalEntries:"number",offset:"number",limit:"number",hasMore:"boolean"}}},_generateRegistryId:function(){return"reg_"+Ox.randomHex(16)},_generateRegistrationId:function(e){var t="reg_"+e+"_"+Date.now();return Wa.sha256(d.Buffer.from(t)).toString("hex").substring(0,16)},_generateRevocationId:function(e){var t="rev_"+e+"_"+Date.now();return Wa.sha256(d.Buffer.from(t)).toString("hex").substring(0,16)},_hashToken:function(e){var t=JSON.parse(JSON.stringify(e));return delete t.proof,delete t.tokenHash,Wa.sha256(d.Buffer.from(JSON.stringify(t))).toString("hex")},_generateRevocationHash:function(e,t){var r=e+(t.reason||"")+(t.revokedBy||"")+Date.now();return Wa.sha256(d.Buffer.from(r)).toString("hex")},_validateTokenForRegistration:function(e,t){var r=[],n=!0;return e.id?r.push({field:"id",valid:!0}):(r.push({field:"id",valid:!1,error:"Missing token ID"}),n=!1),e.type?r.push({field:"type",valid:!0}):(r.push({field:"type",valid:!1,error:"Missing token type"}),n=!1),e.issuanceDate?r.push({field:"issuanceDate",valid:!0}):(r.push({field:"issuanceDate",valid:!1,error:"Missing issuance date"}),n=!1),e.proof?r.push({field:"proof",valid:!0}):(r.push({field:"proof",valid:!1,error:"Missing cryptographic proof"}),n=!1),{valid:n,checks:r}},_calculateComplianceLevel:function(e){var t="BASIC";return e.proof&&e.proof.type&&(t="STANDARD"),e.jurisdiction&&e.legalBasis&&(t="ENHANCED"),e.attestations&&e.attestations.length>0&&(t="PREMIUM"),t},_prepareAuditEntry:function(e){var t={id:this._generateAuditId(),action:e.action,actor:e.actor||"SYSTEM",tokenId:e.tokenId||null,timestamp:e.timestamp||new Date().toISOString(),metadata:e.metadata||{},hash:this._generateAuditHash(e)};return t},_generateAuditId:function(){return"audit_"+Ox.randomHex(32)},_generateAuditHash:function(e){var t=(e.action||"")+(e.actor||"")+(e.tokenId||"")+(e.timestamp||"");return Wa.sha256(d.Buffer.from(t)).toString("hex").substring(0,16)}};Rx.exports=Lk});var Mx=P((D5,Nx)=>{"use strict";m();var Up=Tr(),Fp=Qt(),Px=ka(),Dk=ir(),Bx=io(),mr=ke(),Uk=Ka();function Fk(e,t){if(t=t||{},t.issuerPublicKey)return t.issuerPublicKey instanceof Up?t.issuerPublicKey:Up.fromString(t.issuerPublicKey);var r=e&&e.issuer;if(typeof r!="string")return null;try{var n=r.split("#")[0].split(":")[2];return n?Up.fromString(n):null}catch{return null}}var Uc={CORRELATIVE_OBLIGATION:"CorrelativeObligation",CONTRACTUAL_OBLIGATION:"ContractualObligation",PAYMENT_OBLIGATION:"PaymentObligation",DELIVERY_OBLIGATION:"DeliveryObligation",PERFORMANCE_OBLIGATION:"PerformanceObligation",MAINTENANCE_OBLIGATION:"MaintenanceObligation",COMPLIANCE_OBLIGATION:"ComplianceObligation",REPORTING_OBLIGATION:"ReportingObligation",CONFIDENTIALITY_OBLIGATION:"ConfidentialityObligation",NON_COMPETE_OBLIGATION:"NonCompeteObligation",INDEMNIFICATION_OBLIGATION:"IndemnificationObligation",WARRANTY_OBLIGATION:"WarrantyObligation",SUPPORT_OBLIGATION:"SupportObligation",REGULATORY_OBLIGATION:"RegulatoryObligation",FIDUCIARY_OBLIGATION:"FiduciaryObligation"},ps={CRITICAL:"CRITICAL",HIGH:"HIGH",MEDIUM:"MEDIUM",LOW:"LOW",DEFERRED:"DEFERRED"},lr={PENDING:"PENDING",ACTIVE:"ACTIVE",IN_PROGRESS:"IN_PROGRESS",COMPLETED:"COMPLETED",OVERDUE:"OVERDUE",BREACHED:"BREACHED",WAIVED:"WAIVED",TERMINATED:"TERMINATED"},Fc={prepareObligationToken:function(e,t,r,n,i,o){o=o||{},mr.checkArgument(typeof e=="string","Obligation type must be string"),mr.checkArgument(typeof t=="string","Issuer DID must be string"),mr.checkArgument(typeof r=="string","Obligor DID must be string"),mr.checkArgument(n&&typeof n=="object","Obligation must be object"),mr.checkArgument(i instanceof Bx,"Invalid issuer private key");var s=Object.values(Uc);mr.checkArgument(s.includes(e),"Invalid obligation type: "+e);try{var a={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","LegalObligationToken",e],issuer:t,issuanceDate:new Date().toISOString(),credentialSubject:{id:r,obligationType:e,obligation:n,jurisdiction:o.jurisdiction||"US",priority:o.priority||ps.MEDIUM,status:lr.PENDING,dueDate:o.dueDate||null,effectiveDate:o.effectiveDate||new Date().toISOString(),expirationDate:o.expirationDate||null,correlativeRight:o.correlativeRight||null,rightHolder:o.rightHolder||null,enforceable:o.enforceable!==!1,penalties:o.penalties||null,remedies:o.remedies||null}};o.metadata&&(a.credentialSubject.metadata=o.metadata);var c=this._signToken(a,i);return{success:!0,obligationToken:c,tokenHash:c.tokenHash,metadata:{type:e,issuer:t,obligor:r,priority:a.credentialSubject.priority,status:a.credentialSubject.status,jurisdiction:a.credentialSubject.jurisdiction,dueDate:a.credentialSubject.dueDate,correlativeRight:a.credentialSubject.correlativeRight},externalOperations:{storeToken:{endpoint:"POST /obligations/tokens",data:{token:c,metadata:{type:e,issuer:t,obligor:r,priority:a.credentialSubject.priority,status:a.credentialSubject.status,jurisdiction:a.credentialSubject.jurisdiction,dueDate:a.credentialSubject.dueDate,correlativeRight:a.credentialSubject.correlativeRight}}},indexToken:{endpoint:"POST /obligations/index",data:{tokenId:c.id,tokenHash:c.tokenHash,type:e,issuer:t,obligor:r,issuedAt:c.issuanceDate,dueDate:a.credentialSubject.dueDate,priority:a.credentialSubject.priority}},notifyObligor:{endpoint:"POST /notifications/obligation-issued",data:{tokenId:c.id,issuer:t,obligor:r,obligationType:e,dueDate:a.credentialSubject.dueDate,priority:a.credentialSubject.priority}},scheduleReminders:a.credentialSubject.dueDate?{endpoint:"POST /obligations/schedule-reminders",data:{tokenId:c.id,obligor:r,dueDate:a.credentialSubject.dueDate,reminderSchedule:o.reminderSchedule||["7d","3d","1d"]}}:null}}}catch(h){return{success:!1,error:h.message}}},prepareObligationVerification:function(e,t){t=t||{};try{var r=[],n=[];this._validateTokenStructure(e,r),this._verifyTokenSignature(e,r,t),this._validateTokenTemporal(e,r,n),this._validateObligationType(e,r),this._validateObligationStatus(e,r,n),this._validateObligationPriority(e,n);var i={valid:r.length===0,errors:r,warnings:n,issuerDID:e.issuer,obligorDID:e.credentialSubject?e.credentialSubject.id:null,obligationType:e.credentialSubject?e.credentialSubject.obligationType:null,status:e.credentialSubject?e.credentialSubject.status:null,priority:e.credentialSubject?e.credentialSubject.priority:null,isOverdue:this._checkIfOverdue(e),verifiedAt:new Date().toISOString()};return{success:!0,verification:i,externalOperations:{recordVerification:{endpoint:"POST /obligations/verification-record",data:{tokenId:e.id,result:i.valid,errors:r,warnings:n,verifiedAt:i.verifiedAt,isOverdue:i.isOverdue}},auditVerification:{endpoint:"POST /audit/obligation-verification",data:{tokenId:e.id,obligationType:i.obligationType,issuer:i.issuerDID,obligor:i.obligorDID,result:i.valid,verifiedAt:i.verifiedAt}},updateStatus:i.isOverdue&&e.credentialSubject.status===lr.ACTIVE?{endpoint:"PUT /obligations/tokens/"+e.id+"/status",data:{status:lr.OVERDUE,updatedAt:i.verifiedAt,reason:"Due date passed"}}:null}}}catch(o){return{success:!1,error:"Verification preparation failed: "+o.message}}},prepareObligationFulfillment:function(e,t,r,n){n=n||{},mr.checkArgument(e&&typeof e=="object","Invalid token"),mr.checkArgument(t&&typeof t=="object","Invalid fulfillment"),mr.checkArgument(r instanceof Bx,"Invalid obligor key");try{var i=this.prepareObligationVerification(e,{});if(!i.success||!i.verification.valid)return{success:!1,error:"Cannot fulfill invalid obligation: "+i.verification.errors.join(", ")};if(e.credentialSubject.status===lr.COMPLETED)return{success:!1,error:"Obligation already fulfilled"};if(e.credentialSubject.status===lr.TERMINATED)return{success:!1,error:"Obligation has been terminated"};var o={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","ObligationFulfillment"],issuer:e.credentialSubject.id,issuanceDate:new Date().toISOString(),credentialSubject:{id:e.id,fulfillmentType:t.type||"FULL_FULFILLMENT",fulfillmentDate:new Date().toISOString(),evidence:t.evidence||null,description:t.description||"",completionPercentage:t.completionPercentage||100,attestations:t.attestations||[],notes:t.notes||null}},s=this._signToken(o,r),a=o.credentialSubject.completionPercentage>=100?lr.COMPLETED:lr.IN_PROGRESS;return{success:!0,fulfillmentRecord:s,newStatus:a,fulfillmentId:s.id,externalOperations:{recordFulfillment:{endpoint:"POST /obligations/fulfillments",data:{obligationId:e.id,fulfillmentRecord:s,obligor:e.credentialSubject.id,fulfillmentDate:o.credentialSubject.fulfillmentDate,completionPercentage:o.credentialSubject.completionPercentage}},updateStatus:{endpoint:"PUT /obligations/tokens/"+e.id+"/status",data:{status:a,fulfillmentId:s.id,updatedAt:o.credentialSubject.fulfillmentDate,completionPercentage:o.credentialSubject.completionPercentage}},notifyRightHolder:e.credentialSubject.rightHolder?{endpoint:"POST /notifications/obligation-fulfilled",data:{obligationId:e.id,fulfillmentId:s.id,obligor:e.credentialSubject.id,rightHolder:e.credentialSubject.rightHolder,completionPercentage:o.credentialSubject.completionPercentage,newStatus:a}}:null,auditFulfillment:{endpoint:"POST /audit/obligation-fulfillment",data:{obligationId:e.id,fulfillmentId:s.id,obligor:e.credentialSubject.id,fulfilledAt:o.credentialSubject.fulfillmentDate,completionPercentage:o.credentialSubject.completionPercentage}}}}}catch(c){return{success:!1,error:c.message}}},prepareObligationBreachAssessment:function(e,t,r){mr.checkArgument(e&&typeof e=="object","Invalid token"),mr.checkArgument(t&&typeof t=="object","Invalid breach details"),mr.checkArgument(r&&typeof r=="object","Invalid assessor");try{var n={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","ObligationBreachAssessment"],issuer:r.did||r.id,issuanceDate:new Date().toISOString(),credentialSubject:{id:e.id,breachType:t.type||"MATERIAL_BREACH",breachDate:t.date||new Date().toISOString(),description:t.description||"",severity:t.severity||"MODERATE",evidence:t.evidence||[],assessor:{did:r.did||r.id,name:r.name||"Unknown",authority:r.authority||null,jurisdiction:r.jurisdiction||null},damages:t.damages||null,recommendedRemedies:t.recommendedRemedies||[],assessmentDate:new Date().toISOString()}},i=Fp.sha256(d.Buffer.from(JSON.stringify(n))).toString("hex");return n.credentialSubject.assessmentHash=i,{success:!0,breachAssessment:n,breachId:n.id,severity:t.severity||"MODERATE",externalOperations:{recordBreach:{endpoint:"POST /obligations/breaches",data:{obligationId:e.id,breachAssessment:n,obligor:e.credentialSubject.id,rightHolder:e.credentialSubject.rightHolder,breachDate:t.date||new Date().toISOString(),severity:t.severity||"MODERATE"}},updateStatus:{endpoint:"PUT /obligations/tokens/"+e.id+"/status",data:{status:lr.BREACHED,breachId:n.id,breachDate:t.date||new Date().toISOString(),updatedAt:new Date().toISOString()}},notifyParties:{endpoint:"POST /notifications/obligation-breached",data:{obligationId:e.id,breachId:n.id,obligor:e.credentialSubject.id,rightHolder:e.credentialSubject.rightHolder,breachType:t.type||"MATERIAL_BREACH",severity:t.severity||"MODERATE"}},escalateBreach:t.severity==="CRITICAL"?{endpoint:"POST /legal/escalate-breach",data:{obligationId:e.id,breachId:n.id,severity:t.severity,jurisdiction:e.credentialSubject.jurisdiction}}:null,auditBreach:{endpoint:"POST /audit/obligation-breach",data:{obligationId:e.id,breachId:n.id,obligor:e.credentialSubject.id,assessedAt:n.credentialSubject.assessmentDate,severity:t.severity||"MODERATE"}}}}}catch(o){return{success:!1,error:o.message}}},prepareObligationMonitoringReport:function(e,t){t=t||{},mr.checkArgument(Array.isArray(e),"Obligations must be array");try{var r={reportId:"rpt_"+this._generateUUID(),generatedAt:new Date().toISOString(),criteria:t,summary:{totalObligations:e.length,byStatus:{},byPriority:{},byType:{},overdue:0,dueSoon:0,completed:0},obligations:[],alerts:[],recommendations:[]},n=new Date,i=new Date(n.getTime()+10080*60*1e3);return e.forEach(function(o){var s={id:o.id,type:o.credentialSubject.obligationType,status:o.credentialSubject.status,priority:o.credentialSubject.priority,obligor:o.credentialSubject.id,dueDate:o.credentialSubject.dueDate,isOverdue:this._checkIfOverdue(o),isDueSoon:!1};if(o.credentialSubject.dueDate){var a=new Date(o.credentialSubject.dueDate);s.isDueSoon=a<=i&&a>n}r.summary.byStatus[s.status]=(r.summary.byStatus[s.status]||0)+1,r.summary.byPriority[s.priority]=(r.summary.byPriority[s.priority]||0)+1,r.summary.byType[s.type]=(r.summary.byType[s.type]||0)+1,s.isOverdue&&r.summary.overdue++,s.isDueSoon&&r.summary.dueSoon++,s.status===lr.COMPLETED&&r.summary.completed++,s.isOverdue&&s.priority===ps.CRITICAL&&r.alerts.push({type:"CRITICAL_OVERDUE",obligationId:o.id,message:"Critical obligation is overdue",priority:"HIGH"}),s.isDueSoon&&s.priority===ps.HIGH&&r.alerts.push({type:"HIGH_PRIORITY_DUE_SOON",obligationId:o.id,message:"High priority obligation due soon",priority:"MEDIUM"}),r.obligations.push(s)}.bind(this)),r.summary.overdue>0&&r.recommendations.push({type:"OVERDUE_MANAGEMENT",message:"Consider prioritizing overdue obligations",count:r.summary.overdue}),r.summary.dueSoon>5&&r.recommendations.push({type:"WORKLOAD_MANAGEMENT",message:"High number of obligations due soon - consider workload distribution",count:r.summary.dueSoon}),{success:!0,report:r,externalOperations:{storeReport:{endpoint:"POST /obligations/monitoring-reports",data:{report:r,generatedAt:r.generatedAt}},sendAlerts:r.alerts.length>0?{endpoint:"POST /notifications/obligation-alerts",data:{reportId:r.reportId,alerts:r.alerts,summary:r.summary}}:null,updateDashboard:{endpoint:"PUT /dashboard/obligation-metrics",data:{summary:r.summary,lastUpdated:r.generatedAt}}}}}catch(o){return{success:!1,error:o.message}}},getObligationTypes:function(){return Uc},getObligationPriority:function(){return ps},getObligationStatus:function(){return lr},_signToken:function(e,t){var r=this._canonicalizeToken(e),n=Fp.sha256(d.Buffer.from(r)),i=new Px;i.hashbuf=n,i.privkey=t,i.pubkey=t.toPublicKey(),i.sign();var o=i.sig,s={type:"EcdsaSecp256k1Signature2019",created:new Date().toISOString(),verificationMethod:"did:smartledger:"+t.toPublicKey().toString()+"#keys-1",proofPurpose:"assertionMethod",jws:this._createJWS(n,o)},a=JSON.parse(JSON.stringify(e));return a.proof=s,a.tokenHash=n.toString("hex"),a},_createJWS:function(e,t){var r={alg:"ES256K",typ:"JWT"},n=d.Buffer.from(JSON.stringify(r)).toString("base64url"),i=e.toString("base64url"),o=t.toDER().toString("base64url");return n+".."+o},_canonicalizeToken:function(e){var t=JSON.parse(JSON.stringify(e));return delete t.proof,delete t.tokenHash,JSON.stringify(this._sortObjectKeys(t))},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e},_validateTokenStructure:function(e,t){e["@context"]||t.push("Missing @context"),e.id||t.push("Missing id"),(!e.type||!Array.isArray(e.type))&&t.push("Missing or invalid type"),e.issuer||t.push("Missing issuer"),e.issuanceDate||t.push("Missing issuanceDate"),e.credentialSubject||t.push("Missing credentialSubject"),e.proof||t.push("Missing proof")},_verifyTokenSignature:function(e,t,r){try{if(!e.proof||!e.proof.jws){t.push("Missing signature proof");return}var n=this._canonicalizeToken(e),i=Fp.sha256(d.Buffer.from(n));if(e.tokenHash&&e.tokenHash!==i.toString("hex")){t.push("Token hash mismatch");return}var o=Fk(e,r);if(!o){t.push("Signature not verified: issuer public key could not be resolved from token.issuer; pass options.issuerPublicKey");return}var s=e.proof.jws.split(".");if(s.length!==3||!s[2]){t.push("Malformed JWS");return}var a=Dk.fromDER(d.Buffer.from(s[2],"base64url")),c=new Px;c.hashbuf=i,c.sig=a,c.pubkey=o,c.verify()!==!0&&t.push("Signature verification failed")}catch(h){t.push("Signature verification failed: "+h.message)}},_validateTokenTemporal:function(e,t,r){var n=new Date,i=new Date(e.issuanceDate);if(i>n&&t.push("Token issued in the future"),e.credentialSubject.effectiveDate){var o=new Date(e.credentialSubject.effectiveDate);n<o&&r.push("Obligation not yet effective")}if(e.credentialSubject.expirationDate){var s=new Date(e.credentialSubject.expirationDate);n>s&&t.push("Obligation expired")}},_validateObligationType:function(e,t){if(!e.credentialSubject.obligationType){t.push("Missing obligationType");return}var r=Object.values(Uc);r.includes(e.credentialSubject.obligationType)||t.push("Invalid obligation type: "+e.credentialSubject.obligationType)},_validateObligationStatus:function(e,t,r){if(!e.credentialSubject.status){t.push("Missing status");return}var n=Object.values(lr);n.includes(e.credentialSubject.status)||t.push("Invalid obligation status: "+e.credentialSubject.status),this._checkIfOverdue(e)&&e.credentialSubject.status===lr.ACTIVE&&r.push("Obligation is overdue but status is still ACTIVE")},_validateObligationPriority:function(e,t){if(e.credentialSubject.priority){var r=Object.values(ps);r.includes(e.credentialSubject.priority)||t.push("Invalid obligation priority: "+e.credentialSubject.priority)}},_checkIfOverdue:function(e){if(!e.credentialSubject.dueDate)return!1;var t=new Date,r=new Date(e.credentialSubject.dueDate);return t>r&&e.credentialSubject.status!==lr.COMPLETED},_generateUUID:function(){return Uk.uuid4()}};Fc.ObligationTypes=Uc;Fc.ObligationPriority=ps;Fc.ObligationStatus=lr;Nx.exports=Fc});var Cx=P((F5,kx)=>{"use strict";m();var uo=bx(),qc=Sx(),Ya=Ex(),qp=Ax(),dn=Tx(),qk=Mx(),Hp=io(),vr=ke(),Re=function(e){return this instanceof Re?(this.config=e||{},this.registry=null,this.config.registry&&(this.registry=dn.createRegistry(this.config.registry)),this):new Re(e)};Re.prototype.createRightToken=function(e,t,r){vr.checkArgument(e&&typeof e=="object","Invalid right data"),vr.checkArgument(t instanceof Hp,"Invalid private key"),r=r||{};try{var n=uo.create(e.type,e.owner,e.owner,e,t,r);if(!n)return{success:!1,error:"Failed to create token"};if(r.addProof!==!1&&(n=uo._signToken(n,t)),r.anchor){var i=Ya.anchorToken(n,r.anchor);i.success&&(n.anchorTx=i.txid,n.anchorBlock=i.blockHeight)}if(this.registry&&r.register!==!1){var o=dn.registerToken(this.registry,n,{registeredBy:r.registeredBy||"SYSTEM"});o.success&&(n.registrationId=o.registrationId,n.registrationStatus=o.status)}return{success:!0,token:n,type:"LegalRightToken"}}catch(s){return{success:!1,error:s.message}}};Re.prototype.validateClaim=function(e,t){return qc.validate(e,t)};Re.prototype.createSelectiveDisclosure=function(e,t,r){return qp.prepareSelectiveDisclosure(e,t,r)};Re.prototype.verifyToken=function(e,t){return!e||!e.proof?{valid:!1,error:"No proof found in token"}:uo.verifyToken(e,t)};Re.prototype.transferRight=function(e,t,r,n){vr.checkArgument(e&&typeof e=="object","Invalid token"),vr.checkArgument(typeof t=="string","New owner must be string"),vr.checkArgument(r instanceof Hp,"Invalid owner key"),n=n||{};try{var i=this.verifyToken(e,r.toPublicKey().toString());if(!i.valid)return{success:!1,error:"Invalid token or ownership proof"};var o=uo.prepareRightTokenTransfer(e,t,r,n);if(!o.success)return{success:!1,error:o.error};var s=o.newToken,a=o.transferProof;if(n.anchor){var c=Ya.anchorToken(s,n.anchor);c.success&&(s.transferAnchorTx=c.txid)}if(this.registry){var h=dn.registerToken(this.registry,s,{registeredBy:n.registeredBy||t,metadata:{transferFrom:e.owner,transferTo:t,originalTokenId:e.id}});h.success&&(s.registrationId=h.registrationId)}return{success:!0,token:s,transferId:a.id,transferredAt:a.issuanceDate,transferProof:a}}catch(g){return{success:!1,error:g.message}}};Re.prototype.createObligation=function(e,t,r){vr.checkArgument(e&&typeof e=="object","Invalid right token"),vr.checkArgument(t&&typeof t=="object","Invalid obligation data"),vr.checkArgument(r instanceof Hp,"Invalid private key");try{var n=uo.prepareObligationToken(e,t.obligor,t,r);return n.success?{success:!0,obligation:n.obligationToken,rightTokenId:e.id}:{success:!1,error:n.error}}catch(i){return{success:!1,error:i.message}}};Re.prototype.revokeToken=function(e,t,r){return vr.checkArgument(typeof e=="string","Token ID must be string"),vr.checkArgument(t&&typeof t=="object","Invalid revocation data"),vr.checkArgument(typeof r=="string","Authority must be string"),this.registry?dn.revokeToken(this.registry,e,{reason:t.reason,revokedBy:r,legalBasis:t.legalBasis,evidence:t.evidence}):{success:!1,error:"No registry available for revocation"}};Re.prototype.checkTokenStatus=function(e){return vr.checkArgument(typeof e=="string","Token ID must be string"),this.registry?dn.checkTokenStatus(this.registry,e):{found:!1,error:"No registry available"}};Re.prototype.searchTokens=function(e){return this.registry?dn.searchTokens(this.registry,e):{success:!1,error:"No registry available"}};Re.prototype.getRegistryStats=function(){return this.registry?dn.getStatistics(this.registry):{error:"No registry available"}};Re.prototype.createLegalValidityProof=function(e,t,r){return qp.prepareLegalValidityProof(e,t,r)};Re.prototype.anchorTokenBatch=function(e,t){return Ya.anchorBatch(e,t)};Re.prototype.verifyAnchor=function(e,t){return Ya.verifyAnchor(e,t)};Re.prototype.getRightTypes=function(){return uo.getRightTypes()};Re.prototype.getClaimSchemas=function(){return qc.getSchemas()};Re.prototype.createRegistry=function(e){return this.registry=dn.createRegistry(e),this.registry};Re.prototype.setRegistry=function(e){vr.checkArgument(e&&typeof e=="object","Invalid registry"),this.registry=e};Re.create=function(e){return new Re(e)};Re.createRightToken=function(e,t,r){var n=new Re;return n.createRightToken(e,t,r)};Re.validateClaim=function(e,t){return qc.validate(e,t)};Re.verifyToken=function(e,t){var r=new Re;return r.verifyToken(e,t)};Re.createRegistry=function(e){return dn.createRegistry(e)};Re.Right=uo;Re.Claim=qc;Re.Anchor=Ya;Re.Proof=qp;Re.Registry=dn;Re.Obligation=qk;kx.exports=Re});var Hk=P((H5,Lx)=>{m();Lx.exports=Cx()});return Hk();})();
|
|
69
|
+
`));var a=new li({actual:e,expected:t,message:r,operator:i,stackStartFn:n});throw a.generatedMessage=s,a}}Ge.match=function e(t,r,n){ZE(t,r,n,e,"match")};Ge.doesNotMatch=function e(t,r,n){ZE(t,r,n,e,"doesNotMatch")};function XE(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];KE.apply(void 0,[XE,t.length].concat(t))}Ge.strict=f6(XE,Ge,{equal:Ge.strictEqual,deepEqual:Ge.deepStrictEqual,notEqual:Ge.notStrictEqual,notDeepEqual:Ge.notDeepStrictEqual});Ge.strict.strict=Ge.strict});var Qi=P((RF,e1)=>{"use strict";m();var QE=oc(),tt=function e(t){if(!(this instanceof e))return new e(t);this.bufLen=0,t?this.set(t):this.bufs=[]};tt.prototype.set=function(e){return this.bufs=e.bufs||this.bufs||[],this.bufLen=this.bufs.reduce(function(t,r){return t+r.length},0),this};tt.prototype.toBuffer=function(){return this.concat()};tt.prototype.concat=function(){return d.Buffer.concat(this.bufs,this.bufLen)};tt.prototype.write=function(e){return QE(d.Buffer.isBuffer(e)),this.bufs.push(e),this.bufLen+=e.length,this};tt.prototype.writeReverse=function(e){return QE(d.Buffer.isBuffer(e)),this.bufs.push(d.Buffer.from(e).reverse()),this.bufLen+=e.length,this};tt.prototype.writeUInt8=function(e){var t=d.Buffer.alloc(1);return t.writeUInt8(e,0),this.write(t),this};tt.prototype.writeUInt16BE=function(e){var t=d.Buffer.alloc(2);return t.writeUInt16BE(e,0),this.write(t),this};tt.prototype.writeUInt16LE=function(e){var t=d.Buffer.alloc(2);return t.writeUInt16LE(e,0),this.write(t),this};tt.prototype.writeUInt32BE=function(e){var t=d.Buffer.alloc(4);return t.writeUInt32BE(e,0),this.write(t),this};tt.prototype.writeInt32LE=function(e){var t=d.Buffer.alloc(4);return t.writeInt32LE(e,0),this.write(t),this};tt.prototype.writeUInt32LE=function(e){var t=d.Buffer.alloc(4);return t.writeUInt32LE(e,0),this.write(t),this};tt.prototype.writeUInt64BEBN=function(e){var t=e.toBuffer({size:8});return this.write(t),this};tt.prototype.writeUInt64LEBN=function(e){var t=e.toBuffer({size:8});return this.writeReverse(t),this};tt.prototype.writeVarintNum=function(e){var t=tt.varintBufNum(e);return this.write(t),this};tt.prototype.writeVarintBN=function(e){var t=tt.varintBufBN(e);return this.write(t),this};tt.varintBufNum=function(e){var t;return e<253?(t=d.Buffer.alloc(1),t.writeUInt8(e,0)):e<65536?(t=d.Buffer.alloc(3),t.writeUInt8(253,0),t.writeUInt16LE(e,1)):e<4294967296?(t=d.Buffer.alloc(5),t.writeUInt8(254,0),t.writeUInt32LE(e,1)):(t=d.Buffer.alloc(9),t.writeUInt8(255,0),t.writeInt32LE(e&-1,1),t.writeUInt32LE(Math.floor(e/4294967296),5)),t};tt.varintBufBN=function(e){var t,r=e.toNumber();if(r<253)t=d.Buffer.alloc(1),t.writeUInt8(r,0);else if(r<65536)t=d.Buffer.alloc(3),t.writeUInt8(253,0),t.writeUInt16LE(r,1);else if(r<4294967296)t=d.Buffer.alloc(5),t.writeUInt8(254,0),t.writeUInt32LE(r,1);else{var n=new tt;n.writeUInt8(255),n.writeUInt64LEBN(e),t=n.concat()}return t};e1.exports=tt});var sp=P((PF,t1)=>{"use strict";m();var is=Ve(),Na=ke(),l6=pr();function Pe(e){if(!(this instanceof Pe))return new Pe(e);var t;if(is.isNumber(e))t=e;else if(is.isString(e))t=Pe.map[e];else throw new TypeError('Unrecognized num type: "'+typeof e+'" for Opcode');return l6.defineImmutable(this,{num:t}),this}Pe.fromBuffer=function(e){return Na.checkArgument(d.Buffer.isBuffer(e)),new Pe(+("0x"+e.toString("hex")))};Pe.fromNumber=function(e){return Na.checkArgument(is.isNumber(e)),new Pe(e)};Pe.fromString=function(e){Na.checkArgument(is.isString(e));var t=Pe.map[e];if(typeof t>"u")throw new TypeError("Invalid opcodestr");return new Pe(t)};Pe.prototype.toHex=function(){return this.num.toString(16)};Pe.prototype.toBuffer=function(){return d.Buffer.from(this.toHex(),"hex")};Pe.prototype.toNumber=function(){return this.num};Pe.prototype.toString=function(){var e=Pe.reverseMap[this.num];if(typeof e>"u")throw new Error("Opcode does not have a string representation");return e};Pe.smallInt=function(e){return Na.checkArgument(is.isNumber(e),"Invalid Argument: n should be number"),Na.checkArgument(e>=0&&e<=16,"Invalid Argument: n must be between 0 and 16"),e===0?Pe("OP_0"):new Pe(Pe.map.OP_1+e-1)};Pe.map={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SPLIT:127,OP_NUM2BIN:128,OP_BIN2NUM:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_CHECKLOCKTIMEVERIFY:177,OP_CHECKSEQUENCEVERIFY:178,OP_NOP1:176,OP_NOP2:177,OP_NOP3:178,OP_SUBSTR:179,OP_LEFT:180,OP_RIGHT:181,OP_LSHIFTNUM:182,OP_RSHIFTNUM:183,OP_NOP9:184,OP_NOP10:185,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255};Pe.reverseMap=[];for(op in Pe.map)Pe.reverseMap[Pe.map[op]]=op;var op;is.extend(Pe,Pe.map);Pe.isSmallIntOp=function(e){return e instanceof Pe&&(e=e.toNumber()),e===Pe.map.OP_0||e>=Pe.map.OP_1&&e<=Pe.map.OP_16};Pe.prototype.inspect=function(){return"<Opcode: "+this.toString()+", hex: "+this.toHex()+", decimal: "+this.num+">"};t1.exports=Pe});var ir=P((NF,n1)=>{"use strict";m();var eo=Er(),h6=Ve(),nr=ke(),d6=pr(),Ie=function e(t,r){if(!(this instanceof e))return new e(t,r);if(t instanceof eo)this.set({r:t,s:r});else if(t){var n=t;this.set(n)}};Ie.prototype.set=function(e){return this.r=e.r||this.r||void 0,this.s=e.s||this.s||void 0,this.i=typeof e.i<"u"?e.i:this.i,this.compressed=typeof e.compressed<"u"?e.compressed:this.compressed,this.nhashtype=e.nhashtype||this.nhashtype||void 0,this};Ie.fromCompact=function(e){nr.checkArgument(d.Buffer.isBuffer(e),"Argument is expected to be a Buffer");var t=new Ie,r=!0,n=e.slice(0,1)[0]-27-4;n<0&&(r=!1,n=n+4);var i=e.slice(1,33),o=e.slice(33,65);return nr.checkArgument(n===0||n===1||n===2||n===3,new Error("i must be 0, 1, 2, or 3")),nr.checkArgument(i.length===32,new Error("r must be 32 bytes")),nr.checkArgument(o.length===32,new Error("s must be 32 bytes")),t.compressed=r,t.i=n,t.r=eo.fromBuffer(i),t.s=eo.fromBuffer(o),t};Ie.fromDER=Ie.fromBuffer=function(e,t){var r=Ie.parseDER(e,t),n=new Ie;return n.r=r.r,n.s=r.s,n};Ie.fromTxFormat=function(e){var t=e.readUInt8(e.length-1),r=e.slice(0,e.length-1),n=Ie.fromDER(r,!1);return n.nhashtype=t,n};Ie.fromString=function(e){var t=d.Buffer.from(e,"hex");return Ie.fromDER(t)};function r1(e,t){nr.checkArgument(t.length>0,new Error("Length of "+e+" is zero")),nr.checkArgument(!(t[0]&128),new Error("Value of "+e+" is negative")),nr.checkArgument(!(t.length>1&&t[0]===0&&!(t[1]&128)),new Error("Value of "+e+" is excessively padded"))}Ie.parseDER=function(e,t){nr.checkArgument(d.Buffer.isBuffer(e),new Error("DER formatted signature should be a buffer")),h6.isUndefined(t)&&(t=!0);var r=e[0];nr.checkArgument(r===48,new Error("Header byte should be 0x30"));var n=e[1],i=e.slice(2).length;nr.checkArgument(!t||n===i,new Error("Length byte should length of what follows")),n=n<i?n:i;var o=e[2];nr.checkArgument(o===2,new Error("Integer byte for r should be 0x02"));var s=e[3],a=e.slice(4,4+s),c=eo.fromBuffer(a),h=e[4]===0;nr.checkArgument(s===a.length,new Error("Length of r incorrect"));var g=e[4+s+0];nr.checkArgument(g===2,new Error("Integer byte for s should be 0x02"));var y=e[4+s+1],w=e.slice(4+s+2,4+s+2+y),I=eo.fromBuffer(w),T=e[4+s+2]===0;nr.checkArgument(y===w.length,new Error("Length of s incorrect"));var M=4+s+2+y;nr.checkArgument(n===M-2,new Error("Length of signature incorrect")),t&&(r1("r",a),r1("s",w));var L={header:r,length:n,rheader:o,rlength:s,rneg:h,rbuf:a,r:c,sheader:g,slength:y,sneg:T,sbuf:w,s:I};return L};Ie.prototype.toCompact=function(e,t){if(e=typeof e=="number"?e:this.i,t=typeof t=="boolean"?t:this.compressed,!(e===0||e===1||e===2||e===3))throw new Error("i must be equal to 0, 1, 2, or 3");var r=e+27+4;t===!1&&(r=r-4);var n=d.Buffer.from([r]),i=this.r.toBuffer({size:32}),o=this.s.toBuffer({size:32});return d.Buffer.concat([n,i,o])};Ie.prototype.toBuffer=Ie.prototype.toDER=function(){var e=this.r.toBuffer(),t=this.s.toBuffer(),r=!!(e[0]&128),n=!!(t[0]&128),i=r?d.Buffer.concat([d.Buffer.from([0]),e]):e,o=n?d.Buffer.concat([d.Buffer.from([0]),t]):t,s=i.length,a=o.length,c=2+s+2+a,h=2,g=2,y=48,w=d.Buffer.concat([d.Buffer.from([y,c,h,s]),i,d.Buffer.from([g,a]),o]);return w};Ie.prototype.toString=function(){var e=this.toDER();return e.toString("hex")};Ie.isTxDER=function(e){if(e.length<9||e.length>73||e[0]!==48||e[1]!==e.length-3)return!1;var t=e[3];if(5+t>=e.length)return!1;var r=e[5+t];if(t+r+7!==e.length)return!1;var n=e.slice(4);if(e[2]!==2||t===0||n[0]&128||t>1&&n[0]===0&&!(n[1]&128))return!1;var i=e.slice(6+t);return!(e[6+t-2]!==2||r===0||i[0]&128||r>1&&i[0]===0&&!(i[1]&128))};Ie.prototype.hasLowS=function(){return!(this.s.lt(new eo(1))||this.s.gt(new eo("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex")))};Ie.prototype.hasDefinedHashtype=function(){if(!d6.isNaturalNumber(this.nhashtype))return!1;var e=this.nhashtype&31;return!(e<Ie.SIGHASH_ALL||e>Ie.SIGHASH_SINGLE)};Ie.prototype.toTxFormat=function(){var e=this.toDER(),t=d.Buffer.alloc(1);return t.writeUInt8(this.nhashtype,0),d.Buffer.concat([e,t])};Ie.SIGHASH_ALL=1;Ie.SIGHASH_NONE=2;Ie.SIGHASH_SINGLE=3;Ie.SIGHASH_CHRONICLE=32;Ie.SIGHASH_FORKID=64;Ie.SIGHASH_ANYONECANPAY=128;Ie.prototype.isCanonical=function(){var e=ii(),t=e.getN().shrn(1);return this.s.lte(t)};Ie.prototype.toCanonical=function(){if(this.isCanonical())return new Ie({r:this.r,s:this.s,i:this.i,compressed:this.compressed,nhashtype:this.nhashtype});var e=ii(),t=e.getN(),r=t.sub(this.s);return new Ie({r:this.r,s:r,i:this.i,compressed:this.compressed,nhashtype:this.nhashtype})};Ie.prototype.validate=function(){if(!this.r||!this.s)throw new Error("Signature missing r or s component");if(this.r.isZero())throw new Error("Signature r component is zero");if(this.s.isZero())throw new Error("Signature s component is zero");var e=ii(),t=e.getN();if(this.r.gte(t))throw new Error("Signature r component >= curve order");if(this.s.gte(t))throw new Error("Signature s component >= curve order");if(this.r.isNeg())throw new Error("Signature r component is negative");if(this.s.isNeg())throw new Error("Signature s component is negative");return!0};Ie.prototype.isValid=function(){try{return this.validate(),!0}catch{return!1}};Ie.prototype.applySecurityPatches=function(){var e=ii(),t=e.getN(),r=t.shrn(1);if(this.r.isZero()||this.s.isZero())throw new Error("Invalid signature: zero r or s");if(this.r.gte(t)||this.s.gte(t))throw new Error("Invalid signature: out of range");if(this.s.gt(r))throw new Error("Invalid signature: non-canonical (high) s");return this};n1.exports=Ie});var fp=P((kF,s1)=>{"use strict";m();var Hr=no(),p6=va(),g6=Qi(),ap=Qt(),X=sp(),ro=Tr(),to=ir(),i1=ga(),$e=ke(),Ae=Ve(),up=Jn(),o1=Tt(),y6=pr(),D=function e(t){if(!(this instanceof e))return new e(t);if(this.chunks=[],d.Buffer.isBuffer(t))return e.fromBuffer(t);if(t instanceof Hr)return e.fromAddress(t);if(t instanceof e)return e.fromBuffer(t.toBuffer());if(Ae.isString(t))return e.fromString(t);Ae.isObject(t)&&Ae.isArray(t.chunks)&&this.set(t)};D.prototype.set=function(e){return $e.checkArgument(Ae.isObject(e)),$e.checkArgument(Ae.isArray(e.chunks)),this.chunks=e.chunks,this};D.fromBuffer=function(e){var t=new D;t.chunks=[];for(var r=new p6(e);!r.finished();)try{var n=r.readUInt8(),i,o;n>0&&n<X.OP_PUSHDATA1?(i=n,t.chunks.push({buf:r.read(i),len:i,opcodenum:n})):n===X.OP_PUSHDATA1?(i=r.readUInt8(),o=r.read(i),t.chunks.push({buf:o,len:i,opcodenum:n})):n===X.OP_PUSHDATA2?(i=r.readUInt16LE(),o=r.read(i),t.chunks.push({buf:o,len:i,opcodenum:n})):n===X.OP_PUSHDATA4?(i=r.readUInt32LE(),o=r.read(i),t.chunks.push({buf:o,len:i,opcodenum:n})):t.chunks.push({opcodenum:n})}catch(s){throw s instanceof RangeError?new up.Script.InvalidBuffer(e.toString("hex")):s}return t};D.prototype.toBuffer=function(){for(var e=new g6,t=0;t<this.chunks.length;t++){var r=this.chunks[t],n=r.opcodenum;e.writeUInt8(r.opcodenum),r.buf&&(n<X.OP_PUSHDATA1?e.write(r.buf):n===X.OP_PUSHDATA1?(e.writeUInt8(r.len),e.write(r.buf)):n===X.OP_PUSHDATA2?(e.writeUInt16LE(r.len),e.write(r.buf)):n===X.OP_PUSHDATA4&&(e.writeUInt32LE(r.len),e.write(r.buf)))}return e.concat()};D.fromASM=function(e){var t=new D;t.chunks=[];for(var r=e.split(" "),n=0;n<r.length;){var i=r[n],o=X(i),s=o.toNumber();if(i==="0")s=0,t.chunks.push({opcodenum:s}),n=n+1;else if(i==="-1")s=X.OP_1NEGATE,t.chunks.push({opcodenum:s}),n=n+1;else if(Ae.isUndefined(s)){var a=d.Buffer.from(r[n],"hex");if(a.toString("hex")!==r[n])throw new Error("invalid hex string in script");var c=a.length;c>=0&&c<X.OP_PUSHDATA1?s=c:c<Math.pow(2,8)?s=X.OP_PUSHDATA1:c<Math.pow(2,16)?s=X.OP_PUSHDATA2:c<Math.pow(2,32)&&(s=X.OP_PUSHDATA4),t.chunks.push({buf:a,len:a.length,opcodenum:s}),n=n+1}else t.chunks.push({opcodenum:s}),n=n+1}return t};D.fromHex=function(e){return new D(o1.Buffer.from(e,"hex"))};D.fromString=function(e){if(y6.isHexa(e)||e.length===0)return new D(o1.Buffer.from(e,"hex"));var t=new D;t.chunks=[];for(var r=e.split(" "),n=0;n<r.length;){var i=r[n],o=X(i),s=o.toNumber();if(Ae.isUndefined(s))if(s=parseInt(i),s>0&&s<X.OP_PUSHDATA1)t.chunks.push({buf:d.Buffer.from(r[n+1].slice(2),"hex"),len:s,opcodenum:s}),n=n+2;else throw new Error("Invalid script: "+JSON.stringify(e));else if(s===X.OP_PUSHDATA1||s===X.OP_PUSHDATA2||s===X.OP_PUSHDATA4){if(r[n+2].slice(0,2)!=="0x")throw new Error("Pushdata data must start with 0x");t.chunks.push({buf:d.Buffer.from(r[n+2].slice(2),"hex"),len:parseInt(r[n+1]),opcodenum:s}),n=n+3}else t.chunks.push({opcodenum:s}),n=n+1}return t};D.prototype._chunkToString=function(e,t){var r=e.opcodenum,n=t==="asm",i="";if(e.buf)!n&&(r===X.OP_PUSHDATA1||r===X.OP_PUSHDATA2||r===X.OP_PUSHDATA4)&&(i=i+" "+X(r).toString()),e.len>0&&(n?i=i+" "+e.buf.toString("hex"):i=i+" "+e.len+" 0x"+e.buf.toString("hex"));else if(typeof X.reverseMap[r]<"u")n?r===0?i=i+" 0":r===79?i=i+" -1":i=i+" "+X(r).toString():i=i+" "+X(r).toString();else{var o=r.toString(16);o.length%2!==0&&(o="0"+o),n?i=i+" "+o:i=i+" 0x"+o}return i};D.prototype.toASM=function(){for(var e="",t=0;t<this.chunks.length;t++){var r=this.chunks[t];e+=this._chunkToString(r,"asm")}return e.substr(1)};D.prototype.toString=function(){for(var e="",t=0;t<this.chunks.length;t++){var r=this.chunks[t];e+=this._chunkToString(r)}return e.substr(1)};D.prototype.toHex=function(){return this.toBuffer().toString("hex")};D.prototype.inspect=function(){return"<Script: "+this.toString()+">"};D.prototype.isPublicKeyHashOut=function(){return!!(this.chunks.length===5&&this.chunks[0].opcodenum===X.OP_DUP&&this.chunks[1].opcodenum===X.OP_HASH160&&this.chunks[2].buf&&this.chunks[2].buf.length===20&&this.chunks[3].opcodenum===X.OP_EQUALVERIFY&&this.chunks[4].opcodenum===X.OP_CHECKSIG)};D.prototype.isPublicKeyHashOutPrefix=function(){return!!(this.chunks.length>=5&&this.chunks[0].opcodenum===X.OP_DUP&&this.chunks[1].opcodenum===X.OP_HASH160&&this.chunks[2].buf&&this.chunks[2].buf.length===20&&this.chunks[3].opcodenum===X.OP_EQUALVERIFY&&this.chunks[4].opcodenum===X.OP_CHECKSIG)};D.prototype.isPublicKeyHashIn=function(){if(this.chunks.length===2){var e=this.chunks[0].buf,t=this.chunks[1].buf;if(e&&e.length&&e[0]===48&&t&&t.length){var r=t[0];if((r===4||r===6||r===7)&&t.length===65)return!0;if((r===3||r===2)&&t.length===33)return!0}}return!1};D.prototype.getPublicKey=function(){return $e.checkState(this.isPublicKeyOut(),"Can't retrieve PublicKey from a non-PK output"),this.chunks[0].buf};D.prototype.getPublicKeyHash=function(){return $e.checkState(this.isPublicKeyHashOut(),"Can't retrieve PublicKeyHash from a non-PKH output"),this.chunks[2].buf};D.prototype.isPublicKeyOut=function(){if(this.chunks.length===2&&this.chunks[0].buf&&this.chunks[0].buf.length&&this.chunks[1].opcodenum===X.OP_CHECKSIG){var e=this.chunks[0].buf,t=e[0],r=!1;if(((t===4||t===6||t===7)&&e.length===65||(t===3||t===2)&&e.length===33)&&(r=!0),r)return ro.isValid(e)}return!1};D.prototype.isPublicKeyIn=function(){if(this.chunks.length===1){var e=this.chunks[0].buf;if(e&&e.length&&e[0]===48)return!0}return!1};D.prototype.isScriptHashOut=function(){var e=this.toBuffer();return e.length===23&&e[0]===X.OP_HASH160&&e[1]===20&&e[e.length-1]===X.OP_EQUAL};D.prototype.isScriptHashIn=function(){if(this.chunks.length<=1)return!1;var e=this.chunks[this.chunks.length-1],t=e.buf;if(!t)return!1;var r;try{r=D.fromBuffer(t)}catch(i){if(i instanceof up.Script.InvalidBuffer)return!1;throw i}var n=r.classify();return n!==D.types.UNKNOWN};D.prototype.isMultisigOut=function(){return this.chunks.length>3&&X.isSmallIntOp(this.chunks[0].opcodenum)&&this.chunks.slice(1,this.chunks.length-2).every(function(e){return e.buf&&d.Buffer.isBuffer(e.buf)})&&X.isSmallIntOp(this.chunks[this.chunks.length-2].opcodenum)&&this.chunks[this.chunks.length-1].opcodenum===X.OP_CHECKMULTISIG};D.prototype.isMultisigIn=function(){return this.chunks.length>=2&&this.chunks[0].opcodenum===0&&this.chunks.slice(1,this.chunks.length).every(function(e){return e.buf&&d.Buffer.isBuffer(e.buf)&&to.isTxDER(e.buf)})};D.prototype.isDataOut=function(){var e=this.chunks.length>=1&&this.chunks[0].opcodenum===X.OP_RETURN;if(!e)return!1;var t=this.chunks.slice(1),r=new D({chunks:t});return r.isPushOnly()};D.prototype.isSafeDataOut=function(){if(this.chunks.length<2||this.chunks[0].opcodenum!==X.OP_FALSE)return!1;var e=this.chunks.slice(1),t=new D({chunks:e});return t.isDataOut()};D.prototype.getData=function(){if(this.isSafeDataOut()){var e=this.chunks.slice(2),t=e.map(r=>r.buf);return t}if(this.isDataOut()||this.isScriptHashOut())return Ae.isUndefined(this.chunks[1])?d.Buffer.alloc(0):d.Buffer.from(this.chunks[1].buf);if(this.isPublicKeyHashOut())return d.Buffer.from(this.chunks[2].buf);throw new Error("Unrecognized script type to get data from")};D.prototype.isPushOnly=function(){return Ae.every(this.chunks,function(e){return e.opcodenum<=X.OP_16||e.opcodenum===X.OP_PUSHDATA1||e.opcodenum===X.OP_PUSHDATA2||e.opcodenum===X.OP_PUSHDATA4})};D.types={};D.types.UNKNOWN="Unknown";D.types.PUBKEY_OUT="Pay to public key";D.types.PUBKEY_IN="Spend from public key";D.types.PUBKEYHASH_OUT="Pay to public key hash";D.types.PUBKEYHASH_IN="Spend from public key hash";D.types.SCRIPTHASH_OUT="Pay to script hash";D.types.SCRIPTHASH_IN="Spend from script hash";D.types.MULTISIG_OUT="Pay to multisig";D.types.MULTISIG_IN="Spend from multisig";D.types.DATA_OUT="Data push";D.types.SAFE_DATA_OUT="Safe data push";D.OP_RETURN_STANDARD_SIZE=220;D.prototype.classify=function(){if(this._isInput)return this.classifyInput();if(this._isOutput)return this.classifyOutput();var e=this.classifyOutput();return e!==D.types.UNKNOWN?e:this.classifyInput()};D.outputIdentifiers={};D.outputIdentifiers.PUBKEY_OUT=D.prototype.isPublicKeyOut;D.outputIdentifiers.PUBKEYHASH_OUT=D.prototype.isPublicKeyHashOut;D.outputIdentifiers.MULTISIG_OUT=D.prototype.isMultisigOut;D.outputIdentifiers.SCRIPTHASH_OUT=D.prototype.isScriptHashOut;D.outputIdentifiers.DATA_OUT=D.prototype.isDataOut;D.outputIdentifiers.SAFE_DATA_OUT=D.prototype.isSafeDataOut;D.prototype.classifyOutput=function(){for(var e in D.outputIdentifiers)if(D.outputIdentifiers[e].bind(this)())return D.types[e];return D.types.UNKNOWN};D.inputIdentifiers={};D.inputIdentifiers.PUBKEY_IN=D.prototype.isPublicKeyIn;D.inputIdentifiers.PUBKEYHASH_IN=D.prototype.isPublicKeyHashIn;D.inputIdentifiers.MULTISIG_IN=D.prototype.isMultisigIn;D.inputIdentifiers.SCRIPTHASH_IN=D.prototype.isScriptHashIn;D.prototype.classifyInput=function(){for(var e in D.inputIdentifiers)if(D.inputIdentifiers[e].bind(this)())return D.types[e];return D.types.UNKNOWN};D.prototype.isStandard=function(){return this.classify()!==D.types.UNKNOWN};D.prototype.prepend=function(e){return this._addByType(e,!0),this};D.prototype.equals=function(e){if($e.checkState(e instanceof D,"Must provide another script"),this.chunks.length!==e.chunks.length)return!1;var t;for(t=0;t<this.chunks.length;t++){if(d.Buffer.isBuffer(this.chunks[t].buf)&&!d.Buffer.isBuffer(e.chunks[t].buf)||d.Buffer.isBuffer(this.chunks[t].buf)&&!this.chunks[t].buf.equals(e.chunks[t].buf))return!1;if(this.chunks[t].opcodenum!==e.chunks[t].opcodenum)return!1}return!0};D.prototype.add=function(e){return this._addByType(e,!1),this};D.prototype._addByType=function(e,t){if(typeof e=="string")this._addOpcode(e,t);else if(typeof e=="number")this._addOpcode(e,t);else if(e instanceof X)this._addOpcode(e,t);else if(d.Buffer.isBuffer(e))this._addBuffer(e,t);else if(e instanceof D)this.chunks=this.chunks.concat(e.chunks);else if(typeof e=="object")this._insertAtPosition(e,t);else throw new Error("Invalid script chunk")};D.prototype._insertAtPosition=function(e,t){t?this.chunks.unshift(e):this.chunks.push(e)};D.prototype._addOpcode=function(e,t){var r;return typeof e=="number"?r=e:e instanceof X?r=e.toNumber():r=X(e).toNumber(),this._insertAtPosition({opcodenum:r},t),this};D.prototype._addBuffer=function(e,t){var r,n=e.length;if(n>=0&&n<X.OP_PUSHDATA1)r=n;else if(n<Math.pow(2,8))r=X.OP_PUSHDATA1;else if(n<Math.pow(2,16))r=X.OP_PUSHDATA2;else if(n<Math.pow(2,32))r=X.OP_PUSHDATA4;else throw new Error("You can't push that much data");return this._insertAtPosition({buf:e,len:n,opcodenum:r},t),this};D.prototype.removeCodeseparators=function(){for(var e=[],t=0;t<this.chunks.length;t++)this.chunks[t].opcodenum!==X.OP_CODESEPARATOR&&e.push(this.chunks[t]);return this.chunks=e,this};D.buildMultisigOut=function(e,t,r){$e.checkArgument(t<=e.length,"Number of required signatures must be less than or equal to the number of public keys"),r=r||{};var n=new D;n.add(X.smallInt(t)),e=Ae.map(e,ro);var i=e;r.noSorting||(i=e.map(a=>a.toString("hex")).sort().map(a=>new ro(a)));for(var o=0;o<i.length;o++){var s=i[o];n.add(s.toBuffer())}return n.add(X.smallInt(e.length)),n.add(X.OP_CHECKMULTISIG),n};D.buildMultisigIn=function(e,t,r,n){$e.checkArgument(Ae.isArray(e)),$e.checkArgument(Ae.isNumber(t)),$e.checkArgument(Ae.isArray(r)),n=n||{};var i=new D;return i.add(X.OP_0),Ae.each(r,function(o){$e.checkArgument(d.Buffer.isBuffer(o),"Signatures must be an array of Buffers"),i.add(o)}),i};D.buildP2SHMultisigIn=function(e,t,r,n){$e.checkArgument(Ae.isArray(e)),$e.checkArgument(Ae.isNumber(t)),$e.checkArgument(Ae.isArray(r)),n=n||{};var i=new D;return i.add(X.OP_0),Ae.each(r,function(o){$e.checkArgument(d.Buffer.isBuffer(o),"Signatures must be an array of Buffers"),i.add(o)}),i.add((n.cachedMultisig||D.buildMultisigOut(e,t,n)).toBuffer()),i};D.buildPublicKeyHashOut=function(e){$e.checkArgument(!Ae.isUndefined(e)),$e.checkArgument(e instanceof ro||e instanceof Hr||Ae.isString(e)),e instanceof ro?e=e.toAddress():Ae.isString(e)&&(e=new Hr(e));var t=new D;return t.add(X.OP_DUP).add(X.OP_HASH160).add(e.hashBuffer).add(X.OP_EQUALVERIFY).add(X.OP_CHECKSIG),t._network=e.network,t};D.buildPublicKeyOut=function(e){$e.checkArgument(e instanceof ro);var t=new D;return t.add(e.toBuffer()).add(X.OP_CHECKSIG),t};D.buildDataOut=function(e,t){$e.checkArgument(Ae.isUndefined(e)||Ae.isString(e)||Ae.isArray(e)||d.Buffer.isBuffer(e));var r=e;Ae.isArray(r)||(r=[e]);var n=new D;n.add(X.OP_RETURN);for(let i of r)$e.checkArgument(Ae.isUndefined(i)||Ae.isString(i)||d.Buffer.isBuffer(i)),Ae.isString(i)&&(i=d.Buffer.from(i,t)),Ae.isUndefined(i)||n.add(i);return n};D.buildSafeDataOut=function(e,t){var r=D.buildDataOut(e,t),n=new D;return n.add(X.OP_FALSE),n.add(r),n};D.buildScriptHashOut=function(e){$e.checkArgument(e instanceof D||e instanceof Hr&&e.isPayToScriptHash());var t=new D;return t.add(X.OP_HASH160).add(e instanceof Hr?e.hashBuffer:ap.sha256ripemd160(e.toBuffer())).add(X.OP_EQUAL),t._network=e._network||e.network,t};D.buildPublicKeyIn=function(e,t){$e.checkArgument(e instanceof to||d.Buffer.isBuffer(e)),$e.checkArgument(Ae.isUndefined(t)||Ae.isNumber(t)),e instanceof to&&(e=e.toBuffer());var r=new D;return r.add(d.Buffer.concat([e,d.Buffer.from([(t||to.SIGHASH_ALL)&255])])),r};D.buildPublicKeyHashIn=function(e,t,r){$e.checkArgument(t instanceof to||d.Buffer.isBuffer(t)),$e.checkArgument(Ae.isUndefined(r)||Ae.isNumber(r)),t instanceof to&&(t=t.toBuffer());var n=new D().add(d.Buffer.concat([t,d.Buffer.from([(r||to.SIGHASH_ALL)&255])])).add(new ro(e).toBuffer());return n};D.empty=function(){return new D};D.prototype.toScriptHashOut=function(){return D.buildScriptHashOut(this)};D.fromAddress=function(e){if(e=Hr(e),e.isPayToScriptHash())return D.buildScriptHashOut(e);if(e.isPayToPublicKeyHash())return D.buildPublicKeyHashOut(e);throw new up.Script.UnrecognizedAddress(e)};D.prototype.getAddressInfo=function(e){if(this._isInput)return this._getInputAddressInfo();if(this._isOutput)return this._getOutputAddressInfo();var t=this._getOutputAddressInfo();return t||this._getInputAddressInfo()};D.prototype._getOutputAddressInfo=function(){var e={};if(this.isScriptHashOut())e.hashBuffer=this.getData(),e.type=Hr.PayToScriptHash;else if(this.isPublicKeyHashOut())e.hashBuffer=this.getData(),e.type=Hr.PayToPublicKeyHash;else return!1;return e};D.prototype._getInputAddressInfo=function(){var e={};if(this.isPublicKeyHashIn())e.hashBuffer=ap.sha256ripemd160(this.chunks[1].buf),e.type=Hr.PayToPublicKeyHash;else if(this.isScriptHashIn())e.hashBuffer=ap.sha256ripemd160(this.chunks[this.chunks.length-1].buf),e.type=Hr.PayToScriptHash;else return!1;return e};D.prototype.toAddress=function(e){var t=this.getAddressInfo();return t?(t.network=i1.get(e)||this._network||i1.defaultNetwork,new Hr(t)):!1};D.prototype.findAndDelete=function(e){for(var t=e.toBuffer(),r=t.toString("hex"),n=0;n<this.chunks.length;n++){var i=D({chunks:[this.chunks[n]]}),o=i.toBuffer(),s=o.toString("hex");r===s&&this.chunks.splice(n,1)}return this};D.prototype.checkMinimalPush=function(e){var t=this.chunks[e],r=t.buf,n=t.opcodenum;return r?r.length===0?n===X.OP_0:r.length===1&&r[0]>=1&&r[0]<=16?n===X.OP_1+(r[0]-1):r.length===1&&r[0]===129?n===X.OP_1NEGATE:r.length<=75?n===r.length:r.length<=255?n===X.OP_PUSHDATA1:r.length<=65535?n===X.OP_PUSHDATA2:!0:!0};D.prototype._decodeOP_N=function(e){if(e===X.OP_0)return 0;if(e>=X.OP_1&&e<=X.OP_16)return e-(X.OP_1-1);throw new Error("Invalid opcode: "+JSON.stringify(e))};D.prototype.getSignatureOperationsCount=function(e){e=Ae.isUndefined(e)?!0:e;var t=this,r=0,n=X.OP_INVALIDOPCODE;return Ae.each(t.chunks,function(o){var s=o.opcodenum;s===X.OP_CHECKSIG||s===X.OP_CHECKSIGVERIFY?r++:(s===X.OP_CHECKMULTISIG||s===X.OP_CHECKMULTISIGVERIFY)&&(e&&n>=X.OP_1&&n<=X.OP_16?r+=t._decodeOP_N(n):r+=20),n=s}),r};s1.exports=D});var Ma=P((LF,f1)=>{"use strict";m();var a1=Qi(),u1=va(),m6=Er(),jr=function e(t){if(!(this instanceof e))return new e(t);if(d.Buffer.isBuffer(t))this.buf=t;else if(typeof t=="number"){var r=t;this.fromNumber(r)}else if(t instanceof m6){var n=t;this.fromBN(n)}else if(t){var i=t;this.set(i)}};jr.prototype.set=function(e){return this.buf=e.buf||this.buf,this};jr.prototype.fromString=function(e){return this.set({buf:d.Buffer.from(e,"hex")}),this};jr.prototype.toString=function(){return this.buf.toString("hex")};jr.prototype.fromBuffer=function(e){return this.buf=e,this};jr.prototype.fromBufferReader=function(e){return this.buf=e.readVarintBuf(),this};jr.prototype.fromBN=function(e){return this.buf=a1().writeVarintBN(e).concat(),this};jr.prototype.fromNumber=function(e){return this.buf=a1().writeVarintNum(e).concat(),this};jr.prototype.toBuffer=function(){return this.buf};jr.prototype.toBN=function(){return u1(this.buf).readVarintBN()};jr.prototype.toNumber=function(){return u1(this.buf).readVarintNum()};f1.exports=jr});var Dn=P((UF,l1)=>{"use strict";m();var Ec=Ve(),cp=Er(),c1=Tt(),xc=pr(),v6=Qi(),b6=Ma(),lp=Kr(),hp=ke(),_6=Jn(),S6=9007199254740991;function Ut(e){if(!(this instanceof Ut))return new Ut(e);if(Ec.isObject(e))if(this.satoshis=e.satoshis,d.Buffer.isBuffer(e.script))this._scriptBuffer=e.script;else{var t;Ec.isString(e.script)&&xc.isHexa(e.script)?t=c1.Buffer.from(e.script,"hex"):t=e.script,this.setScript(t)}else throw new TypeError("Unrecognized argument for Output")}Object.defineProperty(Ut.prototype,"script",{configurable:!1,enumerable:!0,get:function(){return this._script?this._script:(this.setScriptFromBuffer(this._scriptBuffer),this._script)}});Object.defineProperty(Ut.prototype,"satoshis",{configurable:!1,enumerable:!0,get:function(){return this._satoshis},set:function(e){e instanceof cp?(this._satoshisBN=e,this._satoshis=e.toNumber()):Ec.isString(e)?(this._satoshis=parseInt(e),this._satoshisBN=cp.fromNumber(this._satoshis)):(hp.checkArgument(xc.isNaturalNumber(e),"Output satoshis is not a natural number"),this._satoshisBN=cp.fromNumber(e),this._satoshis=e),hp.checkState(xc.isNaturalNumber(this._satoshis),"Output satoshis is not a natural number")}});Ut.prototype.invalidSatoshis=function(){return this._satoshis>S6?"transaction txout satoshis greater than max safe integer":this._satoshis!==this._satoshisBN.toNumber()?"transaction txout satoshis has corrupted value":this._satoshis<0?"transaction txout negative":!1};Object.defineProperty(Ut.prototype,"satoshisBN",{configurable:!1,enumerable:!0,get:function(){return this._satoshisBN},set:function(e){this._satoshisBN=e,this._satoshis=e.toNumber(),hp.checkState(xc.isNaturalNumber(this._satoshis),"Output satoshis is not a natural number")}});Ut.prototype.toObject=Ut.prototype.toJSON=function(){var t={satoshis:this.satoshis};return t.script=this._scriptBuffer.toString("hex"),t};Ut.fromObject=function(e){return new Ut(e)};Ut.prototype.setScriptFromBuffer=function(e){this._scriptBuffer=e;try{this._script=lp.fromBuffer(this._scriptBuffer),this._script._isOutput=!0}catch(t){if(t instanceof _6.Script.InvalidBuffer)this._script=null;else throw t}};Ut.prototype.setScript=function(e){if(e instanceof lp)this._scriptBuffer=e.toBuffer(),this._script=e,this._script._isOutput=!0;else if(Ec.isString(e))this._script=lp.fromString(e),this._scriptBuffer=this._script.toBuffer(),this._script._isOutput=!0;else if(d.Buffer.isBuffer(e))this.setScriptFromBuffer(e);else throw new TypeError("Invalid argument type: script");return this};Ut.prototype.inspect=function(){var e;return this.script?e=this.script.inspect():e=this._scriptBuffer.toString("hex"),"<Output ("+this.satoshis+" sats) "+e+">"};Ut.fromBufferReader=function(e){var t={};t.satoshis=e.readUInt64LEBN();var r=e.readVarintNum();return r!==0?t.script=e.read(r):t.script=c1.Buffer.from([]),new Ut(t)};Ut.prototype.toBufferWriter=function(e){e||(e=new v6),e.writeUInt64LEBN(this._satoshisBN);var t=this._scriptBuffer;return e.writeVarintNum(t.length),e.write(t),e};Ut.prototype.getSize=function(){var e=this.script.toBuffer().length,t=b6(e).toBuffer().length;return 8+t+e};l1.exports=Ut});var ka=P((qF,h1)=>{"use strict";m();var gr=Er(),cn=ii(),w6=ir(),E6=Tr(),x6=ea(),hi=Qt(),I6=Ve(),dp=ke(),qe=function e(t){if(!(this instanceof e))return new e(t);t&&this.set(t)};Object.defineProperty(qe.prototype,"k",{get:function(){return this._k},set:function(e){this._k=e,this._kFresh=!0},enumerable:!0,configurable:!0});qe.prototype.set=function(e){if(this.hashbuf=e.hashbuf||this.hashbuf,this.endian=e.endian||this.endian,this.privkey=e.privkey||this.privkey,this.pubkey=e.pubkey||(this.privkey?this.privkey.publicKey:this.pubkey),e.sig)if(d.Buffer.isBuffer(e.sig)){var t=ir();this.sig=t.fromDER(e.sig)}else this.sig=e.sig;else this.sig=this.sig;return e.k&&(this.k=e.k),this.verified=e.verified||this.verified,this};qe.prototype.privkey2pubkey=function(){this.pubkey=this.privkey.toPublicKey()};qe.prototype.calci=function(){for(var e=0;e<4;e++){this.sig.i=e;var t;try{t=this.toPublicKey()}catch(r){console.error(r);continue}if(t.point.eq(this.pubkey.point))return this.sig.compressed=this.pubkey.compressed,this}throw this.sig.i=void 0,new Error("Unable to find valid recovery factor")};qe.fromString=function(e){var t=JSON.parse(e);return new qe(t)};qe.prototype.randomK=function(){var e=cn.getN(),t;do t=gr.fromBuffer(x6.getRandomBuffer(32));while(!(t.lt(e)&&t.gt(gr.Zero)));return this.k=t,this};qe.prototype.deterministicK=function(e){I6.isUndefined(e)&&(e=0);var t=d.Buffer.alloc(32);t.fill(1);var r=d.Buffer.alloc(32);r.fill(0);var n=this.privkey.bn.toBuffer({size:32}),i=this.endian==="little"?d.Buffer.from(this.hashbuf).reverse():this.hashbuf;r=hi.sha256hmac(d.Buffer.concat([t,d.Buffer.from([0]),n,i]),r),t=hi.sha256hmac(t,r),r=hi.sha256hmac(d.Buffer.concat([t,d.Buffer.from([1]),n,i]),r),t=hi.sha256hmac(t,r),t=hi.sha256hmac(t,r);for(var o=gr.fromBuffer(t),s=cn.getN(),a=0;a<e||!(o.lt(s)&&o.gt(gr.Zero));a++)r=hi.sha256hmac(d.Buffer.concat([t,d.Buffer.from([0])]),r),t=hi.sha256hmac(t,r),t=hi.sha256hmac(t,r),o=gr.fromBuffer(t);return this.k=o,this};qe.prototype.toPublicKey=function(){var e=this.sig.i;dp.checkArgument(e===0||e===1||e===2||e===3,new Error("i must be equal to 0, 1, 2, or 3"));var t=gr.fromBuffer(this.hashbuf),r=this.sig.r,n=this.sig.s,i=e&1,o=e>>1,s=cn.getN(),a=cn.getG(),c=o?r.add(s):r,h=cn.fromX(i,c),g=h.mul(s);if(!g.isInfinity())throw new Error("nR is not a valid curve point");var y=t.neg().umod(s),w=r.invm(s),I=h.mul(n).add(a.mul(y)).mul(w),T=E6.fromPoint(I,this.sig.compressed);return T};qe.prototype.sigError=function(){if(!d.Buffer.isBuffer(this.hashbuf)||this.hashbuf.length!==32)return"hashbuf must be a 32 byte buffer";var e=this.sig.r,t=this.sig.s,r=cn.getN();try{if(e.lte(gr.Zero)||t.lte(gr.Zero)||e.gte(r)||t.gte(r))return"r and s not in range";var n=gr.fromBuffer(this.hashbuf,this.endian?{endian:this.endian}:void 0),i=t.invm(r),o=i.mul(n).umod(r),s=i.mul(e).umod(r),a=cn.getG().mulAdd(o,this.pubkey.point,s);return a.isInfinity()?"p is infinity":a.getX().umod(r).cmp(e)!==0?"Invalid signature":!1}catch(c){return"Signature security validation failed: "+c.message}};qe.toLowS=function(e){return e.gt(gr.fromBuffer(d.Buffer.from("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex")))&&(e=cn.getN().sub(e)),e};qe.prototype._findSignature=function(e,t){var r=cn.getN(),n=cn.getG(),i=0,o,s,a,c;do(!this.k||!this._kFresh||i>0)&&this.deterministicK(i),i++,o=this.k,s=n.mul(o),a=s.x.umod(r),c=o.invm(r).mul(t.add(e.mul(a))).umod(r);while(a.cmp(gr.Zero)<=0||c.cmp(gr.Zero)<=0);return this._kFresh=!1,c=qe.toLowS(c),{s:c,r:a}};qe.prototype.sign=function(){var e=this.hashbuf,t=this.privkey,r=t.bn;dp.checkState(e&&t&&r,new Error("invalid parameters")),dp.checkState(d.Buffer.isBuffer(e)&&e.length===32,new Error("hashbuf must be a 32 byte buffer"));var n=gr.fromBuffer(e,this.endian?{endian:this.endian}:void 0),i=this._findSignature(r,n);return i.compressed=this.pubkey.compressed,this.sig=new w6(i),this};qe.prototype.signRandomK=function(){return this.randomK(),this.sign()};qe.prototype.toString=function(){var e={};return this.hashbuf&&(e.hashbuf=this.hashbuf.toString("hex")),this.privkey&&(e.privkey=this.privkey.toString()),this.pubkey&&(e.pubkey=this.pubkey.toString()),this.sig&&(e.sig=this.sig.toString()),this.k&&(e.k=this.k.toString()),JSON.stringify(e)};qe.prototype.verify=function(){return this.verified=!this.sigError(),this.verified};qe.prototype.verifyBool=function(){return this.verify()===!0};qe.sign=function(e,t,r){return qe().set({hashbuf:e,endian:r,privkey:t}).sign().sig};qe.signWithCalcI=function(e,t,r){return qe().set({hashbuf:e,endian:r,privkey:t}).sign().calci().sig};qe.signRandomK=function(e,t,r){return qe().set({hashbuf:e,endian:r,privkey:t}).signRandomK().sig};qe.verify=function(e,t,r,n){return qe().set({hashbuf:e,endian:n,sig:t,pubkey:r}).verify()};h1.exports=qe});var os=P((jF,y1)=>{"use strict";m();var di=Ve(),A6=ke(),Ca=Jn(),O6=Qi(),pp=Tt(),p1=pr(),Ic=Kr(),R6=pi(),d1=Dn(),Ac=4294967295,T6=Ac-2,g1=Ac,P6=Ac-1;function He(e){if(!(this instanceof He))return new He(e);if(e)return this._fromObject(e)}He.MAXINT=Ac;He.DEFAULT_SEQNUMBER=g1;He.DEFAULT_LOCKTIME_SEQNUMBER=P6;He.DEFAULT_RBF_SEQNUMBER=T6;He.BASE_SIZE=40;Object.defineProperty(He.prototype,"script",{configurable:!1,enumerable:!0,get:function(){return this.isNull()?null:(this._script||(this._script=new Ic(this._scriptBuffer),this._script._isInput=!0),this._script)}});He.fromObject=function(e){A6.checkArgument(di.isObject(e));var t=new He;return t._fromObject(e)};He.prototype._fromObject=function(e){var t;if(di.isString(e.prevTxId)&&p1.isHexa(e.prevTxId)?t=pp.Buffer.from(e.prevTxId,"hex"):t=e.prevTxId,this.output=e.output?e.output instanceof d1?e.output:new d1(e.output):void 0,this.prevTxId=t||e.txidbuf,this.outputIndex=di.isUndefined(e.outputIndex)?e.txoutnum:e.outputIndex,this.sequenceNumber=di.isUndefined(e.sequenceNumber)?di.isUndefined(e.seqnum)?g1:e.seqnum:e.sequenceNumber,di.isUndefined(e.script)&&di.isUndefined(e.scriptBuffer))throw new Ca.Transaction.Input.MissingScript;return this.setScript(e.scriptBuffer||e.script),this};He.prototype.toObject=He.prototype.toJSON=function(){var t={prevTxId:this.prevTxId.toString("hex"),outputIndex:this.outputIndex,sequenceNumber:this.sequenceNumber,script:this._scriptBuffer.toString("hex")};return this.script&&(t.scriptString=this.script.toString()),this.output&&(t.output=this.output.toObject()),t};He.fromBufferReader=function(e){var t=new He;return t.prevTxId=e.readReverse(32),t.outputIndex=e.readUInt32LE(),t._scriptBuffer=e.readVarLengthBuffer(),t.sequenceNumber=e.readUInt32LE(),t};He.prototype.toBufferWriter=function(e){e||(e=new O6),e.writeReverse(this.prevTxId),e.writeUInt32LE(this.outputIndex);var t=this._scriptBuffer;return e.writeVarintNum(t.length),e.write(t),e.writeUInt32LE(this.sequenceNumber),e};He.prototype.setScript=function(e){if(this._script=null,e instanceof Ic)this._script=e,this._script._isInput=!0,this._scriptBuffer=e.toBuffer();else if(e===null)this._script=Ic.empty(),this._script._isInput=!0,this._scriptBuffer=this._script.toBuffer();else if(p1.isHexa(e))this._scriptBuffer=pp.Buffer.from(e,"hex");else if(di.isString(e))this._script=new Ic(e),this._script._isInput=!0,this._scriptBuffer=this._script.toBuffer();else if(d.Buffer.isBuffer(e))this._scriptBuffer=pp.Buffer.from(e);else throw new TypeError("Invalid argument type: script");return this};He.prototype.getSignatures=function(){throw new Ca.AbstractMethodInvoked("Trying to sign unsupported output type (only P2PKH and P2SH multisig inputs are supported) for input: "+JSON.stringify(this))};He.prototype.isFullySigned=function(){throw new Ca.AbstractMethodInvoked("Input#isFullySigned")};He.prototype.isFinal=function(){return this.sequenceNumber===He.MAXINT};He.prototype.addSignature=function(){throw new Ca.AbstractMethodInvoked("Input#addSignature")};He.prototype.clearSignatures=function(){throw new Ca.AbstractMethodInvoked("Input#clearSignatures")};He.prototype.isValidSignature=function(e,t){return t.signature.nhashtype=t.sigtype,R6.verify(e,t.signature,t.publicKey,t.inputIndex,this.output.script,this.output.satoshisBN)};He.prototype.isNull=function(){return this.prevTxId.toString("hex")==="0000000000000000000000000000000000000000000000000000000000000000"&&this.outputIndex===4294967295};He.prototype._estimateSize=function(){return this.toBufferWriter().toBuffer().length};y1.exports=He});var ss=P((VF,m1)=>{"use strict";m();m1.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}});var us=P((zF,_1)=>{"use strict";m();var as=Ve(),Pr=ke(),B6=ss(),v1=pr(),b1=Tr(),N6=Jn(),La=ir();function Vr(e){if(!(this instanceof Vr))return new Vr(e);if(e instanceof Vr)return e;if(as.isObject(e))return this._fromObject(e);throw new N6.InvalidArgument("TransactionSignatures must be instantiated from an object")}B6(Vr,La);Vr.prototype._fromObject=function(e){return this._checkObjectArgs(e),this.publicKey=new b1(e.publicKey),this.prevTxId=d.Buffer.isBuffer(e.prevTxId)?e.prevTxId:d.Buffer.from(e.prevTxId,"hex"),this.outputIndex=e.outputIndex,this.inputIndex=e.inputIndex,this.signature=e.signature instanceof La?e.signature:d.Buffer.isBuffer(e.signature)?La.fromBuffer(e.signature):La.fromString(e.signature),this.sigtype=e.sigtype,this};Vr.prototype._checkObjectArgs=function(e){Pr.checkArgument(b1(e.publicKey),"publicKey"),Pr.checkArgument(!as.isUndefined(e.inputIndex),"inputIndex"),Pr.checkArgument(!as.isUndefined(e.outputIndex),"outputIndex"),Pr.checkState(as.isNumber(e.inputIndex),"inputIndex must be a number"),Pr.checkState(as.isNumber(e.outputIndex),"outputIndex must be a number"),Pr.checkArgument(e.signature,"signature"),Pr.checkArgument(e.prevTxId,"prevTxId"),Pr.checkState(e.signature instanceof La||d.Buffer.isBuffer(e.signature)||v1.isHexa(e.signature),"signature must be a buffer or hexa value"),Pr.checkState(d.Buffer.isBuffer(e.prevTxId)||v1.isHexa(e.prevTxId),"prevTxId must be a buffer or hexa value"),Pr.checkArgument(e.sigtype,"sigtype"),Pr.checkState(as.isNumber(e.sigtype),"sigtype must be a number")};Vr.prototype.toObject=Vr.prototype.toJSON=function(){return{publicKey:this.publicKey.toString(),prevTxId:this.prevTxId.toString("hex"),outputIndex:this.outputIndex,inputIndex:this.inputIndex,signature:this.signature.toString(),sigtype:this.sigtype}};Vr.fromObject=function(e){return Pr.checkArgument(e),new Vr(e)};_1.exports=Vr});var I1=P((YF,x1)=>{"use strict";m();var M6=ss(),w1=ke(),gp=os(),k6=Dn(),C6=pi(),E1=Kr(),S1=ir(),L6=us();function Un(){gp.apply(this,arguments)}M6(Un,gp);Un.prototype.getSignatures=function(e,t,r,n){w1.checkState(this.output instanceof k6),n=n||S1.SIGHASH_ALL|S1.SIGHASH_FORKID;var i=t.toPublicKey();return i.toString()===this.output.script.getPublicKey().toString("hex")?[new L6({publicKey:i,prevTxId:this.prevTxId,outputIndex:this.outputIndex,inputIndex:r,signature:C6.sign(e,t,n,r,this.output.script,this.output.satoshisBN),sigtype:n})]:[]};Un.prototype.addSignature=function(e,t){return w1.checkState(this.isValidSignature(e,t),"Signature is invalid"),this.setScript(E1.buildPublicKeyIn(t.signature.toDER(),t.sigtype)),this};Un.prototype.clearSignatures=function(){return this.setScript(E1.empty()),this};Un.prototype.isFullySigned=function(){return this.script.isPublicKeyIn()};Un.SCRIPT_MAX_SIZE=74;Un.prototype._estimateSize=function(){return gp.BASE_SIZE+Un.SCRIPT_MAX_SIZE};x1.exports=Un});var P1=P((ZF,T1)=>{"use strict";m();var D6=ss(),O1=ke(),U6=Qt(),yp=os(),F6=Dn(),q6=pi(),R1=Kr(),A1=ir(),H6=us();function Fn(){yp.apply(this,arguments)}D6(Fn,yp);Fn.prototype.getSignatures=function(e,t,r,n,i){O1.checkState(this.output instanceof F6),i=i||U6.sha256ripemd160(t.publicKey.toBuffer()),n=n||A1.SIGHASH_ALL|A1.SIGHASH_FORKID;var o=this.output.script.chunks[2]&&this.output.script.chunks[2].buf;return o&&i.equals(o)?[new H6({publicKey:t.publicKey,prevTxId:this.prevTxId,outputIndex:this.outputIndex,inputIndex:r,signature:q6.sign(e,t,n,r,this.output.script,this.output.satoshisBN),sigtype:n})]:[]};Fn.prototype.addSignature=function(e,t){return O1.checkState(this.isValidSignature(e,t),"Signature is invalid"),this.setScript(R1.buildPublicKeyHashIn(t.publicKey,t.signature.toDER(),t.sigtype)),this};Fn.prototype.clearSignatures=function(){return this.setScript(R1.empty()),this};Fn.prototype.isFullySigned=function(){return this.script.isPublicKeyHashIn()};Fn.SCRIPT_MAX_SIZE=108;Fn.prototype._estimateSize=function(){return yp.BASE_SIZE+Fn.SCRIPT_MAX_SIZE};T1.exports=Fn});var M1=P((JF,N1)=>{"use strict";m();var Gr=Ve(),j6=ss(),Rc=os(),K6=Dn(),Da=ke(),B1=Kr(),Oc=ir(),mp=pi(),vp=us(),V6=Tr(),G6=Ma();function Pt(e,t,r,n){Rc.apply(this,arguments);var i=this;t=t||e.publicKeys,r=r||e.threshold,n=n||e.signatures,this.publicKeys=t.map(o=>o.toString("hex")).sort().map(o=>new V6(o)),Da.checkState(B1.buildMultisigOut(this.publicKeys,r).equals(this.output.script),"Provided public keys don't match to the provided output script"),this.publicKeyIndex={},Gr.each(this.publicKeys,function(o,s){i.publicKeyIndex[o.toString()]=s}),this.threshold=r,this.signatures=n?this._deserializeSignatures(n):new Array(this.publicKeys.length)}j6(Pt,Rc);Pt.prototype.toObject=function(){var e=Rc.prototype.toObject.apply(this,arguments);return e.threshold=this.threshold,e.publicKeys=Gr.map(this.publicKeys,function(t){return t.toString()}),e.signatures=this._serializeSignatures(),e};Pt.prototype._deserializeSignatures=function(e){return Gr.map(e,function(t){if(t)return new vp(t)})};Pt.prototype._serializeSignatures=function(){return Gr.map(this.signatures,function(e){if(e)return e.toObject()})};Pt.prototype.getSignatures=function(e,t,r,n){Da.checkState(this.output instanceof K6),n=n||Oc.SIGHASH_ALL|Oc.SIGHASH_FORKID;var i=this,o=[];return Gr.each(this.publicKeys,function(s){s.toString()===t.publicKey.toString()&&o.push(new vp({publicKey:t.publicKey,prevTxId:i.prevTxId,outputIndex:i.outputIndex,inputIndex:r,signature:mp.sign(e,t,n,r,i.output.script,i.output.satoshisBN),sigtype:n}))}),o};Pt.prototype.addSignature=function(e,t){return Da.checkState(!this.isFullySigned(),"All needed signatures have already been added"),Da.checkArgument(!Gr.isUndefined(this.publicKeyIndex[t.publicKey.toString()]),"Signature has no matching public key"),Da.checkState(this.isValidSignature(e,t)),this.signatures[this.publicKeyIndex[t.publicKey.toString()]]=t,this._updateScript(),this};Pt.prototype._updateScript=function(){return this.setScript(B1.buildMultisigIn(this.publicKeys,this.threshold,this._createSignatures())),this};Pt.prototype._createSignatures=function(){return Gr.map(Gr.filter(this.signatures,function(e){return!Gr.isUndefined(e)}),function(e){return d.Buffer.concat([e.signature.toDER(),d.Buffer.from([e.sigtype&255])])})};Pt.prototype.clearSignatures=function(){this.signatures=new Array(this.publicKeys.length),this._updateScript()};Pt.prototype.isFullySigned=function(){return this.countSignatures()===this.threshold};Pt.prototype.countMissingSignatures=function(){return this.threshold-this.countSignatures()};Pt.prototype.countSignatures=function(){return Gr.reduce(this.signatures,function(e,t){return e+!!t},0)};Pt.prototype.publicKeysWithoutSignature=function(){var e=this;return Gr.filter(this.publicKeys,function(t){return!e.signatures[e.publicKeyIndex[t.toString()]]})};Pt.prototype.isValidSignature=function(e,t){return t.signature.nhashtype=t.sigtype,mp.verify(e,t.signature,t.publicKey,t.inputIndex,this.output.script,this.output.satoshisBN)};Pt.normalizeSignatures=function(e,t,r,n,i){return i.map(function(o){var s=null;return n=n.filter(function(a){if(s)return!0;var c=new vp({signature:Oc.fromTxFormat(a),publicKey:o,prevTxId:t.prevTxId,outputIndex:t.outputIndex,inputIndex:r,sigtype:Oc.SIGHASH_ALL});c.signature.nhashtype=c.sigtype;var h=mp.verify(e,c.signature,c.publicKey,c.inputIndex,t.output.script);return h?(s=c,!1):!0}),s||null})};Pt.SIGNATURE_SIZE=73;Pt.prototype._estimateSize=function(){var e=1+this.threshold*Pt.SIGNATURE_SIZE;return Rc.BASE_SIZE+G6(e).toBuffer().length+e};N1.exports=Pt});var U1=P((e5,D1)=>{"use strict";m();var zr=Ve(),z6=ss(),Tc=os(),W6=Dn(),Ua=ke(),bp=Kr(),k1=ir(),C1=pi(),L1=us(),Y6=Tr(),$6=Ma();function Ot(e,t,r,n){Tc.apply(this,arguments);var i=this;t=t||e.publicKeys,r=r||e.threshold,n=n||e.signatures,this.publicKeys=t.map(o=>o.toString("hex")).sort().map(o=>new Y6(o)),this.redeemScript=bp.buildMultisigOut(this.publicKeys,r),Ua.checkState(bp.buildScriptHashOut(this.redeemScript).equals(this.output.script),"Provided public keys don't hash to the provided output"),this.publicKeyIndex={},zr.each(this.publicKeys,function(o,s){i.publicKeyIndex[o.toString()]=s}),this.threshold=r,this.signatures=n?this._deserializeSignatures(n):new Array(this.publicKeys.length)}z6(Ot,Tc);Ot.prototype.toObject=function(){var e=Tc.prototype.toObject.apply(this,arguments);return e.threshold=this.threshold,e.publicKeys=zr.map(this.publicKeys,function(t){return t.toString()}),e.signatures=this._serializeSignatures(),e};Ot.prototype._deserializeSignatures=function(e){return zr.map(e,function(t){if(t)return new L1(t)})};Ot.prototype._serializeSignatures=function(){return zr.map(this.signatures,function(e){if(e)return e.toObject()})};Ot.prototype.getSignatures=function(e,t,r,n){Ua.checkState(this.output instanceof W6),n=n||k1.SIGHASH_ALL|k1.SIGHASH_FORKID;var i=this,o=[];return zr.each(this.publicKeys,function(s){s.toString()===t.publicKey.toString()&&o.push(new L1({publicKey:t.publicKey,prevTxId:i.prevTxId,outputIndex:i.outputIndex,inputIndex:r,signature:C1.sign(e,t,n,r,i.redeemScript,i.output.satoshisBN),sigtype:n}))}),o};Ot.prototype.addSignature=function(e,t){return Ua.checkState(!this.isFullySigned(),"All needed signatures have already been added"),Ua.checkArgument(!zr.isUndefined(this.publicKeyIndex[t.publicKey.toString()]),"Signature has no matching public key"),Ua.checkState(this.isValidSignature(e,t)),this.signatures[this.publicKeyIndex[t.publicKey.toString()]]=t,this._updateScript(),this};Ot.prototype._updateScript=function(){return this.setScript(bp.buildP2SHMultisigIn(this.publicKeys,this.threshold,this._createSignatures(),{cachedMultisig:this.redeemScript})),this};Ot.prototype._createSignatures=function(){return zr.map(zr.filter(this.signatures,function(e){return!zr.isUndefined(e)}),function(e){return d.Buffer.concat([e.signature.toDER(),d.Buffer.from([e.sigtype&255])])})};Ot.prototype.clearSignatures=function(){this.signatures=new Array(this.publicKeys.length),this._updateScript()};Ot.prototype.isFullySigned=function(){return this.countSignatures()===this.threshold};Ot.prototype.countMissingSignatures=function(){return this.threshold-this.countSignatures()};Ot.prototype.countSignatures=function(){return zr.reduce(this.signatures,function(e,t){return e+!!t},0)};Ot.prototype.publicKeysWithoutSignature=function(){var e=this;return zr.filter(this.publicKeys,function(t){return!e.signatures[e.publicKeyIndex[t.toString()]]})};Ot.prototype.isValidSignature=function(e,t){return t.signature.nhashtype=t.sigtype,C1.verify(e,t.signature,t.publicKey,t.inputIndex,this.redeemScript,this.output.satoshisBN)};Ot.SIGNATURE_SIZE=73;Ot.PUBKEY_SIZE=34;Ot.prototype._estimateSize=function(){var e=this.publicKeys.length*Ot.PUBKEY_SIZE,t=this.threshold*Ot.SIGNATURE_SIZE,r=3+e,n=r<=75?1:r<=255?2:3,i=t+1+n+r;return Tc.BASE_SIZE+$6(i).toBuffer().length+i};D1.exports=Ot});var Pc=P((r5,fs)=>{m();fs.exports=os();fs.exports.PublicKey=I1();fs.exports.PublicKeyHash=P1();fs.exports.MultiSig=M1();fs.exports.MultiSigScriptHash=U1()});var pi=P((i5,K1)=>{"use strict";m();var Z6=Tt(),fr=ir(),_p=Kr(),X6=Dn(),J6=va(),Fa=Qi(),F1=Er(),Bc=Qt(),q1=ka(),Sp=ke(),wp=Nc(),gi=Ve(),H1=d.Buffer.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),Q6="ffffffffffffffff",ek=wp.SCRIPT_ENABLE_SIGHASH_FORKID,tk=function(e,t,r,n,i){var o=e.inputs[r];Sp.checkArgument(i instanceof F1,"For ForkId=0 signatures, satoshis or complete input must be provided");function s(M){var L=new Fa;gi.each(M.inputs,function(q){L.writeReverse(q.prevTxId),L.writeUInt32LE(q.outputIndex)});var j=L.toBuffer(),G=Bc.sha256sha256(j);return G}function a(M){var L=new Fa;gi.each(M.inputs,function(q){L.writeUInt32LE(q.sequenceNumber)});var j=L.toBuffer(),G=Bc.sha256sha256(j);return G}function c(M,L){var j=new Fa;gi.isUndefined(L)?gi.each(M.outputs,function(W){W.toBufferWriter(j)}):M.outputs[L].toBufferWriter(j);var G=j.toBuffer(),q=Bc.sha256sha256(G);return q}var h=d.Buffer.alloc(32),g=d.Buffer.alloc(32),y=d.Buffer.alloc(32);t&fr.SIGHASH_ANYONECANPAY||(h=s(e)),!(t&fr.SIGHASH_ANYONECANPAY)&&(t&31)!==fr.SIGHASH_SINGLE&&(t&31)!==fr.SIGHASH_NONE&&(g=a(e)),(t&31)!==fr.SIGHASH_SINGLE&&(t&31)!==fr.SIGHASH_NONE?y=c(e):(t&31)===fr.SIGHASH_SINGLE&&r<e.outputs.length&&(y=c(e,r));var w=new Fa;w.writeInt32LE(e.version),w.write(h),w.write(g),w.writeReverse(o.prevTxId),w.writeUInt32LE(o.outputIndex),w.writeVarintNum(n.toBuffer().length),w.write(n.toBuffer()),w.writeUInt64LEBN(i);var I=o.sequenceNumber;w.writeUInt32LE(I),w.write(y),w.writeUInt32LE(e.nLockTime),w.writeUInt32LE(t>>>0);var T=w.toBuffer();return T},j1=function(t,r,n,i,o,s){var a=xp(),c=Pc();gi.isUndefined(s)&&(s=ek);var h=a.shallowCopy(t);if(i=new _p(i),s&wp.SCRIPT_ENABLE_REPLAY_PROTECTION){var g=r>>8,y=16711680|g^57005;r=y<<8|r&255}if(r&fr.SIGHASH_FORKID&&!(r&fr.SIGHASH_CHRONICLE)&&s&wp.SCRIPT_ENABLE_SIGHASH_FORKID)return tk(h,r,n,i,o);i.removeCodeseparators();var w;for(w=0;w<h.inputs.length;w++)h.inputs[w]=new c(h.inputs[w]).setScript(_p.empty());if(h.inputs[n]=new c(h.inputs[n]).setScript(i),(r&31)===fr.SIGHASH_NONE||(r&31)===fr.SIGHASH_SINGLE)for(w=0;w<h.inputs.length;w++)w!==n&&(h.inputs[w].sequenceNumber=0);if((r&31)===fr.SIGHASH_NONE)h.outputs=[];else if((r&31)===fr.SIGHASH_SINGLE){if(n>=h.outputs.length)return H1;for(h.outputs.length=n+1,w=0;w<n;w++)h.outputs[w]=new X6({satoshis:F1.fromBuffer(Z6.Buffer.from(Q6,"hex")),script:_p.empty()})}r&fr.SIGHASH_ANYONECANPAY&&(h.inputs=[h.inputs[n]]);var I=new Fa().write(h.toBuffer()).writeInt32LE(r).toBuffer();return I},Ep=function(t,r,n,i,o,s){var a=j1(t,r,n,i,o,s);if(a.compare(H1)===0)return a;var c=Bc.sha256sha256(a);return c=new J6(c).readReverse(),c};function rk(e,t,r,n,i,o,s){var a=Ep(e,r,n,i,o,s),c=q1.sign(a,t,"little").set({nhashtype:r});return c}function nk(e,t,r,n,i,o,s){Sp.checkArgument(!gi.isUndefined(e)),Sp.checkArgument(!gi.isUndefined(t)&&!gi.isUndefined(t.nhashtype));var a=Ep(e,t.nhashtype,n,i,o,s);return q1.verify(a,t,r,"little")}K1.exports={sighashPreimage:j1,sighash:Ep,sign:rk,verify:nk}});var Ip=P((s5,G1)=>{"use strict";m();var qn=Ve(),Mc=ke(),V1=pr(),ik=Kr(),ok=no();function Hn(e){if(!(this instanceof Hn))return new Hn(e);Mc.checkArgument(qn.isObject(e),"Must provide an object from where to extract data");var t=e.address?new ok(e.address):void 0,r=e.txid?e.txid:e.txId;if(!r||!V1.isHexaString(r)||r.length>64)throw new Error("Invalid TXID in object",e);var n=qn.isUndefined(e.vout)?e.outputIndex:e.vout;if(!qn.isNumber(n))throw new Error("Invalid outputIndex, received "+n);Mc.checkArgument(!qn.isUndefined(e.scriptPubKey)||!qn.isUndefined(e.script),"Must provide the scriptPubKey for that output!");var i=new ik(e.scriptPubKey||e.script);Mc.checkArgument(!qn.isUndefined(e.amount)||!qn.isUndefined(e.satoshis),"Must provide an amount for the output");var o=qn.isUndefined(e.amount)?e.satoshis:Math.round(e.amount*1e8);Mc.checkArgument(qn.isNumber(o),"Amount must be a number"),V1.defineImmutable(this,{address:t,txId:r,outputIndex:n,script:i,satoshis:o})}Hn.prototype.inspect=function(){return"<UnspentOutput: "+this.txId+":"+this.outputIndex+", satoshis: "+this.satoshis+", address: "+this.address+">"};Hn.prototype.toString=function(){return this.txId+":"+this.outputIndex};Hn.fromObject=function(e){return new Hn(e)};Hn.prototype.toObject=Hn.prototype.toJSON=function(){return{address:this.address?this.address.toString():void 0,txid:this.txId,vout:this.outputIndex,scriptPubKey:this.script.toBuffer().toString("hex"),amount:Number.parseFloat((this.satoshis/1e8).toFixed(8))}};G1.exports=Hn});var xp=P((u5,Q1)=>{"use strict";m();var pe=Ve(),Ft=ke(),sk=Tt(),Nt=Jn(),W1=pr(),Y1=va(),ak=Qi(),z1=Ma(),$1=Qt(),Cc=ir(),Z1=pi(),uk=no(),X1=Ip(),Bt=Pc(),fk=Bt.PublicKeyHash,ck=Bt.PublicKey,lk=Bt.MultiSigScriptHash,hk=Bt.MultiSig,Wr=Dn(),ln=Kr(),dk=io(),kc=Er(),pk=Nc(),gk=pk.SCRIPT_ENABLE_SIGHASH_FORKID;function z(e){if(!(this instanceof z))return new z(e);if(this.inputs=[],this.outputs=[],this._inputAmount=void 0,this._outputAmount=void 0,e){if(e instanceof z)return z.shallowCopy(e);if(W1.isHexa(e))this.fromString(e);else if(d.Buffer.isBuffer(e))this.fromBuffer(e);else if(pe.isObject(e))this.fromObject(e);else throw new Nt.InvalidArgument("Must provide an object or string to deserialize a transaction")}else this._newTransaction()}var yk=1,mk=0,vk=1e6;z.DUST_AMOUNT=546;z.FEE_SECURITY_MARGIN=150;z.MAX_MONEY=21e6*1e8;z.NLOCKTIME_BLOCKHEIGHT_LIMIT=5e8;z.NLOCKTIME_MAX_VALUE=4294967295;z.FEE_PER_KB=500;z.CHANGE_OUTPUT_MAX_SIZE=62;z.shallowCopy=function(e){var t=new z(e.toBuffer());return t};var J1={configurable:!1,enumerable:!0,get:function(){return this._hash=new Y1(this._getHash()).readReverse().toString("hex"),this._hash}};Object.defineProperty(z.prototype,"hash",J1);Object.defineProperty(z.prototype,"id",J1);var Ap={configurable:!1,enumerable:!0,get:function(){return this._getInputAmount()}};Object.defineProperty(z.prototype,"inputAmount",Ap);Ap.get=function(){return this._getOutputAmount()};Object.defineProperty(z.prototype,"outputAmount",Ap);z.prototype._getHash=function(){return $1.sha256sha256(this.toBuffer())};z.prototype.serialize=function(e){return e===!0||e&&e.disableAll?this.uncheckedSerialize():this.checkedSerialize(e)};z.prototype.uncheckedSerialize=z.prototype.toString=function(){return this.toBuffer().toString("hex")};z.prototype.checkedSerialize=function(e){var t=this.getSerializationError(e);if(t)throw t.message+=" - For more information please see: https://bsv.io/api/lib/transaction#serialization-checks",t;return this.uncheckedSerialize()};z.prototype.invalidSatoshis=function(){for(var e=!1,t=0;t<this.outputs.length;t++)this.outputs[t].invalidSatoshis()&&(e=!0);return e};z.prototype.getSerializationError=function(e){if(e=e||{},this.invalidSatoshis())return new Nt.Transaction.InvalidSatoshis;var t=this._getUnspentValue(),r;return t<0?e.disableMoreOutputThanInput||(r=new Nt.Transaction.InvalidOutputAmountSum):r=this._hasFeeError(e,t),r||this._hasDustOutputs(e)||this._isMissingSignatures(e)};z.prototype._hasFeeError=function(e,t){if(!pe.isUndefined(this._fee)&&this._fee!==t)return new Nt.Transaction.FeeError.Different("Unspent value is "+t+" but specified fee is "+this._fee);if(!e.disableLargeFees){var r=Math.floor(z.FEE_SECURITY_MARGIN*this._estimateFee());if(t>r)return this._missingChange()?new Nt.Transaction.ChangeAddressMissing("Fee is too large and no change address was provided"):new Nt.Transaction.FeeError.TooLarge("expected less than "+r+" but got "+t)}};z.prototype._missingChange=function(){return!this._changeScript};z.prototype._hasDustOutputs=function(e){if(!e.disableDustOutputs){var t,r;for(t in this.outputs)if(r=this.outputs[t],r.satoshis<z.DUST_AMOUNT&&!r.script.isDataOut()&&!r.script.isSafeDataOut())return new Nt.Transaction.DustOutputs}};z.prototype._isMissingSignatures=function(e){if(!e.disableIsFullySigned&&!this.isFullySigned())return new Nt.Transaction.MissingSignatures};z.prototype.inspect=function(){return"<Transaction: "+this.uncheckedSerialize()+">"};z.prototype.toBuffer=function(){var e=new ak;return this.toBufferWriter(e).toBuffer()};z.prototype.toBufferWriter=function(e){return e.writeInt32LE(this.version),e.writeVarintNum(this.inputs.length),pe.each(this.inputs,function(t){t.toBufferWriter(e)}),e.writeVarintNum(this.outputs.length),pe.each(this.outputs,function(t){t.toBufferWriter(e)}),e.writeUInt32LE(this.nLockTime),e};z.prototype.fromBuffer=function(e){var t=new Y1(e);return this.fromBufferReader(t)};z.prototype.fromBufferReader=function(e){Ft.checkArgument(!e.finished(),"No transaction data received");var t,r,n;for(this.version=e.readInt32LE(),r=e.readVarintNum(),t=0;t<r;t++){var i=Bt.fromBufferReader(e);this.inputs.push(i)}for(n=e.readVarintNum(),t=0;t<n;t++)this.outputs.push(Wr.fromBufferReader(e));return this.nLockTime=e.readUInt32LE(),this};z.prototype.toObject=z.prototype.toJSON=function(){var t=[];this.inputs.forEach(function(i){t.push(i.toObject())});var r=[];this.outputs.forEach(function(i){r.push(i.toObject())});var n={hash:this.hash,version:this.version,inputs:t,outputs:r,nLockTime:this.nLockTime};return this._changeScript&&(n.changeScript=this._changeScript.toString()),pe.isUndefined(this._changeIndex)||(n.changeIndex=this._changeIndex),pe.isUndefined(this._fee)||(n.fee=this._fee),n};z.prototype.fromObject=function(t){Ft.checkArgument(pe.isObject(t)||t instanceof z);var r=this,n;return t instanceof z?n=t.toObject():n=t,pe.each(n.inputs,function(i){if(!i.output||!i.output.script){r.uncheckedAddInput(new Bt(i));return}var o=new ln(i.output.script),s;if(o.isPublicKeyHashOut())s=new Bt.PublicKeyHash(i);else if(o.isScriptHashOut()&&i.publicKeys&&i.threshold)s=new Bt.MultiSigScriptHash(i,i.publicKeys,i.threshold,i.signatures);else if(o.isPublicKeyOut())s=new Bt.PublicKey(i);else throw new Nt.Transaction.Input.UnsupportedScript(i.output.script);r.addInput(s)}),pe.each(n.outputs,function(i){r.addOutput(new Wr(i))}),n.changeIndex&&(this._changeIndex=n.changeIndex),n.changeScript&&(this._changeScript=new ln(n.changeScript)),n.fee&&(this._fee=n.fee),this.nLockTime=n.nLockTime,this.version=n.version,this._checkConsistency(t),this};z.prototype._checkConsistency=function(e){pe.isUndefined(this._changeIndex)||(Ft.checkState(this._changeScript,"Change script is expected."),Ft.checkState(this.outputs[this._changeIndex],"Change index points to undefined output."),Ft.checkState(this.outputs[this._changeIndex].script.toString()===this._changeScript.toString(),"Change output has an unexpected script.")),e&&e.hash&&Ft.checkState(e.hash===this.hash,"Hash in object does not match transaction hash.")};z.prototype.lockUntilDate=function(e){if(Ft.checkArgument(e),pe.isNumber(e)&&e<z.NLOCKTIME_BLOCKHEIGHT_LIMIT)throw new Nt.Transaction.LockTimeTooEarly;pe.isDate(e)&&(e=e.getTime()/1e3);for(var t=0;t<this.inputs.length;t++)this.inputs[t].sequenceNumber===Bt.DEFAULT_SEQNUMBER&&(this.inputs[t].sequenceNumber=Bt.DEFAULT_LOCKTIME_SEQNUMBER);return this.nLockTime=e,this};z.prototype.lockUntilBlockHeight=function(e){if(Ft.checkArgument(pe.isNumber(e)),e>=z.NLOCKTIME_BLOCKHEIGHT_LIMIT)throw new Nt.Transaction.BlockHeightTooHigh;if(e<0)throw new Nt.Transaction.NLockTimeOutOfRange;for(var t=0;t<this.inputs.length;t++)this.inputs[t].sequenceNumber===Bt.DEFAULT_SEQNUMBER&&(this.inputs[t].sequenceNumber=Bt.DEFAULT_LOCKTIME_SEQNUMBER);return this.nLockTime=e,this};z.prototype.getLockTime=function(){return this.nLockTime?this.nLockTime<z.NLOCKTIME_BLOCKHEIGHT_LIMIT?this.nLockTime:new Date(1e3*this.nLockTime):null};z.prototype.fromString=function(e){this.fromBuffer(sk.Buffer.from(e,"hex"))};z.prototype._newTransaction=function(){this.version=yk,this.nLockTime=mk};z.prototype.from=function(e,t,r){if(pe.isArray(e)){var n=this;return pe.each(e,function(o){n.from(o,t,r)}),this}var i=pe.some(this.inputs,function(o){return o.prevTxId.toString("hex")===e.txId&&o.outputIndex===e.outputIndex});return i?this:(t&&r?this._fromMultisigUtxo(e,t,r):this._fromNonP2SH(e),this)};z.prototype._fromNonP2SH=function(e){var t;e=new X1(e),e.script.isPublicKeyHashOutPrefix()?t=fk:e.script.isPublicKeyOut()?t=ck:t=Bt,this.addInput(new t({output:new Wr({script:e.script,satoshis:e.satoshis}),prevTxId:e.txId,outputIndex:e.outputIndex,script:ln.empty()}))};z.prototype._fromMultisigUtxo=function(e,t,r){Ft.checkArgument(r<=t.length,"Number of required signatures must be greater than the number of public keys");var n;if(e=new X1(e),e.script.isMultisigOut())n=hk;else if(e.script.isScriptHashOut())n=lk;else throw new Nt.Transaction.Input.UnsupportedScript(e.script.toString());this.addInput(new n({output:new Wr({script:e.script,satoshis:e.satoshis}),prevTxId:e.txId,outputIndex:e.outputIndex,script:ln.empty()},t,r))};z.prototype.addInput=function(e,t,r){if(Ft.checkArgumentType(e,Bt,"input"),!e.output&&(pe.isUndefined(t)||pe.isUndefined(r)))throw new Nt.Transaction.NeedMoreInfo("Need information about the UTXO script and satoshis");return!e.output&&t&&!pe.isUndefined(r)&&(t=t instanceof ln?t:new ln(t),Ft.checkArgumentType(r,"number","satoshis"),e.output=new Wr({script:t,satoshis:r})),this.uncheckedAddInput(e)};z.prototype.uncheckedAddInput=function(e){return Ft.checkArgumentType(e,Bt,"input"),this.inputs.push(e),this._inputAmount=void 0,this._updateChangeOutput(),this};z.prototype.hasAllUtxoInfo=function(){return pe.every(this.inputs.map(function(e){return!!e.output}))};z.prototype.fee=function(e){return Ft.checkArgument(pe.isNumber(e),"amount must be a number"),this._fee=e,this._updateChangeOutput(),this};z.prototype.feePerKb=function(e){return Ft.checkArgument(pe.isNumber(e),"amount must be a number"),this._feePerKb=e,this._updateChangeOutput(),this};z.prototype.change=function(e){return Ft.checkArgument(e,"address is required"),this._changeScript=ln.fromAddress(e),this._updateChangeOutput(),this};z.prototype.getChangeOutput=function(){return pe.isUndefined(this._changeIndex)?null:this.outputs[this._changeIndex]};z.prototype.to=function(e,t){if(pe.isArray(e)){var r=this;return pe.each(e,function(n){r.to(n.address,n.satoshis)}),this}return Ft.checkArgument(W1.isNaturalNumber(t),"Amount is expected to be a positive integer"),this.addOutput(new Wr({script:ln(new uk(e)),satoshis:t})),this};z.prototype.addData=function(e){return this.addOutput(new Wr({script:ln.buildDataOut(e),satoshis:0})),this};z.prototype.addSafeData=function(e){return this.addOutput(new Wr({script:ln.buildSafeDataOut(e),satoshis:0})),this};z.prototype.addOutput=function(e){return Ft.checkArgumentType(e,Wr,"output"),this._addOutput(e),this._updateChangeOutput(),this};z.prototype.clearOutputs=function(){return this.outputs=[],this._clearSignatures(),this._outputAmount=void 0,this._changeIndex=void 0,this._updateChangeOutput(),this};z.prototype._addOutput=function(e){this.outputs.push(e),this._outputAmount=void 0};z.prototype._getOutputAmount=function(){if(pe.isUndefined(this._outputAmount)){var e=this;this._outputAmount=0,pe.each(this.outputs,function(t){e._outputAmount+=t.satoshis})}return this._outputAmount};z.prototype._getInputAmount=function(){if(pe.isUndefined(this._inputAmount)){var e=this;this._inputAmount=0,pe.each(this.inputs,function(t){if(pe.isUndefined(t.output))throw new Nt.Transaction.Input.MissingPreviousOutput;e._inputAmount+=t.output.satoshis})}return this._inputAmount};z.prototype._updateChangeOutput=function(){if(this._changeScript){this._clearSignatures(),pe.isUndefined(this._changeIndex)||this._removeOutput(this._changeIndex),this._changeIndex=this.outputs.length,this._addOutput(new Wr({script:this._changeScript,satoshis:0}));var e=this._getUnspentValue(),t=this.getFee(),r=e-t;this._removeOutput(this._changeIndex),this._changeIndex=void 0,r>=z.DUST_AMOUNT&&(this._changeIndex=this.outputs.length,this._addOutput(new Wr({script:this._changeScript,satoshis:r})))}};z.prototype.getFee=function(){return this.isCoinbase()?0:pe.isUndefined(this._fee)?this._changeScript?this._estimateFee():this._getUnspentValue():this._fee};z.prototype._estimateFee=function(){var e=this._estimateSize();return Math.ceil(e/1e3*(this._feePerKb||z.FEE_PER_KB))};z.prototype._getUnspentValue=function(){return this._getInputAmount()-this._getOutputAmount()};z.prototype._clearSignatures=function(){pe.each(this.inputs,function(e){e.clearSignatures!==Bt.prototype.clearSignatures&&e.clearSignatures()})};z.prototype._estimateSize=function(){var e=8;return e+=z1(this.inputs.length).toBuffer().length,e+=z1(this.outputs.length).toBuffer().length,pe.each(this.inputs,function(t){e+=t._estimateSize()}),pe.each(this.outputs,function(t){e+=t.getSize()}),e};z.prototype._removeOutput=function(e){var t=this.outputs[e];this.outputs=pe.without(this.outputs,t),this._outputAmount=void 0};z.prototype.removeOutput=function(e){this._removeOutput(e),this._updateChangeOutput()};z.prototype.sort=function(){return this.sortInputs(function(e){var t=Array.prototype.concat.apply([],e);return t.sort(function(r,n){return r.prevTxId.compare(n.prevTxId)||r.outputIndex-n.outputIndex}),t}),this.sortOutputs(function(e){var t=Array.prototype.concat.apply([],e);return t.sort(function(r,n){return r.satoshis-n.satoshis||r.script.toBuffer().compare(n.script.toBuffer())}),t}),this};z.prototype.shuffleOutputs=function(){return this.sortOutputs(pe.shuffle)};z.prototype.sortOutputs=function(e){var t=e(this.outputs);return this._newOutputOrder(t)};z.prototype.sortInputs=function(e){return this.inputs=e(this.inputs),this._clearSignatures(),this};z.prototype._newOutputOrder=function(e){var t=this.outputs.length!==e.length||pe.difference(this.outputs,e).length!==0;if(t)throw new Nt.Transaction.InvalidSorting;if(!pe.isUndefined(this._changeIndex)){var r=this.outputs[this._changeIndex];this._changeIndex=e.indexOf(r)}return this.outputs=e,this};z.prototype.removeInput=function(e,t){var r;if(!t&&pe.isNumber(e)?r=e:r=pe.findIndex(this.inputs,function(i){return i.prevTxId.toString("hex")===e&&i.outputIndex===t}),r<0||r>=this.inputs.length)throw new Nt.Transaction.InvalidIndex(r,this.inputs.length);var n=this.inputs[r];this.inputs=pe.without(this.inputs,n),this._inputAmount=void 0,this._updateChangeOutput()};z.prototype.sign=function(e,t){Ft.checkState(this.hasAllUtxoInfo(),"Not all utxo information is available to sign the transaction.");var r=this;return pe.isArray(e)?(pe.each(e,function(n){r.sign(n,t)}),this):(pe.each(this.getSignatures(e,t),function(n){r.applySignature(n)}),this)};z.prototype.getSignatures=function(e,t){e=new dk(e),t=t||Cc.SIGHASH_ALL|Cc.SIGHASH_FORKID;var r=this,n=[],i=$1.sha256ripemd160(e.publicKey.toBuffer());return pe.each(this.inputs,function(s,a){pe.each(s.getSignatures(r,e,a,t,i),function(c){n.push(c)})}),n};z.prototype.applySignature=function(e){return this.inputs[e.inputIndex].addSignature(this,e),this};z.prototype.isFullySigned=function(){return pe.each(this.inputs,function(e){if(e.isFullySigned===Bt.prototype.isFullySigned)throw new Nt.Transaction.UnableToVerifySignature("Unrecognized script kind, or not enough information to execute script.This usually happens when creating a transaction from a serialized transaction")}),pe.every(pe.map(this.inputs,function(e){return e.isFullySigned()}))};z.prototype.isValidSignature=function(e){var t=this;if(this.inputs[e.inputIndex].isValidSignature===Bt.prototype.isValidSignature)throw new Nt.Transaction.UnableToVerifySignature("Unrecognized script kind, or not enough information to execute script.This usually happens when creating a transaction from a serialized transaction");return this.inputs[e.inputIndex].isValidSignature(t,e)};z.prototype.verifySignature=function(e,t,r,n,i,o){return Z1.verify(this,e,t,r,n,i,o)};z.prototype.verify=function(){if(this.inputs.length===0)return"transaction txins empty";if(this.outputs.length===0)return"transaction txouts empty";for(var e=new kc(0),t=0;t<this.outputs.length;t++){var r=this.outputs[t];if(r.invalidSatoshis())return"transaction txout "+t+" satoshis is invalid";if(r._satoshisBN.gt(new kc(z.MAX_MONEY,10)))return"transaction txout "+t+" greater than MAX_MONEY";if(e=e.add(r._satoshisBN),e.gt(new kc(z.MAX_MONEY)))return"transaction txout "+t+" total output greater than MAX_MONEY"}if(this.toBuffer().length>vk)return"transaction over the maximum block size";var n={};for(t=0;t<this.inputs.length;t++){var i=this.inputs[t],o=i.prevTxId+":"+i.outputIndex;if(!pe.isUndefined(n[o]))return"transaction input "+t+" duplicate input";n[o]=!0}var s=this.isCoinbase();if(s){var a=this.inputs[0]._scriptBuffer;if(a.length<2||a.length>100)return"coinbase transaction script size invalid"}else for(t=0;t<this.inputs.length;t++)if(this.inputs[t].isNull())return"transaction input "+t+" has null input";return!0};z.prototype.isCoinbase=function(){return this.inputs.length===1&&this.inputs[0].isNull()};z.prototype.sighash=function(e,t,r,n,i){t=t||Cc.SIGHASH_ALL|Cc.SIGHASH_FORKID;var o=this.inputs[e];if(!o)throw new Error("Input index "+e+" does not exist");return!r&&o.output&&(r=o.output.script),!n&&o.output&&(n=new kc(o.output.satoshis)),i=i||gk,Z1.sighash(this,t,e,r,n,i)};Q1.exports=z});var Op=P((c5,oo)=>{m();oo.exports=xp();oo.exports.Input=Pc();oo.exports.Output=Dn();oo.exports.UnspentOutput=Ip();oo.exports.Signature=us();oo.exports.Sighash=pi()});var Nc=P((h5,rx)=>{"use strict";m();var Lc=Ve(),Ha=fp(),N=sp(),fe=Er(),qa=Qt(),yi=ir(),Rp=Tr();function ex(e){return e.map(function(t){return d.Buffer.isBuffer(t)?d.Buffer.from(t):t})}var B=function e(t){if(!(this instanceof e))return new e(t);t?(this.initialize(),this.set(t)):this.initialize()};B.prototype.verify=function(e,t,r,n,i,o){var s=Op();if(Lc.isUndefined(r)&&(r=new s),Lc.isUndefined(n)&&(n=0),Lc.isUndefined(i)&&(i=B.currentConsensusFlags(),o||(i&=~B.SCRIPT_ENABLE_SIGHASH_FORKID)),i&B.SCRIPT_ENABLE_SIGHASH_FORKID&&(i|=B.SCRIPT_VERIFY_STRICTENC,!o))throw new Error("internal error - need satoshisBN to verify FORKID transactions");this.set({script:e,tx:r,nin:n,flags:i,satoshisBN:o});var a;if((i&B.SCRIPT_VERIFY_SIGPUSHONLY)!==0&&!e.isPushOnly())return this.errstr="SCRIPT_ERR_SIG_PUSHONLY",!1;if(!this.evaluate())return!1;var c=(i&B.SCRIPT_VERIFY_P2SH)!==0&&(i&B.SCRIPT_UTXO_AFTER_GENESIS)===0;c&&(a=this.stack.slice());var h=this.stack;if(this.initialize(),this.set({script:t,stack:h,tx:r,nin:n,flags:i,satoshisBN:o}),!this.evaluate())return!1;if(this.stack.length===0)return this.errstr="SCRIPT_ERR_EVAL_FALSE_NO_RESULT",!1;var g=this.stack[this.stack.length-1];if(!B.castToBool(g))return this.errstr="SCRIPT_ERR_EVAL_FALSE_IN_STACK",!1;if(c&&t.isScriptHashOut()){if(!e.isPushOnly())return this.errstr="SCRIPT_ERR_SIG_PUSHONLY",!1;if(a.length===0)throw new Error("internal error - stack copy empty");var y=a[a.length-1],w=Ha.fromBuffer(y);if(a.pop(),this.initialize(),this.set({script:w,stack:a,tx:r,nin:n,flags:i,satoshisBN:o}),!this.evaluate())return!1;if(a.length===0)return this.errstr="SCRIPT_ERR_EVAL_FALSE_NO_P2SH_STACK",!1;if(!B.castToBool(a[a.length-1]))return this.errstr="SCRIPT_ERR_EVAL_FALSE_IN_P2SH_STACK",!1}if((i&B.SCRIPT_VERIFY_CLEANSTACK)!==0){if((i&B.SCRIPT_VERIFY_P2SH)===0&&(i&B.SCRIPT_UTXO_AFTER_GENESIS)===0)throw new Error("internal error - CLEANSTACK without P2SH");if(this.stack.length!==1)return this.errstr="SCRIPT_ERR_CLEANSTACK",!1}return!0};rx.exports=B;B.prototype.initialize=function(e){this.stack=[],this.altstack=[],this.pc=0,this.pbegincodehash=0,this.nOpCount=0,this.returned=!1,this.nonTopLevelReturnAfterGenesis=!1,this.vfExec=[],this.vfElse=[],this.errstr="",this.flags=0};B.prototype.set=function(e){this.script=e.script||this.script,this.tx=e.tx||this.tx,this.nin=typeof e.nin<"u"?e.nin:this.nin,this.satoshisBN=e.satoshisBN||this.satoshisBN,this.stack=e.stack||this.stack,this.altstack=e.altstack||this.altstack,this.pc=typeof e.pc<"u"?e.pc:this.pc,this.pbegincodehash=typeof e.pbegincodehash<"u"?e.pbegincodehash:this.pbegincodehash,this.nOpCount=typeof e.nOpCount<"u"?e.nOpCount:this.nOpCount,this.returned=typeof e.returned<"u"?e.returned:this.returned,this.nonTopLevelReturnAfterGenesis=typeof e.nonTopLevelReturnAfterGenesis<"u"?e.nonTopLevelReturnAfterGenesis:this.nonTopLevelReturnAfterGenesis,this.vfExec=e.vfExec||this.vfExec,this.vfElse=e.vfElse||this.vfElse,this.errstr=e.errstr||this.errstr,this.flags=typeof e.flags<"u"?e.flags:this.flags};B.true=d.Buffer.from([1]);B.false=d.Buffer.from([]);B.MAX_SCRIPT_ELEMENT_SIZE=520;B.MAXIMUM_ELEMENT_SIZE=4;B.MAX_OPS_PER_SCRIPT=500;B.MAX_SCRIPT_SIZE=1e4;B.UNLIMITED=Number.MAX_SAFE_INTEGER;B.MAX_SCRIPT_NUM_LENGTH_AFTER_GENESIS=75e4;B.MAX_SCRIPT_NUM_LENGTH_AFTER_CHRONICLE=32e6;B.MAX_PUBKEYS_PER_MULTISIG_AFTER_GENESIS=4294967295;B.LOCKTIME_THRESHOLD=5e8;B.LOCKTIME_THRESHOLD_BN=new fe(B.LOCKTIME_THRESHOLD);B.useGenesisLimits=function(e){return e=e||2147483647,B.MAX_SCRIPT_ELEMENT_SIZE=e,B.MAX_OPS_PER_SCRIPT=e,B.MAX_SCRIPT_SIZE=e,B};B.getLimits=function(){return{maxScriptElementSize:B.MAX_SCRIPT_ELEMENT_SIZE,maximumElementSize:B.MAXIMUM_ELEMENT_SIZE,maxOpsPerScript:B.MAX_OPS_PER_SCRIPT,maxScriptSize:B.MAX_SCRIPT_SIZE}};B.setLimits=function(e){return e=e||{},e.maxScriptElementSize!=null&&(B.MAX_SCRIPT_ELEMENT_SIZE=e.maxScriptElementSize),e.maximumElementSize!=null&&(B.MAXIMUM_ELEMENT_SIZE=e.maximumElementSize),e.maxOpsPerScript!=null&&(B.MAX_OPS_PER_SCRIPT=e.maxOpsPerScript),e.maxScriptSize!=null&&(B.MAX_SCRIPT_SIZE=e.maxScriptSize),B};B.SCRIPT_VERIFY_NONE=0;B.SCRIPT_VERIFY_P2SH=1;B.SCRIPT_VERIFY_STRICTENC=2;B.SCRIPT_VERIFY_DERSIG=4;B.SCRIPT_VERIFY_LOW_S=8;B.SCRIPT_VERIFY_NULLDUMMY=16;B.SCRIPT_VERIFY_SIGPUSHONLY=32;B.SCRIPT_VERIFY_MINIMALDATA=64;B.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS=128;B.SCRIPT_VERIFY_CLEANSTACK=256;B.SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY=512;B.SCRIPT_VERIFY_CHECKSEQUENCEVERIFY=1024;B.SCRIPT_VERIFY_MINIMALIF=8192;B.SCRIPT_VERIFY_NULLFAIL=16384;B.SCRIPT_VERIFY_COMPRESSED_PUBKEYTYPE=32768;B.SCRIPT_ENABLE_SIGHASH_FORKID=65536;B.SCRIPT_ENABLE_REPLAY_PROTECTION=1<<17;B.SCRIPT_ENABLE_MONOLITH_OPCODES=2048;B.SCRIPT_ENABLE_MAGNETIC_OPCODES=4096;B.SCRIPT_GENESIS=1<<18;B.SCRIPT_UTXO_AFTER_GENESIS=1<<19;B.SCRIPT_ENABLE_CHRONICLE=1<<20;B.SCRIPT_CHRONICLE=B.SCRIPT_ENABLE_CHRONICLE;B.SCRIPT_UTXO_AFTER_CHRONICLE=1<<21;B.CHRONICLE_ACTIVATION_HEIGHT=943816;B.mainnetFlags=function(e){e=e||{};var t=B.SCRIPT_VERIFY_P2SH|B.SCRIPT_VERIFY_STRICTENC|B.SCRIPT_VERIFY_DERSIG|B.SCRIPT_VERIFY_LOW_S|B.SCRIPT_VERIFY_NULLFAIL|B.SCRIPT_VERIFY_MINIMALDATA|B.SCRIPT_ENABLE_SIGHASH_FORKID|B.SCRIPT_ENABLE_MAGNETIC_OPCODES|B.SCRIPT_ENABLE_MONOLITH_OPCODES|B.SCRIPT_GENESIS|B.SCRIPT_UTXO_AFTER_GENESIS;return e.afterChronicle!==!1&&(t|=B.SCRIPT_ENABLE_CHRONICLE|B.SCRIPT_UTXO_AFTER_CHRONICLE),t};B.currentConsensusFlags=function(){return B.SCRIPT_ENABLE_MONOLITH_OPCODES|B.SCRIPT_ENABLE_MAGNETIC_OPCODES|B.SCRIPT_GENESIS|B.SCRIPT_UTXO_AFTER_GENESIS|B.SCRIPT_ENABLE_CHRONICLE|B.SCRIPT_UTXO_AFTER_CHRONICLE|B.SCRIPT_ENABLE_SIGHASH_FORKID};B.useMainnetConsensus=function(e){return e=e||{},B.useGenesisLimits(e.max),B.mainnetFlags(e)};B.SEQUENCE_LOCKTIME_DISABLE_FLAG=1<<31;B.SEQUENCE_LOCKTIME_TYPE_FLAG=1<<22;B.SEQUENCE_LOCKTIME_MASK=65535;B.castToBool=function(e){for(var t=0;t<e.length;t++)if(e[t]!==0)return!(t===e.length-1&&e[t]===128);return!1};B.prototype.checkSignatureEncoding=function(e){var t;if(e.length===0)return!0;if((this.flags&(B.SCRIPT_VERIFY_DERSIG|B.SCRIPT_VERIFY_LOW_S|B.SCRIPT_VERIFY_STRICTENC))!==0&&!yi.isTxDER(e))return this.errstr="SCRIPT_ERR_SIG_DER_INVALID_FORMAT",!1;if((this.flags&B.SCRIPT_VERIFY_LOW_S)!==0){if(t=yi.fromTxFormat(e),!t.hasLowS())return this.errstr="SCRIPT_ERR_SIG_DER_HIGH_S",!1}else if((this.flags&B.SCRIPT_VERIFY_STRICTENC)!==0){if(t=yi.fromTxFormat(e),!t.hasDefinedHashtype())return this.errstr="SCRIPT_ERR_SIG_HASHTYPE",!1;if(!(this.flags&B.SCRIPT_ENABLE_SIGHASH_FORKID)&&t.nhashtype&yi.SIGHASH_FORKID)return this.errstr="SCRIPT_ERR_ILLEGAL_FORKID",!1;if(!(this.flags&B.SCRIPT_CHRONICLE)&&t.nhashtype&yi.SIGHASH_CHRONICLE)return this.errstr="SCRIPT_ERR_ILLEGAL_CHRONICLE",!1;if(this.flags&B.SCRIPT_ENABLE_SIGHASH_FORKID&&!(t.nhashtype&yi.SIGHASH_FORKID))return this.errstr="SCRIPT_ERR_MUST_USE_FORKID",!1}return!0};B.prototype.checkPubkeyEncoding=function(e){return(this.flags&B.SCRIPT_VERIFY_STRICTENC)!==0&&!Rp.isValid(e)?(this.errstr="SCRIPT_ERR_PUBKEYTYPE",!1):!0};B.prototype.isAfterGenesis=function(){return(this.flags&B.SCRIPT_UTXO_AFTER_GENESIS)!==0};B.prototype.isAfterChronicle=function(){return(this.flags&(B.SCRIPT_UTXO_AFTER_CHRONICLE|B.SCRIPT_ENABLE_CHRONICLE))!==0};B.prototype.maxScriptElementSize=function(){return this.isAfterGenesis()?B.UNLIMITED:B.MAX_SCRIPT_ELEMENT_SIZE};B.prototype.maxScriptSize=function(){return this.isAfterGenesis()?B.UNLIMITED:B.MAX_SCRIPT_SIZE};B.prototype.maxOpsPerScript=function(){return this.isAfterGenesis()?B.UNLIMITED:B.MAX_OPS_PER_SCRIPT};B.prototype.maxScriptNumLength=function(){return this.isAfterChronicle()?B.MAX_SCRIPT_NUM_LENGTH_AFTER_CHRONICLE:this.isAfterGenesis()?B.MAX_SCRIPT_NUM_LENGTH_AFTER_GENESIS:B.MAXIMUM_ELEMENT_SIZE};B.prototype.maxPubKeysPerMultisig=function(){return this.isAfterGenesis()?B.MAX_PUBKEYS_PER_MULTISIG_AFTER_GENESIS:20};B._isMinimallyEncoded=function(e,t){return t=t||B.MAXIMUM_ELEMENT_SIZE,!(e.length>t||e.length>0&&(e[e.length-1]&127)===0&&(e.length<=1||(e[e.length-2]&128)===0))};B._minimallyEncode=function(e){if(e.length===0)return e;var t=e[e.length-1];if(t&127)return e;if(e.length===1)return d.Buffer.from("");if(e[e.length-2]&128)return e;for(var r=e.length-1;r>0;r--)if(e[r-1]!==0)return e[r-1]&128?e[r++]=t:e[r-1]|=t,e.slice(0,r);return d.Buffer.from("")};B.prototype.evaluate=function(){if(this.script.toBuffer().length>this.maxScriptSize())return this.errstr="SCRIPT_ERR_SCRIPT_SIZE",!1;try{for(;this.pc<this.script.chunks.length;){let t={pc:this.pc,opcode:N.fromNumber(this.script.chunks[this.pc].opcodenum)};var e=this.step();if(!e)return!1;if(this._callbackStep(t),this.returned)return!0}if(this.stack.length+this.altstack.length>1e3)return this.errstr="SCRIPT_ERR_STACK_SIZE",!1}catch(t){return this.errstr=t.scriptErr||"SCRIPT_ERR_UNKNOWN_ERROR: "+t,!1}return this.vfExec.length>0?(this.errstr="SCRIPT_ERR_UNBALANCED_CONDITIONAL",!1):!0};B.prototype._callbackStep=function(e){if(typeof this.stepListener=="function")try{this.stepListener(e,ex(this.stack),ex(this.altstack))}catch(t){console.log(`Error in Step callback:${t}`)}};B.prototype.checkLockTime=function(e){if(!(this.tx.nLockTime<B.LOCKTIME_THRESHOLD&&e.lt(B.LOCKTIME_THRESHOLD_BN)||this.tx.nLockTime>=B.LOCKTIME_THRESHOLD&&e.gte(B.LOCKTIME_THRESHOLD_BN))||e.gt(new fe(this.tx.nLockTime)))return!1;var t=this.tx.inputs[this.nin];return!(!t||t.isFinal())};B.prototype.checkSequence=function(e){var t=this.tx.inputs[this.nin];if(!t)return!1;var r=t.sequenceNumber;if(this.tx.version<2||r&B.SEQUENCE_LOCKTIME_DISABLE_FLAG)return!1;var n=B.SEQUENCE_LOCKTIME_TYPE_FLAG|B.SEQUENCE_LOCKTIME_MASK,i=new fe(r&n),o=e.and(new fe(n)),s=new fe(B.SEQUENCE_LOCKTIME_TYPE_FLAG);return!(!(i.lt(s)&&o.lt(s)||i.gte(s)&&o.gte(s))||o.gt(i))};function bk(e,t){let r=e;for(;r.length<t;)r=d.Buffer.concat([d.Buffer.from([0]),r]);return r}function tx(e){var t=d.Buffer.alloc(4);return t.writeInt32LE(e|0,0),t}B.prototype.step=function(){var e=this;function t(re){return e.stack[e.stack.length+re]}function r(re){switch(re){case N.OP_2MUL:case N.OP_2DIV:if(!e.isAfterChronicle())return!0;break;case N.OP_INVERT:case N.OP_MUL:case N.OP_LSHIFT:case N.OP_RSHIFT:if((e.flags&B.SCRIPT_ENABLE_MAGNETIC_OPCODES)===0)return!0;break;case N.OP_DIV:case N.OP_MOD:case N.OP_SPLIT:case N.OP_CAT:case N.OP_AND:case N.OP_OR:case N.OP_XOR:case N.OP_BIN2NUM:case N.OP_NUM2BIN:return!1;default:break}return!1}var n=(this.flags&B.SCRIPT_VERIFY_MINIMALDATA)!==0,i,o,s,a,c,h,g,y,w,I,T,M,L,j,G,q,W,J=this.script.chunks[this.pc];this.pc++;var Y=J.opcodenum,be=this.vfExec.indexOf(!1)===-1&&(!this.nonTopLevelReturnAfterGenesis||Y===N.OP_RETURN);if(Lc.isUndefined(Y))return this.errstr="SCRIPT_ERR_UNDEFINED_OPCODE",!1;if(J.buf&&J.buf.length>this.maxScriptElementSize())return this.errstr="SCRIPT_ERR_PUSH_SIZE",!1;if(Y>N.OP_16&&++this.nOpCount>this.maxOpsPerScript())return this.errstr="SCRIPT_ERR_OP_COUNT",!1;if(r(Y)&&(!this.isAfterGenesis()||be))return this.errstr="SCRIPT_ERR_DISABLED_OPCODE",!1;if(be&&Y>=0&&Y<=N.OP_PUSHDATA4){if(n&&!this.script.checkMinimalPush(this.pc-1))return this.errstr="SCRIPT_ERR_MINIMALDATA",!1;if(!J.buf)this.stack.push(B.false);else{if(J.len!==J.buf.length)return this.errstr="SCRIPT_ERR_BAD_OPCODE",!1;this.stack.push(J.buf)}}else if(be||N.OP_IF<=Y&&Y<=N.OP_ENDIF)switch(Y){case N.OP_1NEGATE:case N.OP_1:case N.OP_2:case N.OP_3:case N.OP_4:case N.OP_5:case N.OP_6:case N.OP_7:case N.OP_8:case N.OP_9:case N.OP_10:case N.OP_11:case N.OP_12:case N.OP_13:case N.OP_14:case N.OP_15:case N.OP_16:c=Y-(N.OP_1-1),i=new fe(c).toScriptNumBuffer(),this.stack.push(i);break;case N.OP_NOP:break;case N.OP_NOP2:case N.OP_CHECKLOCKTIMEVERIFY:if(!(this.flags&B.SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)||this.isAfterGenesis()){if(this.flags&B.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)return this.errstr="SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS",!1;break}if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;var se=fe.fromScriptNumBuffer(this.stack[this.stack.length-1],n,5);if(se.lt(new fe(0)))return this.errstr="SCRIPT_ERR_NEGATIVE_LOCKTIME",!1;if(!this.checkLockTime(se))return this.errstr="SCRIPT_ERR_UNSATISFIED_LOCKTIME",!1;break;case N.OP_NOP3:case N.OP_CHECKSEQUENCEVERIFY:if(!(this.flags&B.SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)||this.isAfterGenesis()){if(this.flags&B.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)return this.errstr="SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS",!1;break}if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;var de=fe.fromScriptNumBuffer(t(-1),n,5);if(de.lt(new fe(0)))return this.errstr="SCRIPT_ERR_NEGATIVE_LOCKTIME",!1;if((de&B.SEQUENCE_LOCKTIME_DISABLE_FLAG)!==0)break;if(!this.checkSequence(de))return this.errstr="SCRIPT_ERR_UNSATISFIED_LOCKTIME",!1;break;case N.OP_NOP1:case N.OP_NOP9:case N.OP_NOP10:if(this.flags&B.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)return this.errstr="SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS",!1;break;case N.OP_LSHIFTNUM:case N.OP_RSHIFTNUM:if(!this.isAfterChronicle()){if(this.flags&B.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)return this.errstr="SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS",!1;break}if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;var A=this.maxScriptNumLength(),u=fe.fromScriptNumBuffer(t(-1),n,A);if(u.isNeg())return this.errstr="SCRIPT_ERR_INVALID_NUMBER_RANGE",!1;this.stack.pop();var l=fe.fromScriptNumBuffer(t(-1),n,A);this.stack.pop();var p=u.toNumber(),v=l.isNeg(),b=l.abs(),E;if(Y===N.OP_LSHIFTNUM){var O=l.toScriptNumBuffer().length;if(O+Math.floor(p/8)>A)return this.errstr="SCRIPT_ERR_SCRIPTNUM_OVERFLOW",!1;E=b.shln(p)}else E=p>=b.bitLength()?new fe(0):b.shrn(p);if(v&&!E.isZero()&&(E=E.neg()),E.toScriptNumBuffer().length>A)return this.errstr="SCRIPT_ERR_SCRIPTNUM_OVERFLOW",!1;this.stack.push(E.toScriptNumBuffer());break;case N.OP_VER:if(!this.isAfterChronicle())return this.errstr="SCRIPT_ERR_BAD_OPCODE",!1;if(this.tx==null)return this.errstr="SCRIPT_ERR_UNKNOWN_ERROR",!1;this.stack.push(tx(this.tx.version));break;case N.OP_VERIF:case N.OP_VERNOTIF:if(!this.isAfterChronicle()){if(this.isAfterGenesis()&&!be)break;return this.errstr="SCRIPT_ERR_BAD_OPCODE",!1}if(q=!1,be){if(this.stack.length<1)return this.errstr="SCRIPT_ERR_UNBALANCED_CONDITIONAL",!1;if(this.tx==null)return this.errstr="SCRIPT_ERR_UNKNOWN_ERROR",!1;i=t(-1),q=i.length===4&&i.equals(tx(this.tx.version)),Y===N.OP_VERNOTIF&&(q=!q),this.stack.pop()}this.vfExec.push(q),this.vfElse.push(!1);break;case N.OP_IF:case N.OP_NOTIF:if(q=!1,be){if(this.stack.length<1)return this.errstr="SCRIPT_ERR_UNBALANCED_CONDITIONAL",!1;if(i=t(-1),this.flags&B.SCRIPT_VERIFY_MINIMALIF){if(i.length>1)return this.errstr="SCRIPT_ERR_MINIMALIF",!1;if(i.length===1&&i[0]!==1)return this.errstr="SCRIPT_ERR_MINIMALIF",!1}q=B.castToBool(i),Y===N.OP_NOTIF&&(q=!q),this.stack.pop()}this.vfExec.push(q),this.vfElse.push(!1);break;case N.OP_ELSE:if(this.vfExec.length===0||this.vfElse[this.vfElse.length-1]&&this.isAfterGenesis())return this.errstr="SCRIPT_ERR_UNBALANCED_CONDITIONAL",!1;this.vfExec[this.vfExec.length-1]=!this.vfExec[this.vfExec.length-1],this.vfElse[this.vfElse.length-1]=!0;break;case N.OP_ENDIF:if(this.vfExec.length===0)return this.errstr="SCRIPT_ERR_UNBALANCED_CONDITIONAL",!1;this.vfExec.pop(),this.vfElse.pop();break;case N.OP_VERIFY:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(i=t(-1),q=B.castToBool(i),q)this.stack.pop();else return this.errstr="SCRIPT_ERR_VERIFY",!1;break;case N.OP_RETURN:if(this.isAfterGenesis()){if(this.vfExec.length===0){this.returned=!0;break}this.nonTopLevelReturnAfterGenesis=!0;break}return this.errstr="SCRIPT_ERR_OP_RETURN",!1;case N.OP_TOALTSTACK:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.altstack.push(this.stack.pop());break;case N.OP_FROMALTSTACK:if(this.altstack.length<1)return this.errstr="SCRIPT_ERR_INVALID_ALTSTACK_OPERATION",!1;this.stack.push(this.altstack.pop());break;case N.OP_2DROP:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.stack.pop(),this.stack.pop();break;case N.OP_2DUP:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;o=t(-2),s=t(-1),this.stack.push(d.Buffer.from(o)),this.stack.push(d.Buffer.from(s));break;case N.OP_3DUP:if(this.stack.length<3)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;o=t(-3),s=t(-2);var _=t(-1);this.stack.push(d.Buffer.from(o)),this.stack.push(d.Buffer.from(s)),this.stack.push(d.Buffer.from(_));break;case N.OP_2OVER:if(this.stack.length<4)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;o=t(-4),s=t(-3),this.stack.push(d.Buffer.from(o)),this.stack.push(d.Buffer.from(s));break;case N.OP_2ROT:if(this.stack.length<6)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;a=this.stack.splice(this.stack.length-6,2),this.stack.push(a[0]),this.stack.push(a[1]);break;case N.OP_2SWAP:if(this.stack.length<4)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;a=this.stack.splice(this.stack.length-4,2),this.stack.push(a[0]),this.stack.push(a[1]);break;case N.OP_IFDUP:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;i=t(-1),q=B.castToBool(i),q&&this.stack.push(d.Buffer.from(i));break;case N.OP_DEPTH:i=new fe(this.stack.length).toScriptNumBuffer(),this.stack.push(i);break;case N.OP_DROP:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.stack.pop();break;case N.OP_DUP:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.stack.push(d.Buffer.from(t(-1)));break;case N.OP_NIP:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.stack.splice(this.stack.length-2,1);break;case N.OP_OVER:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.stack.push(d.Buffer.from(t(-2)));break;case N.OP_PICK:case N.OP_ROLL:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(i=t(-1),y=fe.fromScriptNumBuffer(i,n,this.maxScriptNumLength()),c=y.toNumber(),this.stack.pop(),c<0||c>=this.stack.length)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;i=t(-c-1),Y===N.OP_ROLL&&this.stack.splice(this.stack.length-c-1,1),this.stack.push(d.Buffer.from(i));break;case N.OP_ROT:if(this.stack.length<3)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;h=t(-3),g=t(-2);var f=t(-1);this.stack[this.stack.length-3]=g,this.stack[this.stack.length-2]=f,this.stack[this.stack.length-1]=h;break;case N.OP_SWAP:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;h=t(-2),g=t(-1),this.stack[this.stack.length-2]=g,this.stack[this.stack.length-1]=h;break;case N.OP_TUCK:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.stack.splice(this.stack.length-2,0,d.Buffer.from(t(-1)));break;case N.OP_SIZE:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;y=new fe(t(-1).length),this.stack.push(y.toScriptNumBuffer());break;case N.OP_AND:case N.OP_OR:case N.OP_XOR:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(o=t(-2),s=t(-1),o.length!==s.length)return this.errstr="SCRIPT_ERR_INVALID_OPERAND_SIZE",!1;switch(Y){case N.OP_AND:for(let re=0;re<o.length;re++)o[re]&=s[re];break;case N.OP_OR:for(let re=0;re<o.length;re++)o[re]|=s[re];break;case N.OP_XOR:for(let re=0;re<o.length;re++)o[re]^=s[re];break;default:break}this.stack.pop();break;case N.OP_INVERT:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;i=t(-1);for(let re=0;re<i.length;re++)i[re]=~i[re];break;case N.OP_LSHIFT:case N.OP_RSHIFT:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(o=t(-2),o.length===0)this.stack.pop();else{if(w=new fe(o),I=fe.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength()),c=I.toNumber(),c<0)return this.errstr="SCRIPT_ERR_INVALID_NUMBER_RANGE",!1;this.stack.pop(),this.stack.pop();let re;Y===N.OP_LSHIFT&&(re=w.ushln(c)),Y===N.OP_RSHIFT&&(re=w.ushrn(c));let me=bk(d.Buffer.from(re.toArray().slice(o.length*-1)),o.length);this.stack.push(me)}break;case N.OP_EQUAL:case N.OP_EQUALVERIFY:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;o=t(-2),s=t(-1);var S=o.toString("hex")===s.toString("hex");if(this.stack.pop(),this.stack.pop(),this.stack.push(S?B.true:B.false),Y===N.OP_EQUALVERIFY)if(S)this.stack.pop();else return this.errstr="SCRIPT_ERR_EQUALVERIFY",!1;break;case N.OP_2MUL:case N.OP_2DIV:case N.OP_1ADD:case N.OP_1SUB:case N.OP_NEGATE:case N.OP_ABS:case N.OP_NOT:case N.OP_0NOTEQUAL:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;switch(i=t(-1),y=fe.fromScriptNumBuffer(i,n,this.maxScriptNumLength()),Y){case N.OP_2MUL:y=y.mul(new fe(2));break;case N.OP_2DIV:y=y.div(new fe(2));break;case N.OP_1ADD:y=y.add(fe.One);break;case N.OP_1SUB:y=y.sub(fe.One);break;case N.OP_NEGATE:y=y.neg();break;case N.OP_ABS:y.cmp(fe.Zero)<0&&(y=y.neg());break;case N.OP_NOT:y=new fe((y.cmp(fe.Zero)===0)+0);break;case N.OP_0NOTEQUAL:y=new fe((y.cmp(fe.Zero)!==0)+0);break}this.stack.pop(),this.stack.push(y.toScriptNumBuffer());break;case N.OP_ADD:case N.OP_SUB:case N.OP_MUL:case N.OP_MOD:case N.OP_DIV:case N.OP_BOOLAND:case N.OP_BOOLOR:case N.OP_NUMEQUAL:case N.OP_NUMEQUALVERIFY:case N.OP_NUMNOTEQUAL:case N.OP_LESSTHAN:case N.OP_GREATERTHAN:case N.OP_LESSTHANOREQUAL:case N.OP_GREATERTHANOREQUAL:case N.OP_MIN:case N.OP_MAX:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;switch(w=fe.fromScriptNumBuffer(t(-2),n,this.maxScriptNumLength()),I=fe.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength()),y=new fe(0),Y){case N.OP_ADD:y=w.add(I);break;case N.OP_SUB:y=w.sub(I);break;case N.OP_MUL:y=w.mul(I);break;case N.OP_DIV:if(I.cmp(fe.Zero)===0)return this.errstr="SCRIPT_ERR_DIV_BY_ZERO",!1;y=w.div(I);break;case N.OP_MOD:if(I.cmp(fe.Zero)===0)return this.errstr="SCRIPT_ERR_MOD_BY_ZERO",!1;y=w.mod(I);break;case N.OP_BOOLAND:y=new fe((w.cmp(fe.Zero)!==0&&I.cmp(fe.Zero)!==0)+0);break;case N.OP_BOOLOR:y=new fe((w.cmp(fe.Zero)!==0||I.cmp(fe.Zero)!==0)+0);break;case N.OP_NUMEQUAL:y=new fe((w.cmp(I)===0)+0);break;case N.OP_NUMEQUALVERIFY:y=new fe((w.cmp(I)===0)+0);break;case N.OP_NUMNOTEQUAL:y=new fe((w.cmp(I)!==0)+0);break;case N.OP_LESSTHAN:y=new fe((w.cmp(I)<0)+0);break;case N.OP_GREATERTHAN:y=new fe((w.cmp(I)>0)+0);break;case N.OP_LESSTHANOREQUAL:y=new fe((w.cmp(I)<=0)+0);break;case N.OP_GREATERTHANOREQUAL:y=new fe((w.cmp(I)>=0)+0);break;case N.OP_MIN:y=w.cmp(I)<0?w:I;break;case N.OP_MAX:y=w.cmp(I)>0?w:I;break}if(this.stack.pop(),this.stack.pop(),this.stack.push(y.toScriptNumBuffer()),Y===N.OP_NUMEQUALVERIFY)if(B.castToBool(t(-1)))this.stack.pop();else return this.errstr="SCRIPT_ERR_NUMEQUALVERIFY",!1;break;case N.OP_WITHIN:if(this.stack.length<3)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;w=fe.fromScriptNumBuffer(t(-3),n,this.maxScriptNumLength()),I=fe.fromScriptNumBuffer(t(-2),n,this.maxScriptNumLength());var K=fe.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength());q=I.cmp(w)<=0&&w.cmp(K)<0,this.stack.pop(),this.stack.pop(),this.stack.pop(),this.stack.push(q?B.true:B.false);break;case N.OP_RIPEMD160:case N.OP_SHA1:case N.OP_SHA256:case N.OP_HASH160:case N.OP_HASH256:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;i=t(-1);var F;Y===N.OP_RIPEMD160?F=qa.ripemd160(i):Y===N.OP_SHA1?F=qa.sha1(i):Y===N.OP_SHA256?F=qa.sha256(i):Y===N.OP_HASH160?F=qa.sha256ripemd160(i):Y===N.OP_HASH256&&(F=qa.sha256sha256(i)),this.stack.pop(),this.stack.push(F);break;case N.OP_CODESEPARATOR:this.pbegincodehash=this.pc;break;case N.OP_CHECKSIG:case N.OP_CHECKSIGVERIFY:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(T=t(-2),M=t(-1),!this.checkSignatureEncoding(T)||!this.checkPubkeyEncoding(M))return!1;L=new Ha().set({chunks:this.script.chunks.slice(this.pbegincodehash)});var $=new Ha().add(T);L.findAndDelete($);try{j=yi.fromTxFormat(T),G=Rp.fromBuffer(M,!1),W=this.tx.verifySignature(j,G,this.nin,L,this.satoshisBN,this.flags)}catch{W=!1}if(!W&&this.flags&B.SCRIPT_VERIFY_NULLFAIL&&T.length)return this.errstr="SCRIPT_ERR_NULLFAIL",!1;if(this.stack.pop(),this.stack.pop(),this.stack.push(W?B.true:B.false),Y===N.OP_CHECKSIGVERIFY)if(W)this.stack.pop();else return this.errstr="SCRIPT_ERR_CHECKSIGVERIFY",!1;break;case N.OP_CHECKMULTISIG:case N.OP_CHECKMULTISIGVERIFY:var Z=1;if(this.stack.length<Z)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;var Q=fe.fromScriptNumBuffer(t(-Z),n,this.maxScriptNumLength()).toNumber();if(Q<0||Q>this.maxPubKeysPerMultisig())return this.errstr="SCRIPT_ERR_PUBKEY_COUNT",!1;if(this.nOpCount+=Q,this.nOpCount>B.MAX_OPS_PER_SCRIPT)return this.errstr="SCRIPT_ERR_OP_COUNT",!1;var ae=++Z;Z+=Q;var ge=Q+2;if(this.stack.length<Z)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;var le=fe.fromScriptNumBuffer(t(-Z),n,this.maxScriptNumLength()).toNumber();if(le<0||le>Q)return this.errstr="SCRIPT_ERR_SIG_COUNT",!1;var R=++Z;if(Z+=le,this.stack.length<Z)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;L=new Ha().set({chunks:this.script.chunks.slice(this.pbegincodehash)});for(var k=0;k<le;k++)T=t(-R-k),L.findAndDelete(new Ha().add(T));for(W=!0;W&&le>0;){if(T=t(-R),M=t(-ae),!this.checkSignatureEncoding(T)||!this.checkPubkeyEncoding(M))return!1;var H;try{j=yi.fromTxFormat(T),G=Rp.fromBuffer(M,!1),H=this.tx.verifySignature(j,G,this.nin,L,this.satoshisBN,this.flags)}catch{H=!1}H&&(R++,le--),ae++,Q--,le>Q&&(W=!1)}for(;Z-- >1;){if(!W&&this.flags&B.SCRIPT_VERIFY_NULLFAIL&&!ge&&t(-1).length)return this.errstr="SCRIPT_ERR_NULLFAIL",!1;ge>0&&ge--,this.stack.pop()}if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(this.flags&B.SCRIPT_VERIFY_NULLDUMMY&&t(-1).length)return this.errstr="SCRIPT_ERR_SIG_NULLDUMMY",!1;if(this.stack.pop(),this.stack.push(W?B.true:B.false),Y===N.OP_CHECKMULTISIGVERIFY)if(W)this.stack.pop();else return this.errstr="SCRIPT_ERR_CHECKMULTISIGVERIFY",!1;break;case N.OP_CAT:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(o=t(-2),s=t(-1),o.length+s.length>this.maxScriptElementSize())return this.errstr="SCRIPT_ERR_PUSH_SIZE",!1;this.stack[this.stack.length-2]=d.Buffer.concat([o,s]),this.stack.pop();break;case N.OP_SPLIT:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;o=t(-2);var V=fe.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength()).toNumber();if(V<0||V>o.length)return this.errstr="SCRIPT_ERR_INVALID_SPLIT_RANGE",!1;var ie=d.Buffer.from(o);this.stack[this.stack.length-2]=ie.slice(0,V),this.stack[this.stack.length-1]=ie.slice(V);break;case N.OP_LEFT:case N.OP_RIGHT:if(!this.isAfterChronicle()){if(this.flags&B.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)return this.errstr="SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS",!1;break}if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(o=t(-2),c=fe.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength()).toNumber(),c<0||c>o.length)return this.errstr="SCRIPT_ERR_INVALID_NUMBER_RANGE",!1;this.stack.pop(),Y===N.OP_LEFT?this.stack[this.stack.length-1]=d.Buffer.from(o).slice(0,c):this.stack[this.stack.length-1]=d.Buffer.from(o).slice(o.length-c);break;case N.OP_SUBSTR:if(!this.isAfterChronicle()){if(this.flags&B.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)return this.errstr="SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS",!1;break}if(this.stack.length<3)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;o=t(-3);var ee=fe.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength()).toNumber(),te=fe.fromScriptNumBuffer(t(-2),n,this.maxScriptNumLength()).toNumber();if(te<0||te>=o.length||ee<0||ee>o.length-te)return this.errstr="SCRIPT_ERR_INVALID_NUMBER_RANGE",!1;this.stack.pop(),this.stack.pop(),this.stack[this.stack.length-1]=d.Buffer.from(o).slice(te,te+ee);break;case N.OP_NUM2BIN:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;var he=fe.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength()).toNumber();if(he<0||he>this.maxScriptElementSize())return this.errstr="SCRIPT_ERR_PUSH_SIZE",!1;this.stack.pop();var oe=t(-1);if(oe=B._minimallyEncode(oe),oe.length>he)return this.errstr="SCRIPT_ERR_IMPOSSIBLE_ENCODING",!1;if(oe.length===he){this.stack[this.stack.length-1]=oe;break}var ue=0;oe.length>0&&(ue=oe[oe.length-1]&128,oe[oe.length-1]&=127);var We=d.Buffer.alloc(he);oe.copy(We,0);for(var Oe=oe.length-1;Oe++<he-2;)We[Oe]=0;We[Oe]=ue,this.stack[this.stack.length-1]=We;break;case N.OP_BIN2NUM:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(o=t(-1),s=B._minimallyEncode(o),this.stack[this.stack.length-1]=s,!B._isMinimallyEncoded(s))return this.errstr="SCRIPT_ERR_INVALID_NUMBER_RANGE",!1;break;default:return this.errstr="SCRIPT_ERR_BAD_OPCODE",!1}return!0}});var Kr=P((p5,Tp)=>{m();Tp.exports=fp();Tp.exports.Interpreter=Nc()});var no=P((y5,sx)=>{"use strict";m();var Pp=Ve(),jn=ke(),_k=Jn(),nx=Fd(),Br=ga(),ix=Qt(),ox=pr(),Bp=Tr();function ne(e,t,r){if(!(this instanceof ne))return new ne(e,t,r);if(Pp.isArray(e)&&Pp.isNumber(t))return ne.createMultisig(e,t,r);if(e instanceof ne)return e;if(jn.checkArgument(e,"First argument is required, please include address data.","guide/address.html"),t&&!Br.get(t))throw new TypeError('Second argument must be "livenet", "testnet", or "regtest".');if(r&&r!==ne.PayToPublicKeyHash&&r!==ne.PayToScriptHash)throw new TypeError('Third argument must be "pubkeyhash" or "scripthash".');var n=this._classifyArguments(e,t,r);return n.network=n.network||Br.get(t)||Br.defaultNetwork,n.type=n.type||r||ne.PayToPublicKeyHash,ox.defineImmutable(this,{hashBuffer:n.hashBuffer,network:n.network,type:n.type}),this}ne.prototype._classifyArguments=function(e,t,r){if((e instanceof d.Buffer||e instanceof Uint8Array)&&e.length===20)return ne._transformHash(e);if((e instanceof d.Buffer||e instanceof Uint8Array)&&e.length===21)return ne._transformBuffer(e,t,r);if(e instanceof Bp)return ne._transformPublicKey(e);if(e instanceof ja())return ne._transformScript(e,t);if(typeof e=="string")return ne._transformString(e,t,r);if(Pp.isObject(e))return ne._transformObject(e);throw new TypeError("First argument is an unrecognized data format.")};ne.PayToPublicKeyHash="pubkeyhash";ne.PayToScriptHash="scripthash";ne._transformHash=function(e){var t={};if(!(e instanceof d.Buffer)&&!(e instanceof Uint8Array))throw new TypeError("Address supplied is not a buffer.");if(e.length!==20)throw new TypeError("Address hashbuffers must be exactly 20 bytes.");return t.hashBuffer=e,t};ne._transformObject=function(e){return jn.checkArgument(e.hash||e.hashBuffer,"Must provide a `hash` or `hashBuffer` property"),jn.checkArgument(e.type,"Must provide a `type` property"),{hashBuffer:e.hash?d.Buffer.from(e.hash,"hex"):e.hashBuffer,network:Br.get(e.network)||Br.defaultNetwork,type:e.type}};ne._classifyFromVersion=function(e){var t={},r=Br.get(e[0],"pubkeyhash"),n=Br.get(e[0],"scripthash");return r?(t.network=r,t.type=ne.PayToPublicKeyHash):n&&(t.network=n,t.type=ne.PayToScriptHash),t};ne._transformBuffer=function(e,t,r){var n={};if(!(e instanceof d.Buffer)&&!(e instanceof Uint8Array))throw new TypeError("Address supplied is not a buffer.");if(e.length!==21)throw new TypeError("Address buffers must be exactly 21 bytes.");var i=Br.get(t),o=ne._classifyFromVersion(e);if(t&&!i)throw new TypeError("Unknown network");if(!o.network||i&&i!==o.network)throw new TypeError("Address has mismatched network type.");if(!o.type||r&&r!==o.type)throw new TypeError("Address has mismatched type.");return n.hashBuffer=e.slice(1),n.network=o.network,n.type=o.type,n};ne._transformPublicKey=function(e){var t={};if(!(e instanceof Bp))throw new TypeError("Address must be an instance of PublicKey.");return t.hashBuffer=ix.sha256ripemd160(e.toBuffer()),t.type=ne.PayToPublicKeyHash,t};ne._transformScript=function(e,t){jn.checkArgument(e instanceof ja(),"script must be a Script instance");var r=e.getAddressInfo(t);if(!r)throw new _k.Script.CantDeriveAddress(e);return r};ne.createMultisig=function(e,t,r){return r=r||e[0].network||Br.defaultNetwork,ne.payingTo(ja().buildMultisigOut(e,t),r)};ne._transformString=function(e,t,r){if(typeof e!="string")throw new TypeError("data parameter supplied is not a string.");if(e.length<27)throw new Error("Invalid Address string provided");e=e.trim();var n=Br.get(t);if(t&&!n)throw new TypeError("Unknown network");var i=nx.decode(e);return ne._transformBuffer(i,t,r)};ne.fromPublicKey=function(e,t){var r=ne._transformPublicKey(e);return t=t||Br.defaultNetwork,new ne(r.hashBuffer,t,r.type)};ne.fromPrivateKey=function(e,t){let r=Bp.fromPrivateKey(e);return t=t||e.network||Br.defaultNetwork,ne.fromPublicKey(r,t)};ne.fromPublicKeyHash=function(e,t){var r=ne._transformHash(e);return new ne(r.hashBuffer,t,ne.PayToPublicKeyHash)};ne.fromScriptHash=function(e,t){jn.checkArgument(e,"hash parameter is required");var r=ne._transformHash(e);return new ne(r.hashBuffer,t,ne.PayToScriptHash)};ne.payingTo=function(e,t){return jn.checkArgument(e,"script is required"),jn.checkArgument(e instanceof ja(),"script must be instance of Script"),ne.fromScriptHash(ix.sha256ripemd160(e.toBuffer()),t)};ne.fromScript=function(e,t){jn.checkArgument(e instanceof ja(),"script must be a Script instance");var r=ne._transformScript(e,t);return new ne(r.hashBuffer,t,r.type)};ne.fromBuffer=function(e,t,r){var n=ne._transformBuffer(e,t,r);return new ne(n.hashBuffer,n.network,n.type)};ne.fromHex=function(e,t,r){return ne.fromBuffer(d.Buffer.from(e,"hex"),t,r)};ne.fromString=function(e,t,r){var n=ne._transformString(e,t,r);return new ne(n.hashBuffer,n.network,n.type)};ne.fromObject=function(t){jn.checkState(ox.isHexa(t.hash),'Unexpected hash property, "'+t.hash+'", expected to be hex.');var r=d.Buffer.from(t.hash,"hex");return new ne(r,t.network,t.type)};ne.getValidationError=function(e,t,r){var n;try{new ne(e,t,r)}catch(i){n=i}return n};ne.isValid=function(e,t,r){return!ne.getValidationError(e,t,r)};ne.prototype.isPayToPublicKeyHash=function(){return this.type===ne.PayToPublicKeyHash};ne.prototype.isPayToScriptHash=function(){return this.type===ne.PayToScriptHash};ne.prototype.toBuffer=function(){var e=d.Buffer.from([this.network[this.type]]),t=d.Buffer.concat([e,this.hashBuffer]);return t};ne.prototype.toHex=function(){return this.toBuffer().toString("hex")};ne.prototype.toObject=ne.prototype.toJSON=function(){return{hash:this.hashBuffer.toString("hex"),type:this.type,network:this.network.toString()}};ne.prototype.inspect=function(){return"<Address: "+this.toString()+", type: "+this.type+", network: "+this.network+">"};ne.prototype.toString=function(){return nx.encode(this.toBuffer())};sx.exports=ne;function ja(){return Kr()}});var io=P((v5,cx)=>{"use strict";m();var Dc=Ve(),Sk=no(),ax=Fd(),mi=Er(),ux=pr(),hn=ga(),Mp=ii(),wk=Tr(),Ek=ea(),fx=ke(),Np="[REDACTED]";function ye(e,t){if(!(this instanceof ye))return new ye(e,t);if(e instanceof ye)return e;var r=this._classifyArguments(e,t);if(!r.bn||r.bn.cmp(new mi(0))===0)throw new TypeError("Number can not be equal to zero, undefined, null or false");if(!r.bn.lt(Mp.getN()))throw new TypeError("Number must be less than N");if(typeof r.network>"u")throw new TypeError('Must specify the network ("livenet" or "testnet")');return ux.defineImmutable(this,{bn:r.bn,compressed:r.compressed,network:r.network}),Object.defineProperty(this,"publicKey",{configurable:!1,enumerable:!0,get:this.toPublicKey.bind(this)}),this}ye.prototype._classifyArguments=function(e,t){var r={compressed:!0,network:t?hn.get(t):hn.defaultNetwork};if(Dc.isUndefined(e)||Dc.isNull(e))r.bn=ye._getRandomBN();else if(e instanceof mi)r.bn=e;else if(e instanceof d.Buffer||e instanceof Uint8Array)r=ye._transformBuffer(e,t);else if(e.bn&&e.network)r=ye._transformObject(e);else if(!t&&hn.get(e))r.bn=ye._getRandomBN(),r.network=hn.get(e);else if(typeof e=="string")ux.isHexa(e)?r.bn=new mi(d.Buffer.from(e,"hex")):r=ye._transformWIF(e,t);else throw new TypeError("First argument is an unrecognized data type.");return r};ye._getRandomBN=function(){var e,t;do{var r=Ek.getRandomBuffer(32);t=mi.fromBuffer(r),e=t.lt(Mp.getN())}while(!e);return t};ye._transformBuffer=function(e,t){var r={};if(e.length===32)return ye._transformBNBuffer(e,t);if(r.network=hn.get(e[0],"privatekey"),!r.network)throw new Error("Invalid network");if(t&&r.network!==hn.get(t))throw new TypeError("Private key network mismatch");if(e.length===34&&e[33]===1)r.compressed=!0;else if(e.length===33)r.compressed=!1;else throw new Error("Length of buffer must be 33 (uncompressed) or 34 (compressed)");return r.bn=mi.fromBuffer(e.slice(1,33)),r};ye._transformBNBuffer=function(e,t,r){var n={};return n.network=hn.get(t)||hn.defaultNetwork,n.bn=mi.fromBuffer(e),n.compressed=r===void 0?!0:!!r,n};ye._transformWIF=function(e,t){return ye._transformBuffer(ax.decode(e),t)};ye.fromBuffer=function(e,t,r){return r!==void 0&&e&&e.length===32?new ye(ye._transformBNBuffer(e,t,r)):new ye(e,t)};ye.fromHex=function(e,t,r){return ye.fromBuffer(d.Buffer.from(e,"hex"),t,r)};ye._transformObject=function(e){if(e.bn instanceof mi)return{bn:e.bn,network:hn.get(e.network),compressed:e.compressed};if(typeof e.bn!="string"||!e.bn.length)throw new TypeError("Invalid private key: `bn` must be a hex string");if(e.bn===Np)throw new TypeError('Invalid private key: `bn` is "'+Np+'". JSON.stringify() redacts the secret on purpose \u2014 use toObject() for a round-trippable export, or toWIF().');if(!/^[0-9a-fA-F]+$/.test(e.bn))throw new TypeError("Invalid private key: `bn` is not hexadecimal");var t=new mi(e.bn,"hex");if(t.isZero()||t.gte(Mp.getN()))throw new TypeError("Invalid private key: outside the range of valid keys");var r=hn.get(e.network);return{bn:t,network:r,compressed:e.compressed}};ye.fromString=ye.fromWIF=function(e,t){return fx.checkArgument(Dc.isString(e),"First argument is expected to be a string."),new ye(e,t)};ye.fromObject=ye.fromJSON=function(e){return fx.checkArgument(Dc.isObject(e),"First argument is expected to be an object."),new ye(e)};ye.fromRandom=function(e){var t=ye._getRandomBN();return new ye(t,e)};ye.getValidationError=function(e,t){var r;try{new ye(e,t)}catch(n){r=n}return r};ye.isValid=function(e,t){return e?!ye.getValidationError(e,t):!1};ye.prototype.toString=function(){return this.toWIF()};ye.prototype.toWIF=function(){var e=this.network,t=this.compressed,r;return t?r=d.Buffer.concat([d.Buffer.from([e.privatekey]),this.bn.toBuffer({size:32}),d.Buffer.from([1])]):r=d.Buffer.concat([d.Buffer.from([e.privatekey]),this.bn.toBuffer({size:32})]),ax.encode(r)};ye.prototype.toBigNumber=function(){return this.bn};ye.prototype.toBuffer=function(){return this.bn.toBuffer({size:32})};ye.prototype.toHex=function(){return this.toBuffer().toString("hex")};ye.prototype.toPublicKey=function(){return this._pubkey||(this._pubkey=wk.fromPrivateKey(this)),this._pubkey};ye.prototype.toAddress=function(e){var t=this.toPublicKey();return Sk.fromPublicKey(t,e||this.network)};ye.prototype.toObject=function(){return{bn:this.bn.toString("hex"),compressed:this.compressed,network:this.network.toString()}};ye.prototype.toJSON=function(){return{bn:Np,compressed:this.compressed,network:this.network.toString()}};ye.prototype.inspect=function(){var e=this.compressed?"":", uncompressed";return"<PrivateKey: "+this.toHex()+", network: "+this.network+e+">"};cx.exports=ye});var Tr=P((_5,hx)=>{"use strict";m();var cs=Er(),ls=ii(),xk=Qt(),Ik=pr(),lx=ga(),kp=Ve(),so=ke();function ce(e,t){if(!(this instanceof ce))return new ce(e,t);if(so.checkArgument(e,"First argument is required, please include public key data."),e instanceof ce)return e;t=t||{};var r=this._classifyArgs(e,t);return r.point.validate(),Ik.defineImmutable(this,{point:r.point,compressed:r.compressed,network:r.network||lx.defaultNetwork}),this}ce.prototype._classifyArgs=function(e,t){var r={compressed:kp.isUndefined(t.compressed)||t.compressed};if(e instanceof ls)r.point=e;else if(e.x&&e.y)r=ce._transformObject(e);else if(typeof e=="string")r=ce._transformDER(d.Buffer.from(e,"hex"));else if(ce._isBuffer(e))r=ce._transformDER(e);else if(ce._isPrivateKey(e))r=ce._transformPrivateKey(e);else throw new TypeError("First argument is an unrecognized data format.");return r.network||(r.network=kp.isUndefined(t.network)?void 0:lx.get(t.network)),r};ce._isPrivateKey=function(e){var t=io();return e instanceof t};ce._isBuffer=function(e){return e instanceof d.Buffer||e instanceof Uint8Array};ce._transformPrivateKey=function(e){so.checkArgument(ce._isPrivateKey(e),"Must be an instance of PrivateKey");var t={};return t.point=ls.getG().mul(e.bn),t.compressed=e.compressed,t.network=e.network,t};ce._transformDER=function(e,t){so.checkArgument(ce._isBuffer(e),"Must be a buffer of DER encoded public key");var r={};t=kp.isUndefined(t)?!0:t;var n,i,o,s;if(e[0]===4||!t&&(e[0]===6||e[0]===7)){if(o=e.slice(1,33),s=e.slice(33,65),o.length!==32||s.length!==32||e.length!==65)throw new TypeError("Length of x and y must be 32 bytes");n=new cs(o),i=new cs(s),r.point=new ls(n,i),r.compressed=!1}else if(e[0]===3)o=e.slice(1),n=new cs(o),r=ce._transformX(!0,n),r.compressed=!0;else if(e[0]===2)o=e.slice(1),n=new cs(o),r=ce._transformX(!1,n),r.compressed=!0;else throw new TypeError("Invalid DER format public key");return r};ce._transformX=function(e,t){so.checkArgument(typeof e=="boolean","Must specify whether y is odd or not (true or false)");var r={};return r.point=ls.fromX(e,t),r};ce._transformObject=function(e){var t=new cs(e.x,"hex"),r=new cs(e.y,"hex"),n=new ls(t,r);return new ce(n,{compressed:e.compressed})};ce.fromPrivateKey=function(e){so.checkArgument(ce._isPrivateKey(e),"Must be an instance of PrivateKey");var t=ce._transformPrivateKey(e);return new ce(t.point,{compressed:t.compressed,network:t.network})};ce.fromDER=ce.fromBuffer=function(e,t){so.checkArgument(ce._isBuffer(e),"Must be a buffer of DER encoded public key");var r=ce._transformDER(e,t);return new ce(r.point,{compressed:r.compressed})};ce.fromPoint=function(e,t){return so.checkArgument(e instanceof ls,"First argument must be an instance of Point."),new ce(e,{compressed:t})};ce.fromHex=ce.fromString=function(e,t){var r=d.Buffer.from(e,t||"hex"),n=ce._transformDER(r);return new ce(n.point,{compressed:n.compressed})};ce.fromX=function(e,t){var r=ce._transformX(e,t);return new ce(r.point,{compressed:r.compressed})};ce.getValidationError=function(e){var t;try{new ce(e)}catch(r){t=r}return t};ce.isValid=function(e){return!ce.getValidationError(e)};ce.prototype.toObject=ce.prototype.toJSON=function(){return{x:this.point.getX().toString("hex",2),y:this.point.getY().toString("hex",2),compressed:this.compressed}};ce.prototype.toBuffer=ce.prototype.toDER=function(){var e=this.point.getX(),t=this.point.getY(),r=e.toBuffer({size:32}),n=t.toBuffer({size:32}),i;if(this.compressed){var o=n[n.length-1]%2;return o?i=d.Buffer.from([3]):i=d.Buffer.from([2]),d.Buffer.concat([i,r])}else return i=d.Buffer.from([4]),d.Buffer.concat([i,r,n])};ce.prototype._getID=function(){return xk.sha256ripemd160(this.toBuffer())};ce.prototype.toAddress=function(e){var t=no();return t.fromPublicKey(this,e||this.network)};ce.prototype.toString=ce.prototype.toHex=function(){return this.toDER().toString("hex")};ce.prototype.inspect=function(){return"<PublicKey: "+this.toHex()+(this.compressed?"":", uncompressed")+">"};hx.exports=ce});var Ka=P((w5,px)=>{"use strict";m();var dx=ea();function Ak(){var e=dx.getRandomBuffer(16);e[6]=e[6]&15|64,e[8]=e[8]&63|128;var t=e.toString("hex");return[t.substring(0,8),t.substring(8,12),t.substring(12,16),t.substring(16,20),t.substring(20,32)].join("-")}function Ok(e){return dx.getRandomBuffer(Math.ceil(e/2)).toString("hex").substring(0,e)}px.exports={uuid4:Ak,randomHex:Ok}});var bx=P((I5,vx)=>{"use strict";m();var Va=Tr(),Cp=Qt(),Lp=ka(),gx=ir(),Dp=io(),Rt=ke(),x5=Ve(),Rk=Ka();function yx(e,t){if(t=t||{},t.issuerPublicKey)return t.issuerPublicKey instanceof Va?t.issuerPublicKey:Va.fromString(t.issuerPublicKey);var r=e&&e.issuer;if(typeof r!="string")return null;try{var n=r.split("#")[0].split(":")[2];return n?Va.fromString(n):null}catch{return null}}var hs={PROPERTY_TITLE:"PropertyTitle",VEHICLE_TITLE:"VehicleTitle",INTELLECTUAL_PROPERTY:"IntellectualProperty",MUSIC_LICENSE:"MusicLicense",SOFTWARE_LICENSE:"SoftwareLicense",FINANCIAL_INSTRUMENT:"FinancialInstrument",PROMISSORY_NOTE:"PromissoryNote",BOND:"Bond",EQUITY_SHARE:"EquityShare",PROFESSIONAL_LICENSE:"ProfessionalLicense",REGULATORY_PERMIT:"RegulatoryPermit",ACCESS_RIGHT:"AccessRight",VOTING_RIGHT:"VotingRight",ROYALTY_RIGHT:"RoyaltyRight",USAGE_RIGHT:"UsageRight"},mx={create:function(e,t,r,n,i,o){o=o||{},Rt.checkArgument(typeof e=="string","Right type must be string"),Rt.checkArgument(typeof t=="string","Issuer DID must be string"),Rt.checkArgument(typeof r=="string","Subject DID must be string"),Rt.checkArgument(n&&typeof n=="object","Claim must be object");var s=Object.values(hs);Rt.checkArgument(s.includes(e),"Invalid right type: "+e);var a={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","LegalRightToken",e],issuer:t,issuanceDate:new Date().toISOString(),credentialSubject:{id:r,rightType:e,claim:n,jurisdiction:o.jurisdiction||"US",purpose:o.purpose||"legal_right",validFrom:o.validFrom||new Date().toISOString(),validUntil:o.validUntil||null,transferable:o.transferable!==!1,revocable:o.revocable!==!1}};return o.metadata&&(a.credentialSubject.metadata=o.metadata),a},prepareRightToken:function(e,t,r,n,i,o){o=o||{},Rt.checkArgument(typeof e=="string","Right type must be string"),Rt.checkArgument(typeof t=="string","Issuer DID must be string"),Rt.checkArgument(typeof r=="string","Subject DID must be string"),Rt.checkArgument(n&&typeof n=="object","Claim must be object"),Rt.checkArgument(i instanceof Dp,"Invalid issuer private key");var s=Object.values(hs);Rt.checkArgument(s.includes(e),"Invalid right type: "+e);try{var a=this.create(e,t,r,n,i,o),c=this._signToken(a,i);return{success:!0,rightToken:c,tokenHash:c.tokenHash,metadata:{type:e,issuer:t,subject:r,transferable:a.credentialSubject.transferable,revocable:a.credentialSubject.revocable,jurisdiction:a.credentialSubject.jurisdiction},externalOperations:{storeToken:{endpoint:"POST /rights/tokens",data:{token:c,metadata:{type:e,issuer:t,subject:r,transferable:a.credentialSubject.transferable,revocable:a.credentialSubject.revocable,jurisdiction:a.credentialSubject.jurisdiction}}},indexToken:{endpoint:"POST /rights/index",data:{tokenId:c.id,tokenHash:c.tokenHash,type:e,issuer:t,subject:r,issuedAt:c.issuanceDate}},notifyParties:{endpoint:"POST /notifications/right-issued",data:{tokenId:c.id,issuer:t,subject:r,rightType:e}}}}}catch(h){return{success:!1,error:h.message}}},prepareRightTokenVerification:function(e,t){t=t||{};try{var r=[],n=[];this._validateTokenStructure(e,r),this._verifyTokenSignature(e,r,t),this._validateTokenTemporal(e,r,n),this._validateRightType(e,r),t.requireJurisdiction&&this._validateJurisdiction(e,t.allowedJurisdictions,r);var i={valid:r.length===0,errors:r,warnings:n,issuerDID:e.issuer,subjectDID:e.credentialSubject?e.credentialSubject.id:null,rightType:e.credentialSubject?e.credentialSubject.rightType:null,transferable:e.credentialSubject?e.credentialSubject.transferable:null,revocable:e.credentialSubject?e.credentialSubject.revocable:null,verifiedAt:new Date().toISOString()};return{success:!0,verification:i,externalOperations:{recordVerification:{endpoint:"POST /rights/verification-record",data:{tokenId:e.id,result:i.valid,errors:r,warnings:n,verifiedAt:i.verifiedAt}},auditVerification:{endpoint:"POST /audit/right-verification",data:{tokenId:e.id,rightType:i.rightType,issuer:i.issuerDID,subject:i.subjectDID,result:i.valid,verifiedAt:i.verifiedAt}},updateTokenStatus:i.valid?{endpoint:"PUT /rights/tokens/"+e.id+"/status",data:{status:"VERIFIED",verifiedAt:i.verifiedAt}}:null}}}catch(o){return{success:!1,error:"Verification preparation failed: "+o.message}}},prepareRightTokenTransfer:function(e,t,r,n){n=n||{},Rt.checkArgument(e&&typeof e=="object","Invalid token"),Rt.checkArgument(typeof t=="string","New owner DID must be string"),Rt.checkArgument(r instanceof Dp,"Invalid current owner key");try{var i=this.prepareRightTokenVerification(e,{});if(!i.success||!i.verification.valid)return{success:!1,error:"Cannot transfer invalid token: "+i.verification.errors.join(", ")};if(!e.credentialSubject.transferable)return{success:!1,error:"Token is not transferable"};var o=e.credentialSubject&&e.credentialSubject.id,s=yx({issuer:o},{issuerPublicKey:n.currentOwnerPublicKey});if(!s)return{success:!1,error:"Cannot resolve current owner public key from token.credentialSubject.id; pass options.currentOwnerPublicKey"};if(r.toPublicKey().toString()!==s.toString())return{success:!1,error:"Unauthorized transfer: signing key does not match the current owner"};var a={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","LegalRightTransfer"],issuer:e.credentialSubject.id,issuanceDate:new Date().toISOString(),credentialSubject:{id:t,originalToken:e.id,transferFrom:e.credentialSubject.id,transferTo:t,transferDate:new Date().toISOString(),transferReason:n.reason||"ownership_transfer",consideration:n.consideration||null}},c=this._signToken(a,r),h=JSON.parse(JSON.stringify(e));h.id="urn:uuid:"+this._generateUUID(),h.issuanceDate=new Date().toISOString(),h.credentialSubject.id=t,h.credentialSubject.transferHistory=h.credentialSubject.transferHistory||[],h.credentialSubject.transferHistory.push({transferId:c.id,transferDate:c.issuanceDate,from:e.credentialSubject.id,to:t}),delete h.proof;var g=this._signToken(h,r);return{success:!0,newToken:g,transferProof:c,transferId:c.id,externalOperations:{recordTransfer:{endpoint:"POST /rights/transfers",data:{originalTokenId:e.id,newTokenId:g.id,transferProof:c,fromOwner:e.credentialSubject.id,toOwner:t,transferDate:c.issuanceDate}},updateOwnership:{endpoint:"PUT /rights/tokens/"+e.id+"/ownership",data:{newOwner:t,transferId:c.id,transferDate:c.issuanceDate,previousOwner:e.credentialSubject.id}},notifyParties:{endpoint:"POST /notifications/right-transferred",data:{originalTokenId:e.id,newTokenId:g.id,fromOwner:e.credentialSubject.id,toOwner:t,rightType:e.credentialSubject.rightType}},auditTransfer:{endpoint:"POST /audit/right-transfer",data:{originalTokenId:e.id,newTokenId:g.id,transferId:c.id,fromOwner:e.credentialSubject.id,toOwner:t,transferredAt:c.issuanceDate}}}}}catch(y){return{success:!1,error:y.message}}},prepareObligationToken:function(e,t,r,n){Rt.checkArgument(e&&typeof e=="object","Invalid right token"),Rt.checkArgument(typeof t=="string","Obligor DID must be string"),Rt.checkArgument(r&&typeof r=="object","Obligation must be object"),Rt.checkArgument(n instanceof Dp,"Invalid issuer key");try{var i={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","LegalObligationToken"],issuer:e.issuer,issuanceDate:new Date().toISOString(),credentialSubject:{id:t,obligationType:"correlative_obligation",correlativeRight:e.id,rightHolder:e.credentialSubject.id,obligation:r,jurisdiction:e.credentialSubject.jurisdiction,purpose:e.credentialSubject.purpose}},o=this._signToken(i,n);return{success:!0,obligationToken:o,correlativeRight:e.id,externalOperations:{storeObligation:{endpoint:"POST /obligations/tokens",data:{obligationToken:o,correlativeRightId:e.id,obligor:t,rightHolder:e.credentialSubject.id}},linkToRight:{endpoint:"POST /rights/tokens/"+e.id+"/obligations",data:{obligationId:o.id,obligor:t,obligationType:"correlative_obligation"}},notifyObligor:{endpoint:"POST /notifications/obligation-created",data:{obligationId:o.id,obligor:t,rightHolder:e.credentialSubject.id,correlativeRight:e.id}}}}}catch(s){return{success:!1,error:s.message}}},prepareRightTypeValidation:function(e){Rt.checkArgument(typeof e=="string","Right type must be string");var t=Object.values(hs),r=t.includes(e);return{success:!0,validation:{type:e,valid:r,availableTypes:t,category:this._categorizeRightType(e),description:this._getRightTypeDescription(e)},externalOperations:{validateType:{endpoint:"POST /rights/validate-type",data:{type:e,valid:r}}}}},_categorizeRightType:function(e){var t={PropertyTitle:"PROPERTY_RIGHT",VehicleTitle:"PROPERTY_RIGHT",IntellectualProperty:"IP_RIGHT",MusicLicense:"IP_RIGHT",SoftwareLicense:"IP_RIGHT",FinancialInstrument:"FINANCIAL_RIGHT",PromissoryNote:"FINANCIAL_RIGHT",Bond:"FINANCIAL_RIGHT",EquityShare:"FINANCIAL_RIGHT",ProfessionalLicense:"LICENSE_RIGHT",RegulatoryPermit:"LICENSE_RIGHT",AccessRight:"ACCESS_RIGHT",VotingRight:"GOVERNANCE_RIGHT",RoyaltyRight:"IP_RIGHT",UsageRight:"ACCESS_RIGHT"};return t[e]||"UNKNOWN"},_getRightTypeDescription:function(e){var t={PropertyTitle:"Legal ownership of real estate property",VehicleTitle:"Legal ownership of motor vehicle",IntellectualProperty:"Rights to intellectual property assets",MusicLicense:"License for music performance and usage",SoftwareLicense:"License for software usage and distribution",FinancialInstrument:"Rights related to financial instruments",PromissoryNote:"Promise to pay a specified amount",Bond:"Debt security representing loan",EquityShare:"Ownership stake in company",ProfessionalLicense:"License for professional practice",RegulatoryPermit:"Permit for regulated activities",AccessRight:"Right to access resources or locations",VotingRight:"Right to participate in governance",RoyaltyRight:"Right to receive royalty payments",UsageRight:"Right to use specific assets or services"};return t[e]||"Unknown right type"},getRightTypes:function(){return hs},verifyToken:function(e,t){var r=[];try{if(Rt.checkArgument(e&&typeof e=="object","Invalid token"),!e.proof||!e.proof.jws)return r.push("Missing signature proof"),{valid:!1,errors:r};var n=t instanceof Va?t:Va.fromString(t),i=this._canonicalizeToken(e),o=Cp.sha256(d.Buffer.from(i));if(e.tokenHash&&e.tokenHash!==o.toString("hex"))return r.push("Token hash mismatch"),{valid:!1,errors:r};var s=e.proof.jws.split(".");if(s.length!==3||!s[2])return r.push("Malformed JWS"),{valid:!1,errors:r};var a=gx.fromDER(d.Buffer.from(s[2],"base64url")),c=new Lp;return c.hashbuf=o,c.sig=a,c.pubkey=n,c.verify()||r.push("Signature verification failed"),{valid:r.length===0,errors:r,tokenHash:o.toString("hex"),verifiedAt:new Date().toISOString()}}catch(h){return r.push(h.message),{valid:!1,errors:r}}},_signToken:function(e,t){var r=this._canonicalizeToken(e),n=Cp.sha256(d.Buffer.from(r)),i=new Lp;i.hashbuf=n,i.privkey=t,i.pubkey=t.toPublicKey(),i.sign();var o=i.sig,s={type:"EcdsaSecp256k1Signature2019",created:new Date().toISOString(),verificationMethod:"did:smartledger:"+t.toPublicKey().toString()+"#keys-1",proofPurpose:"assertionMethod",jws:this._createJWS(n,o)},a=JSON.parse(JSON.stringify(e));return a.proof=s,a.tokenHash=n.toString("hex"),a},_createJWS:function(e,t){var r={alg:"ES256K",typ:"JWT"},n=d.Buffer.from(JSON.stringify(r)).toString("base64url"),i=t.toDER().toString("base64url");return n+".."+i},_canonicalizeToken:function(e){var t=JSON.parse(JSON.stringify(e));return delete t.proof,delete t.tokenHash,JSON.stringify(this._sortObjectKeys(t))},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e},_validateTokenStructure:function(e,t){e["@context"]||t.push("Missing @context"),e.id||t.push("Missing id"),(!e.type||!Array.isArray(e.type))&&t.push("Missing or invalid type"),e.issuer||t.push("Missing issuer"),e.issuanceDate||t.push("Missing issuanceDate"),e.credentialSubject||t.push("Missing credentialSubject"),e.proof||t.push("Missing proof")},_verifyTokenSignature:function(e,t,r){try{if(!e.proof||!e.proof.jws){t.push("Missing signature proof");return}var n=this._canonicalizeToken(e),i=Cp.sha256(d.Buffer.from(n));if(e.tokenHash&&e.tokenHash!==i.toString("hex")){t.push("Token hash mismatch");return}var o=yx(e,r);if(!o){t.push("Signature not verified: issuer public key could not be resolved from token.issuer; pass options.issuerPublicKey");return}var s=e.proof.jws.split(".");if(s.length!==3||!s[2]){t.push("Malformed JWS");return}var a=gx.fromDER(d.Buffer.from(s[2],"base64url")),c=new Lp;c.hashbuf=i,c.sig=a,c.pubkey=o,c.verify()!==!0&&t.push("Signature verification failed")}catch(h){t.push("Signature verification failed: "+h.message)}},_validateTokenTemporal:function(e,t,r){var n=new Date,i=new Date(e.issuanceDate);if(i>n&&t.push("Token issued in the future"),e.credentialSubject.validFrom){var o=new Date(e.credentialSubject.validFrom);n<o&&r.push("Token not yet valid")}if(e.credentialSubject.validUntil){var s=new Date(e.credentialSubject.validUntil);n>s&&t.push("Token expired")}},_validateRightType:function(e,t){if(!e.credentialSubject.rightType){t.push("Missing rightType");return}var r=Object.values(hs);r.includes(e.credentialSubject.rightType)||t.push("Invalid right type: "+e.credentialSubject.rightType)},_validateJurisdiction:function(e,t,r){if(!e.credentialSubject.jurisdiction){r.push("Missing jurisdiction");return}t&&Array.isArray(t)&&(t.includes(e.credentialSubject.jurisdiction)||r.push("Jurisdiction not allowed: "+e.credentialSubject.jurisdiction))},_generateUUID:function(){return Rk.uuid4()}};mx.RightTypes=hs;vx.exports=mx});var Sx=P((O5,_x)=>{"use strict";m();var Ga=Qt(),yr=ke(),Tk=Ka(),ao={PropertyTitle:{title:"Property Title",description:"Real estate property ownership title",type:"object",required:["propertyId","address","ownershipType"],properties:{propertyId:{type:"string",description:"Unique property identifier"},address:{type:"object",required:["street","city","state","country"],properties:{street:{type:"string"},city:{type:"string"},state:{type:"string"},country:{type:"string"},postalCode:{type:"string"}}},ownershipType:{type:"string",enum:["fee_simple","leasehold","joint_tenancy","tenancy_in_common"]},titleNumber:{type:"string"},registeredDate:{type:"string",format:"date-time"},legalDescription:{type:"string"},encumbrances:{type:"array",items:{type:"object",properties:{type:{type:"string"},amount:{type:"number"},description:{type:"string"}}}}}},VehicleTitle:{title:"Vehicle Title",description:"Motor vehicle ownership title",type:"object",required:["vin","make","model","year"],properties:{vin:{type:"string",pattern:"^[A-HJ-NPR-Z0-9]{17}$",description:"Vehicle Identification Number"},make:{type:"string"},model:{type:"string"},year:{type:"integer",minimum:1900,maximum:2030},titleNumber:{type:"string"},registeredState:{type:"string"},mileage:{type:"integer",minimum:0},color:{type:"string"},fuelType:{type:"string",enum:["gasoline","diesel","electric","hybrid","other"]},liens:{type:"array",items:{type:"object",properties:{lienholderName:{type:"string"},lienAmount:{type:"number"},lienDate:{type:"string",format:"date"}}}}}},PromissoryNote:{title:"Promissory Note",description:"Legal promise to pay a specified amount",type:"object",required:["principal","interestRate","maturityDate","borrower","lender"],properties:{principalAmount:{type:"number",minimum:0,description:"Principal amount in base currency units"},currency:{type:"string",default:"USD"},interestRate:{type:"number",minimum:0,maximum:100,description:"Annual interest rate percentage"},maturityDate:{type:"string",format:"date",description:"Date when principal and interest are due"},payee:{type:"string",description:"DID of the payee (creditor)"},payor:{type:"string",description:"DID of the payor (debtor)"},paymentSchedule:{type:"string",enum:["lump_sum","monthly","quarterly","annually"]},collateral:{type:"array",items:{type:"object",properties:{description:{type:"string"},value:{type:"number"},type:{type:"string"}}}},defaultProvisions:{type:"string"},governingLaw:{type:"string"}}},IntellectualProperty:{title:"Intellectual Property",description:"Intellectual property rights and licensing",type:"object",required:["ipType","title","registrationNumber"],properties:{ipType:{type:"string",enum:["patent","trademark","copyright","trade_secret"]},title:{type:"string"},creator:{type:"string",description:"Creator DID"},registrationNumber:{type:"string"},registrationDate:{type:"string",format:"date"},expirationDate:{type:"string",format:"date"},jurisdiction:{type:"string"},description:{type:"string"},claims:{type:"array",items:{type:"string"}},priorArt:{type:"array",items:{type:"object",properties:{reference:{type:"string"},date:{type:"string",format:"date"},relevance:{type:"string"}}}}}},ProfessionalLicense:{title:"Professional License",description:"Professional practice license or certification",type:"object",required:["licenseType","licenseNumber","issuingAuthority","expirationDate"],properties:{licenseType:{type:"string"},licenseNumber:{type:"string"},issuingAuthority:{type:"string"},licensee:{type:"string",description:"Licensee DID"},issueDate:{type:"string",format:"date"},expirationDate:{type:"string",format:"date"},renewalDate:{type:"string",format:"date"},jurisdiction:{type:"string"},scope:{type:"string"},restrictions:{type:"array",items:{type:"string"}},continuing_education:{type:"object",properties:{hours_required:{type:"integer"},deadline:{type:"string",format:"date"},completed_hours:{type:"integer"}}}}},MusicLicense:{title:"Music License",description:"Music performance and usage licensing",type:"object",required:["songTitle","artist","licenseType","royaltyRate"],properties:{workTitle:{type:"string"},composer:{type:"string",description:"Composer DID"},performer:{type:"string",description:"Performer DID"},licenseType:{type:"string",enum:["mechanical","performance","synchronization","master_use"]},territory:{type:"string"},duration:{type:"string"},royaltyRate:{type:"number",minimum:0,maximum:100},advancePayment:{type:"number",minimum:0},exclusivity:{type:"boolean"},mediaTypes:{type:"array",items:{type:"string",enum:["cd","vinyl","digital","streaming","broadcast","film","tv"]}},usage_restrictions:{type:"string"},copyrightNotice:{type:"string"}}}},Pk={prepareClaimValidation:function(e,t){try{yr.checkArgument(e&&typeof e=="object","Invalid claim"),yr.checkArgument(typeof t=="string","Schema name must be string");var r=ao[t];if(!r)return{success:!1,error:"Unknown schema: "+t};var n=[],i=[];this._validateObject(e,r,"",n,i);var o={valid:n.length===0,errors:n,warnings:i,schema:t,claimHash:this.hash(e),canonical:this.canonicalize(e)};return{success:!0,validation:o,claim:e,schema:r,externalOperations:{store:{endpoint:"POST /claims/validate",data:{claim:e,validation:o,schema:t}},index:{endpoint:"POST /claims/index",data:{claimHash:o.claimHash,schemaName:t,valid:o.valid}}}}}catch(s){return{success:!1,error:"Validation preparation failed: "+s.message}}},prepareClaimAttestation:function(e,t,r){try{yr.checkArgument(e&&typeof e=="object","Invalid claim"),yr.checkArgument(typeof t=="string","Schema name must be string"),yr.checkArgument(r&&typeof r=="object","Invalid attestor");var n=this.prepareClaimValidation(e,t);if(!n.success||!n.validation.valid)return{success:!1,error:"Cannot attest invalid claim",validation:n};var i={type:"LTP_CLAIM_ATTESTATION",claimHash:n.validation.claimHash,schemaName:t,attestor:{did:r.did||r.id,name:r.name||"Unknown",authority:r.authority||null,jurisdiction:r.jurisdiction||null},attestedAt:new Date().toISOString(),confidence:r.confidence||100,evidence:r.evidence||null,notes:r.notes||null},o=Ga.sha256(d.Buffer.from(this.canonicalize(i))).toString("hex");return i.attestationHash=o,{success:!0,attestation:i,claim:e,validation:n.validation,externalOperations:{storeAttestation:{endpoint:"POST /claims/"+n.validation.claimHash+"/attestations",data:i},notifyStakeholders:{endpoint:"POST /notifications/claim-attested",data:{claimHash:n.validation.claimHash,attestorDid:i.attestor.did,attestationHash:o}}}}}catch(s){return{success:!1,error:"Attestation preparation failed: "+s.message}}},prepareClaimDispute:function(e,t,r){try{yr.checkArgument(typeof e=="string","Claim hash must be string"),yr.checkArgument(t&&typeof t=="object","Invalid disputant"),yr.checkArgument(r&&typeof r=="object","Invalid dispute");var n={type:"LTP_CLAIM_DISPUTE",claimHash:e,disputant:{did:t.did||t.id,name:t.name||"Unknown",jurisdiction:t.jurisdiction||null},dispute:{reason:r.reason||"UNSPECIFIED",category:r.category||"ACCURACY",description:r.description||"",evidence:r.evidence||null,requestedAction:r.requestedAction||"REVIEW"},disputedAt:new Date().toISOString(),status:"FILED",priority:r.priority||"NORMAL"},i=Ga.sha256(d.Buffer.from(this.canonicalize(n))).toString("hex");return n.disputeHash=i,{success:!0,dispute:n,disputeId:this._generateDisputeId(e),externalOperations:{fileDispute:{endpoint:"POST /claims/"+e+"/disputes",data:n},notifyStakeholders:{endpoint:"POST /notifications/claim-disputed",data:{claimHash:e,disputantDid:n.disputant.did,disputeHash:i}},escalate:{endpoint:"POST /disputes/escalate",data:{disputeHash:i,priority:n.priority}}}}}catch(o){return{success:!1,error:"Dispute preparation failed: "+o.message}}},prepareBulkClaimValidation:function(e,t){try{yr.checkArgument(Array.isArray(e),"Claims must be array"),yr.checkArgument(typeof t=="string","Schema name must be string");var r=[],n=[],i=0;e.forEach(function(a,c){try{var h=this.prepareClaimValidation(a,t);h.success&&h.validation.valid&&i++,r.push({index:c,result:h})}catch(g){n.push({index:c,error:g.message})}}.bind(this));var o=this._generateBatchId(),s=Ga.sha256(d.Buffer.from(JSON.stringify(r.map(a=>a.result.validation.claimHash)))).toString("hex");return{success:!0,batchId:o,batchHash:s,totalClaims:e.length,validClaims:i,invalidClaims:e.length-i,validations:r,errors:n,externalOperations:{storeBatch:{endpoint:"POST /claims/batch-validate",data:{batchId:o,batchHash:s,schemaName:t,validations:r}},generateReport:{endpoint:"POST /reports/bulk-validation",data:{batchId:o,summary:{total:e.length,valid:i,invalid:e.length-i}}}}}}catch(a){return{success:!1,error:"Bulk validation preparation failed: "+a.message}}},canonicalize:function(e){yr.checkArgument(e&&typeof e=="object","Invalid claim");var t=this._sortObjectKeys(e);return JSON.stringify(t)},hash:function(e){var t=this.canonicalize(e);return Ga.sha256(d.Buffer.from(t)).toString("hex")},prepareClaimTemplate:function(e,t){t=t||{};try{var r=ao[e];if(!r)return{success:!1,error:"Unknown schema: "+e};var n=this._createTemplateFromSchema(r),i=this._generateFormStructure(r);return{success:!0,schemaName:e,template:n,schema:r,formStructure:i,validation:{required:r.required||[],patterns:this._extractPatterns(r),enums:this._extractEnums(r)},externalOperations:{generateForm:{endpoint:"POST /forms/generate",data:{schemaName:e,formStructure:i,template:n}},saveTemplate:{endpoint:"POST /templates/claim",data:{schemaName:e,template:n,customizations:t.customizations||{}}}}}}catch(o){return{success:!1,error:"Template preparation failed: "+o.message}}},getSchemas:function(){return ao},getSchemaNames:function(){return Object.keys(ao)},getSchema:function(e){return ao[e]||null},addSchema:function(e,t){yr.checkArgument(typeof e=="string","Schema name must be string"),yr.checkArgument(t&&typeof t=="object","Invalid schema"),ao[e]=t},createTemplate:function(e){var t=ao[e];if(!t)throw new Error("Unknown schema: "+e);return this._createTemplateFromSchema(t)},_generateDisputeId:function(e){var t="dispute_"+e+"_"+Date.now();return Ga.sha256(d.Buffer.from(t)).toString("hex").substring(0,16)},_generateBatchId:function(){return Tk.randomHex(16)},_generateFormStructure:function(e){var t={type:"form",title:e.title||"Legal Claim Form",description:e.description||"",fields:[]};return e.properties&&Object.keys(e.properties).forEach(function(r){var n=e.properties[r],i={name:r,label:this._humanizeFieldName(r),type:this._mapSchemaTypeToFormType(n),required:e.required&&e.required.includes(r),validation:this._extractFieldValidation(n)};n.enum&&(i.options=n.enum.map(function(o){return{value:o,label:this._humanizeValue(o)}}.bind(this))),t.fields.push(i)}.bind(this)),t},_extractPatterns:function(e){var t={};return e.properties&&Object.keys(e.properties).forEach(function(r){var n=e.properties[r];n.pattern&&(t[r]=n.pattern)}),t},_extractEnums:function(e){var t={};return e.properties&&Object.keys(e.properties).forEach(function(r){var n=e.properties[r];n.enum&&(t[r]=n.enum)}),t},_mapSchemaTypeToFormType:function(e){switch(e.type){case"string":return e.enum?"select":e.format==="date"?"date":e.format==="date-time"?"datetime":"text";case"number":case"integer":return"number";case"boolean":return"checkbox";case"array":return"list";case"object":return"fieldset";default:return"text"}},_extractFieldValidation:function(e){var t={};return e.pattern&&(t.pattern=e.pattern),e.minimum!==void 0&&(t.min=e.minimum),e.maximum!==void 0&&(t.max=e.maximum),e.format&&(t.format=e.format),t},_humanizeFieldName:function(e){return e.replace(/([A-Z])/g," $1").replace(/^./,function(t){return t.toUpperCase()}).replace(/_/g," ")},_humanizeValue:function(e){return e.replace(/_/g," ").replace(/\b\w/g,function(t){return t.toUpperCase()})},_validateObject:function(e,t,r,n,i){t.type==="object"?(t.required&&Array.isArray(t.required)&&t.required.forEach(function(o){e.hasOwnProperty(o)||n.push("Missing required field: "+this._getFieldPath(r,o))}.bind(this)),t.properties&&Object.keys(e).forEach(function(o){var s=this._getFieldPath(r,o),a=t.properties[o];a?this._validateValue(e[o],a,s,n,i):i.push("Unknown field: "+s)}.bind(this))):this._validateValue(e,t,r,n,i)},_validateValue:function(e,t,r,n,i){if(t.type){var o=Array.isArray(e)?"array":typeof e;if(o!==t.type){n.push("Invalid type for "+r+": expected "+t.type+", got "+o);return}}if(t.type==="string"&&(t.pattern&&!new RegExp(t.pattern).test(e)&&n.push("Value does not match pattern for "+r),t.enum&&!t.enum.includes(e)&&n.push("Invalid enum value for "+r+": "+e),t.format==="date"&&!this._isValidDate(e)&&n.push("Invalid date format for "+r),t.format==="date-time"&&!this._isValidDateTime(e)&&n.push("Invalid date-time format for "+r)),(t.type==="number"||t.type==="integer")&&(t.minimum!==void 0&&e<t.minimum&&n.push("Value below minimum for "+r+": "+e+" < "+t.minimum),t.maximum!==void 0&&e>t.maximum&&n.push("Value above maximum for "+r+": "+e+" > "+t.maximum),t.type==="integer"&&!Number.isInteger(e)&&n.push("Value must be integer for "+r)),t.type==="array"&&t.items)for(var s=0;s<e.length;s++)this._validateValue(e[s],t.items,r+"["+s+"]",n,i);t.type==="object"&&this._validateObject(e,t,r,n,i)},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e},_createTemplateFromSchema:function(e){if(e.type==="object"){var t={};return e.properties&&Object.keys(e.properties).forEach(function(r){var n=e.properties[r];t[r]=this._getDefaultValue(n)}.bind(this)),t}return this._getDefaultValue(e)},_getDefaultValue:function(e){if(e.default!==void 0)return e.default;switch(e.type){case"string":return e.enum?e.enum[0]:e.format==="date"?"2023-01-01":e.format==="date-time"?new Date().toISOString():"PLACEHOLDER_STRING";case"number":case"integer":return e.minimum||0;case"boolean":return!1;case"array":return[];case"object":return this._createTemplateFromSchema(e);default:return null}},_getFieldPath:function(e,t){return e?e+"."+t:t},_isValidDate:function(e){var t=new Date(e);return!isNaN(t.getTime())&&e.match(/^\d{4}-\d{2}-\d{2}$/)},_isValidDateTime:function(e){var t=new Date(e);return!isNaN(t.getTime())}};_x.exports=Pk});var Ex=P((T5,wx)=>{"use strict";m();var za=Qt(),ds=ke(),Bk={prepareTokenCommitment:function(e,t){t=t||{},ds.checkArgument(e&&typeof e=="object","Invalid token");try{var r=this._createCommitment(e,t),n=this._formatOpReturn(r,t),i=this._createTxTemplate(n,t);return{success:!0,commitment:r,opReturnData:n,txTemplate:i,preparedAt:new Date().toISOString(),metadata:{tokenId:e.id,purpose:t.purpose||"legal_token_anchor",version:"LTP.v1"}}}catch(o){return{success:!1,error:o.message}}},prepareBatchCommitment:function(e,t){t=t||{},ds.checkArgument(Array.isArray(e),"Tokens must be array");try{var r=this._createBatchCommitment(e,t),n=this._formatOpReturn(r,t),i=this._createTxTemplate(n,t);return{success:!0,batchCommitment:r,opReturnData:n,txTemplate:i,tokenCount:e.length,preparedAt:new Date().toISOString(),metadata:{purpose:t.purpose||"legal_token_batch_anchor",version:"LTP.v1"}}}catch(o){return{success:!1,error:o.message}}},verifyTokenAnchor:function(e,t,r){ds.checkArgument(e&&typeof e=="object","Invalid token"),ds.checkArgument(typeof t=="string","Transaction ID must be string");try{var n=this._createCommitment(e,{}),i=this._extractOpReturn(r);if(!i)return{valid:!1,error:"No OP_RETURN data found in transaction"};var o=this._verifyCommitment(n,i);return{valid:o,chainVerified:!1,txid:t,commitment:n,anchorData:i,verifiedAt:new Date().toISOString()}}catch(s){return{valid:!1,error:s.message}}},formatRevocation:function(e,t){ds.checkArgument(typeof e=="string","Token ID must be string"),ds.checkArgument(t&&typeof t=="object","Invalid revocation data");try{var r={type:"LTP_REVOCATION",tokenId:e,reason:t.reason||"UNSPECIFIED",revokedBy:t.revokedBy||"UNKNOWN",revokedAt:new Date().toISOString(),effectiveDate:t.effectiveDate||new Date().toISOString(),legalBasis:t.legalBasis||null,evidence:t.evidence||null},n=za.sha256(d.Buffer.from(JSON.stringify(r))).toString("hex");return{success:!0,revocation:r,revocationHash:n,opReturnData:this._formatOpReturn({hash:n,type:"REVOCATION"},{})}}catch(i){return{success:!1,error:i.message}}},_createCommitment:function(e,t){var r=this._canonicalizeToken(e),n={type:"LTP_TOKEN",tokenHash:za.sha256(d.Buffer.from(r)).toString("hex"),tokenId:e.id,timestamp:new Date().toISOString(),purpose:t.purpose||"legal_token"},i=za.sha256(d.Buffer.from(JSON.stringify(n))).toString("hex");return{hash:i,data:n,canonical:r}},_createBatchCommitment:function(e,t){var r=[],n=[];e.forEach(function(a){var c=this._createCommitment(a,t);r.push(c.hash),n.push(a.id)}.bind(this));var i=this._createMerkleRoot(r),o={type:"LTP_BATCH",merkleRoot:i,tokenCount:e.length,tokenIds:n,timestamp:new Date().toISOString(),purpose:t.purpose||"batch_anchor"},s=za.sha256(d.Buffer.from(JSON.stringify(o))).toString("hex");return{hash:s,data:o,merkleRoot:i,tokenHashes:r}},_formatOpReturn:function(e,t){var r=t.prefix||"LTP.v1",n=e.hash;return{prefix:r,data:n,full:r+"."+n,bytes:d.Buffer.from(r+"."+n,"utf8"),size:d.Buffer.from(r+"."+n,"utf8").length}},_createTxTemplate:function(e,t){try{var r={version:1,inputs:[],outputs:[{satoshis:0,script:"OP_RETURN "+e.data}],locktime:0};return t.feeOutput&&r.outputs.push(t.feeOutput),{template:r,opReturn:e,estimatedSize:this._estimateSize(r),instructions:{step1:"Add input UTXOs to cover fees",step2:"Add change output if needed",step3:"Sign transaction with appropriate keys",step4:"Broadcast to BSV network"}}}catch(n){throw new Error("Failed to create transaction template: "+n.message)}},_extractOpReturn:function(e){try{if(!e||!e.outputs)return null;for(var t=0;t<e.outputs.length;t++){var r=e.outputs[t];if(r.script&&r.script.startsWith("OP_RETURN")){var n=r.script.replace("OP_RETURN ","");return{raw:n,decoded:d.Buffer.from(n,"hex").toString("utf8")}}}return null}catch{return null}},_verifyCommitment:function(e,t){try{return!t||!t.decoded?!1:t.decoded.includes(e.hash)}catch{return!1}},_canonicalizeToken:function(e){var t=JSON.parse(JSON.stringify(e));return delete t.proof,delete t.tokenHash,delete t.anchorTx,delete t.anchorBlock,JSON.stringify(this._sortObjectKeys(t))},_createMerkleRoot:function(e){if(e.length===0)return null;if(e.length===1)return e[0];for(var t=e.slice();t.length>1;){for(var r=[],n=0;n<t.length;n+=2){var i=t[n],o=t[n+1]||i,s=d.Buffer.concat([d.Buffer.from(i,"hex"),d.Buffer.from(o,"hex")]),a=za.sha256(s).toString("hex");r.push(a)}t=r}return t[0]},_estimateSize:function(e){var t=10,r=e.outputs.length*34,n=148;return{base:t+r,withOneInput:t+r+n,bytesPerInput:n}},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e}};wx.exports=Bk});var Ax=P((B5,Ix)=>{"use strict";m();var Nk=Tr(),Yr=Qt(),xx=ka(),Mk=ir(),kk=io(),or=ke(),Ck={prepareSignatureProof:function(e,t,r){r=r||{},or.checkArgument(e&&typeof e=="object","Invalid token"),or.checkArgument(t instanceof kk,"Invalid private key");try{var n=this._canonicalizeForSigning(e),i=Yr.sha256(d.Buffer.from(n)),o=new xx;o.hashbuf=i,o.privkey=t,o.pubkey=t.toPublicKey(),o.sign();var s=o.sig,a={type:"EcdsaSecp256k1Signature2019",created:new Date().toISOString(),verificationMethod:"did:smartledger:"+t.toPublicKey().toString()+"#keys-1",proofPurpose:r.purpose||"assertionMethod",jws:this._createJWS(i,s),proofValue:s.toDER().toString("hex")};return{success:!0,proof:a,tokenHash:i.toString("hex"),canonical:n,signingKey:{publicKey:t.toPublicKey().toString(),keyId:"did:smartledger:"+t.toPublicKey().toString()+"#keys-1"},externalOperations:{storeProof:{endpoint:"POST /proofs/signature",data:{tokenHash:i.toString("hex"),proof:a,signingKey:t.toPublicKey().toString()}},verifyProof:{endpoint:"POST /proofs/verify-signature",data:{tokenHash:i.toString("hex"),signature:s.toDER().toString("hex"),publicKey:t.toPublicKey().toString()}}}}}catch(c){return{success:!1,error:c.message}}},prepareSignatureVerification:function(e,t){try{if(or.checkArgument(e&&typeof e=="object","Invalid token"),or.checkArgument(typeof t=="string","Public key must be string"),!e.proof)return{success:!1,error:"No proof found in token"};var r=this._canonicalizeForSigning(e),n=Yr.sha256(d.Buffer.from(r)),i=Mk.fromDER(d.Buffer.from(e.proof.proofValue,"hex")),o={tokenHash:n.toString("hex"),signature:i.toDER().toString("hex"),publicKey:t,proof:e.proof,canonical:r},s=new xx;s.hashbuf=n,s.sig=i,s.pubkey=Nk.fromString(t);var a=s.verify()===!0;return{success:!0,verification:{valid:a,tokenHash:n.toString("hex"),signatureValid:a,publicKey:t,verifiedAt:new Date().toISOString()},verificationData:o,externalOperations:{recordVerification:{endpoint:"POST /proofs/verification-record",data:{tokenHash:n.toString("hex"),result:a,publicKey:t,verifiedAt:new Date().toISOString()}},auditVerification:{endpoint:"POST /audit/proof-verification",data:{tokenId:e.id,proofType:e.proof.type,result:a,verifier:t}}}}}catch(c){return{success:!1,error:c.message}}},prepareSelectiveDisclosure:function(e,t,r){or.checkArgument(e&&typeof e=="object","Invalid token"),or.checkArgument(Array.isArray(t),"Revealed fields must be array"),or.checkArgument(typeof r=="string","Nonce must be string");try{var n=this._createFieldCommitments(e,r),i=this._createMerkleTree(n),o=[],s=[];t.forEach(function(c){var h=this._getNestedValue(e,c),g=this._findFieldCommitment(n,c);if(g){o.push({path:c,value:h,commitment:g.hash,salt:g.salt});var y=this._generateMerkleProof(i,g.index);s.push({path:c,leafIndex:g.index,proof:y})}}.bind(this));var a={type:"LegalTokenSelectiveDisclosure",created:new Date().toISOString(),proofPurpose:"selectiveDisclosure",verificationMethod:e.proof?e.proof.verificationMethod:null,nonce:r,merkleRoot:i.root,disclosures:o,merkleProofs:s,totalFields:n.length};return{success:!0,proof:a,hiddenFieldCount:n.length-o.length,revealedFieldCount:o.length,externalOperations:{storeDisclosure:{endpoint:"POST /proofs/selective-disclosure",data:{tokenId:e.id,proof:a,merkleRoot:i.root}},verifyDisclosure:{endpoint:"POST /proofs/verify-disclosure",data:{proof:a,expectedNonce:r}},auditDisclosure:{endpoint:"POST /audit/selective-disclosure",data:{tokenId:e.id,revealedFields:t,totalFields:n.length,disclosedAt:new Date().toISOString()}}}}}catch(c){return{success:!1,error:c.message}}},prepareSelectiveDisclosureVerification:function(e,t){try{if(or.checkArgument(e&&typeof e=="object","Invalid proof"),or.checkArgument(typeof t=="string","Expected nonce must be string"),e.nonce!==t)return{success:!1,error:"Nonce mismatch"};var r=[],n=[];e.disclosures.forEach(function(o,s){var a=e.merkleProofs[s],c=this._hashField(o.path,o.value,o.salt);if(c!==o.commitment){n.push("Invalid commitment for field: "+o.path);return}var h=this._verifyMerkleProof(o.commitment,a.leafIndex,a.proof,e.merkleRoot);h?r.push({path:o.path,value:o.value,verified:!0}):n.push("Invalid Merkle proof for field: "+o.path)}.bind(this));var i={valid:n.length===0,errors:n,disclosures:r,merkleRoot:e.merkleRoot,totalFields:e.totalFields,verifiedAt:new Date().toISOString()};return{success:!0,verification:i,externalOperations:{recordVerification:{endpoint:"POST /proofs/disclosure-verification",data:{proofId:e.id||"unknown",result:i.valid,verifiedFields:r.length,totalFields:e.totalFields,verifiedAt:i.verifiedAt}},auditVerification:{endpoint:"POST /audit/disclosure-verification",data:{merkleRoot:e.merkleRoot,disclosuresVerified:r.length,errors:n.length,result:i.valid}}}}}catch(o){return{success:!1,error:o.message}}},prepareLegalValidityProof:function(e,t,r){or.checkArgument(e&&typeof e=="object","Invalid token"),or.checkArgument(t&&typeof t=="object","Invalid jurisdiction"),or.checkArgument(typeof r=="string","Nonce must be string");try{var n=t.requirements||[],i=[],o=!0;n.forEach(function(a){var c=this._checkLegalRequirement(e,a);i.push(c),c.satisfied||(o=!1)}.bind(this));var s={type:"LegalValidityProof",created:new Date().toISOString(),proofPurpose:"legalValidity",jurisdiction:t.code,nonce:r,valid:o,checks:i,complianceHash:this._hashCompliance(e,t,r)};return{success:!0,proof:s,valid:o,complianceReport:{jurisdiction:t.code,totalRequirements:n.length,satisfiedRequirements:i.filter(a=>a.satisfied).length,failedRequirements:i.filter(a=>!a.satisfied).length,overallCompliance:o},externalOperations:{submitCompliance:{endpoint:"POST /compliance/legal-validity",data:{tokenId:e.id,jurisdiction:t.code,proof:s,complianceReport:{jurisdiction:t.code,totalRequirements:n.length,satisfiedRequirements:i.filter(a=>a.satisfied).length,failedRequirements:i.filter(a=>!a.satisfied).length,overallCompliance:o}}},auditCompliance:{endpoint:"POST /audit/compliance-check",data:{tokenId:e.id,jurisdiction:t.code,result:o,checkedAt:new Date().toISOString(),requirements:i}},notifyRegulator:o?null:{endpoint:"POST /notifications/compliance-failure",data:{tokenId:e.id,jurisdiction:t.code,failedRequirements:i.filter(a=>!a.satisfied)}}}}}catch(a){return{success:!1,error:a.message}}},prepareZeroKnowledgeProof:function(e,t,r){or.checkArgument(e&&typeof e=="object","Invalid token"),or.checkArgument(t&&typeof t=="object","Invalid statement"),or.checkArgument(typeof r=="string","Nonce must be string");try{var n=Yr.sha256(d.Buffer.from(this._canonicalizeForSigning(e)+r)).toString("hex"),i={type:"LegalTokenZKProof",created:new Date().toISOString(),proofPurpose:"zeroKnowledge",statement:{claim:t.claim||"UNSPECIFIED",predicate:t.predicate||"SATISFIES",threshold:t.threshold||null},commitment:n,nonce:r,proofData:this._generateZKProofData(e,t,r)};return{success:!0,proof:i,commitment:n,externalOperations:{storeZKProof:{endpoint:"POST /proofs/zero-knowledge",data:{tokenId:e.id,proof:i,statement:t}},verifyZKProof:{endpoint:"POST /proofs/verify-zk",data:{proof:i,expectedNonce:r}},auditZKProof:{endpoint:"POST /audit/zk-proof",data:{tokenId:e.id,statement:t.claim,proofGenerated:new Date().toISOString()}}}}}catch(o){return{success:!1,error:o.message}}},_generateZKProofData:function(e,t,r){var n={challenge:Yr.sha256(d.Buffer.from(t.claim+r)).toString("hex"),response:Yr.sha256(d.Buffer.from(this._canonicalizeForSigning(e)+t.claim)).toString("hex"),witness:Yr.sha256(d.Buffer.from(r+e.id+t.predicate)).toString("hex")};return n},_createJWS:function(e,t){var r={alg:"ES256K",typ:"JWT"},n=d.Buffer.from(JSON.stringify(r)).toString("base64url"),i=e.toString("base64url"),o=t.toDER().toString("base64url");return n+".."+o},_canonicalizeForSigning:function(e){var t=JSON.parse(JSON.stringify(e));delete t.proof,delete t.tokenHash;var r=this._sortObjectKeys(t);return JSON.stringify(r)},_createFieldCommitments:function(e,t){var r=[],n=0;return this._traverseObject(e,"",function(i,o){if(i!=="proof"&&i!=="tokenHash"){var s=Yr.sha256(d.Buffer.from(t+i+n)).toString("hex"),a=this._hashField(i,o,s);r.push({path:i,value:o,salt:s,hash:a,index:n}),n++}}.bind(this)),r},_hashField:function(e,t,r){var n=e+":"+JSON.stringify(t)+":"+r;return Yr.sha256(d.Buffer.from(n)).toString("hex")},_createMerkleTree:function(e){var t=e.map(function(g){return g.hash});if(t.length===0)return{root:null,levels:[]};for(var r=[t],n=t;n.length>1;){for(var i=[],o=0;o<n.length;o+=2){var s=n[o],a=n[o+1]||s,c=d.Buffer.concat([d.Buffer.from(s,"hex"),d.Buffer.from(a,"hex")]),h=Yr.sha256(c).toString("hex");i.push(h)}r.push(i),n=i}return{root:n[0],levels:r}},_generateMerkleProof:function(e,t){for(var r=[],n=t,i=0;i<e.levels.length-1;i++){var o=e.levels[i],s=n%2===0,a=s?n+1:n-1;a<o.length&&r.push({hash:o[a],isLeft:!s}),n=Math.floor(n/2)}return r},_verifyMerkleProof:function(e,t,r,n){for(var i=e,o=t,s=0;s<r.length;s++){var a=r[s],c=o%2===0,h;a.isLeft?h=d.Buffer.concat([d.Buffer.from(a.hash,"hex"),d.Buffer.from(i,"hex")]):h=d.Buffer.concat([d.Buffer.from(i,"hex"),d.Buffer.from(a.hash,"hex")]),i=Yr.sha256(h).toString("hex"),o=Math.floor(o/2)}return i===n},_traverseObject:function(e,t,r){Array.isArray(e)?e.forEach(function(n,i){var o=t+"["+i+"]";this._traverseObject(n,o,r)}.bind(this)):e!==null&&typeof e=="object"?Object.keys(e).forEach(function(n){var i=t?t+"."+n:n;this._traverseObject(e[n],i,r)}.bind(this)):r(t,e)},_getNestedValue:function(e,t){return t.split(".").reduce(function(r,n){return r&&r[n]},e)},_findFieldCommitment:function(e,t){return e.find(function(r){return r.path===t})},_checkLegalRequirement:function(e,t){switch(t.type){case"field_present":var r=this._getNestedValue(e,t.field);return{requirement:t.type,field:t.field,satisfied:r!=null};case"field_value":var r=this._getNestedValue(e,t.field);return{requirement:t.type,field:t.field,satisfied:r===t.expectedValue};case"temporal_validity":var n=new Date,i=new Date(e.issuanceDate);return{requirement:t.type,satisfied:i<=n};default:return{requirement:t.type,satisfied:!1,error:"Unknown requirement type"}}},_hashCompliance:function(e,t,r){var n={tokenId:e.id,jurisdiction:t.code,nonce:r,timestamp:new Date().toISOString()};return Yr.sha256(d.Buffer.from(JSON.stringify(n))).toString("hex")},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e}};Ix.exports=Ck});var Tx=P((C5,Rx)=>{"use strict";m();var Wa=Qt(),M5=no(),k5=Op(),cr=ke(),Ox=Ka(),Lk={prepareRegistry:function(e){e=e||{},cr.checkArgument(typeof e=="object","Config must be object");var t={id:e.id||this._generateRegistryId(),name:e.name||"Legal Token Registry",jurisdiction:e.jurisdiction||"GLOBAL",authority:e.authority||null,created:new Date().toISOString(),version:"1.0.0",config:{allowPublicRegistration:e.allowPublicRegistration||!1,requireApproval:e.requireApproval||!0,enableRevocation:e.enableRevocation!==!1,enableAuditTrail:e.enableAuditTrail!==!1,retentionPeriod:e.retentionPeriod||"7Y",complianceLevel:e.complianceLevel||"STANDARD"},dataStructure:{tokens:"Map<tokenId, registrationRecord>",revocations:"Map<tokenId, revocationRecord>",auditLog:"Array<auditEntry>",statistics:{totalTokens:0,activeTokens:0,revokedTokens:0,registrations:0}},externalStorage:{required:!0,type:"database_or_blockchain",endpoints:{store:"POST /registry/{id}/tokens",retrieve:"GET /registry/{id}/tokens/{tokenId}",search:"GET /registry/{id}/search",revoke:"POST /registry/{id}/revocations"}}},r=this._prepareAuditEntry({action:"REGISTRY_CREATED",actor:e.authority,timestamp:t.created,metadata:{jurisdiction:t.jurisdiction,config:t.config}});return{success:!0,registry:t,initialAudit:r,instructions:{step1:"Store registry configuration in external system",step2:"Initialize token storage with provided data structure",step3:"Set up audit logging with provided templates",step4:"Configure external endpoints for registry operations"}}},prepareTokenRegistration:function(e,t,r){r=r||{},cr.checkArgument(e&&typeof e=="object","Invalid token"),cr.checkArgument(t&&typeof t=="object","Invalid registry config");try{var n=this._validateTokenForRegistration(e,t);if(!n.valid)return{success:!1,error:"Token validation failed: "+n.error};var i={tokenId:e.id,tokenHash:this._hashToken(e),token:e,status:t.requireApproval?"PENDING":"ACTIVE",registeredBy:r.registeredBy||"UNKNOWN",registeredAt:new Date().toISOString(),approvedBy:null,approvedAt:null,metadata:r.metadata||{},compliance:{jurisdiction:e.jurisdiction||t.jurisdiction,level:this._calculateComplianceLevel(e),checks:n.checks||[]}},o=this._prepareAuditEntry({action:"TOKEN_REGISTERED",actor:r.registeredBy,tokenId:e.id,timestamp:i.registeredAt,metadata:{status:i.status,tokenType:e.type,compliance:i.compliance}});return{success:!0,registrationRecord:i,auditEntry:o,registrationId:this._generateRegistrationId(e.id),validation:n,externalOperations:{store:{endpoint:"POST /registry/"+t.id+"/tokens",data:i},audit:{endpoint:"POST /registry/"+t.id+"/audit",data:o}}}}catch(s){return{success:!1,error:s.message}}},prepareTokenApproval:function(e,t,r){try{cr.checkArgument(typeof e=="string","Token ID must be string"),cr.checkArgument(typeof t=="string","Approver must be string"),cr.checkArgument(r&&typeof r=="object","Invalid registry config");var n={tokenId:e,status:"ACTIVE",approvedBy:t,approvedAt:new Date().toISOString()},i=this._prepareAuditEntry({action:"TOKEN_APPROVED",actor:t,tokenId:e,timestamp:n.approvedAt});return{success:!0,approvalData:n,auditEntry:i,externalOperations:{update:{endpoint:"PUT /registry/"+r.id+"/tokens/"+e+"/status",data:n},audit:{endpoint:"POST /registry/"+r.id+"/audit",data:i}}}}catch(o){return{success:!1,error:o.message}}},prepareTokenRevocation:function(e,t,r){try{if(cr.checkArgument(typeof e=="string","Token ID must be string"),cr.checkArgument(t&&typeof t=="object","Invalid revocation"),cr.checkArgument(r&&typeof r=="object","Invalid registry config"),!r.enableRevocation)return{success:!1,error:"Revocation is disabled for this registry"};var n={tokenId:e,reason:t.reason||"UNSPECIFIED",revokedBy:t.revokedBy||"UNKNOWN",revokedAt:new Date().toISOString(),effectiveDate:t.effectiveDate||new Date().toISOString(),legalBasis:t.legalBasis||null,evidence:t.evidence||null,revocationHash:this._generateRevocationHash(e,t)},i={tokenId:e,status:"REVOKED",revokedAt:n.revokedAt,revocationReason:n.reason},o=this._prepareAuditEntry({action:"TOKEN_REVOKED",actor:t.revokedBy,tokenId:e,timestamp:n.revokedAt,metadata:{reason:n.reason,legalBasis:n.legalBasis}});return{success:!0,revocationRecord:n,statusUpdate:i,auditEntry:o,revocationId:this._generateRevocationId(e),externalOperations:{storeRevocation:{endpoint:"POST /registry/"+r.id+"/revocations",data:n},updateStatus:{endpoint:"PUT /registry/"+r.id+"/tokens/"+e+"/status",data:i},audit:{endpoint:"POST /registry/"+r.id+"/audit",data:o}}}}catch(s){return{success:!1,error:s.message}}},prepareTokenStatusQuery:function(e,t){try{return cr.checkArgument(typeof e=="string","Token ID must be string"),cr.checkArgument(t&&typeof t=="object","Invalid registry config"),{success:!0,query:{tokenId:e,registryId:t.id},externalOperations:{retrieve:{endpoint:"GET /registry/"+t.id+"/tokens/"+e,method:"GET"},checkRevocation:{endpoint:"GET /registry/"+t.id+"/revocations/"+e,method:"GET"}},expectedResponse:{found:"boolean",status:"string (PENDING|ACTIVE|REVOKED)",registeredAt:"ISO datetime",registeredBy:"string",approvedAt:"ISO datetime or null",approvedBy:"string or null",revokedAt:"ISO datetime or null",revocationReason:"string or null",compliance:"object",revocation:"object or null"}}}catch(r){return{success:!1,error:r.message}}},prepareTokenSearch:function(e,t){e=e||{};try{cr.checkArgument(t&&typeof t=="object","Invalid registry config");var r=[];e.status&&r.push("status="+encodeURIComponent(e.status)),e.type&&r.push("type="+encodeURIComponent(e.type)),e.registeredBy&&r.push("registeredBy="+encodeURIComponent(e.registeredBy)),e.jurisdiction&&r.push("jurisdiction="+encodeURIComponent(e.jurisdiction)),e.dateFrom&&r.push("dateFrom="+encodeURIComponent(e.dateFrom)),e.dateTo&&r.push("dateTo="+encodeURIComponent(e.dateTo)),e.includeTokens&&r.push("includeTokens=true"),e.sortBy&&r.push("sortBy="+encodeURIComponent(e.sortBy)),e.sortOrder&&r.push("sortOrder="+encodeURIComponent(e.sortOrder));var n=e.offset||0,i=e.limit||100;r.push("offset="+n),r.push("limit="+i);var o=r.length>0?"?"+r.join("&"):"";return{success:!0,searchCriteria:e,externalOperations:{search:{endpoint:"GET /registry/"+t.id+"/search"+o,method:"GET"}},expectedResponse:{success:"boolean",results:"Array<tokenRecord>",totalCount:"number",totalRegistrations:"number",offset:"number",limit:"number",hasMore:"boolean"}}}catch(s){return{success:!1,error:s.message}}},prepareStatisticsQuery:function(e){return cr.checkArgument(e&&typeof e=="object","Invalid registry config"),{success:!0,query:{registryId:e.id},externalOperations:{getStatistics:{endpoint:"GET /registry/"+e.id+"/statistics",method:"GET"}},expectedResponse:{id:"string",name:"string",jurisdiction:"string",created:"ISO datetime",statistics:{totalTokens:"number",activeTokens:"number",revokedTokens:"number",registrations:"number"},auditEntries:"number",lastActivity:"ISO datetime"}}},prepareAuditLogQuery:function(e,t){if(t=t||{},cr.checkArgument(e&&typeof e=="object","Invalid registry config"),!e.enableAuditTrail)return{success:!1,error:"Audit trail is disabled"};var r=[];t.action&&r.push("action="+encodeURIComponent(t.action)),t.actor&&r.push("actor="+encodeURIComponent(t.actor)),t.tokenId&&r.push("tokenId="+encodeURIComponent(t.tokenId)),t.dateFrom&&r.push("dateFrom="+encodeURIComponent(t.dateFrom)),t.dateTo&&r.push("dateTo="+encodeURIComponent(t.dateTo));var n=t.offset||0,i=t.limit||100;r.push("offset="+n),r.push("limit="+i);var o=r.length>0?"?"+r.join("&"):"";return{success:!0,auditOptions:t,externalOperations:{getAuditLog:{endpoint:"GET /registry/"+e.id+"/audit"+o,method:"GET"}},expectedResponse:{success:"boolean",entries:"Array<auditEntry>",totalEntries:"number",offset:"number",limit:"number",hasMore:"boolean"}}},_generateRegistryId:function(){return"reg_"+Ox.randomHex(16)},_generateRegistrationId:function(e){var t="reg_"+e+"_"+Date.now();return Wa.sha256(d.Buffer.from(t)).toString("hex").substring(0,16)},_generateRevocationId:function(e){var t="rev_"+e+"_"+Date.now();return Wa.sha256(d.Buffer.from(t)).toString("hex").substring(0,16)},_hashToken:function(e){var t=JSON.parse(JSON.stringify(e));return delete t.proof,delete t.tokenHash,Wa.sha256(d.Buffer.from(JSON.stringify(t))).toString("hex")},_generateRevocationHash:function(e,t){var r=e+(t.reason||"")+(t.revokedBy||"")+Date.now();return Wa.sha256(d.Buffer.from(r)).toString("hex")},_validateTokenForRegistration:function(e,t){var r=[],n=!0;return e.id?r.push({field:"id",valid:!0}):(r.push({field:"id",valid:!1,error:"Missing token ID"}),n=!1),e.type?r.push({field:"type",valid:!0}):(r.push({field:"type",valid:!1,error:"Missing token type"}),n=!1),e.issuanceDate?r.push({field:"issuanceDate",valid:!0}):(r.push({field:"issuanceDate",valid:!1,error:"Missing issuance date"}),n=!1),e.proof?r.push({field:"proof",valid:!0}):(r.push({field:"proof",valid:!1,error:"Missing cryptographic proof"}),n=!1),{valid:n,checks:r}},_calculateComplianceLevel:function(e){var t="BASIC";return e.proof&&e.proof.type&&(t="STANDARD"),e.jurisdiction&&e.legalBasis&&(t="ENHANCED"),e.attestations&&e.attestations.length>0&&(t="PREMIUM"),t},_prepareAuditEntry:function(e){var t={id:this._generateAuditId(),action:e.action,actor:e.actor||"SYSTEM",tokenId:e.tokenId||null,timestamp:e.timestamp||new Date().toISOString(),metadata:e.metadata||{},hash:this._generateAuditHash(e)};return t},_generateAuditId:function(){return"audit_"+Ox.randomHex(32)},_generateAuditHash:function(e){var t=(e.action||"")+(e.actor||"")+(e.tokenId||"")+(e.timestamp||"");return Wa.sha256(d.Buffer.from(t)).toString("hex").substring(0,16)}};Rx.exports=Lk});var Mx=P((D5,Nx)=>{"use strict";m();var Up=Tr(),Fp=Qt(),Px=ka(),Dk=ir(),Bx=io(),mr=ke(),Uk=Ka();function Fk(e,t){if(t=t||{},t.issuerPublicKey)return t.issuerPublicKey instanceof Up?t.issuerPublicKey:Up.fromString(t.issuerPublicKey);var r=e&&e.issuer;if(typeof r!="string")return null;try{var n=r.split("#")[0].split(":")[2];return n?Up.fromString(n):null}catch{return null}}var Uc={CORRELATIVE_OBLIGATION:"CorrelativeObligation",CONTRACTUAL_OBLIGATION:"ContractualObligation",PAYMENT_OBLIGATION:"PaymentObligation",DELIVERY_OBLIGATION:"DeliveryObligation",PERFORMANCE_OBLIGATION:"PerformanceObligation",MAINTENANCE_OBLIGATION:"MaintenanceObligation",COMPLIANCE_OBLIGATION:"ComplianceObligation",REPORTING_OBLIGATION:"ReportingObligation",CONFIDENTIALITY_OBLIGATION:"ConfidentialityObligation",NON_COMPETE_OBLIGATION:"NonCompeteObligation",INDEMNIFICATION_OBLIGATION:"IndemnificationObligation",WARRANTY_OBLIGATION:"WarrantyObligation",SUPPORT_OBLIGATION:"SupportObligation",REGULATORY_OBLIGATION:"RegulatoryObligation",FIDUCIARY_OBLIGATION:"FiduciaryObligation"},ps={CRITICAL:"CRITICAL",HIGH:"HIGH",MEDIUM:"MEDIUM",LOW:"LOW",DEFERRED:"DEFERRED"},lr={PENDING:"PENDING",ACTIVE:"ACTIVE",IN_PROGRESS:"IN_PROGRESS",COMPLETED:"COMPLETED",OVERDUE:"OVERDUE",BREACHED:"BREACHED",WAIVED:"WAIVED",TERMINATED:"TERMINATED"},Fc={prepareObligationToken:function(e,t,r,n,i,o){o=o||{},mr.checkArgument(typeof e=="string","Obligation type must be string"),mr.checkArgument(typeof t=="string","Issuer DID must be string"),mr.checkArgument(typeof r=="string","Obligor DID must be string"),mr.checkArgument(n&&typeof n=="object","Obligation must be object"),mr.checkArgument(i instanceof Bx,"Invalid issuer private key");var s=Object.values(Uc);mr.checkArgument(s.includes(e),"Invalid obligation type: "+e);try{var a={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","LegalObligationToken",e],issuer:t,issuanceDate:new Date().toISOString(),credentialSubject:{id:r,obligationType:e,obligation:n,jurisdiction:o.jurisdiction||"US",priority:o.priority||ps.MEDIUM,status:lr.PENDING,dueDate:o.dueDate||null,effectiveDate:o.effectiveDate||new Date().toISOString(),expirationDate:o.expirationDate||null,correlativeRight:o.correlativeRight||null,rightHolder:o.rightHolder||null,enforceable:o.enforceable!==!1,penalties:o.penalties||null,remedies:o.remedies||null}};o.metadata&&(a.credentialSubject.metadata=o.metadata);var c=this._signToken(a,i);return{success:!0,obligationToken:c,tokenHash:c.tokenHash,metadata:{type:e,issuer:t,obligor:r,priority:a.credentialSubject.priority,status:a.credentialSubject.status,jurisdiction:a.credentialSubject.jurisdiction,dueDate:a.credentialSubject.dueDate,correlativeRight:a.credentialSubject.correlativeRight},externalOperations:{storeToken:{endpoint:"POST /obligations/tokens",data:{token:c,metadata:{type:e,issuer:t,obligor:r,priority:a.credentialSubject.priority,status:a.credentialSubject.status,jurisdiction:a.credentialSubject.jurisdiction,dueDate:a.credentialSubject.dueDate,correlativeRight:a.credentialSubject.correlativeRight}}},indexToken:{endpoint:"POST /obligations/index",data:{tokenId:c.id,tokenHash:c.tokenHash,type:e,issuer:t,obligor:r,issuedAt:c.issuanceDate,dueDate:a.credentialSubject.dueDate,priority:a.credentialSubject.priority}},notifyObligor:{endpoint:"POST /notifications/obligation-issued",data:{tokenId:c.id,issuer:t,obligor:r,obligationType:e,dueDate:a.credentialSubject.dueDate,priority:a.credentialSubject.priority}},scheduleReminders:a.credentialSubject.dueDate?{endpoint:"POST /obligations/schedule-reminders",data:{tokenId:c.id,obligor:r,dueDate:a.credentialSubject.dueDate,reminderSchedule:o.reminderSchedule||["7d","3d","1d"]}}:null}}}catch(h){return{success:!1,error:h.message}}},prepareObligationVerification:function(e,t){t=t||{};try{var r=[],n=[];this._validateTokenStructure(e,r),this._verifyTokenSignature(e,r,t),this._validateTokenTemporal(e,r,n),this._validateObligationType(e,r),this._validateObligationStatus(e,r,n),this._validateObligationPriority(e,n);var i={valid:r.length===0,errors:r,warnings:n,issuerDID:e.issuer,obligorDID:e.credentialSubject?e.credentialSubject.id:null,obligationType:e.credentialSubject?e.credentialSubject.obligationType:null,status:e.credentialSubject?e.credentialSubject.status:null,priority:e.credentialSubject?e.credentialSubject.priority:null,isOverdue:this._checkIfOverdue(e),verifiedAt:new Date().toISOString()};return{success:!0,verification:i,externalOperations:{recordVerification:{endpoint:"POST /obligations/verification-record",data:{tokenId:e.id,result:i.valid,errors:r,warnings:n,verifiedAt:i.verifiedAt,isOverdue:i.isOverdue}},auditVerification:{endpoint:"POST /audit/obligation-verification",data:{tokenId:e.id,obligationType:i.obligationType,issuer:i.issuerDID,obligor:i.obligorDID,result:i.valid,verifiedAt:i.verifiedAt}},updateStatus:i.isOverdue&&e.credentialSubject.status===lr.ACTIVE?{endpoint:"PUT /obligations/tokens/"+e.id+"/status",data:{status:lr.OVERDUE,updatedAt:i.verifiedAt,reason:"Due date passed"}}:null}}}catch(o){return{success:!1,error:"Verification preparation failed: "+o.message}}},prepareObligationFulfillment:function(e,t,r,n){n=n||{},mr.checkArgument(e&&typeof e=="object","Invalid token"),mr.checkArgument(t&&typeof t=="object","Invalid fulfillment"),mr.checkArgument(r instanceof Bx,"Invalid obligor key");try{var i=this.prepareObligationVerification(e,{});if(!i.success||!i.verification.valid)return{success:!1,error:"Cannot fulfill invalid obligation: "+i.verification.errors.join(", ")};if(e.credentialSubject.status===lr.COMPLETED)return{success:!1,error:"Obligation already fulfilled"};if(e.credentialSubject.status===lr.TERMINATED)return{success:!1,error:"Obligation has been terminated"};var o={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","ObligationFulfillment"],issuer:e.credentialSubject.id,issuanceDate:new Date().toISOString(),credentialSubject:{id:e.id,fulfillmentType:t.type||"FULL_FULFILLMENT",fulfillmentDate:new Date().toISOString(),evidence:t.evidence||null,description:t.description||"",completionPercentage:t.completionPercentage||100,attestations:t.attestations||[],notes:t.notes||null}},s=this._signToken(o,r),a=o.credentialSubject.completionPercentage>=100?lr.COMPLETED:lr.IN_PROGRESS;return{success:!0,fulfillmentRecord:s,newStatus:a,fulfillmentId:s.id,externalOperations:{recordFulfillment:{endpoint:"POST /obligations/fulfillments",data:{obligationId:e.id,fulfillmentRecord:s,obligor:e.credentialSubject.id,fulfillmentDate:o.credentialSubject.fulfillmentDate,completionPercentage:o.credentialSubject.completionPercentage}},updateStatus:{endpoint:"PUT /obligations/tokens/"+e.id+"/status",data:{status:a,fulfillmentId:s.id,updatedAt:o.credentialSubject.fulfillmentDate,completionPercentage:o.credentialSubject.completionPercentage}},notifyRightHolder:e.credentialSubject.rightHolder?{endpoint:"POST /notifications/obligation-fulfilled",data:{obligationId:e.id,fulfillmentId:s.id,obligor:e.credentialSubject.id,rightHolder:e.credentialSubject.rightHolder,completionPercentage:o.credentialSubject.completionPercentage,newStatus:a}}:null,auditFulfillment:{endpoint:"POST /audit/obligation-fulfillment",data:{obligationId:e.id,fulfillmentId:s.id,obligor:e.credentialSubject.id,fulfilledAt:o.credentialSubject.fulfillmentDate,completionPercentage:o.credentialSubject.completionPercentage}}}}}catch(c){return{success:!1,error:c.message}}},prepareObligationBreachAssessment:function(e,t,r){mr.checkArgument(e&&typeof e=="object","Invalid token"),mr.checkArgument(t&&typeof t=="object","Invalid breach details"),mr.checkArgument(r&&typeof r=="object","Invalid assessor");try{var n={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","ObligationBreachAssessment"],issuer:r.did||r.id,issuanceDate:new Date().toISOString(),credentialSubject:{id:e.id,breachType:t.type||"MATERIAL_BREACH",breachDate:t.date||new Date().toISOString(),description:t.description||"",severity:t.severity||"MODERATE",evidence:t.evidence||[],assessor:{did:r.did||r.id,name:r.name||"Unknown",authority:r.authority||null,jurisdiction:r.jurisdiction||null},damages:t.damages||null,recommendedRemedies:t.recommendedRemedies||[],assessmentDate:new Date().toISOString()}},i=Fp.sha256(d.Buffer.from(JSON.stringify(n))).toString("hex");return n.credentialSubject.assessmentHash=i,{success:!0,breachAssessment:n,breachId:n.id,severity:t.severity||"MODERATE",externalOperations:{recordBreach:{endpoint:"POST /obligations/breaches",data:{obligationId:e.id,breachAssessment:n,obligor:e.credentialSubject.id,rightHolder:e.credentialSubject.rightHolder,breachDate:t.date||new Date().toISOString(),severity:t.severity||"MODERATE"}},updateStatus:{endpoint:"PUT /obligations/tokens/"+e.id+"/status",data:{status:lr.BREACHED,breachId:n.id,breachDate:t.date||new Date().toISOString(),updatedAt:new Date().toISOString()}},notifyParties:{endpoint:"POST /notifications/obligation-breached",data:{obligationId:e.id,breachId:n.id,obligor:e.credentialSubject.id,rightHolder:e.credentialSubject.rightHolder,breachType:t.type||"MATERIAL_BREACH",severity:t.severity||"MODERATE"}},escalateBreach:t.severity==="CRITICAL"?{endpoint:"POST /legal/escalate-breach",data:{obligationId:e.id,breachId:n.id,severity:t.severity,jurisdiction:e.credentialSubject.jurisdiction}}:null,auditBreach:{endpoint:"POST /audit/obligation-breach",data:{obligationId:e.id,breachId:n.id,obligor:e.credentialSubject.id,assessedAt:n.credentialSubject.assessmentDate,severity:t.severity||"MODERATE"}}}}}catch(o){return{success:!1,error:o.message}}},prepareObligationMonitoringReport:function(e,t){t=t||{},mr.checkArgument(Array.isArray(e),"Obligations must be array");try{var r={reportId:"rpt_"+this._generateUUID(),generatedAt:new Date().toISOString(),criteria:t,summary:{totalObligations:e.length,byStatus:{},byPriority:{},byType:{},overdue:0,dueSoon:0,completed:0},obligations:[],alerts:[],recommendations:[]},n=new Date,i=new Date(n.getTime()+10080*60*1e3);return e.forEach(function(o){var s={id:o.id,type:o.credentialSubject.obligationType,status:o.credentialSubject.status,priority:o.credentialSubject.priority,obligor:o.credentialSubject.id,dueDate:o.credentialSubject.dueDate,isOverdue:this._checkIfOverdue(o),isDueSoon:!1};if(o.credentialSubject.dueDate){var a=new Date(o.credentialSubject.dueDate);s.isDueSoon=a<=i&&a>n}r.summary.byStatus[s.status]=(r.summary.byStatus[s.status]||0)+1,r.summary.byPriority[s.priority]=(r.summary.byPriority[s.priority]||0)+1,r.summary.byType[s.type]=(r.summary.byType[s.type]||0)+1,s.isOverdue&&r.summary.overdue++,s.isDueSoon&&r.summary.dueSoon++,s.status===lr.COMPLETED&&r.summary.completed++,s.isOverdue&&s.priority===ps.CRITICAL&&r.alerts.push({type:"CRITICAL_OVERDUE",obligationId:o.id,message:"Critical obligation is overdue",priority:"HIGH"}),s.isDueSoon&&s.priority===ps.HIGH&&r.alerts.push({type:"HIGH_PRIORITY_DUE_SOON",obligationId:o.id,message:"High priority obligation due soon",priority:"MEDIUM"}),r.obligations.push(s)}.bind(this)),r.summary.overdue>0&&r.recommendations.push({type:"OVERDUE_MANAGEMENT",message:"Consider prioritizing overdue obligations",count:r.summary.overdue}),r.summary.dueSoon>5&&r.recommendations.push({type:"WORKLOAD_MANAGEMENT",message:"High number of obligations due soon - consider workload distribution",count:r.summary.dueSoon}),{success:!0,report:r,externalOperations:{storeReport:{endpoint:"POST /obligations/monitoring-reports",data:{report:r,generatedAt:r.generatedAt}},sendAlerts:r.alerts.length>0?{endpoint:"POST /notifications/obligation-alerts",data:{reportId:r.reportId,alerts:r.alerts,summary:r.summary}}:null,updateDashboard:{endpoint:"PUT /dashboard/obligation-metrics",data:{summary:r.summary,lastUpdated:r.generatedAt}}}}}catch(o){return{success:!1,error:o.message}}},getObligationTypes:function(){return Uc},getObligationPriority:function(){return ps},getObligationStatus:function(){return lr},_signToken:function(e,t){var r=this._canonicalizeToken(e),n=Fp.sha256(d.Buffer.from(r)),i=new Px;i.hashbuf=n,i.privkey=t,i.pubkey=t.toPublicKey(),i.sign();var o=i.sig,s={type:"EcdsaSecp256k1Signature2019",created:new Date().toISOString(),verificationMethod:"did:smartledger:"+t.toPublicKey().toString()+"#keys-1",proofPurpose:"assertionMethod",jws:this._createJWS(n,o)},a=JSON.parse(JSON.stringify(e));return a.proof=s,a.tokenHash=n.toString("hex"),a},_createJWS:function(e,t){var r={alg:"ES256K",typ:"JWT"},n=d.Buffer.from(JSON.stringify(r)).toString("base64url"),i=e.toString("base64url"),o=t.toDER().toString("base64url");return n+".."+o},_canonicalizeToken:function(e){var t=JSON.parse(JSON.stringify(e));return delete t.proof,delete t.tokenHash,JSON.stringify(this._sortObjectKeys(t))},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e},_validateTokenStructure:function(e,t){e["@context"]||t.push("Missing @context"),e.id||t.push("Missing id"),(!e.type||!Array.isArray(e.type))&&t.push("Missing or invalid type"),e.issuer||t.push("Missing issuer"),e.issuanceDate||t.push("Missing issuanceDate"),e.credentialSubject||t.push("Missing credentialSubject"),e.proof||t.push("Missing proof")},_verifyTokenSignature:function(e,t,r){try{if(!e.proof||!e.proof.jws){t.push("Missing signature proof");return}var n=this._canonicalizeToken(e),i=Fp.sha256(d.Buffer.from(n));if(e.tokenHash&&e.tokenHash!==i.toString("hex")){t.push("Token hash mismatch");return}var o=Fk(e,r);if(!o){t.push("Signature not verified: issuer public key could not be resolved from token.issuer; pass options.issuerPublicKey");return}var s=e.proof.jws.split(".");if(s.length!==3||!s[2]){t.push("Malformed JWS");return}var a=Dk.fromDER(d.Buffer.from(s[2],"base64url")),c=new Px;c.hashbuf=i,c.sig=a,c.pubkey=o,c.verify()!==!0&&t.push("Signature verification failed")}catch(h){t.push("Signature verification failed: "+h.message)}},_validateTokenTemporal:function(e,t,r){var n=new Date,i=new Date(e.issuanceDate);if(i>n&&t.push("Token issued in the future"),e.credentialSubject.effectiveDate){var o=new Date(e.credentialSubject.effectiveDate);n<o&&r.push("Obligation not yet effective")}if(e.credentialSubject.expirationDate){var s=new Date(e.credentialSubject.expirationDate);n>s&&t.push("Obligation expired")}},_validateObligationType:function(e,t){if(!e.credentialSubject.obligationType){t.push("Missing obligationType");return}var r=Object.values(Uc);r.includes(e.credentialSubject.obligationType)||t.push("Invalid obligation type: "+e.credentialSubject.obligationType)},_validateObligationStatus:function(e,t,r){if(!e.credentialSubject.status){t.push("Missing status");return}var n=Object.values(lr);n.includes(e.credentialSubject.status)||t.push("Invalid obligation status: "+e.credentialSubject.status),this._checkIfOverdue(e)&&e.credentialSubject.status===lr.ACTIVE&&r.push("Obligation is overdue but status is still ACTIVE")},_validateObligationPriority:function(e,t){if(e.credentialSubject.priority){var r=Object.values(ps);r.includes(e.credentialSubject.priority)||t.push("Invalid obligation priority: "+e.credentialSubject.priority)}},_checkIfOverdue:function(e){if(!e.credentialSubject.dueDate)return!1;var t=new Date,r=new Date(e.credentialSubject.dueDate);return t>r&&e.credentialSubject.status!==lr.COMPLETED},_generateUUID:function(){return Uk.uuid4()}};Fc.ObligationTypes=Uc;Fc.ObligationPriority=ps;Fc.ObligationStatus=lr;Nx.exports=Fc});var Cx=P((F5,kx)=>{"use strict";m();var uo=bx(),qc=Sx(),Ya=Ex(),qp=Ax(),dn=Tx(),qk=Mx(),Hp=io(),vr=ke(),Re=function(e){return this instanceof Re?(this.config=e||{},this.registry=null,this.config.registry&&(this.registry=dn.createRegistry(this.config.registry)),this):new Re(e)};Re.prototype.createRightToken=function(e,t,r){vr.checkArgument(e&&typeof e=="object","Invalid right data"),vr.checkArgument(t instanceof Hp,"Invalid private key"),r=r||{};try{var n=uo.create(e.type,e.owner,e.owner,e,t,r);if(!n)return{success:!1,error:"Failed to create token"};if(r.addProof!==!1&&(n=uo._signToken(n,t)),r.anchor){var i=Ya.anchorToken(n,r.anchor);i.success&&(n.anchorTx=i.txid,n.anchorBlock=i.blockHeight)}if(this.registry&&r.register!==!1){var o=dn.registerToken(this.registry,n,{registeredBy:r.registeredBy||"SYSTEM"});o.success&&(n.registrationId=o.registrationId,n.registrationStatus=o.status)}return{success:!0,token:n,type:"LegalRightToken"}}catch(s){return{success:!1,error:s.message}}};Re.prototype.validateClaim=function(e,t){return qc.validate(e,t)};Re.prototype.createSelectiveDisclosure=function(e,t,r){return qp.prepareSelectiveDisclosure(e,t,r)};Re.prototype.verifyToken=function(e,t){return!e||!e.proof?{valid:!1,error:"No proof found in token"}:uo.verifyToken(e,t)};Re.prototype.transferRight=function(e,t,r,n){vr.checkArgument(e&&typeof e=="object","Invalid token"),vr.checkArgument(typeof t=="string","New owner must be string"),vr.checkArgument(r instanceof Hp,"Invalid owner key"),n=n||{};try{var i=this.verifyToken(e,r.toPublicKey().toString());if(!i.valid)return{success:!1,error:"Invalid token or ownership proof"};var o=uo.prepareRightTokenTransfer(e,t,r,n);if(!o.success)return{success:!1,error:o.error};var s=o.newToken,a=o.transferProof;if(n.anchor){var c=Ya.anchorToken(s,n.anchor);c.success&&(s.transferAnchorTx=c.txid)}if(this.registry){var h=dn.registerToken(this.registry,s,{registeredBy:n.registeredBy||t,metadata:{transferFrom:e.owner,transferTo:t,originalTokenId:e.id}});h.success&&(s.registrationId=h.registrationId)}return{success:!0,token:s,transferId:a.id,transferredAt:a.issuanceDate,transferProof:a}}catch(g){return{success:!1,error:g.message}}};Re.prototype.createObligation=function(e,t,r){vr.checkArgument(e&&typeof e=="object","Invalid right token"),vr.checkArgument(t&&typeof t=="object","Invalid obligation data"),vr.checkArgument(r instanceof Hp,"Invalid private key");try{var n=uo.prepareObligationToken(e,t.obligor,t,r);return n.success?{success:!0,obligation:n.obligationToken,rightTokenId:e.id}:{success:!1,error:n.error}}catch(i){return{success:!1,error:i.message}}};Re.prototype.revokeToken=function(e,t,r){return vr.checkArgument(typeof e=="string","Token ID must be string"),vr.checkArgument(t&&typeof t=="object","Invalid revocation data"),vr.checkArgument(typeof r=="string","Authority must be string"),this.registry?dn.revokeToken(this.registry,e,{reason:t.reason,revokedBy:r,legalBasis:t.legalBasis,evidence:t.evidence}):{success:!1,error:"No registry available for revocation"}};Re.prototype.checkTokenStatus=function(e){return vr.checkArgument(typeof e=="string","Token ID must be string"),this.registry?dn.checkTokenStatus(this.registry,e):{found:!1,error:"No registry available"}};Re.prototype.searchTokens=function(e){return this.registry?dn.searchTokens(this.registry,e):{success:!1,error:"No registry available"}};Re.prototype.getRegistryStats=function(){return this.registry?dn.getStatistics(this.registry):{error:"No registry available"}};Re.prototype.createLegalValidityProof=function(e,t,r){return qp.prepareLegalValidityProof(e,t,r)};Re.prototype.anchorTokenBatch=function(e,t){return Ya.anchorBatch(e,t)};Re.prototype.verifyAnchor=function(e,t){return Ya.verifyAnchor(e,t)};Re.prototype.getRightTypes=function(){return uo.getRightTypes()};Re.prototype.getClaimSchemas=function(){return qc.getSchemas()};Re.prototype.createRegistry=function(e){return this.registry=dn.createRegistry(e),this.registry};Re.prototype.setRegistry=function(e){vr.checkArgument(e&&typeof e=="object","Invalid registry"),this.registry=e};Re.create=function(e){return new Re(e)};Re.createRightToken=function(e,t,r){var n=new Re;return n.createRightToken(e,t,r)};Re.validateClaim=function(e,t){return qc.validate(e,t)};Re.verifyToken=function(e,t){var r=new Re;return r.verifyToken(e,t)};Re.createRegistry=function(e){return dn.createRegistry(e)};Re.Right=uo;Re.Claim=qc;Re.Anchor=Ya;Re.Proof=qp;Re.Registry=dn;Re.Obligation=qk;kx.exports=Re});var Hk=P((H5,Lx)=>{m();Lx.exports=Cx()});return Hk();})();
|
|
70
70
|
if(typeof module!=="undefined"&&module.exports){module.exports=bsvLTP}else if(typeof define==="function"&&define.amd){define([],function(){return bsvLTP})}
|