@smartledger/bsv 9.5.0 → 9.6.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/bsv-ltp.min.js CHANGED
@@ -71,5 +71,5 @@ The flags passed to verify() (0x`+(e>>>0).toString(16)+`) carry no era bit, so t
71
71
  To validate against BSV as it is today, omit the flags argument or pass Interpreter.mainnetFlags(). If you are deliberately testing pre-Genesis consensus this failure is correct \u2014 set Interpreter.eraDiagnostics = false (or BSV_NO_ERA_HINT=1) to silence this.`,P.eraDiagnostics&&!Mp&&(Mp=!0,console.warn(`
72
72
  [@smartledger/bsv] `+this.eraHint+`
73
73
  (shown once per process)
74
- `))}}};P.prototype.verify=function(e,t,r,n,i,o){this.eraHint=null;var s=this._verifyCore(e,t,r,n,i,o);return s||this._eraDiagnose(i),s};P._resetEraWarning=function(){Mp=!1};P.mainnetFlags=function(e){e=e||{};var t=P.SCRIPT_VERIFY_P2SH|P.SCRIPT_VERIFY_STRICTENC|P.SCRIPT_VERIFY_DERSIG|P.SCRIPT_VERIFY_SIGPUSHONLY|P.SCRIPT_VERIFY_LOW_S|P.SCRIPT_VERIFY_NULLFAIL|P.SCRIPT_VERIFY_MINIMALDATA|P.SCRIPT_ENABLE_SIGHASH_FORKID|P.SCRIPT_ENABLE_MAGNETIC_OPCODES|P.SCRIPT_ENABLE_MONOLITH_OPCODES|P.SCRIPT_GENESIS|P.SCRIPT_UTXO_AFTER_GENESIS;return e.afterChronicle!==!1&&(t|=P.SCRIPT_ENABLE_CHRONICLE|P.SCRIPT_UTXO_AFTER_CHRONICLE),t};P.currentConsensusFlags=function(){return P.SCRIPT_ENABLE_MONOLITH_OPCODES|P.SCRIPT_ENABLE_MAGNETIC_OPCODES|P.SCRIPT_GENESIS|P.SCRIPT_UTXO_AFTER_GENESIS|P.SCRIPT_ENABLE_CHRONICLE|P.SCRIPT_UTXO_AFTER_CHRONICLE|P.SCRIPT_ENABLE_SIGHASH_FORKID|P.SCRIPT_VERIFY_SIGPUSHONLY|P.SCRIPT_VERIFY_LOW_S|P.SCRIPT_VERIFY_NULLFAIL};P.useMainnetConsensus=function(e){return e=e||{},P.useGenesisLimits(e.max),P.mainnetFlags(e)};P.SEQUENCE_LOCKTIME_DISABLE_FLAG=1<<31;P.SEQUENCE_LOCKTIME_TYPE_FLAG=1<<22;P.SEQUENCE_LOCKTIME_MASK=65535;P.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};P.prototype.checkSignatureEncoding=function(e){var t;if(e.length===0)return!0;if((this.flags&(P.SCRIPT_VERIFY_DERSIG|P.SCRIPT_VERIFY_LOW_S|P.SCRIPT_VERIFY_STRICTENC))!==0&&!_i.isTxDER(e))return this.errstr="SCRIPT_ERR_SIG_DER_INVALID_FORMAT",!1;if((this.flags&P.SCRIPT_VERIFY_LOW_S)!==0){if(t=_i.fromTxFormat(e),!t.hasLowS())return this.errstr="SCRIPT_ERR_SIG_DER_HIGH_S",!1}else if((this.flags&P.SCRIPT_VERIFY_STRICTENC)!==0){if(t=_i.fromTxFormat(e),!t.hasDefinedHashtype())return this.errstr="SCRIPT_ERR_SIG_HASHTYPE",!1;if(!(this.flags&P.SCRIPT_ENABLE_SIGHASH_FORKID)&&t.nhashtype&_i.SIGHASH_FORKID)return this.errstr="SCRIPT_ERR_ILLEGAL_FORKID",!1;if(!(this.flags&P.SCRIPT_CHRONICLE)&&t.nhashtype&_i.SIGHASH_CHRONICLE)return this.errstr="SCRIPT_ERR_ILLEGAL_CHRONICLE",!1;if(this.flags&P.SCRIPT_ENABLE_SIGHASH_FORKID&&!(t.nhashtype&_i.SIGHASH_FORKID))return this.errstr="SCRIPT_ERR_MUST_USE_FORKID",!1}return!0};P.prototype.checkPubkeyEncoding=function(e){return(this.flags&P.SCRIPT_VERIFY_STRICTENC)!==0&&!Np.isValid(e)?(this.errstr="SCRIPT_ERR_PUBKEYTYPE",!1):!0};P.prototype.isAfterGenesis=function(){return(this.flags&P.SCRIPT_UTXO_AFTER_GENESIS)!==0};P.prototype.isAfterChronicle=function(){return(this.flags&(P.SCRIPT_UTXO_AFTER_CHRONICLE|P.SCRIPT_ENABLE_CHRONICLE))!==0};P.prototype.maxScriptElementSize=function(){return this.isAfterGenesis()?P.UNLIMITED:P.MAX_SCRIPT_ELEMENT_SIZE};P.prototype.maxScriptSize=function(){return this.isAfterGenesis()?P.UNLIMITED:P.MAX_SCRIPT_SIZE};P.prototype.maxOpsPerScript=function(){return this.isAfterGenesis()?P.UNLIMITED:P.MAX_OPS_PER_SCRIPT};P.prototype.maxScriptNumLength=function(){return this.isAfterChronicle()?P.MAX_SCRIPT_NUM_LENGTH_AFTER_CHRONICLE:this.isAfterGenesis()?P.MAX_SCRIPT_NUM_LENGTH_AFTER_GENESIS:P.MAXIMUM_ELEMENT_SIZE};P.prototype.maxPubKeysPerMultisig=function(){return this.isAfterGenesis()?P.MAX_PUBKEYS_PER_MULTISIG_AFTER_GENESIS:20};P._isMinimallyEncoded=function(e,t){return t=t||P.MAXIMUM_ELEMENT_SIZE,!(e.length>t||e.length>0&&(e[e.length-1]&127)===0&&(e.length<=1||(e[e.length-2]&128)===0))};P._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("")};P.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:M.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};P.prototype._callbackStep=function(e){if(typeof this.stepListener=="function")try{this.stepListener(e,Sx(this.stack),Sx(this.altstack))}catch(t){console.log(`Error in Step callback:${t}`)}};P.prototype.checkLockTime=function(e){if(!(this.tx.nLockTime<P.LOCKTIME_THRESHOLD&&e.lt(P.LOCKTIME_THRESHOLD_BN)||this.tx.nLockTime>=P.LOCKTIME_THRESHOLD&&e.gte(P.LOCKTIME_THRESHOLD_BN))||e.gt(new he(this.tx.nLockTime)))return!1;var t=this.tx.inputs[this.nin];return!(!t||t.isFinal())};P.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&P.SEQUENCE_LOCKTIME_DISABLE_FLAG)return!1;var n=P.SEQUENCE_LOCKTIME_TYPE_FLAG|P.SEQUENCE_LOCKTIME_MASK,i=new he(r&n),o=e.and(new he(n)),s=new he(P.SEQUENCE_LOCKTIME_TYPE_FLAG);return!(!(i.lt(s)&&o.lt(s)||i.gte(s)&&o.gte(s))||o.gt(i))};function aC(e,t){let r=e;for(;r.length<t;)r=d.Buffer.concat([d.Buffer.from([0]),r]);return r}function Ex(e){var t=d.Buffer.alloc(4);return t.writeInt32LE(e|0,0),t}P.prototype.step=function(){var e=this;function t(fe){return e.stack[e.stack.length+fe]}function r(fe){switch(fe){case M.OP_2MUL:case M.OP_2DIV:if(!e.isAfterChronicle())return!0;break;case M.OP_INVERT:case M.OP_MUL:case M.OP_LSHIFT:case M.OP_RSHIFT:if((e.flags&P.SCRIPT_ENABLE_MAGNETIC_OPCODES)===0)return!0;break;case M.OP_DIV:case M.OP_MOD:case M.OP_SPLIT:case M.OP_CAT:case M.OP_AND:case M.OP_OR:case M.OP_XOR:case M.OP_BIN2NUM:case M.OP_NUM2BIN:return!1;default:break}return!1}var n=(this.flags&P.SCRIPT_VERIFY_MINIMALDATA)!==0,i,o,s,a,f,l,m,g,v,E,T,N,L,F,V,z,W,ie=this.script.chunks[this.pc];this.pc++;var ee=ie.opcodenum,ge=this.vfExec.indexOf(!1)===-1&&(!this.nonTopLevelReturnAfterGenesis||ee===M.OP_RETURN);if(Lc.isUndefined(ee))return this.errstr="SCRIPT_ERR_UNDEFINED_OPCODE",!1;if(ie.buf&&ie.buf.length>this.maxScriptElementSize())return this.errstr="SCRIPT_ERR_PUSH_SIZE",!1;if(ee>M.OP_16&&++this.nOpCount>this.maxOpsPerScript())return this.errstr="SCRIPT_ERR_OP_COUNT",!1;if(r(ee)&&(!this.isAfterGenesis()||ge))return this.errstr="SCRIPT_ERR_DISABLED_OPCODE",!1;if(ge&&ee>=0&&ee<=M.OP_PUSHDATA4){if(n&&!this.script.checkMinimalPush(this.pc-1))return this.errstr="SCRIPT_ERR_MINIMALDATA",!1;if(!ie.buf)this.stack.push(P.false);else{if(ie.len!==ie.buf.length)return this.errstr="SCRIPT_ERR_BAD_OPCODE",!1;this.stack.push(ie.buf)}}else if(ge||M.OP_IF<=ee&&ee<=M.OP_ENDIF)switch(ee){case M.OP_1NEGATE:case M.OP_1:case M.OP_2:case M.OP_3:case M.OP_4:case M.OP_5:case M.OP_6:case M.OP_7:case M.OP_8:case M.OP_9:case M.OP_10:case M.OP_11:case M.OP_12:case M.OP_13:case M.OP_14:case M.OP_15:case M.OP_16:f=ee-(M.OP_1-1),i=new he(f).toScriptNumBuffer(),this.stack.push(i);break;case M.OP_NOP:break;case M.OP_NOP2:case M.OP_CHECKLOCKTIMEVERIFY:if(!(this.flags&P.SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)||this.isAfterGenesis()){if(this.flags&P.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 ce=he.fromScriptNumBuffer(this.stack[this.stack.length-1],n,5);if(ce.lt(new he(0)))return this.errstr="SCRIPT_ERR_NEGATIVE_LOCKTIME",!1;if(!this.checkLockTime(ce))return this.errstr="SCRIPT_ERR_UNSATISFIED_LOCKTIME",!1;break;case M.OP_NOP3:case M.OP_CHECKSEQUENCEVERIFY:if(!(this.flags&P.SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)||this.isAfterGenesis()){if(this.flags&P.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 me=he.fromScriptNumBuffer(t(-1),n,5);if(me.lt(new he(0)))return this.errstr="SCRIPT_ERR_NEGATIVE_LOCKTIME",!1;if((me&P.SEQUENCE_LOCKTIME_DISABLE_FLAG)!==0)break;if(!this.checkSequence(me))return this.errstr="SCRIPT_ERR_UNSATISFIED_LOCKTIME",!1;break;case M.OP_NOP1:case M.OP_NOP9:case M.OP_NOP10:if(this.flags&P.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)return this.errstr="SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS",!1;break;case M.OP_LSHIFTNUM:case M.OP_RSHIFTNUM:if(!this.isAfterChronicle()){if(this.flags&P.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 I=this.maxScriptNumLength(),u=he.fromScriptNumBuffer(t(-1),n,I);if(u.isNeg())return this.errstr="SCRIPT_ERR_INVALID_NUMBER_RANGE",!1;this.stack.pop();var h=he.fromScriptNumBuffer(t(-1),n,I);this.stack.pop();var y=u.toNumber(),w=h.isNeg(),S=h.abs(),R;if(ee===M.OP_LSHIFTNUM){var A=h.toScriptNumBuffer().length;if(A+Math.floor(y/8)>I)return this.errstr="SCRIPT_ERR_SCRIPTNUM_OVERFLOW",!1;R=S.shln(y)}else R=y>=S.bitLength()?new he(0):S.shrn(y);if(w&&!R.isZero()&&(R=R.neg()),R.toScriptNumBuffer().length>I)return this.errstr="SCRIPT_ERR_SCRIPTNUM_OVERFLOW",!1;this.stack.push(R.toScriptNumBuffer());break;case M.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(Ex(this.tx.version));break;case M.OP_VERIF:case M.OP_VERNOTIF:if(!this.isAfterChronicle()){if(this.isAfterGenesis()&&!ge)break;return this.errstr="SCRIPT_ERR_BAD_OPCODE",!1}if(z=!1,ge){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),z=i.length===4&&i.equals(Ex(this.tx.version)),ee===M.OP_VERNOTIF&&(z=!z),this.stack.pop()}this.vfExec.push(z),this.vfElse.push(!1);break;case M.OP_IF:case M.OP_NOTIF:if(z=!1,ge){if(this.stack.length<1)return this.errstr="SCRIPT_ERR_UNBALANCED_CONDITIONAL",!1;if(i=t(-1),this.flags&P.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}z=P.castToBool(i),ee===M.OP_NOTIF&&(z=!z),this.stack.pop()}this.vfExec.push(z),this.vfElse.push(!1);break;case M.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 M.OP_ENDIF:if(this.vfExec.length===0)return this.errstr="SCRIPT_ERR_UNBALANCED_CONDITIONAL",!1;this.vfExec.pop(),this.vfElse.pop();break;case M.OP_VERIFY:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(i=t(-1),z=P.castToBool(i),z)this.stack.pop();else return this.errstr="SCRIPT_ERR_VERIFY",!1;break;case M.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 M.OP_TOALTSTACK:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.altstack.push(this.stack.pop());break;case M.OP_FROMALTSTACK:if(this.altstack.length<1)return this.errstr="SCRIPT_ERR_INVALID_ALTSTACK_OPERATION",!1;this.stack.push(this.altstack.pop());break;case M.OP_2DROP:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.stack.pop(),this.stack.pop();break;case M.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 M.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 M.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 M.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 M.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 M.OP_IFDUP:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;i=t(-1),z=P.castToBool(i),z&&this.stack.push(d.Buffer.from(i));break;case M.OP_DEPTH:i=new he(this.stack.length).toScriptNumBuffer(),this.stack.push(i);break;case M.OP_DROP:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.stack.pop();break;case M.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 M.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 M.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 M.OP_PICK:case M.OP_ROLL:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(i=t(-1),g=he.fromScriptNumBuffer(i,n,this.maxScriptNumLength()),f=g.toNumber(),this.stack.pop(),f<0||f>=this.stack.length)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;i=t(-f-1),ee===M.OP_ROLL&&this.stack.splice(this.stack.length-f-1,1),this.stack.push(d.Buffer.from(i));break;case M.OP_ROT:if(this.stack.length<3)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;l=t(-3),m=t(-2);var c=t(-1);this.stack[this.stack.length-3]=m,this.stack[this.stack.length-2]=c,this.stack[this.stack.length-1]=l;break;case M.OP_SWAP:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;l=t(-2),m=t(-1),this.stack[this.stack.length-2]=m,this.stack[this.stack.length-1]=l;break;case M.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 M.OP_SIZE:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;g=new he(t(-1).length),this.stack.push(g.toScriptNumBuffer());break;case M.OP_AND:case M.OP_OR:case M.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(ee){case M.OP_AND:for(let fe=0;fe<o.length;fe++)o[fe]&=s[fe];break;case M.OP_OR:for(let fe=0;fe<o.length;fe++)o[fe]|=s[fe];break;case M.OP_XOR:for(let fe=0;fe<o.length;fe++)o[fe]^=s[fe];break;default:break}this.stack.pop();break;case M.OP_INVERT:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;i=t(-1);for(let fe=0;fe<i.length;fe++)i[fe]=~i[fe];break;case M.OP_LSHIFT:case M.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(v=new he(o),E=he.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength()),f=E.toNumber(),f<0)return this.errstr="SCRIPT_ERR_INVALID_NUMBER_RANGE",!1;this.stack.pop(),this.stack.pop();let fe;ee===M.OP_LSHIFT&&(fe=v.ushln(f)),ee===M.OP_RSHIFT&&(fe=v.ushrn(f));let de=aC(d.Buffer.from(fe.toArray().slice(o.length*-1)),o.length);this.stack.push(de)}break;case M.OP_EQUAL:case M.OP_EQUALVERIFY:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;o=t(-2),s=t(-1);var b=o.toString("hex")===s.toString("hex");if(this.stack.pop(),this.stack.pop(),this.stack.push(b?P.true:P.false),ee===M.OP_EQUALVERIFY)if(b)this.stack.pop();else return this.errstr="SCRIPT_ERR_EQUALVERIFY",!1;break;case M.OP_2MUL:case M.OP_2DIV:case M.OP_1ADD:case M.OP_1SUB:case M.OP_NEGATE:case M.OP_ABS:case M.OP_NOT:case M.OP_0NOTEQUAL:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;switch(i=t(-1),g=he.fromScriptNumBuffer(i,n,this.maxScriptNumLength()),ee){case M.OP_2MUL:g=g.mul(new he(2));break;case M.OP_2DIV:g=g.div(new he(2));break;case M.OP_1ADD:g=g.add(he.One);break;case M.OP_1SUB:g=g.sub(he.One);break;case M.OP_NEGATE:g=g.neg();break;case M.OP_ABS:g.cmp(he.Zero)<0&&(g=g.neg());break;case M.OP_NOT:g=new he((g.cmp(he.Zero)===0)+0);break;case M.OP_0NOTEQUAL:g=new he((g.cmp(he.Zero)!==0)+0);break}this.stack.pop(),this.stack.push(g.toScriptNumBuffer());break;case M.OP_ADD:case M.OP_SUB:case M.OP_MUL:case M.OP_MOD:case M.OP_DIV:case M.OP_BOOLAND:case M.OP_BOOLOR:case M.OP_NUMEQUAL:case M.OP_NUMEQUALVERIFY:case M.OP_NUMNOTEQUAL:case M.OP_LESSTHAN:case M.OP_GREATERTHAN:case M.OP_LESSTHANOREQUAL:case M.OP_GREATERTHANOREQUAL:case M.OP_MIN:case M.OP_MAX:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;switch(v=he.fromScriptNumBuffer(t(-2),n,this.maxScriptNumLength()),E=he.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength()),g=new he(0),ee){case M.OP_ADD:g=v.add(E);break;case M.OP_SUB:g=v.sub(E);break;case M.OP_MUL:g=v.mul(E);break;case M.OP_DIV:if(E.cmp(he.Zero)===0)return this.errstr="SCRIPT_ERR_DIV_BY_ZERO",!1;g=v.div(E);break;case M.OP_MOD:if(E.cmp(he.Zero)===0)return this.errstr="SCRIPT_ERR_MOD_BY_ZERO",!1;g=v.mod(E);break;case M.OP_BOOLAND:g=new he((v.cmp(he.Zero)!==0&&E.cmp(he.Zero)!==0)+0);break;case M.OP_BOOLOR:g=new he((v.cmp(he.Zero)!==0||E.cmp(he.Zero)!==0)+0);break;case M.OP_NUMEQUAL:g=new he((v.cmp(E)===0)+0);break;case M.OP_NUMEQUALVERIFY:g=new he((v.cmp(E)===0)+0);break;case M.OP_NUMNOTEQUAL:g=new he((v.cmp(E)!==0)+0);break;case M.OP_LESSTHAN:g=new he((v.cmp(E)<0)+0);break;case M.OP_GREATERTHAN:g=new he((v.cmp(E)>0)+0);break;case M.OP_LESSTHANOREQUAL:g=new he((v.cmp(E)<=0)+0);break;case M.OP_GREATERTHANOREQUAL:g=new he((v.cmp(E)>=0)+0);break;case M.OP_MIN:g=v.cmp(E)<0?v:E;break;case M.OP_MAX:g=v.cmp(E)>0?v:E;break}if(this.stack.pop(),this.stack.pop(),this.stack.push(g.toScriptNumBuffer()),ee===M.OP_NUMEQUALVERIFY)if(P.castToBool(t(-1)))this.stack.pop();else return this.errstr="SCRIPT_ERR_NUMEQUALVERIFY",!1;break;case M.OP_WITHIN:if(this.stack.length<3)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;v=he.fromScriptNumBuffer(t(-3),n,this.maxScriptNumLength()),E=he.fromScriptNumBuffer(t(-2),n,this.maxScriptNumLength());var k=he.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength());z=E.cmp(v)<=0&&v.cmp(k)<0,this.stack.pop(),this.stack.pop(),this.stack.pop(),this.stack.push(z?P.true:P.false);break;case M.OP_RIPEMD160:case M.OP_SHA1:case M.OP_SHA256:case M.OP_HASH160:case M.OP_HASH256:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;i=t(-1);var D;ee===M.OP_RIPEMD160?D=ja.ripemd160(i):ee===M.OP_SHA1?D=ja.sha1(i):ee===M.OP_SHA256?D=ja.sha256(i):ee===M.OP_HASH160?D=ja.sha256ripemd160(i):ee===M.OP_HASH256&&(D=ja.sha256sha256(i)),this.stack.pop(),this.stack.push(D);break;case M.OP_CODESEPARATOR:this.pbegincodehash=this.pc;break;case M.OP_CHECKSIG:case M.OP_CHECKSIGVERIFY:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(T=t(-2),N=t(-1),!this.checkSignatureEncoding(T)||!this.checkPubkeyEncoding(N))return!1;L=new Ha().set({chunks:this.script.chunks.slice(this.pbegincodehash)});var K=new Ha().add(T);L.findAndDelete(K);try{F=_i.fromTxFormat(T),V=Np.fromBuffer(N,!1),W=this.tx.verifySignature(F,V,this.nin,L,this.satoshisBN,this.flags)}catch{W=!1}if(!W&&this.flags&P.SCRIPT_VERIFY_NULLFAIL&&T.length)return this.errstr="SCRIPT_ERR_NULLFAIL",!1;if(this.stack.pop(),this.stack.pop(),this.stack.push(W?P.true:P.false),ee===M.OP_CHECKSIGVERIFY)if(W)this.stack.pop();else return this.errstr="SCRIPT_ERR_CHECKSIGVERIFY",!1;break;case M.OP_CHECKMULTISIG:case M.OP_CHECKMULTISIGVERIFY:var G=1;if(this.stack.length<G)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;var X=he.fromScriptNumBuffer(t(-G),n,this.maxScriptNumLength()).toNumber();if(X<0||X>this.maxPubKeysPerMultisig())return this.errstr="SCRIPT_ERR_PUBKEY_COUNT",!1;if(this.nOpCount+=X,this.nOpCount>P.MAX_OPS_PER_SCRIPT)return this.errstr="SCRIPT_ERR_OP_COUNT",!1;var Z=++G;G+=X;var le=X+2;if(this.stack.length<G)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;var se=he.fromScriptNumBuffer(t(-G),n,this.maxScriptNumLength()).toNumber();if(se<0||se>X)return this.errstr="SCRIPT_ERR_SIG_COUNT",!1;var O=++G;if(G+=se,this.stack.length<G)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;L=new Ha().set({chunks:this.script.chunks.slice(this.pbegincodehash)});for(var C=0;C<se;C++)T=t(-O-C),L.findAndDelete(new Ha().add(T));for(W=!0;W&&se>0;){if(T=t(-O),N=t(-Z),!this.checkSignatureEncoding(T)||!this.checkPubkeyEncoding(N))return!1;var U;try{F=_i.fromTxFormat(T),V=Np.fromBuffer(N,!1),U=this.tx.verifySignature(F,V,this.nin,L,this.satoshisBN,this.flags)}catch{U=!1}U&&(O++,se--),Z++,X--,se>X&&(W=!1)}for(;G-- >1;){if(!W&&this.flags&P.SCRIPT_VERIFY_NULLFAIL&&!le&&t(-1).length)return this.errstr="SCRIPT_ERR_NULLFAIL",!1;le>0&&le--,this.stack.pop()}if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(this.flags&P.SCRIPT_VERIFY_NULLDUMMY&&t(-1).length)return this.errstr="SCRIPT_ERR_SIG_NULLDUMMY",!1;if(this.stack.pop(),this.stack.push(W?P.true:P.false),ee===M.OP_CHECKMULTISIGVERIFY)if(W)this.stack.pop();else return this.errstr="SCRIPT_ERR_CHECKMULTISIGVERIFY",!1;break;case M.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 M.OP_SPLIT:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;o=t(-2);var j=he.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength()).toNumber();if(j<0||j>o.length)return this.errstr="SCRIPT_ERR_INVALID_SPLIT_RANGE",!1;var re=d.Buffer.from(o);this.stack[this.stack.length-2]=re.slice(0,j),this.stack[this.stack.length-1]=re.slice(j);break;case M.OP_LEFT:case M.OP_RIGHT:if(!this.isAfterChronicle()){if(this.flags&P.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),f=he.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength()).toNumber(),f<0||f>o.length)return this.errstr="SCRIPT_ERR_INVALID_NUMBER_RANGE",!1;this.stack.pop(),ee===M.OP_LEFT?this.stack[this.stack.length-1]=d.Buffer.from(o).slice(0,f):this.stack[this.stack.length-1]=d.Buffer.from(o).slice(o.length-f);break;case M.OP_SUBSTR:if(!this.isAfterChronicle()){if(this.flags&P.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 J=he.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength()).toNumber(),te=he.fromScriptNumBuffer(t(-2),n,this.maxScriptNumLength()).toNumber();if(te<0||te>=o.length||J<0||J>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+J);break;case M.OP_NUM2BIN:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;var ae=he.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength()).toNumber();if(ae<0||ae>this.maxScriptElementSize())return this.errstr="SCRIPT_ERR_PUSH_SIZE",!1;this.stack.pop();var oe=t(-1);if(oe=P._minimallyEncode(oe),oe.length>ae)return this.errstr="SCRIPT_ERR_IMPOSSIBLE_ENCODING",!1;if(oe.length===ae){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 _e=d.Buffer.alloc(ae);oe.copy(_e,0);for(var Se=oe.length-1;Se++<ae-2;)_e[Se]=0;_e[Se]=ue,this.stack[this.stack.length-1]=_e;break;case M.OP_BIN2NUM:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(o=t(-1),s=P._minimallyEncode(o),this.stack[this.stack.length-1]=s,!P._isMinimallyEncoded(s,this.maxScriptNumLength()))return this.errstr="SCRIPT_ERR_INVALID_NUMBER_RANGE",!1;break;default:return this.errstr="SCRIPT_ERR_BAD_OPCODE",!1}return!0}});var qr=B((lq,kp)=>{p();kp.exports=dp();kp.exports.Interpreter=Nc()});var no=B((dq,Rx)=>{"use strict";p();var Cp=ze(),qn=Le(),uC=Xn(),Ix=Kd(),Rr=ya(),Ax=Jt(),Ox=pr(),Lp=Ar();function ne(e,t,r){if(!(this instanceof ne))return new ne(e,t,r);if(Cp.isArray(e)&&Cp.isNumber(t))return ne.createMultisig(e,t,r);if(e instanceof ne)return e;if(qn.checkArgument(e,"First argument is required, please include address data.","guide/address.html"),t&&!Rr.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||Rr.get(t)||Rr.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 Lp)return ne._transformPublicKey(e);if(e instanceof Ka())return ne._transformScript(e,t);if(typeof e=="string")return ne._transformString(e,t,r);if(Cp.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 qn.checkArgument(e.hash||e.hashBuffer,"Must provide a `hash` or `hashBuffer` property"),qn.checkArgument(e.type,"Must provide a `type` property"),{hashBuffer:e.hash?d.Buffer.from(e.hash,"hex"):e.hashBuffer,network:Rr.get(e.network)||Rr.defaultNetwork,type:e.type}};ne._classifyFromVersion=function(e){var t={},r=Rr.get(e[0],"pubkeyhash"),n=Rr.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=Rr.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 Lp))throw new TypeError("Address must be an instance of PublicKey.");return t.hashBuffer=Ax.sha256ripemd160(e.toBuffer()),t.type=ne.PayToPublicKeyHash,t};ne._transformScript=function(e,t){qn.checkArgument(e instanceof Ka(),"script must be a Script instance");var r=e.getAddressInfo(t);if(!r)throw new uC.Script.CantDeriveAddress(e);return r};ne.createMultisig=function(e,t,r){return r=r||e[0].network||Rr.defaultNetwork,ne.payingTo(Ka().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=Rr.get(t);if(t&&!n)throw new TypeError("Unknown network");var i=Ix.decode(e);return ne._transformBuffer(i,t,r)};ne.fromPublicKey=function(e,t){var r=ne._transformPublicKey(e);return t=t||Rr.defaultNetwork,new ne(r.hashBuffer,t,r.type)};ne.fromPrivateKey=function(e,t){let r=Lp.fromPrivateKey(e);return t=t||e.network||Rr.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){qn.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 qn.checkArgument(e,"script is required"),qn.checkArgument(e instanceof Ka(),"script must be instance of Script"),ne.fromScriptHash(Ax.sha256ripemd160(e.toBuffer()),t)};ne.fromScript=function(e,t){qn.checkArgument(e instanceof Ka(),"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){qn.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 Ix.encode(this.toBuffer())};Rx.exports=ne;function Ka(){return qr()}});var io=B((gq,Nx)=>{"use strict";p();var Dc=ze(),fC=no(),Tx=Kd(),wi=Sr(),Px=pr(),hn=ya(),Up=ui(),cC=Ar(),lC=Qs(),Bx=Le(),Dp="[REDACTED]";function ve(e,t){if(!(this instanceof ve))return new ve(e,t);if(e instanceof ve)return e;var r=this._classifyArguments(e,t);if(!r.bn||r.bn.cmp(new wi(0))===0)throw new TypeError("Number can not be equal to zero, undefined, null or false");if(!r.bn.lt(Up.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 Px.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}ve.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=ve._getRandomBN();else if(e instanceof wi)r.bn=e;else if(e instanceof d.Buffer||e instanceof Uint8Array)r=ve._transformBuffer(e,t);else if(e.bn&&e.network)r=ve._transformObject(e);else if(!t&&hn.get(e))r.bn=ve._getRandomBN(),r.network=hn.get(e);else if(typeof e=="string")Px.isHexa(e)?r.bn=new wi(d.Buffer.from(e,"hex")):r=ve._transformWIF(e,t);else throw new TypeError("First argument is an unrecognized data type.");return r};ve._getRandomBN=function(){var e,t;do{var r=lC.getRandomBuffer(32);t=wi.fromBuffer(r),e=t.lt(Up.getN())}while(!e);return t};ve._transformBuffer=function(e,t){var r={};if(e.length===32)return ve._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=wi.fromBuffer(e.slice(1,33)),r};ve._transformBNBuffer=function(e,t,r){var n={};return n.network=hn.get(t)||hn.defaultNetwork,n.bn=wi.fromBuffer(e),n.compressed=r===void 0?!0:!!r,n};ve._transformWIF=function(e,t){return ve._transformBuffer(Tx.decode(e),t)};ve.fromBuffer=function(e,t,r){return r!==void 0&&e&&e.length===32?new ve(ve._transformBNBuffer(e,t,r)):new ve(e,t)};ve.fromHex=function(e,t,r){return ve.fromBuffer(d.Buffer.from(e,"hex"),t,r)};ve._transformObject=function(e){if(e.bn instanceof wi)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===Dp)throw new TypeError('Invalid private key: `bn` is "'+Dp+'". 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 wi(e.bn,"hex");if(t.isZero()||t.gte(Up.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}};ve.fromString=ve.fromWIF=function(e,t){return Bx.checkArgument(Dc.isString(e),"First argument is expected to be a string."),new ve(e,t)};ve.fromObject=ve.fromJSON=function(e){return Bx.checkArgument(Dc.isObject(e),"First argument is expected to be an object."),new ve(e)};ve.fromRandom=function(e){var t=ve._getRandomBN();return new ve(t,e)};ve.getValidationError=function(e,t){var r;try{new ve(e,t)}catch(n){r=n}return r};ve.isValid=function(e,t){return e?!ve.getValidationError(e,t):!1};ve.prototype.toString=function(){return this.toWIF()};ve.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})]),Tx.encode(r)};ve.prototype.toBigNumber=function(){return this.bn};ve.prototype.toBuffer=function(){return this.bn.toBuffer({size:32})};ve.prototype.toHex=function(){return this.toBuffer().toString("hex")};ve.prototype.toPublicKey=function(){return this._pubkey||(this._pubkey=cC.fromPrivateKey(this)),this._pubkey};ve.prototype.toAddress=function(e){var t=this.toPublicKey();return fC.fromPublicKey(t,e||this.network)};ve.prototype.toObject=function(){return{bn:this.bn.toString("hex"),compressed:this.compressed,network:this.network.toString()}};ve.prototype.toJSON=function(){return{bn:Dp,compressed:this.compressed,network:this.network.toString()}};ve.prototype.inspect=function(){var e=this.compressed?"":", uncompressed";return"<PrivateKey: "+this.toHex()+", network: "+this.network+e+">"};Nx.exports=ve});var Ar=B((mq,kx)=>{"use strict";p();var us=Sr(),fs=ui(),hC=Jt(),dC=pr(),Mx=ya(),Fp=ze(),so=Le();function pe(e,t){if(!(this instanceof pe))return new pe(e,t);if(so.checkArgument(e,"First argument is required, please include public key data."),e instanceof pe)return e;t=t||{};var r=this._classifyArgs(e,t);return r.point.validate(),dC.defineImmutable(this,{point:r.point,compressed:r.compressed,network:r.network||Mx.defaultNetwork}),this}pe.prototype._classifyArgs=function(e,t){var r={compressed:Fp.isUndefined(t.compressed)||t.compressed};if(e instanceof fs)r.point=e;else if(e.x&&e.y)r=pe._transformObject(e);else if(typeof e=="string")r=pe._transformDER(d.Buffer.from(e,"hex"));else if(pe._isBuffer(e))r=pe._transformDER(e);else if(pe._isPrivateKey(e))r=pe._transformPrivateKey(e);else throw new TypeError("First argument is an unrecognized data format.");return r.network||(r.network=Fp.isUndefined(t.network)?void 0:Mx.get(t.network)),r};pe._isPrivateKey=function(e){var t=io();return e instanceof t};pe._isBuffer=function(e){return e instanceof d.Buffer||e instanceof Uint8Array};pe._transformPrivateKey=function(e){so.checkArgument(pe._isPrivateKey(e),"Must be an instance of PrivateKey");var t={};return t.point=fs.getG().mul(e.bn),t.compressed=e.compressed,t.network=e.network,t};pe._transformDER=function(e,t){so.checkArgument(pe._isBuffer(e),"Must be a buffer of DER encoded public key");var r={};t=Fp.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 us(o),i=new us(s),r.point=new fs(n,i),r.compressed=!1}else if(e[0]===3)o=e.slice(1),n=new us(o),r=pe._transformX(!0,n),r.compressed=!0;else if(e[0]===2)o=e.slice(1),n=new us(o),r=pe._transformX(!1,n),r.compressed=!0;else throw new TypeError("Invalid DER format public key");return r};pe._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=fs.fromX(e,t),r};pe._transformObject=function(e){var t=new us(e.x,"hex"),r=new us(e.y,"hex"),n=new fs(t,r);return new pe(n,{compressed:e.compressed})};pe.fromPrivateKey=function(e){so.checkArgument(pe._isPrivateKey(e),"Must be an instance of PrivateKey");var t=pe._transformPrivateKey(e);return new pe(t.point,{compressed:t.compressed,network:t.network})};pe.fromDER=pe.fromBuffer=function(e,t){so.checkArgument(pe._isBuffer(e),"Must be a buffer of DER encoded public key");var r=pe._transformDER(e,t);return new pe(r.point,{compressed:r.compressed})};pe.fromPoint=function(e,t){return so.checkArgument(e instanceof fs,"First argument must be an instance of Point."),new pe(e,{compressed:t})};pe.fromHex=pe.fromString=function(e,t){var r=d.Buffer.from(e,t||"hex"),n=pe._transformDER(r);return new pe(n.point,{compressed:n.compressed})};pe.fromX=function(e,t){var r=pe._transformX(e,t);return new pe(r.point,{compressed:r.compressed})};pe.getValidationError=function(e){var t;try{new pe(e)}catch(r){t=r}return t};pe.isValid=function(e){return!pe.getValidationError(e)};pe.prototype.toObject=pe.prototype.toJSON=function(){return{x:this.point.getX().toString("hex",2),y:this.point.getY().toString("hex",2),compressed:this.compressed}};pe.prototype.toBuffer=pe.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])};pe.prototype._getID=function(){return hC.sha256ripemd160(this.toBuffer())};pe.prototype.toAddress=function(e){var t=no();return t.fromPublicKey(this,e||this.network)};pe.prototype.toString=pe.prototype.toHex=function(){return this.toDER().toString("hex")};pe.prototype.inspect=function(){return"<PublicKey: "+this.toHex()+(this.compressed?"":", uncompressed")+">"};kx.exports=pe});var Ga=B((bq,Lx)=>{"use strict";p();var Cx=Qs();function pC(){var e=Cx.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 gC(e){return Cx.getRandomBuffer(Math.ceil(e/2)).toString("hex").substring(0,e)}Lx.exports={uuid4:pC,randomHex:gC}});var jx=B((Sq,qx)=>{"use strict";p();var Va=Ar(),qp=Jt(),jp=Ca(),Dx=nr(),Hp=io(),Bt=Le(),wq=ze(),yC=Ga();function Ux(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 cs={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"},Fx={create:function(e,t,r,n,i,o){o=o||{},Bt.checkArgument(typeof e=="string","Right type must be string"),Bt.checkArgument(typeof t=="string","Issuer DID must be string"),Bt.checkArgument(typeof r=="string","Subject DID must be string"),Bt.checkArgument(n&&typeof n=="object","Claim must be object");var s=Object.values(cs);Bt.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||{},Bt.checkArgument(typeof e=="string","Right type must be string"),Bt.checkArgument(typeof t=="string","Issuer DID must be string"),Bt.checkArgument(typeof r=="string","Subject DID must be string"),Bt.checkArgument(n&&typeof n=="object","Claim must be object"),Bt.checkArgument(i instanceof Hp,"Invalid issuer private key");var s=Object.values(cs);Bt.checkArgument(s.includes(e),"Invalid right type: "+e);try{var a=this.create(e,t,r,n,i,o),f=this._signToken(a,i);return{success:!0,rightToken:f,tokenHash:f.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:f,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:f.id,tokenHash:f.tokenHash,type:e,issuer:t,subject:r,issuedAt:f.issuanceDate}},notifyParties:{endpoint:"POST /notifications/right-issued",data:{tokenId:f.id,issuer:t,subject:r,rightType:e}}}}}catch(l){return{success:!1,error:l.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||{},Bt.checkArgument(e&&typeof e=="object","Invalid token"),Bt.checkArgument(typeof t=="string","New owner DID must be string"),Bt.checkArgument(r instanceof Hp,"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=Ux({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}},f=this._signToken(a,r),l=JSON.parse(JSON.stringify(e));l.id="urn:uuid:"+this._generateUUID(),l.issuanceDate=new Date().toISOString(),l.credentialSubject.id=t,l.credentialSubject.transferHistory=l.credentialSubject.transferHistory||[],l.credentialSubject.transferHistory.push({transferId:f.id,transferDate:f.issuanceDate,from:e.credentialSubject.id,to:t}),delete l.proof;var m=this._signToken(l,r);return{success:!0,newToken:m,transferProof:f,transferId:f.id,externalOperations:{recordTransfer:{endpoint:"POST /rights/transfers",data:{originalTokenId:e.id,newTokenId:m.id,transferProof:f,fromOwner:e.credentialSubject.id,toOwner:t,transferDate:f.issuanceDate}},updateOwnership:{endpoint:"PUT /rights/tokens/"+e.id+"/ownership",data:{newOwner:t,transferId:f.id,transferDate:f.issuanceDate,previousOwner:e.credentialSubject.id}},notifyParties:{endpoint:"POST /notifications/right-transferred",data:{originalTokenId:e.id,newTokenId:m.id,fromOwner:e.credentialSubject.id,toOwner:t,rightType:e.credentialSubject.rightType}},auditTransfer:{endpoint:"POST /audit/right-transfer",data:{originalTokenId:e.id,newTokenId:m.id,transferId:f.id,fromOwner:e.credentialSubject.id,toOwner:t,transferredAt:f.issuanceDate}}}}}catch(g){return{success:!1,error:g.message}}},prepareObligationToken:function(e,t,r,n){Bt.checkArgument(e&&typeof e=="object","Invalid right token"),Bt.checkArgument(typeof t=="string","Obligor DID must be string"),Bt.checkArgument(r&&typeof r=="object","Obligation must be object"),Bt.checkArgument(n instanceof Hp,"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){Bt.checkArgument(typeof e=="string","Right type must be string");var t=Object.values(cs),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 cs},verifyToken:function(e,t){var r=[];try{if(Bt.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=qp.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=Dx.fromDER(d.Buffer.from(s[2],"base64url")),f=new jp;return f.hashbuf=o,f.sig=a,f.pubkey=n,f.verify()||r.push("Signature verification failed"),{valid:r.length===0,errors:r,tokenHash:o.toString("hex"),verifiedAt:new Date().toISOString()}}catch(l){return r.push(l.message),{valid:!1,errors:r}}},_signToken:function(e,t){var r=this._canonicalizeToken(e),n=qp.sha256(d.Buffer.from(r)),i=new jp;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=qp.sha256(d.Buffer.from(n));if(e.tokenHash&&e.tokenHash!==i.toString("hex")){t.push("Token hash mismatch");return}var o=Ux(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=Dx.fromDER(d.Buffer.from(s[2],"base64url")),f=new jp;f.hashbuf=i,f.sig=a,f.pubkey=o,f.verify()!==!0&&t.push("Signature verification failed")}catch(l){t.push("Signature verification failed: "+l.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(cs);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 yC.uuid4()}};Fx.RightTypes=cs;qx.exports=Fx});var Gx=B((xq,Kx)=>{"use strict";p();var Hx={};Hx.stringify=function(e){return Kp(e,[])};function Kp(e,t){if(e===null)return"null";var r=typeof e;if(r==="boolean")return e?"true":"false";if(r==="number"){if(!isFinite(e))throw new Error("Cannot canonicalize non-finite number: "+e);return JSON.stringify(e)}if(r==="string")return JSON.stringify(e);if(r==="bigint")throw new Error("Cannot canonicalize bigint; represent it as a string");if(Array.isArray(e)||r==="object"){if(t.indexOf(e)!==-1)throw new Error("Cannot canonicalize a circular structure");t.push(e);var n;if(Array.isArray(e))n="["+e.map(function(o){return o===void 0?"null":Kp(o,t)}).join(",")+"]";else{var i=Object.keys(e).filter(function(o){return e[o]!==void 0&&typeof e[o]!="function"}).sort();n="{"+i.map(function(o){return JSON.stringify(o)+":"+Kp(e[o],t)}).join(",")+"}"}return t.pop(),n}throw new Error("Cannot canonicalize value of type: "+r)}Kx.exports=Hx});var zx=B((Aq,Wx)=>{"use strict";p();var Gp=Object.create(null),Vp=[],Wp=!(typeof x.default<"u"&&x.default.env&&x.default.env.BSV_NO_DEPRECATION_WARNINGS==="1");function Vx(e,t){if(!e||typeof e.what!="string"||e.what==="")throw new TypeError(t+"() requires { what: string }")}function mC(e){var t="[@smartledger/bsv] "+e.what+" is deprecated";return e.since&&(t+=" since "+e.since),t+=".",e.why&&(t+=" "+e.why.charAt(0).toUpperCase()+e.why.slice(1)+"."),e.use&&(t+=" Use "+e.use+" instead."),t+=e.removeIn?" It will be removed in "+e.removeIn+".":" A removal version has not been set; it will not be removed in a 9.x release.",t}function jn(e){if(!e||!e.what)throw new TypeError("deprecate() requires { what }");if(Gp[e.what])return!1;Gp[e.what]=!0;var t=mC(e);return Vp.push({what:e.what,since:e.since||null,removeIn:e.removeIn||null,use:e.use||null,message:t}),Wp&&console.warn(t),!0}jn.fn=function(e,t){if(typeof e!="function")throw new TypeError("deprecate.fn() requires a function");Vx(t,"deprecate.fn");var r=function(){return jn(t),e.apply(this,arguments)};return Object.defineProperty(r,"name",{value:e.name,configurable:!0}),Object.defineProperty(r,"length",{value:e.length,configurable:!0}),r.__wrapped=e,r.__deprecation=t,r};jn.property=function(e,t,r,n){Vx(n,"deprecate.property");var i,o=!1;return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get:function(){return jn(n),o||(i=r(),o=!0),i}}),e};jn.fired=function(){return Vp.slice()};jn.setEnabled=function(e){Wp=!!e};jn.isEnabled=function(){return Wp};jn.reset=function(){Gp=Object.create(null),Vp.length=0};Wx.exports=jn});var $x=B((Rq,Yx)=>{"use strict";p();var ls=Jt(),cr=Le(),vC=Ga(),bC=Gx(),_C=zx(),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"}}}},wC={prepareClaimValidation:function(e,t){try{cr.checkArgument(e&&typeof e=="object","Invalid claim"),cr.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:ls.sha256(d.Buffer.from(this._canonicalizeWith(e,this.CANONICALIZATION.LEGACY))).toString("hex"),canonical:this._canonicalizeWith(e,this.CANONICALIZATION.LEGACY)};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{cr.checkArgument(e&&typeof e=="object","Invalid claim"),cr.checkArgument(typeof t=="string","Schema name must be string"),cr.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=ls.sha256(d.Buffer.from(this._canonicalizeWith(i,this.CANONICALIZATION.LEGACY))).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{cr.checkArgument(typeof e=="string","Claim hash must be string"),cr.checkArgument(t&&typeof t=="object","Invalid disputant"),cr.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=ls.sha256(d.Buffer.from(this._canonicalizeWith(n,this.CANONICALIZATION.LEGACY))).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{cr.checkArgument(Array.isArray(e),"Claims must be array"),cr.checkArgument(typeof t=="string","Schema name must be string");var r=[],n=[],i=0;e.forEach(function(a,f){try{var l=this.prepareClaimValidation(a,t);l.success&&l.validation.valid&&i++,r.push({index:f,result:l})}catch(m){n.push({index:f,error:m.message})}}.bind(this));var o=this._generateBatchId(),s=ls.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}}},CANONICALIZATION:{JCS:"jcs",LEGACY:"legacy"},canonicalize:function(e,t){return this._canonicalizeWith(e,this._resolveCanonicalization(t,"LTP.Claim.canonicalize"))},hash:function(e,t){var r=this._canonicalizeWith(e,this._resolveCanonicalization(t,"LTP.Claim.hash"));return ls.sha256(d.Buffer.from(r)).toString("hex")},_canonicalizeWith:function(e,t){if(cr.checkArgument(e&&typeof e=="object","Invalid claim"),t===this.CANONICALIZATION.JCS)return bC.stringify(e);var r=this._sortObjectKeys(e);return JSON.stringify(r)},_resolveCanonicalization:function(e,t){return e===void 0?(_C({what:t+"() without a canonicalization argument",since:"9.2.0",removeIn:"10.0.0",use:t+"(claim, bsv.LTP.Claim.CANONICALIZATION.JCS)",why:"the default sorted-key form is not RFC 8785, so other implementations compute a different claim hash"}),this.CANONICALIZATION.LEGACY):(cr.checkArgument(e===this.CANONICALIZATION.JCS||e===this.CANONICALIZATION.LEGACY,"Unknown canonicalization: "+e+". Expected 'jcs' or 'legacy' (bsv.LTP.Claim.CANONICALIZATION)"),e)},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){cr.checkArgument(typeof e=="string","Schema name must be string"),cr.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 ls.sha256(d.Buffer.from(t)).toString("hex").substring(0,16)},_generateBatchId:function(){return vC.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())}};Yx.exports=wC});var Xx=B((Pq,Zx)=>{"use strict";p();var Wa=Jt(),hs=Le(),SC={prepareTokenCommitment:function(e,t){t=t||{},hs.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||{},hs.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){hs.checkArgument(e&&typeof e=="object","Invalid token"),hs.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){hs.checkArgument(typeof e=="string","Token ID must be string"),hs.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=Wa.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:Wa.sha256(d.Buffer.from(r)).toString("hex"),tokenId:e.id,timestamp:new Date().toISOString(),purpose:t.purpose||"legal_token"},i=Wa.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 f=this._createCommitment(a,t);r.push(f.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=Wa.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=Wa.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}};Zx.exports=SC});var eI=B((Nq,Qx)=>{"use strict";p();var EC=Ar(),Vr=Jt(),Jx=Ca(),xC=nr(),IC=io(),ir=Le(),AC={prepareSignatureProof:function(e,t,r){r=r||{},ir.checkArgument(e&&typeof e=="object","Invalid token"),ir.checkArgument(t instanceof IC,"Invalid private key");try{var n=this._canonicalizeForSigning(e),i=Vr.sha256(d.Buffer.from(n)),o=new Jx;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(f){return{success:!1,error:f.message}}},prepareSignatureVerification:function(e,t){try{if(ir.checkArgument(e&&typeof e=="object","Invalid token"),ir.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=Vr.sha256(d.Buffer.from(r)),i=xC.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 Jx;s.hashbuf=n,s.sig=i,s.pubkey=EC.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(f){return{success:!1,error:f.message}}},prepareSelectiveDisclosure:function(e,t,r){ir.checkArgument(e&&typeof e=="object","Invalid token"),ir.checkArgument(Array.isArray(t),"Revealed fields must be array"),ir.checkArgument(typeof r=="string","Nonce must be string");try{var n=this._createFieldCommitments(e,r),i=this._createMerkleTree(n),o=[],s=[];t.forEach(function(f){var l=this._getNestedValue(e,f),m=this._findFieldCommitment(n,f);if(m){o.push({path:f,value:l,commitment:m.hash,salt:m.salt});var g=this._generateMerkleProof(i,m.index);s.push({path:f,leafIndex:m.index,proof:g})}}.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(f){return{success:!1,error:f.message}}},prepareSelectiveDisclosureVerification:function(e,t){try{if(ir.checkArgument(e&&typeof e=="object","Invalid proof"),ir.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],f=this._hashField(o.path,o.value,o.salt);if(f!==o.commitment){n.push("Invalid commitment for field: "+o.path);return}var l=this._verifyMerkleProof(o.commitment,a.leafIndex,a.proof,e.merkleRoot);l?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){ir.checkArgument(e&&typeof e=="object","Invalid token"),ir.checkArgument(t&&typeof t=="object","Invalid jurisdiction"),ir.checkArgument(typeof r=="string","Nonce must be string");try{var n=t.requirements||[],i=[],o=!0;n.forEach(function(a){var f=this._checkLegalRequirement(e,a);i.push(f),f.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){ir.checkArgument(e&&typeof e=="object","Invalid token"),ir.checkArgument(t&&typeof t=="object","Invalid statement"),ir.checkArgument(typeof r=="string","Nonce must be string");try{var n=Vr.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:Vr.sha256(d.Buffer.from(t.claim+r)).toString("hex"),response:Vr.sha256(d.Buffer.from(this._canonicalizeForSigning(e)+t.claim)).toString("hex"),witness:Vr.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=Vr.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 Vr.sha256(d.Buffer.from(n)).toString("hex")},_createMerkleTree:function(e){var t=e.map(function(m){return m.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,f=d.Buffer.concat([d.Buffer.from(s,"hex"),d.Buffer.from(a,"hex")]),l=Vr.sha256(f).toString("hex");i.push(l)}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],f=o%2===0,l;a.isLeft?l=d.Buffer.concat([d.Buffer.from(a.hash,"hex"),d.Buffer.from(i,"hex")]):l=d.Buffer.concat([d.Buffer.from(i,"hex"),d.Buffer.from(a.hash,"hex")]),i=Vr.sha256(l).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 Vr.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}};Qx.exports=AC});var nI=B((Lq,rI)=>{"use strict";p();var za=Jt(),kq=no(),Cq=Bp(),lr=Le(),tI=Ga(),OC={prepareRegistry:function(e){e=e||{},lr.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||{},lr.checkArgument(e&&typeof e=="object","Invalid token"),lr.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{lr.checkArgument(typeof e=="string","Token ID must be string"),lr.checkArgument(typeof t=="string","Approver must be string"),lr.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(lr.checkArgument(typeof e=="string","Token ID must be string"),lr.checkArgument(t&&typeof t=="object","Invalid revocation"),lr.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 lr.checkArgument(typeof e=="string","Token ID must be string"),lr.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{lr.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 lr.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||{},lr.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_"+tI.randomHex(16)},_generateRegistrationId:function(e){var t="reg_"+e+"_"+Date.now();return za.sha256(d.Buffer.from(t)).toString("hex").substring(0,16)},_generateRevocationId:function(e){var t="rev_"+e+"_"+Date.now();return za.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,za.sha256(d.Buffer.from(JSON.stringify(t))).toString("hex")},_generateRevocationHash:function(e,t){var r=e+(t.reason||"")+(t.revokedBy||"")+Date.now();return za.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_"+tI.randomHex(32)},_generateAuditHash:function(e){var t=(e.action||"")+(e.actor||"")+(e.tokenId||"")+(e.timestamp||"");return za.sha256(d.Buffer.from(t)).toString("hex").substring(0,16)}};rI.exports=OC});var aI=B((Uq,sI)=>{"use strict";p();var zp=Ar(),Yp=Jt(),iI=Ca(),RC=nr(),oI=io(),yr=Le(),TC=Ga();function PC(e,t){if(t=t||{},t.issuerPublicKey)return t.issuerPublicKey instanceof zp?t.issuerPublicKey:zp.fromString(t.issuerPublicKey);var r=e&&e.issuer;if(typeof r!="string")return null;try{var n=r.split("#")[0].split(":")[2];return n?zp.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"},ds={CRITICAL:"CRITICAL",HIGH:"HIGH",MEDIUM:"MEDIUM",LOW:"LOW",DEFERRED:"DEFERRED"},hr={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||{},yr.checkArgument(typeof e=="string","Obligation type must be string"),yr.checkArgument(typeof t=="string","Issuer DID must be string"),yr.checkArgument(typeof r=="string","Obligor DID must be string"),yr.checkArgument(n&&typeof n=="object","Obligation must be object"),yr.checkArgument(i instanceof oI,"Invalid issuer private key");var s=Object.values(Uc);yr.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||ds.MEDIUM,status:hr.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 f=this._signToken(a,i);return{success:!0,obligationToken:f,tokenHash:f.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:f,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:f.id,tokenHash:f.tokenHash,type:e,issuer:t,obligor:r,issuedAt:f.issuanceDate,dueDate:a.credentialSubject.dueDate,priority:a.credentialSubject.priority}},notifyObligor:{endpoint:"POST /notifications/obligation-issued",data:{tokenId:f.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:f.id,obligor:r,dueDate:a.credentialSubject.dueDate,reminderSchedule:o.reminderSchedule||["7d","3d","1d"]}}:null}}}catch(l){return{success:!1,error:l.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===hr.ACTIVE?{endpoint:"PUT /obligations/tokens/"+e.id+"/status",data:{status:hr.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||{},yr.checkArgument(e&&typeof e=="object","Invalid token"),yr.checkArgument(t&&typeof t=="object","Invalid fulfillment"),yr.checkArgument(r instanceof oI,"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===hr.COMPLETED)return{success:!1,error:"Obligation already fulfilled"};if(e.credentialSubject.status===hr.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?hr.COMPLETED:hr.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(f){return{success:!1,error:f.message}}},prepareObligationBreachAssessment:function(e,t,r){yr.checkArgument(e&&typeof e=="object","Invalid token"),yr.checkArgument(t&&typeof t=="object","Invalid breach details"),yr.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=Yp.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:hr.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||{},yr.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===hr.COMPLETED&&r.summary.completed++,s.isOverdue&&s.priority===ds.CRITICAL&&r.alerts.push({type:"CRITICAL_OVERDUE",obligationId:o.id,message:"Critical obligation is overdue",priority:"HIGH"}),s.isDueSoon&&s.priority===ds.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 ds},getObligationStatus:function(){return hr},_signToken:function(e,t){var r=this._canonicalizeToken(e),n=Yp.sha256(d.Buffer.from(r)),i=new iI;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=Yp.sha256(d.Buffer.from(n));if(e.tokenHash&&e.tokenHash!==i.toString("hex")){t.push("Token hash mismatch");return}var o=PC(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=RC.fromDER(d.Buffer.from(s[2],"base64url")),f=new iI;f.hashbuf=i,f.sig=a,f.pubkey=o,f.verify()!==!0&&t.push("Signature verification failed")}catch(l){t.push("Signature verification failed: "+l.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(hr);n.includes(e.credentialSubject.status)||t.push("Invalid obligation status: "+e.credentialSubject.status),this._checkIfOverdue(e)&&e.credentialSubject.status===hr.ACTIVE&&r.push("Obligation is overdue but status is still ACTIVE")},_validateObligationPriority:function(e,t){if(e.credentialSubject.priority){var r=Object.values(ds);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!==hr.COMPLETED},_generateUUID:function(){return TC.uuid4()}};Fc.ObligationTypes=Uc;Fc.ObligationPriority=ds;Fc.ObligationStatus=hr;sI.exports=Fc});var fI=B((qq,uI)=>{"use strict";p();var uo=jx(),qc=$x(),Ya=Xx(),$p=eI(),dn=nI(),BC=aI(),Zp=io(),mr=Le(),Pe=function(e){return this instanceof Pe?(this.config=e||{},this.registry=null,this.config.registry&&(this.registry=dn.createRegistry(this.config.registry)),this):new Pe(e)};Pe.prototype.createRightToken=function(e,t,r){mr.checkArgument(e&&typeof e=="object","Invalid right data"),mr.checkArgument(t instanceof Zp,"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}}};Pe.prototype.validateClaim=function(e,t){return qc.validate(e,t)};Pe.prototype.createSelectiveDisclosure=function(e,t,r){return $p.prepareSelectiveDisclosure(e,t,r)};Pe.prototype.verifyToken=function(e,t){return!e||!e.proof?{valid:!1,error:"No proof found in token"}:uo.verifyToken(e,t)};Pe.prototype.transferRight=function(e,t,r,n){mr.checkArgument(e&&typeof e=="object","Invalid token"),mr.checkArgument(typeof t=="string","New owner must be string"),mr.checkArgument(r instanceof Zp,"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 f=Ya.anchorToken(s,n.anchor);f.success&&(s.transferAnchorTx=f.txid)}if(this.registry){var l=dn.registerToken(this.registry,s,{registeredBy:n.registeredBy||t,metadata:{transferFrom:e.owner,transferTo:t,originalTokenId:e.id}});l.success&&(s.registrationId=l.registrationId)}return{success:!0,token:s,transferId:a.id,transferredAt:a.issuanceDate,transferProof:a}}catch(m){return{success:!1,error:m.message}}};Pe.prototype.createObligation=function(e,t,r){mr.checkArgument(e&&typeof e=="object","Invalid right token"),mr.checkArgument(t&&typeof t=="object","Invalid obligation data"),mr.checkArgument(r instanceof Zp,"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}}};Pe.prototype.revokeToken=function(e,t,r){return mr.checkArgument(typeof e=="string","Token ID must be string"),mr.checkArgument(t&&typeof t=="object","Invalid revocation data"),mr.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"}};Pe.prototype.checkTokenStatus=function(e){return mr.checkArgument(typeof e=="string","Token ID must be string"),this.registry?dn.checkTokenStatus(this.registry,e):{found:!1,error:"No registry available"}};Pe.prototype.searchTokens=function(e){return this.registry?dn.searchTokens(this.registry,e):{success:!1,error:"No registry available"}};Pe.prototype.getRegistryStats=function(){return this.registry?dn.getStatistics(this.registry):{error:"No registry available"}};Pe.prototype.createLegalValidityProof=function(e,t,r){return $p.prepareLegalValidityProof(e,t,r)};Pe.prototype.anchorTokenBatch=function(e,t){return Ya.anchorBatch(e,t)};Pe.prototype.verifyAnchor=function(e,t){return Ya.verifyAnchor(e,t)};Pe.prototype.getRightTypes=function(){return uo.getRightTypes()};Pe.prototype.getClaimSchemas=function(){return qc.getSchemas()};Pe.prototype.createRegistry=function(e){return this.registry=dn.createRegistry(e),this.registry};Pe.prototype.setRegistry=function(e){mr.checkArgument(e&&typeof e=="object","Invalid registry"),this.registry=e};Pe.create=function(e){return new Pe(e)};Pe.createRightToken=function(e,t,r){var n=new Pe;return n.createRightToken(e,t,r)};Pe.validateClaim=function(e,t){return qc.validate(e,t)};Pe.verifyToken=function(e,t){var r=new Pe;return r.verifyToken(e,t)};Pe.createRegistry=function(e){return dn.createRegistry(e)};Pe.Right=uo;Pe.Claim=qc;Pe.Anchor=Ya;Pe.Proof=$p;Pe.Registry=dn;Pe.Obligation=BC;uI.exports=Pe});var NC=B((Hq,cI)=>{p();cI.exports=fI()});return NC();})();
74
+ `))}}};P.prototype.verify=function(e,t,r,n,i,o){this.eraHint=null;var s=this._verifyCore(e,t,r,n,i,o);return s||this._eraDiagnose(i),s};P._resetEraWarning=function(){Mp=!1};P.mainnetFlags=function(e){e=e||{};var t=P.SCRIPT_VERIFY_P2SH|P.SCRIPT_VERIFY_STRICTENC|P.SCRIPT_VERIFY_DERSIG|P.SCRIPT_VERIFY_SIGPUSHONLY|P.SCRIPT_VERIFY_LOW_S|P.SCRIPT_VERIFY_NULLFAIL|P.SCRIPT_VERIFY_MINIMALDATA|P.SCRIPT_ENABLE_SIGHASH_FORKID|P.SCRIPT_ENABLE_MAGNETIC_OPCODES|P.SCRIPT_ENABLE_MONOLITH_OPCODES|P.SCRIPT_GENESIS|P.SCRIPT_UTXO_AFTER_GENESIS;return e.afterChronicle!==!1&&(t|=P.SCRIPT_ENABLE_CHRONICLE|P.SCRIPT_UTXO_AFTER_CHRONICLE),t};P.currentConsensusFlags=function(){return P.SCRIPT_ENABLE_MONOLITH_OPCODES|P.SCRIPT_ENABLE_MAGNETIC_OPCODES|P.SCRIPT_GENESIS|P.SCRIPT_UTXO_AFTER_GENESIS|P.SCRIPT_ENABLE_CHRONICLE|P.SCRIPT_UTXO_AFTER_CHRONICLE|P.SCRIPT_ENABLE_SIGHASH_FORKID|P.SCRIPT_VERIFY_SIGPUSHONLY|P.SCRIPT_VERIFY_LOW_S|P.SCRIPT_VERIFY_NULLFAIL};P.useMainnetConsensus=function(e){return e=e||{},P.useGenesisLimits(e.max),P.mainnetFlags(e)};P.SEQUENCE_LOCKTIME_DISABLE_FLAG=1<<31;P.SEQUENCE_LOCKTIME_TYPE_FLAG=1<<22;P.SEQUENCE_LOCKTIME_MASK=65535;P.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};P.prototype.checkSignatureEncoding=function(e){var t;if(e.length===0)return!0;if((this.flags&(P.SCRIPT_VERIFY_DERSIG|P.SCRIPT_VERIFY_LOW_S|P.SCRIPT_VERIFY_STRICTENC))!==0&&!_i.isTxDER(e))return this.errstr="SCRIPT_ERR_SIG_DER_INVALID_FORMAT",!1;if((this.flags&P.SCRIPT_VERIFY_LOW_S)!==0){if(t=_i.fromTxFormat(e),!t.hasLowS())return this.errstr="SCRIPT_ERR_SIG_DER_HIGH_S",!1}else if((this.flags&P.SCRIPT_VERIFY_STRICTENC)!==0){if(t=_i.fromTxFormat(e),!t.hasDefinedHashtype())return this.errstr="SCRIPT_ERR_SIG_HASHTYPE",!1;if(!(this.flags&P.SCRIPT_ENABLE_SIGHASH_FORKID)&&t.nhashtype&_i.SIGHASH_FORKID)return this.errstr="SCRIPT_ERR_ILLEGAL_FORKID",!1;if(!(this.flags&P.SCRIPT_CHRONICLE)&&t.nhashtype&_i.SIGHASH_CHRONICLE)return this.errstr="SCRIPT_ERR_ILLEGAL_CHRONICLE",!1;if(this.flags&P.SCRIPT_ENABLE_SIGHASH_FORKID&&!(t.nhashtype&_i.SIGHASH_FORKID))return this.errstr="SCRIPT_ERR_MUST_USE_FORKID",!1}return!0};P.prototype.checkPubkeyEncoding=function(e){return(this.flags&P.SCRIPT_VERIFY_STRICTENC)!==0&&!Np.isValid(e)?(this.errstr="SCRIPT_ERR_PUBKEYTYPE",!1):!0};P.prototype.isAfterGenesis=function(){return(this.flags&P.SCRIPT_UTXO_AFTER_GENESIS)!==0};P.prototype.isAfterChronicle=function(){return(this.flags&(P.SCRIPT_UTXO_AFTER_CHRONICLE|P.SCRIPT_ENABLE_CHRONICLE))!==0};P.prototype.maxScriptElementSize=function(){return this.isAfterGenesis()?P.UNLIMITED:P.MAX_SCRIPT_ELEMENT_SIZE};P.prototype.maxScriptSize=function(){return this.isAfterGenesis()?P.UNLIMITED:P.MAX_SCRIPT_SIZE};P.prototype.maxOpsPerScript=function(){return this.isAfterGenesis()?P.UNLIMITED:P.MAX_OPS_PER_SCRIPT};P.prototype.maxScriptNumLength=function(){return this.isAfterChronicle()?P.MAX_SCRIPT_NUM_LENGTH_AFTER_CHRONICLE:this.isAfterGenesis()?P.MAX_SCRIPT_NUM_LENGTH_AFTER_GENESIS:P.MAXIMUM_ELEMENT_SIZE};P.prototype.maxPubKeysPerMultisig=function(){return this.isAfterGenesis()?P.MAX_PUBKEYS_PER_MULTISIG_AFTER_GENESIS:20};P._isMinimallyEncoded=function(e,t){return t=t||P.MAXIMUM_ELEMENT_SIZE,!(e.length>t||e.length>0&&(e[e.length-1]&127)===0&&(e.length<=1||(e[e.length-2]&128)===0))};P._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("")};P.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:M.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};P.prototype._callbackStep=function(e){if(typeof this.stepListener=="function")try{this.stepListener(e,Sx(this.stack),Sx(this.altstack))}catch(t){console.log(`Error in Step callback:${t}`)}};P.prototype.checkLockTime=function(e){if(!(this.tx.nLockTime<P.LOCKTIME_THRESHOLD&&e.lt(P.LOCKTIME_THRESHOLD_BN)||this.tx.nLockTime>=P.LOCKTIME_THRESHOLD&&e.gte(P.LOCKTIME_THRESHOLD_BN))||e.gt(new he(this.tx.nLockTime)))return!1;var t=this.tx.inputs[this.nin];return!(!t||t.isFinal())};P.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&P.SEQUENCE_LOCKTIME_DISABLE_FLAG)return!1;var n=P.SEQUENCE_LOCKTIME_TYPE_FLAG|P.SEQUENCE_LOCKTIME_MASK,i=new he(r&n),o=e.and(new he(n)),s=new he(P.SEQUENCE_LOCKTIME_TYPE_FLAG);return!(!(i.lt(s)&&o.lt(s)||i.gte(s)&&o.gte(s))||o.gt(i))};function aC(e,t){let r=e;for(;r.length<t;)r=d.Buffer.concat([d.Buffer.from([0]),r]);return r}function Ex(e){var t=d.Buffer.alloc(4);return t.writeInt32LE(e|0,0),t}P.prototype.step=function(){var e=this;function t(fe){return e.stack[e.stack.length+fe]}function r(fe){switch(fe){case M.OP_2MUL:case M.OP_2DIV:if(!e.isAfterChronicle())return!0;break;case M.OP_INVERT:case M.OP_MUL:case M.OP_LSHIFT:case M.OP_RSHIFT:if((e.flags&P.SCRIPT_ENABLE_MAGNETIC_OPCODES)===0)return!0;break;case M.OP_DIV:case M.OP_MOD:case M.OP_SPLIT:case M.OP_CAT:case M.OP_AND:case M.OP_OR:case M.OP_XOR:case M.OP_BIN2NUM:case M.OP_NUM2BIN:return!1;default:break}return!1}var n=(this.flags&P.SCRIPT_VERIFY_MINIMALDATA)!==0,i,o,s,a,f,l,m,g,v,E,T,N,L,F,V,z,W,ie=this.script.chunks[this.pc];this.pc++;var ee=ie.opcodenum,ge=this.vfExec.indexOf(!1)===-1&&(!this.nonTopLevelReturnAfterGenesis||ee===M.OP_RETURN);if(Lc.isUndefined(ee))return this.errstr="SCRIPT_ERR_UNDEFINED_OPCODE",!1;if(ie.buf&&ie.buf.length>this.maxScriptElementSize())return this.errstr="SCRIPT_ERR_PUSH_SIZE",!1;if(ee>M.OP_16&&++this.nOpCount>this.maxOpsPerScript())return this.errstr="SCRIPT_ERR_OP_COUNT",!1;if(r(ee)&&(!this.isAfterGenesis()||ge))return this.errstr="SCRIPT_ERR_DISABLED_OPCODE",!1;if(ge&&ee>=0&&ee<=M.OP_PUSHDATA4){if(n&&!this.script.checkMinimalPush(this.pc-1))return this.errstr="SCRIPT_ERR_MINIMALDATA",!1;if(!ie.buf)this.stack.push(P.false);else{if(ie.len!==ie.buf.length)return this.errstr="SCRIPT_ERR_BAD_OPCODE",!1;this.stack.push(ie.buf)}}else if(ge||M.OP_IF<=ee&&ee<=M.OP_ENDIF)switch(ee){case M.OP_1NEGATE:case M.OP_1:case M.OP_2:case M.OP_3:case M.OP_4:case M.OP_5:case M.OP_6:case M.OP_7:case M.OP_8:case M.OP_9:case M.OP_10:case M.OP_11:case M.OP_12:case M.OP_13:case M.OP_14:case M.OP_15:case M.OP_16:f=ee-(M.OP_1-1),i=new he(f).toScriptNumBuffer(),this.stack.push(i);break;case M.OP_NOP:break;case M.OP_NOP2:case M.OP_CHECKLOCKTIMEVERIFY:if(!(this.flags&P.SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)||this.isAfterGenesis()){if(this.flags&P.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 ce=he.fromScriptNumBuffer(this.stack[this.stack.length-1],n,5);if(ce.lt(new he(0)))return this.errstr="SCRIPT_ERR_NEGATIVE_LOCKTIME",!1;if(!this.checkLockTime(ce))return this.errstr="SCRIPT_ERR_UNSATISFIED_LOCKTIME",!1;break;case M.OP_NOP3:case M.OP_CHECKSEQUENCEVERIFY:if(!(this.flags&P.SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)||this.isAfterGenesis()){if(this.flags&P.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 me=he.fromScriptNumBuffer(t(-1),n,5);if(me.lt(new he(0)))return this.errstr="SCRIPT_ERR_NEGATIVE_LOCKTIME",!1;if((me&P.SEQUENCE_LOCKTIME_DISABLE_FLAG)!==0)break;if(!this.checkSequence(me))return this.errstr="SCRIPT_ERR_UNSATISFIED_LOCKTIME",!1;break;case M.OP_NOP1:case M.OP_NOP9:case M.OP_NOP10:if(this.flags&P.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)return this.errstr="SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS",!1;break;case M.OP_LSHIFTNUM:case M.OP_RSHIFTNUM:if(!this.isAfterChronicle()){if(this.flags&P.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 I=this.maxScriptNumLength(),u=he.fromScriptNumBuffer(t(-1),n,I);if(u.isNeg())return this.errstr="SCRIPT_ERR_INVALID_NUMBER_RANGE",!1;this.stack.pop();var h=he.fromScriptNumBuffer(t(-1),n,I);this.stack.pop();var y=u.toNumber(),w=h.isNeg(),S=h.abs(),R;if(ee===M.OP_LSHIFTNUM){var A=h.toScriptNumBuffer().length;if(A+Math.floor(y/8)>I)return this.errstr="SCRIPT_ERR_SCRIPTNUM_OVERFLOW",!1;R=S.shln(y)}else R=y>=S.bitLength()?new he(0):S.shrn(y);if(w&&!R.isZero()&&(R=R.neg()),R.toScriptNumBuffer().length>I)return this.errstr="SCRIPT_ERR_SCRIPTNUM_OVERFLOW",!1;this.stack.push(R.toScriptNumBuffer());break;case M.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(Ex(this.tx.version));break;case M.OP_VERIF:case M.OP_VERNOTIF:if(!this.isAfterChronicle()){if(this.isAfterGenesis()&&!ge)break;return this.errstr="SCRIPT_ERR_BAD_OPCODE",!1}if(z=!1,ge){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),z=i.length===4&&i.equals(Ex(this.tx.version)),ee===M.OP_VERNOTIF&&(z=!z),this.stack.pop()}this.vfExec.push(z),this.vfElse.push(!1);break;case M.OP_IF:case M.OP_NOTIF:if(z=!1,ge){if(this.stack.length<1)return this.errstr="SCRIPT_ERR_UNBALANCED_CONDITIONAL",!1;if(i=t(-1),this.flags&P.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}z=P.castToBool(i),ee===M.OP_NOTIF&&(z=!z),this.stack.pop()}this.vfExec.push(z),this.vfElse.push(!1);break;case M.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 M.OP_ENDIF:if(this.vfExec.length===0)return this.errstr="SCRIPT_ERR_UNBALANCED_CONDITIONAL",!1;this.vfExec.pop(),this.vfElse.pop();break;case M.OP_VERIFY:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(i=t(-1),z=P.castToBool(i),z)this.stack.pop();else return this.errstr="SCRIPT_ERR_VERIFY",!1;break;case M.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 M.OP_TOALTSTACK:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.altstack.push(this.stack.pop());break;case M.OP_FROMALTSTACK:if(this.altstack.length<1)return this.errstr="SCRIPT_ERR_INVALID_ALTSTACK_OPERATION",!1;this.stack.push(this.altstack.pop());break;case M.OP_2DROP:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.stack.pop(),this.stack.pop();break;case M.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 M.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 M.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 M.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 M.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 M.OP_IFDUP:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;i=t(-1),z=P.castToBool(i),z&&this.stack.push(d.Buffer.from(i));break;case M.OP_DEPTH:i=new he(this.stack.length).toScriptNumBuffer(),this.stack.push(i);break;case M.OP_DROP:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.stack.pop();break;case M.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 M.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 M.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 M.OP_PICK:case M.OP_ROLL:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(i=t(-1),g=he.fromScriptNumBuffer(i,n,this.maxScriptNumLength()),f=g.toNumber(),this.stack.pop(),f<0||f>=this.stack.length)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;i=t(-f-1),ee===M.OP_ROLL&&this.stack.splice(this.stack.length-f-1,1),this.stack.push(d.Buffer.from(i));break;case M.OP_ROT:if(this.stack.length<3)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;l=t(-3),m=t(-2);var c=t(-1);this.stack[this.stack.length-3]=m,this.stack[this.stack.length-2]=c,this.stack[this.stack.length-1]=l;break;case M.OP_SWAP:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;l=t(-2),m=t(-1),this.stack[this.stack.length-2]=m,this.stack[this.stack.length-1]=l;break;case M.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 M.OP_SIZE:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;g=new he(t(-1).length),this.stack.push(g.toScriptNumBuffer());break;case M.OP_AND:case M.OP_OR:case M.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(ee){case M.OP_AND:for(let fe=0;fe<o.length;fe++)o[fe]&=s[fe];break;case M.OP_OR:for(let fe=0;fe<o.length;fe++)o[fe]|=s[fe];break;case M.OP_XOR:for(let fe=0;fe<o.length;fe++)o[fe]^=s[fe];break;default:break}this.stack.pop();break;case M.OP_INVERT:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;i=t(-1);for(let fe=0;fe<i.length;fe++)i[fe]=~i[fe];break;case M.OP_LSHIFT:case M.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(v=new he(o),E=he.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength()),f=E.toNumber(),f<0)return this.errstr="SCRIPT_ERR_INVALID_NUMBER_RANGE",!1;this.stack.pop(),this.stack.pop();let fe;ee===M.OP_LSHIFT&&(fe=v.ushln(f)),ee===M.OP_RSHIFT&&(fe=v.ushrn(f));let de=aC(d.Buffer.from(fe.toArray().slice(o.length*-1)),o.length);this.stack.push(de)}break;case M.OP_EQUAL:case M.OP_EQUALVERIFY:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;o=t(-2),s=t(-1);var b=o.toString("hex")===s.toString("hex");if(this.stack.pop(),this.stack.pop(),this.stack.push(b?P.true:P.false),ee===M.OP_EQUALVERIFY)if(b)this.stack.pop();else return this.errstr="SCRIPT_ERR_EQUALVERIFY",!1;break;case M.OP_2MUL:case M.OP_2DIV:case M.OP_1ADD:case M.OP_1SUB:case M.OP_NEGATE:case M.OP_ABS:case M.OP_NOT:case M.OP_0NOTEQUAL:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;switch(i=t(-1),g=he.fromScriptNumBuffer(i,n,this.maxScriptNumLength()),ee){case M.OP_2MUL:g=g.mul(new he(2));break;case M.OP_2DIV:g=g.div(new he(2));break;case M.OP_1ADD:g=g.add(he.One);break;case M.OP_1SUB:g=g.sub(he.One);break;case M.OP_NEGATE:g=g.neg();break;case M.OP_ABS:g.cmp(he.Zero)<0&&(g=g.neg());break;case M.OP_NOT:g=new he((g.cmp(he.Zero)===0)+0);break;case M.OP_0NOTEQUAL:g=new he((g.cmp(he.Zero)!==0)+0);break}this.stack.pop(),this.stack.push(g.toScriptNumBuffer());break;case M.OP_ADD:case M.OP_SUB:case M.OP_MUL:case M.OP_MOD:case M.OP_DIV:case M.OP_BOOLAND:case M.OP_BOOLOR:case M.OP_NUMEQUAL:case M.OP_NUMEQUALVERIFY:case M.OP_NUMNOTEQUAL:case M.OP_LESSTHAN:case M.OP_GREATERTHAN:case M.OP_LESSTHANOREQUAL:case M.OP_GREATERTHANOREQUAL:case M.OP_MIN:case M.OP_MAX:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;switch(v=he.fromScriptNumBuffer(t(-2),n,this.maxScriptNumLength()),E=he.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength()),g=new he(0),ee){case M.OP_ADD:g=v.add(E);break;case M.OP_SUB:g=v.sub(E);break;case M.OP_MUL:g=v.mul(E);break;case M.OP_DIV:if(E.cmp(he.Zero)===0)return this.errstr="SCRIPT_ERR_DIV_BY_ZERO",!1;g=v.div(E);break;case M.OP_MOD:if(E.cmp(he.Zero)===0)return this.errstr="SCRIPT_ERR_MOD_BY_ZERO",!1;g=v.mod(E);break;case M.OP_BOOLAND:g=new he((v.cmp(he.Zero)!==0&&E.cmp(he.Zero)!==0)+0);break;case M.OP_BOOLOR:g=new he((v.cmp(he.Zero)!==0||E.cmp(he.Zero)!==0)+0);break;case M.OP_NUMEQUAL:g=new he((v.cmp(E)===0)+0);break;case M.OP_NUMEQUALVERIFY:g=new he((v.cmp(E)===0)+0);break;case M.OP_NUMNOTEQUAL:g=new he((v.cmp(E)!==0)+0);break;case M.OP_LESSTHAN:g=new he((v.cmp(E)<0)+0);break;case M.OP_GREATERTHAN:g=new he((v.cmp(E)>0)+0);break;case M.OP_LESSTHANOREQUAL:g=new he((v.cmp(E)<=0)+0);break;case M.OP_GREATERTHANOREQUAL:g=new he((v.cmp(E)>=0)+0);break;case M.OP_MIN:g=v.cmp(E)<0?v:E;break;case M.OP_MAX:g=v.cmp(E)>0?v:E;break}if(this.stack.pop(),this.stack.pop(),this.stack.push(g.toScriptNumBuffer()),ee===M.OP_NUMEQUALVERIFY)if(P.castToBool(t(-1)))this.stack.pop();else return this.errstr="SCRIPT_ERR_NUMEQUALVERIFY",!1;break;case M.OP_WITHIN:if(this.stack.length<3)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;v=he.fromScriptNumBuffer(t(-3),n,this.maxScriptNumLength()),E=he.fromScriptNumBuffer(t(-2),n,this.maxScriptNumLength());var k=he.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength());z=E.cmp(v)<=0&&v.cmp(k)<0,this.stack.pop(),this.stack.pop(),this.stack.pop(),this.stack.push(z?P.true:P.false);break;case M.OP_RIPEMD160:case M.OP_SHA1:case M.OP_SHA256:case M.OP_HASH160:case M.OP_HASH256:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;i=t(-1);var D;ee===M.OP_RIPEMD160?D=ja.ripemd160(i):ee===M.OP_SHA1?D=ja.sha1(i):ee===M.OP_SHA256?D=ja.sha256(i):ee===M.OP_HASH160?D=ja.sha256ripemd160(i):ee===M.OP_HASH256&&(D=ja.sha256sha256(i)),this.stack.pop(),this.stack.push(D);break;case M.OP_CODESEPARATOR:this.pbegincodehash=this.pc;break;case M.OP_CHECKSIG:case M.OP_CHECKSIGVERIFY:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(T=t(-2),N=t(-1),!this.checkSignatureEncoding(T)||!this.checkPubkeyEncoding(N))return!1;L=new Ha().set({chunks:this.script.chunks.slice(this.pbegincodehash)});var K=new Ha().add(T);L.findAndDelete(K);try{F=_i.fromTxFormat(T),V=Np.fromBuffer(N,!1),W=this.tx.verifySignature(F,V,this.nin,L,this.satoshisBN,this.flags)}catch{W=!1}if(!W&&this.flags&P.SCRIPT_VERIFY_NULLFAIL&&T.length)return this.errstr="SCRIPT_ERR_NULLFAIL",!1;if(this.stack.pop(),this.stack.pop(),this.stack.push(W?P.true:P.false),ee===M.OP_CHECKSIGVERIFY)if(W)this.stack.pop();else return this.errstr="SCRIPT_ERR_CHECKSIGVERIFY",!1;break;case M.OP_CHECKMULTISIG:case M.OP_CHECKMULTISIGVERIFY:var G=1;if(this.stack.length<G)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;var X=he.fromScriptNumBuffer(t(-G),n,this.maxScriptNumLength()).toNumber();if(X<0||X>this.maxPubKeysPerMultisig())return this.errstr="SCRIPT_ERR_PUBKEY_COUNT",!1;if(this.nOpCount+=X,this.nOpCount>this.maxOpsPerScript())return this.errstr="SCRIPT_ERR_OP_COUNT",!1;var Z=++G;G+=X;var le=X+2;if(this.stack.length<G)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;var se=he.fromScriptNumBuffer(t(-G),n,this.maxScriptNumLength()).toNumber();if(se<0||se>X)return this.errstr="SCRIPT_ERR_SIG_COUNT",!1;var O=++G;if(G+=se,this.stack.length<G)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;L=new Ha().set({chunks:this.script.chunks.slice(this.pbegincodehash)});for(var C=0;C<se;C++)T=t(-O-C),L.findAndDelete(new Ha().add(T));for(W=!0;W&&se>0;){if(T=t(-O),N=t(-Z),!this.checkSignatureEncoding(T)||!this.checkPubkeyEncoding(N))return!1;var U;try{F=_i.fromTxFormat(T),V=Np.fromBuffer(N,!1),U=this.tx.verifySignature(F,V,this.nin,L,this.satoshisBN,this.flags)}catch{U=!1}U&&(O++,se--),Z++,X--,se>X&&(W=!1)}for(;G-- >1;){if(!W&&this.flags&P.SCRIPT_VERIFY_NULLFAIL&&!le&&t(-1).length)return this.errstr="SCRIPT_ERR_NULLFAIL",!1;le>0&&le--,this.stack.pop()}if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(this.flags&P.SCRIPT_VERIFY_NULLDUMMY&&t(-1).length)return this.errstr="SCRIPT_ERR_SIG_NULLDUMMY",!1;if(this.stack.pop(),this.stack.push(W?P.true:P.false),ee===M.OP_CHECKMULTISIGVERIFY)if(W)this.stack.pop();else return this.errstr="SCRIPT_ERR_CHECKMULTISIGVERIFY",!1;break;case M.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 M.OP_SPLIT:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;o=t(-2);var j=he.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength()).toNumber();if(j<0||j>o.length)return this.errstr="SCRIPT_ERR_INVALID_SPLIT_RANGE",!1;var re=d.Buffer.from(o);this.stack[this.stack.length-2]=re.slice(0,j),this.stack[this.stack.length-1]=re.slice(j);break;case M.OP_LEFT:case M.OP_RIGHT:if(!this.isAfterChronicle()){if(this.flags&P.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),f=he.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength()).toNumber(),f<0||f>o.length)return this.errstr="SCRIPT_ERR_INVALID_NUMBER_RANGE",!1;this.stack.pop(),ee===M.OP_LEFT?this.stack[this.stack.length-1]=d.Buffer.from(o).slice(0,f):this.stack[this.stack.length-1]=d.Buffer.from(o).slice(o.length-f);break;case M.OP_SUBSTR:if(!this.isAfterChronicle()){if(this.flags&P.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 J=he.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength()).toNumber(),te=he.fromScriptNumBuffer(t(-2),n,this.maxScriptNumLength()).toNumber();if(te<0||te>=o.length||J<0||J>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+J);break;case M.OP_NUM2BIN:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;var ae=he.fromScriptNumBuffer(t(-1),n,this.maxScriptNumLength()).toNumber();if(ae<0||ae>this.maxScriptElementSize())return this.errstr="SCRIPT_ERR_PUSH_SIZE",!1;this.stack.pop();var oe=t(-1);if(oe=P._minimallyEncode(oe),oe.length>ae)return this.errstr="SCRIPT_ERR_IMPOSSIBLE_ENCODING",!1;if(oe.length===ae){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 _e=d.Buffer.alloc(ae);oe.copy(_e,0);for(var Se=oe.length-1;Se++<ae-2;)_e[Se]=0;_e[Se]=ue,this.stack[this.stack.length-1]=_e;break;case M.OP_BIN2NUM:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(o=t(-1),s=P._minimallyEncode(o),this.stack[this.stack.length-1]=s,!P._isMinimallyEncoded(s,this.maxScriptNumLength()))return this.errstr="SCRIPT_ERR_INVALID_NUMBER_RANGE",!1;break;default:return this.errstr="SCRIPT_ERR_BAD_OPCODE",!1}return!0}});var qr=B((lq,kp)=>{p();kp.exports=dp();kp.exports.Interpreter=Nc()});var no=B((dq,Rx)=>{"use strict";p();var Cp=ze(),qn=Le(),uC=Xn(),Ix=Kd(),Rr=ya(),Ax=Jt(),Ox=pr(),Lp=Ar();function ne(e,t,r){if(!(this instanceof ne))return new ne(e,t,r);if(Cp.isArray(e)&&Cp.isNumber(t))return ne.createMultisig(e,t,r);if(e instanceof ne)return e;if(qn.checkArgument(e,"First argument is required, please include address data.","guide/address.html"),t&&!Rr.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||Rr.get(t)||Rr.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 Lp)return ne._transformPublicKey(e);if(e instanceof Ka())return ne._transformScript(e,t);if(typeof e=="string")return ne._transformString(e,t,r);if(Cp.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 qn.checkArgument(e.hash||e.hashBuffer,"Must provide a `hash` or `hashBuffer` property"),qn.checkArgument(e.type,"Must provide a `type` property"),{hashBuffer:e.hash?d.Buffer.from(e.hash,"hex"):e.hashBuffer,network:Rr.get(e.network)||Rr.defaultNetwork,type:e.type}};ne._classifyFromVersion=function(e){var t={},r=Rr.get(e[0],"pubkeyhash"),n=Rr.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=Rr.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 Lp))throw new TypeError("Address must be an instance of PublicKey.");return t.hashBuffer=Ax.sha256ripemd160(e.toBuffer()),t.type=ne.PayToPublicKeyHash,t};ne._transformScript=function(e,t){qn.checkArgument(e instanceof Ka(),"script must be a Script instance");var r=e.getAddressInfo(t);if(!r)throw new uC.Script.CantDeriveAddress(e);return r};ne.createMultisig=function(e,t,r){return r=r||e[0].network||Rr.defaultNetwork,ne.payingTo(Ka().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=Rr.get(t);if(t&&!n)throw new TypeError("Unknown network");var i=Ix.decode(e);return ne._transformBuffer(i,t,r)};ne.fromPublicKey=function(e,t){var r=ne._transformPublicKey(e);return t=t||Rr.defaultNetwork,new ne(r.hashBuffer,t,r.type)};ne.fromPrivateKey=function(e,t){let r=Lp.fromPrivateKey(e);return t=t||e.network||Rr.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){qn.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 qn.checkArgument(e,"script is required"),qn.checkArgument(e instanceof Ka(),"script must be instance of Script"),ne.fromScriptHash(Ax.sha256ripemd160(e.toBuffer()),t)};ne.fromScript=function(e,t){qn.checkArgument(e instanceof Ka(),"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){qn.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 Ix.encode(this.toBuffer())};Rx.exports=ne;function Ka(){return qr()}});var io=B((gq,Nx)=>{"use strict";p();var Dc=ze(),fC=no(),Tx=Kd(),wi=Sr(),Px=pr(),hn=ya(),Up=ui(),cC=Ar(),lC=Qs(),Bx=Le(),Dp="[REDACTED]";function ve(e,t){if(!(this instanceof ve))return new ve(e,t);if(e instanceof ve)return e;var r=this._classifyArguments(e,t);if(!r.bn||r.bn.cmp(new wi(0))===0)throw new TypeError("Number can not be equal to zero, undefined, null or false");if(!r.bn.lt(Up.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 Px.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}ve.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=ve._getRandomBN();else if(e instanceof wi)r.bn=e;else if(e instanceof d.Buffer||e instanceof Uint8Array)r=ve._transformBuffer(e,t);else if(e.bn&&e.network)r=ve._transformObject(e);else if(!t&&hn.get(e))r.bn=ve._getRandomBN(),r.network=hn.get(e);else if(typeof e=="string")Px.isHexa(e)?r.bn=new wi(d.Buffer.from(e,"hex")):r=ve._transformWIF(e,t);else throw new TypeError("First argument is an unrecognized data type.");return r};ve._getRandomBN=function(){var e,t;do{var r=lC.getRandomBuffer(32);t=wi.fromBuffer(r),e=t.lt(Up.getN())}while(!e);return t};ve._transformBuffer=function(e,t){var r={};if(e.length===32)return ve._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=wi.fromBuffer(e.slice(1,33)),r};ve._transformBNBuffer=function(e,t,r){var n={};return n.network=hn.get(t)||hn.defaultNetwork,n.bn=wi.fromBuffer(e),n.compressed=r===void 0?!0:!!r,n};ve._transformWIF=function(e,t){return ve._transformBuffer(Tx.decode(e),t)};ve.fromBuffer=function(e,t,r){return r!==void 0&&e&&e.length===32?new ve(ve._transformBNBuffer(e,t,r)):new ve(e,t)};ve.fromHex=function(e,t,r){return ve.fromBuffer(d.Buffer.from(e,"hex"),t,r)};ve._transformObject=function(e){if(e.bn instanceof wi)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===Dp)throw new TypeError('Invalid private key: `bn` is "'+Dp+'". 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 wi(e.bn,"hex");if(t.isZero()||t.gte(Up.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}};ve.fromString=ve.fromWIF=function(e,t){return Bx.checkArgument(Dc.isString(e),"First argument is expected to be a string."),new ve(e,t)};ve.fromObject=ve.fromJSON=function(e){return Bx.checkArgument(Dc.isObject(e),"First argument is expected to be an object."),new ve(e)};ve.fromRandom=function(e){var t=ve._getRandomBN();return new ve(t,e)};ve.getValidationError=function(e,t){var r;try{new ve(e,t)}catch(n){r=n}return r};ve.isValid=function(e,t){return e?!ve.getValidationError(e,t):!1};ve.prototype.toString=function(){return this.toWIF()};ve.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})]),Tx.encode(r)};ve.prototype.toBigNumber=function(){return this.bn};ve.prototype.toBuffer=function(){return this.bn.toBuffer({size:32})};ve.prototype.toHex=function(){return this.toBuffer().toString("hex")};ve.prototype.toPublicKey=function(){return this._pubkey||(this._pubkey=cC.fromPrivateKey(this)),this._pubkey};ve.prototype.toAddress=function(e){var t=this.toPublicKey();return fC.fromPublicKey(t,e||this.network)};ve.prototype.toObject=function(){return{bn:this.bn.toString("hex"),compressed:this.compressed,network:this.network.toString()}};ve.prototype.toJSON=function(){return{bn:Dp,compressed:this.compressed,network:this.network.toString()}};ve.prototype.inspect=function(){var e=this.compressed?"":", uncompressed";return"<PrivateKey: "+this.toHex()+", network: "+this.network+e+">"};Nx.exports=ve});var Ar=B((mq,kx)=>{"use strict";p();var us=Sr(),fs=ui(),hC=Jt(),dC=pr(),Mx=ya(),Fp=ze(),so=Le();function pe(e,t){if(!(this instanceof pe))return new pe(e,t);if(so.checkArgument(e,"First argument is required, please include public key data."),e instanceof pe)return e;t=t||{};var r=this._classifyArgs(e,t);return r.point.validate(),dC.defineImmutable(this,{point:r.point,compressed:r.compressed,network:r.network||Mx.defaultNetwork}),this}pe.prototype._classifyArgs=function(e,t){var r={compressed:Fp.isUndefined(t.compressed)||t.compressed};if(e instanceof fs)r.point=e;else if(e.x&&e.y)r=pe._transformObject(e);else if(typeof e=="string")r=pe._transformDER(d.Buffer.from(e,"hex"));else if(pe._isBuffer(e))r=pe._transformDER(e);else if(pe._isPrivateKey(e))r=pe._transformPrivateKey(e);else throw new TypeError("First argument is an unrecognized data format.");return r.network||(r.network=Fp.isUndefined(t.network)?void 0:Mx.get(t.network)),r};pe._isPrivateKey=function(e){var t=io();return e instanceof t};pe._isBuffer=function(e){return e instanceof d.Buffer||e instanceof Uint8Array};pe._transformPrivateKey=function(e){so.checkArgument(pe._isPrivateKey(e),"Must be an instance of PrivateKey");var t={};return t.point=fs.getG().mul(e.bn),t.compressed=e.compressed,t.network=e.network,t};pe._transformDER=function(e,t){so.checkArgument(pe._isBuffer(e),"Must be a buffer of DER encoded public key");var r={};t=Fp.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 us(o),i=new us(s),r.point=new fs(n,i),r.compressed=!1}else if(e[0]===3)o=e.slice(1),n=new us(o),r=pe._transformX(!0,n),r.compressed=!0;else if(e[0]===2)o=e.slice(1),n=new us(o),r=pe._transformX(!1,n),r.compressed=!0;else throw new TypeError("Invalid DER format public key");return r};pe._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=fs.fromX(e,t),r};pe._transformObject=function(e){var t=new us(e.x,"hex"),r=new us(e.y,"hex"),n=new fs(t,r);return new pe(n,{compressed:e.compressed})};pe.fromPrivateKey=function(e){so.checkArgument(pe._isPrivateKey(e),"Must be an instance of PrivateKey");var t=pe._transformPrivateKey(e);return new pe(t.point,{compressed:t.compressed,network:t.network})};pe.fromDER=pe.fromBuffer=function(e,t){so.checkArgument(pe._isBuffer(e),"Must be a buffer of DER encoded public key");var r=pe._transformDER(e,t);return new pe(r.point,{compressed:r.compressed})};pe.fromPoint=function(e,t){return so.checkArgument(e instanceof fs,"First argument must be an instance of Point."),new pe(e,{compressed:t})};pe.fromHex=pe.fromString=function(e,t){var r=d.Buffer.from(e,t||"hex"),n=pe._transformDER(r);return new pe(n.point,{compressed:n.compressed})};pe.fromX=function(e,t){var r=pe._transformX(e,t);return new pe(r.point,{compressed:r.compressed})};pe.getValidationError=function(e){var t;try{new pe(e)}catch(r){t=r}return t};pe.isValid=function(e){return!pe.getValidationError(e)};pe.prototype.toObject=pe.prototype.toJSON=function(){return{x:this.point.getX().toString("hex",2),y:this.point.getY().toString("hex",2),compressed:this.compressed}};pe.prototype.toBuffer=pe.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])};pe.prototype._getID=function(){return hC.sha256ripemd160(this.toBuffer())};pe.prototype.toAddress=function(e){var t=no();return t.fromPublicKey(this,e||this.network)};pe.prototype.toString=pe.prototype.toHex=function(){return this.toDER().toString("hex")};pe.prototype.inspect=function(){return"<PublicKey: "+this.toHex()+(this.compressed?"":", uncompressed")+">"};kx.exports=pe});var Ga=B((bq,Lx)=>{"use strict";p();var Cx=Qs();function pC(){var e=Cx.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 gC(e){return Cx.getRandomBuffer(Math.ceil(e/2)).toString("hex").substring(0,e)}Lx.exports={uuid4:pC,randomHex:gC}});var jx=B((Sq,qx)=>{"use strict";p();var Va=Ar(),qp=Jt(),jp=Ca(),Dx=nr(),Hp=io(),Bt=Le(),wq=ze(),yC=Ga();function Ux(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 cs={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"},Fx={create:function(e,t,r,n,i,o){o=o||{},Bt.checkArgument(typeof e=="string","Right type must be string"),Bt.checkArgument(typeof t=="string","Issuer DID must be string"),Bt.checkArgument(typeof r=="string","Subject DID must be string"),Bt.checkArgument(n&&typeof n=="object","Claim must be object");var s=Object.values(cs);Bt.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||{},Bt.checkArgument(typeof e=="string","Right type must be string"),Bt.checkArgument(typeof t=="string","Issuer DID must be string"),Bt.checkArgument(typeof r=="string","Subject DID must be string"),Bt.checkArgument(n&&typeof n=="object","Claim must be object"),Bt.checkArgument(i instanceof Hp,"Invalid issuer private key");var s=Object.values(cs);Bt.checkArgument(s.includes(e),"Invalid right type: "+e);try{var a=this.create(e,t,r,n,i,o),f=this._signToken(a,i);return{success:!0,rightToken:f,tokenHash:f.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:f,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:f.id,tokenHash:f.tokenHash,type:e,issuer:t,subject:r,issuedAt:f.issuanceDate}},notifyParties:{endpoint:"POST /notifications/right-issued",data:{tokenId:f.id,issuer:t,subject:r,rightType:e}}}}}catch(l){return{success:!1,error:l.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||{},Bt.checkArgument(e&&typeof e=="object","Invalid token"),Bt.checkArgument(typeof t=="string","New owner DID must be string"),Bt.checkArgument(r instanceof Hp,"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=Ux({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}},f=this._signToken(a,r),l=JSON.parse(JSON.stringify(e));l.id="urn:uuid:"+this._generateUUID(),l.issuanceDate=new Date().toISOString(),l.credentialSubject.id=t,l.credentialSubject.transferHistory=l.credentialSubject.transferHistory||[],l.credentialSubject.transferHistory.push({transferId:f.id,transferDate:f.issuanceDate,from:e.credentialSubject.id,to:t}),delete l.proof;var m=this._signToken(l,r);return{success:!0,newToken:m,transferProof:f,transferId:f.id,externalOperations:{recordTransfer:{endpoint:"POST /rights/transfers",data:{originalTokenId:e.id,newTokenId:m.id,transferProof:f,fromOwner:e.credentialSubject.id,toOwner:t,transferDate:f.issuanceDate}},updateOwnership:{endpoint:"PUT /rights/tokens/"+e.id+"/ownership",data:{newOwner:t,transferId:f.id,transferDate:f.issuanceDate,previousOwner:e.credentialSubject.id}},notifyParties:{endpoint:"POST /notifications/right-transferred",data:{originalTokenId:e.id,newTokenId:m.id,fromOwner:e.credentialSubject.id,toOwner:t,rightType:e.credentialSubject.rightType}},auditTransfer:{endpoint:"POST /audit/right-transfer",data:{originalTokenId:e.id,newTokenId:m.id,transferId:f.id,fromOwner:e.credentialSubject.id,toOwner:t,transferredAt:f.issuanceDate}}}}}catch(g){return{success:!1,error:g.message}}},prepareObligationToken:function(e,t,r,n){Bt.checkArgument(e&&typeof e=="object","Invalid right token"),Bt.checkArgument(typeof t=="string","Obligor DID must be string"),Bt.checkArgument(r&&typeof r=="object","Obligation must be object"),Bt.checkArgument(n instanceof Hp,"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){Bt.checkArgument(typeof e=="string","Right type must be string");var t=Object.values(cs),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 cs},verifyToken:function(e,t){var r=[];try{if(Bt.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=qp.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=Dx.fromDER(d.Buffer.from(s[2],"base64url")),f=new jp;return f.hashbuf=o,f.sig=a,f.pubkey=n,f.verify()||r.push("Signature verification failed"),{valid:r.length===0,errors:r,tokenHash:o.toString("hex"),verifiedAt:new Date().toISOString()}}catch(l){return r.push(l.message),{valid:!1,errors:r}}},_signToken:function(e,t){var r=this._canonicalizeToken(e),n=qp.sha256(d.Buffer.from(r)),i=new jp;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=qp.sha256(d.Buffer.from(n));if(e.tokenHash&&e.tokenHash!==i.toString("hex")){t.push("Token hash mismatch");return}var o=Ux(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=Dx.fromDER(d.Buffer.from(s[2],"base64url")),f=new jp;f.hashbuf=i,f.sig=a,f.pubkey=o,f.verify()!==!0&&t.push("Signature verification failed")}catch(l){t.push("Signature verification failed: "+l.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(cs);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 yC.uuid4()}};Fx.RightTypes=cs;qx.exports=Fx});var Gx=B((xq,Kx)=>{"use strict";p();var Hx={};Hx.stringify=function(e){return Kp(e,[])};function Kp(e,t){if(e===null)return"null";var r=typeof e;if(r==="boolean")return e?"true":"false";if(r==="number"){if(!isFinite(e))throw new Error("Cannot canonicalize non-finite number: "+e);return JSON.stringify(e)}if(r==="string")return JSON.stringify(e);if(r==="bigint")throw new Error("Cannot canonicalize bigint; represent it as a string");if(Array.isArray(e)||r==="object"){if(t.indexOf(e)!==-1)throw new Error("Cannot canonicalize a circular structure");t.push(e);var n;if(Array.isArray(e))n="["+e.map(function(o){return o===void 0?"null":Kp(o,t)}).join(",")+"]";else{var i=Object.keys(e).filter(function(o){return e[o]!==void 0&&typeof e[o]!="function"}).sort();n="{"+i.map(function(o){return JSON.stringify(o)+":"+Kp(e[o],t)}).join(",")+"}"}return t.pop(),n}throw new Error("Cannot canonicalize value of type: "+r)}Kx.exports=Hx});var zx=B((Aq,Wx)=>{"use strict";p();var Gp=Object.create(null),Vp=[],Wp=!(typeof x.default<"u"&&x.default.env&&x.default.env.BSV_NO_DEPRECATION_WARNINGS==="1");function Vx(e,t){if(!e||typeof e.what!="string"||e.what==="")throw new TypeError(t+"() requires { what: string }")}function mC(e){var t="[@smartledger/bsv] "+e.what+" is deprecated";return e.since&&(t+=" since "+e.since),t+=".",e.why&&(t+=" "+e.why.charAt(0).toUpperCase()+e.why.slice(1)+"."),e.use&&(t+=" Use "+e.use+" instead."),t+=e.removeIn?" It will be removed in "+e.removeIn+".":" A removal version has not been set; it will not be removed in a 9.x release.",t}function jn(e){if(!e||!e.what)throw new TypeError("deprecate() requires { what }");if(Gp[e.what])return!1;Gp[e.what]=!0;var t=mC(e);return Vp.push({what:e.what,since:e.since||null,removeIn:e.removeIn||null,use:e.use||null,message:t}),Wp&&console.warn(t),!0}jn.fn=function(e,t){if(typeof e!="function")throw new TypeError("deprecate.fn() requires a function");Vx(t,"deprecate.fn");var r=function(){return jn(t),e.apply(this,arguments)};return Object.defineProperty(r,"name",{value:e.name,configurable:!0}),Object.defineProperty(r,"length",{value:e.length,configurable:!0}),r.__wrapped=e,r.__deprecation=t,r};jn.property=function(e,t,r,n){Vx(n,"deprecate.property");var i,o=!1;return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get:function(){return jn(n),o||(i=r(),o=!0),i}}),e};jn.fired=function(){return Vp.slice()};jn.setEnabled=function(e){Wp=!!e};jn.isEnabled=function(){return Wp};jn.reset=function(){Gp=Object.create(null),Vp.length=0};Wx.exports=jn});var $x=B((Rq,Yx)=>{"use strict";p();var ls=Jt(),cr=Le(),vC=Ga(),bC=Gx(),_C=zx(),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"}}}},wC={prepareClaimValidation:function(e,t){try{cr.checkArgument(e&&typeof e=="object","Invalid claim"),cr.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:ls.sha256(d.Buffer.from(this._canonicalizeWith(e,this.CANONICALIZATION.LEGACY))).toString("hex"),canonical:this._canonicalizeWith(e,this.CANONICALIZATION.LEGACY)};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{cr.checkArgument(e&&typeof e=="object","Invalid claim"),cr.checkArgument(typeof t=="string","Schema name must be string"),cr.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=ls.sha256(d.Buffer.from(this._canonicalizeWith(i,this.CANONICALIZATION.LEGACY))).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{cr.checkArgument(typeof e=="string","Claim hash must be string"),cr.checkArgument(t&&typeof t=="object","Invalid disputant"),cr.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=ls.sha256(d.Buffer.from(this._canonicalizeWith(n,this.CANONICALIZATION.LEGACY))).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{cr.checkArgument(Array.isArray(e),"Claims must be array"),cr.checkArgument(typeof t=="string","Schema name must be string");var r=[],n=[],i=0;e.forEach(function(a,f){try{var l=this.prepareClaimValidation(a,t);l.success&&l.validation.valid&&i++,r.push({index:f,result:l})}catch(m){n.push({index:f,error:m.message})}}.bind(this));var o=this._generateBatchId(),s=ls.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}}},CANONICALIZATION:{JCS:"jcs",LEGACY:"legacy"},canonicalize:function(e,t){return this._canonicalizeWith(e,this._resolveCanonicalization(t,"LTP.Claim.canonicalize"))},hash:function(e,t){var r=this._canonicalizeWith(e,this._resolveCanonicalization(t,"LTP.Claim.hash"));return ls.sha256(d.Buffer.from(r)).toString("hex")},_canonicalizeWith:function(e,t){if(cr.checkArgument(e&&typeof e=="object","Invalid claim"),t===this.CANONICALIZATION.JCS)return bC.stringify(e);var r=this._sortObjectKeys(e);return JSON.stringify(r)},_resolveCanonicalization:function(e,t){return e===void 0?(_C({what:t+"() without a canonicalization argument",since:"9.2.0",removeIn:"10.0.0",use:t+"(claim, bsv.LTP.Claim.CANONICALIZATION.JCS)",why:"the default sorted-key form is not RFC 8785, so other implementations compute a different claim hash"}),this.CANONICALIZATION.LEGACY):(cr.checkArgument(e===this.CANONICALIZATION.JCS||e===this.CANONICALIZATION.LEGACY,"Unknown canonicalization: "+e+". Expected 'jcs' or 'legacy' (bsv.LTP.Claim.CANONICALIZATION)"),e)},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){cr.checkArgument(typeof e=="string","Schema name must be string"),cr.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 ls.sha256(d.Buffer.from(t)).toString("hex").substring(0,16)},_generateBatchId:function(){return vC.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())}};Yx.exports=wC});var Xx=B((Pq,Zx)=>{"use strict";p();var Wa=Jt(),hs=Le(),SC={prepareTokenCommitment:function(e,t){t=t||{},hs.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||{},hs.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){hs.checkArgument(e&&typeof e=="object","Invalid token"),hs.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){hs.checkArgument(typeof e=="string","Token ID must be string"),hs.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=Wa.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:Wa.sha256(d.Buffer.from(r)).toString("hex"),tokenId:e.id,timestamp:new Date().toISOString(),purpose:t.purpose||"legal_token"},i=Wa.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 f=this._createCommitment(a,t);r.push(f.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=Wa.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=Wa.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}};Zx.exports=SC});var eI=B((Nq,Qx)=>{"use strict";p();var EC=Ar(),Vr=Jt(),Jx=Ca(),xC=nr(),IC=io(),ir=Le(),AC={prepareSignatureProof:function(e,t,r){r=r||{},ir.checkArgument(e&&typeof e=="object","Invalid token"),ir.checkArgument(t instanceof IC,"Invalid private key");try{var n=this._canonicalizeForSigning(e),i=Vr.sha256(d.Buffer.from(n)),o=new Jx;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(f){return{success:!1,error:f.message}}},prepareSignatureVerification:function(e,t){try{if(ir.checkArgument(e&&typeof e=="object","Invalid token"),ir.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=Vr.sha256(d.Buffer.from(r)),i=xC.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 Jx;s.hashbuf=n,s.sig=i,s.pubkey=EC.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(f){return{success:!1,error:f.message}}},prepareSelectiveDisclosure:function(e,t,r){ir.checkArgument(e&&typeof e=="object","Invalid token"),ir.checkArgument(Array.isArray(t),"Revealed fields must be array"),ir.checkArgument(typeof r=="string","Nonce must be string");try{var n=this._createFieldCommitments(e,r),i=this._createMerkleTree(n),o=[],s=[];t.forEach(function(f){var l=this._getNestedValue(e,f),m=this._findFieldCommitment(n,f);if(m){o.push({path:f,value:l,commitment:m.hash,salt:m.salt});var g=this._generateMerkleProof(i,m.index);s.push({path:f,leafIndex:m.index,proof:g})}}.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(f){return{success:!1,error:f.message}}},prepareSelectiveDisclosureVerification:function(e,t){try{if(ir.checkArgument(e&&typeof e=="object","Invalid proof"),ir.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],f=this._hashField(o.path,o.value,o.salt);if(f!==o.commitment){n.push("Invalid commitment for field: "+o.path);return}var l=this._verifyMerkleProof(o.commitment,a.leafIndex,a.proof,e.merkleRoot);l?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){ir.checkArgument(e&&typeof e=="object","Invalid token"),ir.checkArgument(t&&typeof t=="object","Invalid jurisdiction"),ir.checkArgument(typeof r=="string","Nonce must be string");try{var n=t.requirements||[],i=[],o=!0;n.forEach(function(a){var f=this._checkLegalRequirement(e,a);i.push(f),f.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){ir.checkArgument(e&&typeof e=="object","Invalid token"),ir.checkArgument(t&&typeof t=="object","Invalid statement"),ir.checkArgument(typeof r=="string","Nonce must be string");try{var n=Vr.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:Vr.sha256(d.Buffer.from(t.claim+r)).toString("hex"),response:Vr.sha256(d.Buffer.from(this._canonicalizeForSigning(e)+t.claim)).toString("hex"),witness:Vr.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=Vr.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 Vr.sha256(d.Buffer.from(n)).toString("hex")},_createMerkleTree:function(e){var t=e.map(function(m){return m.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,f=d.Buffer.concat([d.Buffer.from(s,"hex"),d.Buffer.from(a,"hex")]),l=Vr.sha256(f).toString("hex");i.push(l)}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],f=o%2===0,l;a.isLeft?l=d.Buffer.concat([d.Buffer.from(a.hash,"hex"),d.Buffer.from(i,"hex")]):l=d.Buffer.concat([d.Buffer.from(i,"hex"),d.Buffer.from(a.hash,"hex")]),i=Vr.sha256(l).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 Vr.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}};Qx.exports=AC});var nI=B((Lq,rI)=>{"use strict";p();var za=Jt(),kq=no(),Cq=Bp(),lr=Le(),tI=Ga(),OC={prepareRegistry:function(e){e=e||{},lr.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||{},lr.checkArgument(e&&typeof e=="object","Invalid token"),lr.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{lr.checkArgument(typeof e=="string","Token ID must be string"),lr.checkArgument(typeof t=="string","Approver must be string"),lr.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(lr.checkArgument(typeof e=="string","Token ID must be string"),lr.checkArgument(t&&typeof t=="object","Invalid revocation"),lr.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 lr.checkArgument(typeof e=="string","Token ID must be string"),lr.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{lr.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 lr.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||{},lr.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_"+tI.randomHex(16)},_generateRegistrationId:function(e){var t="reg_"+e+"_"+Date.now();return za.sha256(d.Buffer.from(t)).toString("hex").substring(0,16)},_generateRevocationId:function(e){var t="rev_"+e+"_"+Date.now();return za.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,za.sha256(d.Buffer.from(JSON.stringify(t))).toString("hex")},_generateRevocationHash:function(e,t){var r=e+(t.reason||"")+(t.revokedBy||"")+Date.now();return za.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_"+tI.randomHex(32)},_generateAuditHash:function(e){var t=(e.action||"")+(e.actor||"")+(e.tokenId||"")+(e.timestamp||"");return za.sha256(d.Buffer.from(t)).toString("hex").substring(0,16)}};rI.exports=OC});var aI=B((Uq,sI)=>{"use strict";p();var zp=Ar(),Yp=Jt(),iI=Ca(),RC=nr(),oI=io(),yr=Le(),TC=Ga();function PC(e,t){if(t=t||{},t.issuerPublicKey)return t.issuerPublicKey instanceof zp?t.issuerPublicKey:zp.fromString(t.issuerPublicKey);var r=e&&e.issuer;if(typeof r!="string")return null;try{var n=r.split("#")[0].split(":")[2];return n?zp.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"},ds={CRITICAL:"CRITICAL",HIGH:"HIGH",MEDIUM:"MEDIUM",LOW:"LOW",DEFERRED:"DEFERRED"},hr={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||{},yr.checkArgument(typeof e=="string","Obligation type must be string"),yr.checkArgument(typeof t=="string","Issuer DID must be string"),yr.checkArgument(typeof r=="string","Obligor DID must be string"),yr.checkArgument(n&&typeof n=="object","Obligation must be object"),yr.checkArgument(i instanceof oI,"Invalid issuer private key");var s=Object.values(Uc);yr.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||ds.MEDIUM,status:hr.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 f=this._signToken(a,i);return{success:!0,obligationToken:f,tokenHash:f.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:f,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:f.id,tokenHash:f.tokenHash,type:e,issuer:t,obligor:r,issuedAt:f.issuanceDate,dueDate:a.credentialSubject.dueDate,priority:a.credentialSubject.priority}},notifyObligor:{endpoint:"POST /notifications/obligation-issued",data:{tokenId:f.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:f.id,obligor:r,dueDate:a.credentialSubject.dueDate,reminderSchedule:o.reminderSchedule||["7d","3d","1d"]}}:null}}}catch(l){return{success:!1,error:l.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===hr.ACTIVE?{endpoint:"PUT /obligations/tokens/"+e.id+"/status",data:{status:hr.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||{},yr.checkArgument(e&&typeof e=="object","Invalid token"),yr.checkArgument(t&&typeof t=="object","Invalid fulfillment"),yr.checkArgument(r instanceof oI,"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===hr.COMPLETED)return{success:!1,error:"Obligation already fulfilled"};if(e.credentialSubject.status===hr.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?hr.COMPLETED:hr.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(f){return{success:!1,error:f.message}}},prepareObligationBreachAssessment:function(e,t,r){yr.checkArgument(e&&typeof e=="object","Invalid token"),yr.checkArgument(t&&typeof t=="object","Invalid breach details"),yr.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=Yp.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:hr.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||{},yr.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===hr.COMPLETED&&r.summary.completed++,s.isOverdue&&s.priority===ds.CRITICAL&&r.alerts.push({type:"CRITICAL_OVERDUE",obligationId:o.id,message:"Critical obligation is overdue",priority:"HIGH"}),s.isDueSoon&&s.priority===ds.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 ds},getObligationStatus:function(){return hr},_signToken:function(e,t){var r=this._canonicalizeToken(e),n=Yp.sha256(d.Buffer.from(r)),i=new iI;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=Yp.sha256(d.Buffer.from(n));if(e.tokenHash&&e.tokenHash!==i.toString("hex")){t.push("Token hash mismatch");return}var o=PC(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=RC.fromDER(d.Buffer.from(s[2],"base64url")),f=new iI;f.hashbuf=i,f.sig=a,f.pubkey=o,f.verify()!==!0&&t.push("Signature verification failed")}catch(l){t.push("Signature verification failed: "+l.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(hr);n.includes(e.credentialSubject.status)||t.push("Invalid obligation status: "+e.credentialSubject.status),this._checkIfOverdue(e)&&e.credentialSubject.status===hr.ACTIVE&&r.push("Obligation is overdue but status is still ACTIVE")},_validateObligationPriority:function(e,t){if(e.credentialSubject.priority){var r=Object.values(ds);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!==hr.COMPLETED},_generateUUID:function(){return TC.uuid4()}};Fc.ObligationTypes=Uc;Fc.ObligationPriority=ds;Fc.ObligationStatus=hr;sI.exports=Fc});var fI=B((qq,uI)=>{"use strict";p();var uo=jx(),qc=$x(),Ya=Xx(),$p=eI(),dn=nI(),BC=aI(),Zp=io(),mr=Le(),Pe=function(e){return this instanceof Pe?(this.config=e||{},this.registry=null,this.config.registry&&(this.registry=dn.createRegistry(this.config.registry)),this):new Pe(e)};Pe.prototype.createRightToken=function(e,t,r){mr.checkArgument(e&&typeof e=="object","Invalid right data"),mr.checkArgument(t instanceof Zp,"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}}};Pe.prototype.validateClaim=function(e,t){return qc.validate(e,t)};Pe.prototype.createSelectiveDisclosure=function(e,t,r){return $p.prepareSelectiveDisclosure(e,t,r)};Pe.prototype.verifyToken=function(e,t){return!e||!e.proof?{valid:!1,error:"No proof found in token"}:uo.verifyToken(e,t)};Pe.prototype.transferRight=function(e,t,r,n){mr.checkArgument(e&&typeof e=="object","Invalid token"),mr.checkArgument(typeof t=="string","New owner must be string"),mr.checkArgument(r instanceof Zp,"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 f=Ya.anchorToken(s,n.anchor);f.success&&(s.transferAnchorTx=f.txid)}if(this.registry){var l=dn.registerToken(this.registry,s,{registeredBy:n.registeredBy||t,metadata:{transferFrom:e.owner,transferTo:t,originalTokenId:e.id}});l.success&&(s.registrationId=l.registrationId)}return{success:!0,token:s,transferId:a.id,transferredAt:a.issuanceDate,transferProof:a}}catch(m){return{success:!1,error:m.message}}};Pe.prototype.createObligation=function(e,t,r){mr.checkArgument(e&&typeof e=="object","Invalid right token"),mr.checkArgument(t&&typeof t=="object","Invalid obligation data"),mr.checkArgument(r instanceof Zp,"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}}};Pe.prototype.revokeToken=function(e,t,r){return mr.checkArgument(typeof e=="string","Token ID must be string"),mr.checkArgument(t&&typeof t=="object","Invalid revocation data"),mr.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"}};Pe.prototype.checkTokenStatus=function(e){return mr.checkArgument(typeof e=="string","Token ID must be string"),this.registry?dn.checkTokenStatus(this.registry,e):{found:!1,error:"No registry available"}};Pe.prototype.searchTokens=function(e){return this.registry?dn.searchTokens(this.registry,e):{success:!1,error:"No registry available"}};Pe.prototype.getRegistryStats=function(){return this.registry?dn.getStatistics(this.registry):{error:"No registry available"}};Pe.prototype.createLegalValidityProof=function(e,t,r){return $p.prepareLegalValidityProof(e,t,r)};Pe.prototype.anchorTokenBatch=function(e,t){return Ya.anchorBatch(e,t)};Pe.prototype.verifyAnchor=function(e,t){return Ya.verifyAnchor(e,t)};Pe.prototype.getRightTypes=function(){return uo.getRightTypes()};Pe.prototype.getClaimSchemas=function(){return qc.getSchemas()};Pe.prototype.createRegistry=function(e){return this.registry=dn.createRegistry(e),this.registry};Pe.prototype.setRegistry=function(e){mr.checkArgument(e&&typeof e=="object","Invalid registry"),this.registry=e};Pe.create=function(e){return new Pe(e)};Pe.createRightToken=function(e,t,r){var n=new Pe;return n.createRightToken(e,t,r)};Pe.validateClaim=function(e,t){return qc.validate(e,t)};Pe.verifyToken=function(e,t){var r=new Pe;return r.verifyToken(e,t)};Pe.createRegistry=function(e){return dn.createRegistry(e)};Pe.Right=uo;Pe.Claim=qc;Pe.Anchor=Ya;Pe.Proof=$p;Pe.Registry=dn;Pe.Obligation=BC;uI.exports=Pe});var NC=B((Hq,cI)=>{p();cI.exports=fI()});return NC();})();
75
75
  if(typeof module!=="undefined"&&module.exports){module.exports=bsvLTP}else if(typeof define==="function"&&define.amd){define([],function(){return bsvLTP})}