@bsv/sdk 2.0.6 → 2.0.7
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/dist/cjs/package.json +1 -1
- package/dist/cjs/src/script/Spend.js +7 -2
- package/dist/cjs/src/script/Spend.js.map +1 -1
- package/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -1
- package/dist/esm/src/script/Spend.js +7 -2
- package/dist/esm/src/script/Spend.js.map +1 -1
- package/dist/esm/tsconfig.esm.tsbuildinfo +1 -1
- package/dist/types/src/script/Spend.d.ts.map +1 -1
- package/dist/types/tsconfig.types.tsbuildinfo +1 -1
- package/dist/umd/bundle.js +1 -1
- package/dist/umd/bundle.js.map +1 -1
- package/package.json +1 -1
- package/src/script/Spend.ts +8 -2
- package/src/script/__tests/Spend.test.ts +10 -0
package/dist/umd/bundle.js
CHANGED
|
@@ -3,7 +3,7 @@ TXID: ${e.txid}, OutputIdx: ${e.outputIndex}
|
|
|
3
3
|
${r}
|
|
4
4
|
${n}
|
|
5
5
|
${a}
|
|
6
|
-
${s}`),this.name=this.constructor.name,this.txid=e.txid,this.outputIndex=e.outputIndex,this.context=e.context,this.programCounter=e.programCounter,this.stackState=e.stackState.map(e=>e.slice()),this.altStackState=e.altStackState.map(e=>e.slice()),this.ifStackState=e.ifStackState.slice(),this.stackMem=e.stackMem,this.altStackMem=e.altStackMem}}let iC=BigInt(0x7fffffff),iB=Object.freeze(new P(-1).toScriptNum()),iU=Object.freeze(Array.from({length:17},(e,t)=>Object.freeze(new P(t).toScriptNum())));function iV(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}class iD{sourceTXID;sourceOutputIndex;sourceSatoshis;lockingScript;transactionVersion;otherInputs;outputs;inputIndex;unlockingScript;inputSequence;lockTime;context;programCounter;lastCodeSeparator;stack;altStack;ifStack;memoryLimit;stackMem;altStackMem;isRelaxedOverride;sigHashCache;constructor(e){this.sourceTXID=e.sourceTXID,this.sourceOutputIndex=e.sourceOutputIndex,this.sourceSatoshis=e.sourceSatoshis,this.lockingScript=e.lockingScript,this.transactionVersion=e.transactionVersion,this.otherInputs=e.otherInputs,this.outputs=e.outputs,this.inputIndex=e.inputIndex,this.unlockingScript=e.unlockingScript,this.inputSequence=e.inputSequence,this.lockTime=e.lockTime,this.memoryLimit=e.memoryLimit??32e6,this.isRelaxedOverride=!0===e.isRelaxed,this.stack=[],this.altStack=[],this.ifStack=[],this.stackMem=0,this.altStackMem=0,this.sigHashCache={hashOutputsSingle:new Map},this.reset()}isRelaxed(){return this.isRelaxedOverride||this.transactionVersion>1}reset(){this.context="UnlockingScript",this.programCounter=0,this.lastCodeSeparator=null,this.stack=[],this.altStack=[],this.ifStack=[],this.stackMem=0,this.altStackMem=0,this.sigHashCache={hashOutputsSingle:new Map}}ensureStackMem(e){this.stackMem+e>this.memoryLimit&&this.scriptEvaluationError("Stack memory usage has exceeded "+String(this.memoryLimit)+" bytes")}ensureAltStackMem(e){this.altStackMem+e>this.memoryLimit&&this.scriptEvaluationError("Alt stack memory usage has exceeded "+String(this.memoryLimit)+" bytes")}pushStack(e){this.ensureStackMem(e.length),this.stack.push(e),this.stackMem+=e.length}pushStackCopy(e){this.ensureStackMem(e.length);let t=e.slice();this.stack.push(t),this.stackMem+=t.length}popStack(){0===this.stack.length&&this.scriptEvaluationError("Attempted to pop from an empty stack.");let e=this.stack.pop();return this.stackMem-=e.length,e}stackTop(e=-1){return(0===this.stack.length||this.stack.length<Math.abs(e)||e>=0&&e>=this.stack.length)&&this.scriptEvaluationError(`Stack underflow accessing element at index ${e}. Stack length is ${this.stack.length}.`),this.stack[this.stack.length+e]}pushAltStack(e){this.ensureAltStackMem(e.length),this.altStack.push(e),this.altStackMem+=e.length}popAltStack(){0===this.altStack.length&&this.scriptEvaluationError("Attempted to pop from an empty alt stack.");let e=this.altStack.pop();return this.altStackMem-=e.length,e}checkSignatureEncoding(e){if(0===e.length)return!0;if(!function(e){if(e.length<9||e.length>73||48!==e[0]||e[1]!==e.length-3)return!1;let t=e[2],i=e[3];if(2!==t||0===i||5+i>=e.length)return!1;let r=4+i,n=e[r],a=e[r+1];if(2!==n||0===a||(128&e[4])!=0||i>1&&0===e[4]&&(128&e[5])==0)return!1;let s=r+2;return(128&e[s])==0&&(!(a>1)||0!==e[s]||(128&e[s+1])!=0)&&i+a+7===e.length}(e))return this.scriptEvaluationError("The signature format is invalid."),!1;try{let t=iv.fromChecksigFormat(e);if(!this.isRelaxed()&&!t.hasLowS())return this.scriptEvaluationError("The signature must have a low S value."),!1}catch(e){return this.scriptEvaluationError("The signature format is invalid."),!1}return!0}checkPublicKeyEncoding(e){if(0===e.length)return this.scriptEvaluationError("Public key is empty."),!1;if(e.length<33)return this.scriptEvaluationError("The public key is too short, it must be at least 33 bytes."),!1;if(4===e[0]){if(65!==e.length)return this.scriptEvaluationError("The non-compressed public key must be 65 bytes."),!1}else if(2!==e[0]&&3!==e[0])return this.scriptEvaluationError("The public key is in an unknown format."),!1;else if(33!==e.length)return this.scriptEvaluationError("The compressed public key must be 33 bytes."),!1;try{tJ.fromDER(e)}catch(e){return this.scriptEvaluationError("The public key is in an unknown format."),!1}return!0}verifySignature(e,t,i){return tY(new P(eo(iv.formatBytes({sourceTXID:this.sourceTXID,sourceOutputIndex:this.sourceOutputIndex,sourceSatoshis:this.sourceSatoshis,transactionVersion:this.transactionVersion,otherInputs:this.otherInputs,outputs:this.outputs,inputIndex:this.inputIndex,subscript:i,inputSequence:this.inputSequence,lockTime:this.lockTime,scope:e.scope,cache:this.sigHashCache}))),e,t)}step(){if(this.stackMem>this.memoryLimit)return this.scriptEvaluationError("Stack memory usage has exceeded "+String(this.memoryLimit)+" bytes"),!1;if(this.altStackMem>this.memoryLimit)return this.scriptEvaluationError("Alt stack memory usage has exceeded "+String(this.memoryLimit)+" bytes"),!1;"UnlockingScript"===this.context&&this.programCounter>=this.unlockingScript.chunks.length&&(this.context="LockingScript",this.programCounter=0);let e="UnlockingScript"===this.context?this.unlockingScript:this.lockingScript;if(this.programCounter>=e.chunks.length)return!1;let t=e.chunks[this.programCounter],i=t.op;void 0===i&&this.scriptEvaluationError(`Missing opcode in ${this.context} at pc=${this.programCounter}.`),Array.isArray(t.data)&&t.data.length>0x40000000&&this.scriptEvaluationError(`Data push > 1073741824 bytes (pc=${this.programCounter}).`);let r=!this.ifStack.includes(!1);if(r&&i>=0&&i<=im.OP_PUSHDATA4){let e,i;!this.isRelaxed()&&(e=t.data,i=t.op,Array.isArray(e)&&(0===e.length?i!==im.OP_0:1===e.length&&e[0]>=1&&e[0]<=16?i!==im.OP_1+(e[0]-1):1===e.length&&129===e[0]?i!==im.OP_1NEGATE:e.length<=75?i!==e.length:e.length<=255?i!==im.OP_PUSHDATA1:e.length<=65535&&i!==im.OP_PUSHDATA2))&&this.scriptEvaluationError(`This data is not minimally-encoded. (PC: ${this.programCounter})`),this.pushStack(Array.isArray(t.data)?t.data:[])}else if(r||i>=im.OP_IF&&i<=im.OP_ENDIF){let e,t,n,a,s,o,c,l,h,d,u,f,p,g,m,y,b,w,v,I,k,S,E,x,A,N;switch(i){case im.OP_VER:this.pushStackCopy(new P(this.transactionVersion).toScriptNum());break;case im.OP_SUBSTR:{this.stack.length<3&&this.scriptEvaluationError("OP_SUBSTR requires at least three items to be on the stack.");let t=P.fromScriptNum(this.popStack(),!this.isRelaxed()).toNumber(),i=P.fromScriptNum(this.popStack(),!this.isRelaxed()).toNumber(),r=(e=this.popStack()).length;(i<0||i>=r||t<0||t>r-i)&&this.scriptEvaluationError(`OP_SUBSTR offset (${i}) must be in range [0, ${r}) and length (${t}) must be in range [0, ${r-i}]`),this.pushStack(e.slice(i,i+t));break}case im.OP_LEFT:{this.stack.length<2&&this.scriptEvaluationError("OP_LEFT requires at least two items to be on the stack.");let t=P.fromScriptNum(this.popStack(),!this.isRelaxed()).toNumber(),i=(e=this.popStack()).length;(t<0||t>i)&&this.scriptEvaluationError(`OP_LEFT length (${t}) must be in range [0, ${i}]`),this.pushStack(e.slice(0,t));break}case im.OP_RIGHT:{this.stack.length<2&&this.scriptEvaluationError("OP_RIGHT requires at least two items to be on the stack.");let t=P.fromScriptNum(this.popStack(),!this.isRelaxed()).toNumber(),i=(e=this.popStack()).length;(t<0||t>i)&&this.scriptEvaluationError(`OP_RIGHT length (${t}) must be in range [0, ${i}]`),this.pushStack(e.slice(i-t,t));break}case im.OP_LSHIFTNUM:{this.stack.length<2&&this.scriptEvaluationError("OP_LSHIFTNUM requires at least two items to be on the stack.");let e=P.fromScriptNum(this.popStack(),!this.isRelaxed()).toBigInt();e<0&&this.scriptEvaluationError("OP_LSHIFTNUM bits to shift must not be negative.");let t=P.fromScriptNum(this.popStack(),!this.isRelaxed()).toBigInt(),i=new P(t<<e);this.pushStack(i.toScriptNum());break}case im.OP_RSHIFTNUM:{let e;this.stack.length<2&&this.scriptEvaluationError("OP_RSHIFTNUM requires at least two items to be on the stack.");let t=P.fromScriptNum(this.popStack(),!this.isRelaxed()).toBigInt();t<0&&this.scriptEvaluationError("OP_RSHIFTNUM bits to shift must not be negative.");let i=P.fromScriptNum(this.popStack(),!this.isRelaxed()).toBigInt();e=new P(i<0?-(-i>>t):i>>t),this.pushStack(e.toScriptNum());break}case im.OP_1NEGATE:this.pushStackCopy(iB);break;case im.OP_0:this.pushStackCopy(iU[0]);break;case im.OP_1:case im.OP_2:case im.OP_3:case im.OP_4:case im.OP_5:case im.OP_6:case im.OP_7:case im.OP_8:case im.OP_9:case im.OP_10:case im.OP_11:case im.OP_12:case im.OP_13:case im.OP_14:case im.OP_15:case im.OP_16:f=i-(im.OP_1-1),this.pushStackCopy(iU[f]);break;case im.OP_NOP:case im.OP_NOP1:case im.OP_NOP2:case im.OP_NOP3:case im.OP_NOP7:case im.OP_NOP8:case im.OP_NOP9:case im.OP_NOP10:case im.OP_NOP11:case im.OP_NOP12:case im.OP_NOP13:case im.OP_NOP14:case im.OP_NOP15:case im.OP_NOP16:case im.OP_NOP17:case im.OP_NOP18:case im.OP_NOP19:case im.OP_NOP20:case im.OP_NOP21:case im.OP_NOP22:case im.OP_NOP23:case im.OP_NOP24:case im.OP_NOP25:case im.OP_NOP26:case im.OP_NOP27:case im.OP_NOP28:case im.OP_NOP29:case im.OP_NOP30:case im.OP_NOP31:case im.OP_NOP32:case im.OP_NOP33:case im.OP_NOP34:case im.OP_NOP35:case im.OP_NOP36:case im.OP_NOP37:case im.OP_NOP38:case im.OP_NOP39:case im.OP_NOP40:case im.OP_NOP41:case im.OP_NOP42:case im.OP_NOP43:case im.OP_NOP44:case im.OP_NOP45:case im.OP_NOP46:case im.OP_NOP47:case im.OP_NOP48:case im.OP_NOP49:case im.OP_NOP50:case im.OP_NOP51:case im.OP_NOP52:case im.OP_NOP53:case im.OP_NOP54:case im.OP_NOP55:case im.OP_NOP56:case im.OP_NOP57:case im.OP_NOP58:case im.OP_NOP59:case im.OP_NOP60:case im.OP_NOP61:case im.OP_NOP62:case im.OP_NOP63:case im.OP_NOP64:case im.OP_NOP65:case im.OP_NOP66:case im.OP_NOP67:case im.OP_NOP68:case im.OP_NOP69:case im.OP_NOP70:case im.OP_NOP71:case im.OP_NOP72:case im.OP_NOP73:case im.OP_NOP77:break;case im.OP_VERIF:case im.OP_VERNOTIF:g=!1,r&&(this.stack.length<1&&this.scriptEvaluationError("OP_VERIF and OP_VERNOTIF require at least one item on the stack when they are used!"),n=new P(this.transactionVersion).toScriptNum(),g=iV(t=this.popStack(),n),i===im.OP_VERNOTIF&&(g=!g)),this.ifStack.push(g);break;case im.OP_IF:case im.OP_NOTIF:g=!1,r&&(this.stack.length<1&&this.scriptEvaluationError("OP_IF and OP_NOTIF require at least one item on the stack when they are used!"),e=this.popStack(),g=this.castToBool(e),i===im.OP_NOTIF&&(g=!g)),this.ifStack.push(g);break;case im.OP_ELSE:0===this.ifStack.length&&this.scriptEvaluationError("OP_ELSE requires a preceeding OP_IF."),this.ifStack[this.ifStack.length-1]=!this.ifStack[this.ifStack.length-1];break;case im.OP_ENDIF:0===this.ifStack.length&&this.scriptEvaluationError("OP_ENDIF requires a preceeding OP_IF."),this.ifStack.pop();break;case im.OP_VERIFY:this.stack.length<1&&this.scriptEvaluationError("OP_VERIFY requires at least one item to be on the stack."),t=this.stackTop(),(g=this.castToBool(t))||this.scriptEvaluationError("OP_VERIFY requires the top stack value to be truthy."),this.popStack();break;case im.OP_RETURN:"UnlockingScript"===this.context?this.programCounter=this.unlockingScript.chunks.length:this.programCounter=this.lockingScript.chunks.length,this.ifStack=[],this.programCounter--;break;case im.OP_TOALTSTACK:this.stack.length<1&&this.scriptEvaluationError("OP_TOALTSTACK requires at oeast one item to be on the stack."),this.pushAltStack(this.popStack());break;case im.OP_FROMALTSTACK:this.altStack.length<1&&this.scriptEvaluationError("OP_FROMALTSTACK requires at least one item to be on the stack."),this.pushStack(this.popAltStack());break;case im.OP_2DROP:this.stack.length<2&&this.scriptEvaluationError("OP_2DROP requires at least two items to be on the stack."),this.popStack(),this.popStack();break;case im.OP_2DUP:this.stack.length<2&&this.scriptEvaluationError("OP_2DUP requires at least two items to be on the stack."),t=this.stackTop(-2),n=this.stackTop(-1),this.pushStackCopy(t),this.pushStackCopy(n);break;case im.OP_3DUP:this.stack.length<3&&this.scriptEvaluationError("OP_3DUP requires at least three items to be on the stack."),t=this.stackTop(-3),n=this.stackTop(-2),a=this.stackTop(-1),this.pushStackCopy(t),this.pushStackCopy(n),this.pushStackCopy(a);break;case im.OP_2OVER:this.stack.length<4&&this.scriptEvaluationError("OP_2OVER requires at least four items to be on the stack."),t=this.stackTop(-4),n=this.stackTop(-3),this.pushStackCopy(t),this.pushStackCopy(n);break;case im.OP_2ROT:{this.stack.length<6&&this.scriptEvaluationError("OP_2ROT requires at least six items to be on the stack.");let e=this.popStack(),t=this.popStack(),i=this.popStack(),r=this.popStack(),n=this.popStack(),a=this.popStack();this.pushStack(r),this.pushStack(i),this.pushStack(t),this.pushStack(e),this.pushStack(a),this.pushStack(n);break}case im.OP_2SWAP:{this.stack.length<4&&this.scriptEvaluationError("OP_2SWAP requires at least four items to be on the stack.");let e=this.popStack(),t=this.popStack(),i=this.popStack(),r=this.popStack();this.pushStack(t),this.pushStack(e),this.pushStack(r),this.pushStack(i);break}case im.OP_IFDUP:this.stack.length<1&&this.scriptEvaluationError("OP_IFDUP requires at least one item to be on the stack."),t=this.stackTop(),this.castToBool(t)&&this.pushStackCopy(t);break;case im.OP_DEPTH:this.pushStack(new P(this.stack.length).toScriptNum());break;case im.OP_DROP:this.stack.length<1&&this.scriptEvaluationError("OP_DROP requires at least one item to be on the stack."),this.popStack();break;case im.OP_DUP:this.stack.length<1&&this.scriptEvaluationError("OP_DUP requires at least one item to be on the stack."),this.pushStackCopy(this.stackTop());break;case im.OP_NIP:this.stack.length<2&&this.scriptEvaluationError("OP_NIP requires at least two items to be on the stack."),n=this.popStack(),this.popStack(),this.pushStack(n);break;case im.OP_OVER:this.stack.length<2&&this.scriptEvaluationError("OP_OVER requires at least two items to be on the stack."),this.pushStackCopy(this.stackTop(-2));break;case im.OP_PICK:case im.OP_ROLL:{this.stack.length<2&&this.scriptEvaluationError(`${im[i]} requires at least two items to be on the stack.`);let e=(l=P.fromScriptNum(this.popStack(),!this.isRelaxed())).toBigInt();(e<0n||e>=BigInt(this.stack.length))&&this.scriptEvaluationError(`${im[i]} requires the top stack element to be 0 or a positive number less than the current size of the stack.`);let t=Number(e),r=this.stack[this.stack.length-1-t];i===im.OP_ROLL?(this.stack.splice(this.stack.length-1-t,1),this.stackMem-=r.length,this.pushStack(r)):this.pushStackCopy(r);break}case im.OP_ROT:this.stack.length<3&&this.scriptEvaluationError("OP_ROT requires at least three items to be on the stack."),c=this.popStack(),o=this.popStack(),s=this.popStack(),this.pushStack(o),this.pushStack(c),this.pushStack(s);break;case im.OP_SWAP:this.stack.length<2&&this.scriptEvaluationError("OP_SWAP requires at least two items to be on the stack."),o=this.popStack(),s=this.popStack(),this.pushStack(o),this.pushStack(s);break;case im.OP_TUCK:this.stack.length<2&&this.scriptEvaluationError("OP_TUCK requires at least two items to be on the stack."),t=this.stackTop(-1),this.ensureStackMem(t.length),this.stack.splice(this.stack.length-2,0,t.slice()),this.stackMem+=t.length;break;case im.OP_SIZE:this.stack.length<1&&this.scriptEvaluationError("OP_SIZE requires at least one item to be on the stack."),this.pushStack(new P(this.stackTop().length).toScriptNum());break;case im.OP_AND:case im.OP_OR:case im.OP_XOR:{this.stack.length<2&&this.scriptEvaluationError(`${im[i]} requires at least two items on the stack.`),n=this.popStack(),(t=this.popStack()).length!==n.length&&this.scriptEvaluationError(`${im[i]} requires the top two stack items to be the same size.`);let e=Array(t.length);for(let r=0;r<t.length;r++)i===im.OP_AND?e[r]=t[r]&n[r]:i===im.OP_OR?e[r]=t[r]|n[r]:e[r]=t[r]^n[r];this.pushStack(e);break}case im.OP_INVERT:{this.stack.length<1&&this.scriptEvaluationError("OP_INVERT requires at least one item to be on the stack.");let t=Array((e=this.popStack()).length);for(let i=0;i<e.length;i++)t[i]=255&~e[i];this.pushStack(t);break}case im.OP_LSHIFT:case im.OP_RSHIFT:{this.stack.length<2&&this.scriptEvaluationError(`${im[i]} requires at least two items to be on the stack.`),d=P.fromScriptNum(this.popStack(),!this.isRelaxed()),t=this.popStack();let e=d.toBigInt();if(e<0n&&this.scriptEvaluationError(`${im[i]} requires the top item on the stack not to be negative.`),0===t.length){this.pushStack([]);break}h=new P(t);let r=(i===im.OP_LSHIFT?h.ushln(e):h.ushrn(e)).toArray("be",t.length);this.pushStack(r);break}case im.OP_EQUAL:case im.OP_EQUALVERIFY:this.stack.length<2&&this.scriptEvaluationError(`${im[i]} requires at least two items to be on the stack.`),n=this.popStack(),g=iV(t=this.popStack(),n),this.pushStack(g?[1]:[]),i===im.OP_EQUALVERIFY&&(g||this.scriptEvaluationError("OP_EQUALVERIFY requires the top two stack items to be equal."),this.popStack());break;case im.OP_1ADD:case im.OP_1SUB:case im.OP_2MUL:case im.OP_2DIV:case im.OP_NEGATE:case im.OP_ABS:case im.OP_NOT:case im.OP_0NOTEQUAL:switch(this.stack.length<1&&this.scriptEvaluationError(`${im[i]} requires at least one item to be on the stack.`),l=P.fromScriptNum(this.popStack(),!this.isRelaxed()),i){case im.OP_1ADD:l=l.add(new P(1));break;case im.OP_1SUB:l=l.sub(new P(1));break;case im.OP_2MUL:l=l.mul(new P(2));break;case im.OP_2DIV:l=l.div(new P(2));break;case im.OP_NEGATE:l=l.neg();break;case im.OP_ABS:l.isNeg()&&(l=l.neg());break;case im.OP_NOT:l=new P(+(0===l.cmpn(0)));break;case im.OP_0NOTEQUAL:l=new P(+(0!==l.cmpn(0)))}this.pushStack(l.toScriptNum());break;case im.OP_ADD:case im.OP_SUB:case im.OP_MUL:case im.OP_DIV:case im.OP_MOD:case im.OP_BOOLAND:case im.OP_BOOLOR:case im.OP_NUMEQUAL:case im.OP_NUMEQUALVERIFY:case im.OP_NUMNOTEQUAL:case im.OP_LESSTHAN:case im.OP_GREATERTHAN:case im.OP_LESSTHANOREQUAL:case im.OP_GREATERTHANOREQUAL:case im.OP_MIN:case im.OP_MAX:{this.stack.length<2&&this.scriptEvaluationError(`${im[i]} requires at least two items to be on the stack.`),n=this.popStack(),t=this.popStack(),d=P.fromScriptNum(n,!this.isRelaxed()),h=P.fromScriptNum(t,!this.isRelaxed());let e=0;switch(i){case im.OP_MUL:e=h.byteLength()+d.byteLength();break;case im.OP_ADD:case im.OP_SUB:e=Math.max(h.byteLength(),d.byteLength())+1;break;default:e=Math.max(h.byteLength(),d.byteLength())}this.ensureStackMem(e);let r=new P(0);switch(i){case im.OP_ADD:r=h.add(d);break;case im.OP_SUB:r=h.sub(d);break;case im.OP_MUL:r=h.mul(d);break;case im.OP_DIV:0===d.cmpn(0)&&this.scriptEvaluationError("OP_DIV cannot divide by zero!"),r=h.div(d);break;case im.OP_MOD:0===d.cmpn(0)&&this.scriptEvaluationError("OP_MOD cannot divide by zero!"),r=h.mod(d);break;case im.OP_BOOLAND:r=new P(+(0!==h.cmpn(0)&&0!==d.cmpn(0)));break;case im.OP_BOOLOR:r=new P(+(0!==h.cmpn(0)||0!==d.cmpn(0)));break;case im.OP_NUMEQUAL:case im.OP_NUMEQUALVERIFY:r=new P(+(0===h.cmp(d)));break;case im.OP_NUMNOTEQUAL:r=new P(+(0!==h.cmp(d)));break;case im.OP_LESSTHAN:r=new P(+(0>h.cmp(d)));break;case im.OP_GREATERTHAN:r=new P(+(h.cmp(d)>0));break;case im.OP_LESSTHANOREQUAL:r=new P(+(0>=h.cmp(d)));break;case im.OP_GREATERTHANOREQUAL:r=new P(+(h.cmp(d)>=0));break;case im.OP_MIN:r=0>h.cmp(d)?h:d;break;case im.OP_MAX:r=h.cmp(d)>0?h:d}this.pushStack(r.toScriptNum()),i===im.OP_NUMEQUALVERIFY&&(this.castToBool(this.stackTop())||this.scriptEvaluationError("OP_NUMEQUALVERIFY requires the top stack item to be truthy."),this.popStack());break}case im.OP_WITHIN:this.stack.length<3&&this.scriptEvaluationError("OP_WITHIN requires at least three items to be on the stack."),u=P.fromScriptNum(this.popStack(),!this.isRelaxed()),d=P.fromScriptNum(this.popStack(),!this.isRelaxed()),g=(h=P.fromScriptNum(this.popStack(),!this.isRelaxed())).cmp(d)>=0&&0>h.cmp(u),this.pushStack(g?[1]:[]);break;case im.OP_RIPEMD160:case im.OP_SHA1:case im.OP_SHA256:case im.OP_HASH160:case im.OP_HASH256:{this.stack.length<1&&this.scriptEvaluationError(`${im[i]} requires at least one item to be on the stack.`),e=this.popStack();let t=[];i===im.OP_RIPEMD160?t=er(e):i===im.OP_SHA1?t=en(e):i===im.OP_SHA256?t=ea(e):i===im.OP_HASH160?t=ec(e):i===im.OP_HASH256&&(t=eo(e)),this.pushStack(t);break}case im.OP_CODESEPARATOR:this.lastCodeSeparator=this.programCounter;break;case im.OP_CHECKSIG:case im.OP_CHECKSIGVERIFY:if(this.stack.length<2&&this.scriptEvaluationError(`${im[i]} requires at least two items to be on the stack.`),w=this.popStack(),b=this.popStack(),this.checkSignatureEncoding(b)&&this.checkPublicKeyEncoding(w)||this.scriptEvaluationError(`${im[i]} requires correct encoding for the public key and signature.`),m=!1,b.length>0)try{v=iv.fromChecksigFormat(b);let e=("UnlockingScript"===this.context?this.unlockingScript:this.lockingScript).chunks.slice(null===this.lastCodeSeparator?0:this.lastCodeSeparator+1);(y=new ib(e)).findAndDelete(new ib().writeBin(b)),I=tJ.fromDER(w),m=this.verifySignature(v,I,y)}catch(e){m=!1}this.pushStack(m?[1]:[]),i===im.OP_CHECKSIGVERIFY&&(m||this.scriptEvaluationError("OP_CHECKSIGVERIFY requires that a valid signature is provided."),this.popStack());break;case im.OP_CHECKMULTISIG:case im.OP_CHECKMULTISIGVERIFY:{k=1,this.stack.length<k&&this.scriptEvaluationError(`${im[i]} requires at least 1 item for nKeys.`);let e=P.fromScriptNum(this.stackTop(-k),!this.isRelaxed()).toBigInt();(e<0n||e>iC)&&this.scriptEvaluationError(`${im[i]} requires a key count between 0 and 2147483647.`);let t=x=Number(e);S=++k,k+=x,this.stack.length<k&&this.scriptEvaluationError(`${im[i]} stack too small for nKeys and keys. Need ${k}, have ${this.stack.length}.`);let r=P.fromScriptNum(this.stackTop(-k),!this.isRelaxed()).toBigInt();(r<0n||r>BigInt(x))&&this.scriptEvaluationError(`${im[i]} requires the number of signatures to be no greater than the number of keys.`);let n=A=Number(r);E=++k,k+=A,this.stack.length<k&&this.scriptEvaluationError(`${im[i]} stack too small for N, keys, M, sigs, and dummy. Need ${k}, have ${this.stack.length}.`),y=new ib(("UnlockingScript"===this.context?this.unlockingScript:this.lockingScript).chunks.slice(null===this.lastCodeSeparator?0:this.lastCodeSeparator+1));for(let e=0;e<A;e++)b=this.stackTop(-E-e),y.findAndDelete(new ib().writeBin(b));for(m=!0;m&&A>0;){if(0===x){m=!1;break}if(b=this.stackTop(-E),w=this.stackTop(-S),this.checkSignatureEncoding(b)&&this.checkPublicKeyEncoding(w)||this.scriptEvaluationError(`${im[i]} requires correct encoding for the public key and signature.`),N=!1,b.length>0)try{v=iv.fromChecksigFormat(b),I=tJ.fromDER(w),N=this.verifySignature(v,I,y)}catch(e){N=!1}N&&(E++,A--),S++,A>--x&&(m=!1)}let a=1+t+1+n+1-1;for(;a>0;)this.popStack(),a--;this.stack.length<1&&this.scriptEvaluationError(`${im[i]} requires an extra item (dummy) to be on the stack.`);let s=this.popStack();!this.isRelaxed()&&s.length>0&&this.scriptEvaluationError(`${im[i]} requires the extra stack item (dummy) to be empty.`),this.pushStack(m?[1]:[]),i===im.OP_CHECKMULTISIGVERIFY&&(m||this.scriptEvaluationError("OP_CHECKMULTISIGVERIFY requires that a sufficient number of valid signatures are provided."),this.popStack());break}case im.OP_CAT:{this.stack.length<2&&this.scriptEvaluationError("OP_CAT requires at least two items to be on the stack."),n=this.popStack();let e=(t=this.popStack()).concat(n);e.length>0x40000000&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes."),this.pushStack(e);break}case im.OP_SPLIT:{this.stack.length<2&&this.scriptEvaluationError("OP_SPLIT requires at least two items to be on the stack.");let e=this.popStack(),t=this.popStack(),i=P.fromScriptNum(e,!this.isRelaxed()).toBigInt();(i<0n||i>BigInt(t.length))&&this.scriptEvaluationError("OP_SPLIT requires the first stack item to be a non-negative number less than or equal to the size of the second-from-top stack item.");let r=Number(i);this.pushStack(t.slice(0,r)),this.pushStack(t.slice(r));break}case im.OP_NUM2BIN:{this.stack.length<2&&this.scriptEvaluationError("OP_NUM2BIN requires at least two items to be on the stack.");let e=P.fromScriptNum(this.popStack(),!this.isRelaxed()).toBigInt();(e>BigInt(0x40000000)||e<0n)&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes or negative size."),p=Number(e);let t=this.popStack();if((t=tm(t)).length>p&&this.scriptEvaluationError("OP_NUM2BIN requires that the size expressed in the top stack item is large enough to hold the value expressed in the second-from-top stack item."),t.length===p){this.pushStack(t);break}let i=Array(p).fill(0),r=0;t.length>0&&(r=128&t[t.length-1],t[t.length-1]&=127);for(let e=0;e<t.length;e++)i[e]=t[e];0!==r&&(i[p-1]|=128),this.pushStack(i);break}case im.OP_BIN2NUM:{this.stack.length<1&&this.scriptEvaluationError("OP_BIN2NUM requires at least one item to be on the stack.");let e=tm(t=this.popStack());!function(e,t=Number.MAX_SAFE_INTEGER){return!(e.length>t)&&(!(e.length>0)||(127&e[e.length-1])!=0||!(e.length<=1)&&(128&e[e.length-2])!=0)}(e)&&this.scriptEvaluationError("OP_BIN2NUM requires that the resulting number is valid."),this.pushStack(e);break}default:this.scriptEvaluationError(`Invalid opcode ${i} (pc=${this.programCounter}).`)}}return this.programCounter++,!0}validate(){for(this.isRelaxed()||this.unlockingScript.isPushOnly()||this.scriptEvaluationError("Unlocking scripts can only contain push operations, and no other opcodes.");this.step()&&("LockingScript"!==this.context||!(this.programCounter>=this.lockingScript.chunks.length)););return this.ifStack.length>0&&this.scriptEvaluationError("Every OP_IF, OP_NOTIF, or OP_ELSE must be terminated with OP_ENDIF prior to the end of the script."),this.isRelaxed()||1===this.stack.length||this.scriptEvaluationError(`The clean stack rule requires exactly one item to be on the stack after script execution, found ${this.stack.length}.`),0===this.stack.length?this.scriptEvaluationError("The top stack element must be truthy after script evaluation (stack is empty)."):this.castToBool(this.stackTop())||this.scriptEvaluationError("The top stack element must be truthy after script evaluation."),!0}castToBool(e){if(0===e.length)return!1;for(let t=0;t<e.length;t++)if(0!==e[t])return t!==e.length-1||128!==e[t];return!1}scriptEvaluationError(e){throw new iR({message:e,txid:this.sourceTXID,outputIndex:this.sourceOutputIndex,context:this.context,programCounter:this.programCounter,stackState:this.stack,altStackState:this.altStack,ifStackState:this.ifStack,stackMem:this.stackMem,altStackMem:this.altStackMem})}}class iL{lock(e){let t;if("string"==typeof e){let i=tf(e);if(0!==i.prefix[0]&&111!==i.prefix[0])throw Error("only P2PKH is supported");t=i.data}else t=e;if(20!==t.length)throw Error("P2PKH hash length must be 20 bytes");return new iT([{op:im.OP_DUP},{op:im.OP_HASH160},{op:t.length,data:t},{op:im.OP_EQUALVERIFY},{op:im.OP_CHECKSIG}])}unlock(e,t="all",i=!1,r,n){return{sign:async(a,s)=>{let o=iv.SIGHASH_FORKID;"all"===t&&(o|=iv.SIGHASH_ALL),"none"===t&&(o|=iv.SIGHASH_NONE),"single"===t&&(o|=iv.SIGHASH_SINGLE),i&&(o|=iv.SIGHASH_ANYONECANPAY);let c=a.inputs[s],l=a.inputs.filter((e,t)=>t!==s),h=c.sourceTXID??c.sourceTransaction?.id("hex");if(null==h||void 0===h||""===h)throw Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(null==(r||=c.sourceTransaction?.outputs[c.sourceOutputIndex].satoshis)||void 0===r)throw Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");if(null==(n||=c.sourceTransaction?.outputs[c.sourceOutputIndex].lockingScript))throw Error("The lockingScript or input sourceTransaction is required for transaction signing.");let d=iv.format({sourceTXID:h,sourceOutputIndex:tw(c.sourceOutputIndex,"input.sourceOutputIndex must have value"),sourceSatoshis:r,transactionVersion:a.version,otherInputs:l,inputIndex:s,outputs:a.outputs,inputSequence:tw(c.sequence,"input.sequence must have value"),subscript:n,lockTime:a.lockTime,scope:o}),u=e.sign(ea(d)),f=new iv(u.r,u.s,o).toChecksigFormat(),p=e.toPublicKey().encode(!0);return new i_([{op:f.length,data:f},{op:p.length,data:p}])},estimateLength:async()=>108}}}class iF{type="raw";constructor(e="raw"){this.type=e}lock(e){let t=[{op:im.OP_OVER},{op:im.OP_3},{op:im.OP_SPLIT},{op:im.OP_NIP},{op:im.OP_1},{op:im.OP_SPLIT},{op:im.OP_SWAP},{op:im.OP_SPLIT},{op:im.OP_DROP}];return"raw"!==this.type&&t.push({op:im["OP_"+this.type]}),t.push({op:e.length,data:e}),t.push({op:im.OP_EQUALVERIFY}),t.push({op:im.OP_CHECKSIG}),new iT(t)}unlock(e,t,i="all",r=!1){return{sign:async(n,a)=>{void 0===t&&(t=t3.fromRandom());let s=iv.SIGHASH_FORKID;"all"===i&&(s|=iv.SIGHASH_ALL),"none"===i&&(s|=iv.SIGHASH_NONE),"single"===i&&(s|=iv.SIGHASH_SINGLE),r&&(s|=iv.SIGHASH_ANYONECANPAY);let o=[...n.inputs],[c]=o.splice(a,1);if("object"!=typeof c.sourceTransaction)throw Error("The source transaction is needed for transaction signing.");let l=iv.format({sourceTXID:c.sourceTransaction?.id("hex")??"",sourceOutputIndex:c.sourceOutputIndex??0,sourceSatoshis:c.sourceTransaction?.outputs[c.sourceOutputIndex]?.satoshis??0,transactionVersion:n.version,otherInputs:o,inputIndex:a,outputs:n.outputs,inputSequence:c.sequence??0xffffffff,subscript:c.sourceTransaction?.outputs[c.sourceOutputIndex]?.lockingScript??new ib,lockTime:n.lockTime,scope:s}),h=t.sign(ea(l),void 0,!0,e),d=new iv(h.r,h.s,s).toChecksigFormat(),u=t.toPublicKey().encode(!0);return new i_([{op:d.length,data:d},{op:u.length,data:u}])},estimateLength:async()=>108}}}let iH=e=>0===e.length||1===e.length&&0===e[0]?{op:0}:1===e.length&&e[0]>0&&e[0]<=16?{op:80+e[0]}:1===e.length&&129===e[0]?{op:79}:e.length<=75?{op:e.length,data:e}:e.length<=255?{op:76,data:e}:e.length<=65535?{op:77,data:e}:{op:78,data:e};class iK{wallet;originator;static decode(e,t="before"){let i,r;if("before"===t)i=tJ.fromString(te(tw(e.chunks[0].data,"script.chunks[0].data must have value"))),r=2;else{let t=e.chunks.length-1;if(e.chunks[t].op!==im.OP_CHECKSIG)throw Error("Expected OP_CHECKSIG at the end of the script");i=tJ.fromString(te(tw(e.chunks[t-1].data,"public key chunk data must have value"))),r=0}let n=[];for(let t=r;t<e.chunks.length;t++){let i=e.chunks[t+1]?.op,r=e.chunks[t].data??[];if(0===r.length&&(e.chunks[t].op>=80&&e.chunks[t].op<=95?r=[e.chunks[t].op-80]:0===e.chunks[t].op?r=[0]:79===e.chunks[t].op&&(r=[129])),n.push(r),i===im.OP_DROP||i===im.OP_2DROP)break}return{fields:n,lockingPublicKey:i}}constructor(e,t){this.wallet=e,this.originator=t}async lock(e,t,i,r,n=!1,a=!0,s="before"){let{publicKey:o}=await this.wallet.getPublicKey({protocolID:t,keyID:i,counterparty:r,forSelf:n},this.originator),c=[],l=[];if(c.push({op:o.length/2,data:ti(o,"hex")}),c.push({op:im.OP_CHECKSIG}),a){let n=e.reduce((e,t)=>[...e,...t],[]),{signature:a}=await this.wallet.createSignature({data:n,protocolID:t,keyID:i,counterparty:r},this.originator);e.push(a)}for(let t of e)l.push(iH(t));let h=e.length;for(;h>1;)l.push({op:im.OP_2DROP}),h-=2;return new iT((0!==h&&l.push({op:im.OP_DROP}),"before"===s)?[...c,...l]:[...l,...c])}unlock(e,t,i,r="all",n=!1,a,s){return{sign:async(o,c)=>{let l=iv.SIGHASH_FORKID;"all"===r&&(l|=iv.SIGHASH_ALL),"none"===r&&(l|=iv.SIGHASH_NONE),"single"===r&&(l|=iv.SIGHASH_SINGLE),n&&(l|=iv.SIGHASH_ANYONECANPAY);let h=o.inputs[c],d=o.inputs.filter((e,t)=>t!==c),u=h.sourceTXID??h.sourceTransaction?.id("hex");if(null==u||void 0===u)throw Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(null==(a||=h.sourceTransaction?.outputs[h.sourceOutputIndex].satoshis)||void 0===a)throw Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");if(null==(s||=h.sourceTransaction?.outputs[h.sourceOutputIndex].lockingScript))throw Error("The lockingScript or input sourceTransaction is required for transaction signing.");let f=ea(iv.format({sourceTXID:u,sourceOutputIndex:tw(h.sourceOutputIndex,"input.sourceOutputIndex must have value"),sourceSatoshis:a,transactionVersion:o.version,otherInputs:d,inputIndex:c,outputs:o.outputs,inputSequence:h.sequence??0xffffffff,subscript:s,lockTime:o.lockTime,scope:l})),{signature:p}=await this.wallet.createSignature({data:f,protocolID:e,keyID:t,counterparty:i},this.originator),g=tK.fromDER([...p]),m=new iv(g.r,g.s,l).toChecksigFormat();return new i_([{op:m.length,data:m}])},estimateLength:async()=>73}}}class iM{value;constructor(e){this.value=e}async computeFee(e){let t,i=e=>e>0x100000000?9:e>65536?5:e>253?3:1;t=4+i(e.inputs.length);for(let r=0;r<e.inputs.length;r++){let n,a=e.inputs[r];if(t+=40,"object"==typeof a.unlockingScript)n=a.unlockingScript.toBinary().length;else if("object"==typeof a.unlockingScriptTemplate)n=await a.unlockingScriptTemplate.estimateLength(e,r);else throw Error("All inputs must have an unlocking script or an unlocking script template for sat/kb fee computation.");t+=i(n),t+=n}for(let r of(t+=i(e.outputs.length),e.outputs)){t+=8;let e=r.lockingScript.toBinary().length;t+=i(e),t+=e}return Math.ceil((t+=4)/1e3*this.value)}}class iq extends iM{static ARC_POLICY_URL="https://arc.gorillapool.io/v1/policy";static instance=null;cachedRate=null;cacheTimestamp=0;cacheValidityMs;constructor(e=3e5){super(100),this.cacheValidityMs=e}static getInstance(e=3e5){return iq.instance||(iq.instance=new iq(e)),iq.instance}async fetchFeeRate(){let e=Date.now();if(null!==this.cachedRate&&e-this.cacheTimestamp<this.cacheValidityMs)return this.cachedRate;try{let t=await fetch(iq.ARC_POLICY_URL);if(!t.ok)throw Error(`HTTP ${t.status}: ${t.statusText}`);let i=await t.json();if(!i.policy?.miningFee||"number"!=typeof i.policy.miningFee.satoshis||"number"!=typeof i.policy.miningFee.bytes)throw Error("Invalid policy response format");let r=i.policy.miningFee.satoshis/i.policy.miningFee.bytes*1e3;return this.cachedRate=r,this.cacheTimestamp=e,r}catch(e){if(null!==this.cachedRate)return console.warn("Failed to fetch live fee rate, using cached value:",e),this.cachedRate;return console.warn("Failed to fetch live fee rate, using default 100 sat/kb:",e),100}}async computeFee(e){let t=await this.fetchFeeRate();return this.value=t,super.computeFee(e)}}class i${https;constructor(e){this.https=e}async request(e,t){return await new Promise((i,r)=>{let n=this.https.request(e,t,e=>{let t="";e.on("data",e=>{t+=e}),e.on("end",()=>{let r=e.statusCode>=200&&e.statusCode<=299,n=e.headers["content-type"],a=""!==t&&"string"==typeof n&&n.startsWith("application/json")?JSON.parse(t):t;i({status:e.statusCode,statusText:e.statusMessage,ok:r,data:a})})});n.on("error",e=>{r(e)}),null!==t.data&&void 0!==t.data&&n.write(JSON.stringify(t.data)),n.end()})}}class iz{fetch;constructor(e){this.fetch=e}async request(e,t){let i={method:t.method,headers:t.headers,body:JSON.stringify(t.data)},r=await this.fetch(e,i),n=r.headers.get("Content-Type"),a=n?.startsWith("application/json")?await r.json():await r.text();return{ok:r.ok,status:r.status,statusText:r.statusText,data:a}}}function iW(){let e={async request(){throw Error("No method available to perform HTTP request")}};if("u">typeof window&&"function"==typeof window.fetch)return new iz(window.fetch.bind(window));if(!("u">typeof require))return e;try{let e=require("https");return new i$(e)}catch(t){return e}}function ij(){return`ts-sdk-${te(t0(16))}`}class iX{URL;apiKey;deploymentId;callbackUrl;callbackToken;headers;httpClient;constructor(e,t){if(this.URL=e,"string"==typeof t)this.apiKey=t,this.httpClient=iW(),this.deploymentId=ij(),this.callbackToken=void 0,this.callbackUrl=void 0;else{const{apiKey:e,deploymentId:i,httpClient:r,callbackToken:n,callbackUrl:a,headers:s}=t??{};this.apiKey=e,this.httpClient=r??iW(),this.deploymentId=i??ij(),this.callbackToken=n,this.callbackUrl=a,this.headers=s}}requestHeaders(){let e={"Content-Type":"application/json","XDeployment-ID":this.deploymentId};if(null!=this.apiKey&&""!==this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),null!=this.callbackUrl&&""!==this.callbackUrl&&(e["X-CallbackUrl"]=this.callbackUrl),null!=this.callbackToken&&""!==this.callbackToken&&(e["X-CallbackToken"]=this.callbackToken),null!=this.headers)for(let t in this.headers)e[t]=this.headers[t];return e}async broadcast(e){let t;try{t=e.toHexEF()}catch(i){if("All inputs must have source transactions when serializing to EF format"===i.message)t=e.toHex();else throw i}let i={method:"POST",headers:this.requestHeaders(),data:{rawTx:t}};try{let e=await this.httpClient.request(`${this.URL}/v1/tx`,i);if(e.ok){let{txid:t,extraInfo:i,txStatus:r,competingTxs:n}=e.data,a=i?.toUpperCase().includes("ORPHAN")||r?.toUpperCase().includes("ORPHAN");if(["DOUBLE_SPEND_ATTEMPTED","REJECTED","INVALID","MALFORMED","MINED_IN_STALE_BLOCK"].includes(r?.toUpperCase())||a){let e={status:"error",code:r??"UNKNOWN",txid:t,description:`${r??""} ${i??""}`.trim()};return null!=n&&(e.more={competingTxs:n}),e}let s={status:"success",txid:t,message:`${r} ${i}`};return null!=n&&(s.competingTxs=n),s}{let t=typeof e.status,i={status:"error",code:"number"===t||"string"===t?e.status.toString():"ERR_UNKNOWN",description:"Unknown error"},r=e.data;if("string"==typeof r)try{r=JSON.parse(e.data)}catch{}return"object"==typeof r&&(null!==r&&(i.more=r),null!=r&&"string"==typeof r.txid&&(i.txid=r.txid),null!=r&&"detail"in r&&"string"==typeof r.detail&&(i.description=r.detail)),i}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}async broadcastMany(e){let t=e.map(e=>{try{return{rawTx:e.toHexEF()}}catch(t){if("All inputs must have source transactions when serializing to EF format"===t.message)return{rawTx:e.toHex()};throw t}}),i={method:"POST",headers:this.requestHeaders(),data:t};try{return(await this.httpClient.request(`${this.URL}/v1/txs`,i)).data}catch(i){let t={status:"error",code:"500",description:"string"==typeof i.message?i.message:"Internal Server Error"};return e.map(()=>t)}}}function iG(e=!1,t={}){return new iX(e?"https://testnet.arc.gorillapool.io":"https://arc.gorillapool.io",t)}class iY{network;apiKey;URL;httpClient;constructor(e="main",t={}){const{apiKey:i,httpClient:r}=t;this.network=e,this.URL=`https://api.whatsonchain.com/v1/bsv/${e}`,this.httpClient=r??iW(),this.apiKey=i??""}async isValidRootForHeight(e,t){let i={method:"GET",headers:this.getHttpHeaders()},r=await this.httpClient.request(`${this.URL}/block/${t}/header`,i);if(r.ok){let{merkleroot:t}=r.data;return t===e}if(404===r.status)return!1;throw Error(`Failed to verify merkleroot for height ${t} because of an error: ${JSON.stringify(r.data)} `)}async currentHeight(){try{let e={method:"GET",headers:this.getHttpHeaders()},t=await this.httpClient.request(`${this.URL}/block/headers`,e);if(t.ok)return t.data[0].height;throw Error(`Failed to get current height because of an error: ${JSON.stringify(t.data)} `)}catch(e){throw Error(`Failed to get current height because of an error: ${e instanceof Error?e.message:String(e)}`)}}getHttpHeaders(){let e={Accept:"application/json"};return"string"==typeof this.apiKey&&""!==this.apiKey.trim()&&(e.Authorization=this.apiKey),e}}function iJ(){return new iY}class iZ{blockHeight;path;static fromHex(e){return iZ.fromBinary(ti(e,"hex"))}static fromReader(e,t=!0){let i,r,n,a=e.readVarIntNum(),s=e.readUInt8(),o=Array(s).fill(null).map(()=>[]);for(let t=0;t<s;t++){for(n=e.readVarIntNum();n>0;){r=e.readVarIntNum(),i=e.readUInt8();let a={offset:r};(1&i)!=0?a.duplicate=!0:((2&i)!=0&&(a.txid=!0),a.hash=te(e.read(32).reverse())),Array.isArray(o[t])&&0!==o[t].length||(o[t]=[]),o[t].push(a),n--}o[t].sort((e,t)=>e.offset-t.offset)}return new iZ(a,o,t)}static fromBinary(e){let t=new e3(e);return iZ.fromReader(t)}static fromCoinbaseTxidAndHeight(e,t){return new iZ(t,[[{offset:0,hash:e,txid:!0}]])}constructor(e,t,i=!0){let r;this.blockHeight=e,this.path=t;const n=Array(this.path.length).fill(0).map(()=>new Set);this.path.forEach((e,t)=>{if(0===e.length&&0===t)throw Error(`Empty level at height: ${t}`);let r=new Set;e.forEach(e=>{if(r.has(e.offset))throw Error(`Duplicate offset: ${e.offset}, at height: ${t}`);if(r.add(e.offset),0===t){if(!0!==e.duplicate)for(let t=1;t<this.path.length;t++)n[t].add(e.offset>>t^1)}else if(i&&!n[t].has(e.offset))throw Error(`Invalid offset: ${e.offset}, at height: ${t}, with legal offsets: ${Array.from(n[t]).join(", ")}`)})}),this.path[0].forEach((e,t)=>{if(0===t&&(r=this.computeRoot(e.hash)),r!==this.computeRoot(e.hash))throw Error("Mismatched roots")})}toWriter(e){e.writeVarIntNum(this.blockHeight);let t=this.path.length;e.writeUInt8(t);for(let i=0;i<t;i++){let t=Object.keys(this.path[i]).length;for(let r of(e.writeVarIntNum(t),this.path[i])){e.writeVarIntNum(r.offset);let t=0;r?.duplicate===!0&&(t|=1),r?.txid!==void 0&&null!==r.txid&&(t|=2),e.writeUInt8(t),(1&t)==0&&e.write(ti(r.hash,"hex").reverse())}}}toBinary(){let e=new tp;return this.toWriter(e),e.toArray()}toBinaryUint8Array(){let e=new e8;return this.toWriter(e),e.toUint8Array()}toHex(){return te(this.toBinaryUint8Array())}indexOf(e){let t=this.path[0].find(t=>t.hash===e);if(null==t)throw Error(`Transaction ID ${e} not found in the Merkle Path`);return t.offset}computeRoot(e){if("string"!=typeof e){let t=this.path[0].find(e=>!!e?.hash);if(null==t)throw Error("No valid leaf found in the Merkle Path");e=t.hash}if("string"!=typeof e)throw Error("Transaction ID is undefined");let t=this.indexOf(e);if("number"!=typeof t)throw Error(`This proof does not contain the txid: ${e??"undefined"}`);let i=e=>te(eo(ti(e,"hex").reverse()).reverse()),r=e;if(1===this.path.length&&1===this.path[0].length)return r;for(let e=0;e<this.path.length;e++){this.path[e];let n=t>>e^1,a=this.findOrComputeLeaf(e,n);if("object"!=typeof a)throw Error(`Missing hash for index ${t} at height ${e}`);r=i(!0===a.duplicate?(r??"")+(r??""):n%2!=0?(a.hash??"")+(r??""):(r??"")+(a.hash??""))}return r}findOrComputeLeaf(e,t){let i=e=>te(eo(ti(e,"hex").reverse()).reverse()),r=this.path[e].find(e=>e.offset===t);if(null!=r)return r;if(0===e)return;let n=e-1,a=t<<1,s=this.findOrComputeLeaf(n,a);if(null==s||null==s.hash||""===s.hash)return;let o=this.findOrComputeLeaf(n,a+1);if(null!=o)return{offset:t,hash:i(!0===o.duplicate?s.hash+s.hash:(o.hash??"")+(s.hash??""))}}async verify(e,t){let i=this.computeRoot(e);if(0===this.indexOf(e)){let e=await t.currentHeight();if(this.blockHeight+100<e)return!1}return await t.isValidRootForHeight(i,this.blockHeight)}combine(e){if(this.blockHeight!==e.blockHeight)throw Error("You cannot combine paths which do not have the same block height.");if(this.computeRoot()!==e.computeRoot())throw Error("You cannot combine paths which do not have the same root.");let t=[];for(let i=0;i<this.path.length;i++){t.push([]);for(let e=0;e<this.path[i].length;e++)t[i].push(this.path[i][e]);for(let r=0;r<e.path[i].length;r++)if(void 0===t[i].find(t=>t.offset===e.path[i][r].offset))t[i].push(e.path[i][r]);else if(e.path[i][r]?.txid!==void 0&&e.path[i][r]?.txid!==null){let n=t[i].find(t=>t.offset===e.path[i][r].offset);null!=n&&(n.txid=!0)}}this.path=t,this.trim()}trim(){let e=(e,t)=>{(0===t.length||t.slice(-1)[0]!==e)&&t.push(e)},t=(e,t)=>{for(let i=e.length;i>=0;i--){let r=this.path[t].findIndex(t=>t.offset===e[i]);r>=0&&this.path[t].splice(r,1)}},i=t=>{let i=[];for(let r of t)e(r>>1,i);return i},r=[],n=[];for(let e=0;e<this.path.length;e++)this.path[e].sort((e,t)=>e.offset-t.offset);for(let t=0;t<this.path[0].length;t++){let i=this.path[0][t];if(!0===i.txid)e(i.offset>>1,r);else{let r=i.offset%2==1,a=this.path[0][t+(r?-1:1)];void 0!==a.txid&&null!==a.txid&&a.txid||e(a.offset,n)}}t(n,0);for(let e=1;e<this.path.length;e++)n=r,r=i(r),t(n,e)}}class iQ{_bumpIndex;_tx;_rawTx;_txid;inputTxids=[];isValid=void 0;get bumpIndex(){return this._bumpIndex}set bumpIndex(e){this._bumpIndex=e,this.updateInputTxids()}get hasProof(){return void 0!==this._bumpIndex}get isTxidOnly(){return void 0!==this._txid&&null!==this._txid&&null==this._rawTx&&null==this._tx}get txid(){if(void 0!==this._txid&&null!==this._txid&&""!==this._txid)return this._txid;if(null!=this._tx)return this._txid=this._tx.id("hex"),this._txid;if(null!=this._rawTx)return this._txid=te(eo(this._rawTx)),this._txid;throw Error("Internal")}get tx(){return null!=this._tx?this._tx:null!=this._rawTx?(this._tx=i3.fromBinary(this._rawTx),this._tx):void 0}get rawTx(){if(null!=this._rawTx)return Array.from(this._rawTx);if(null!=this._tx){let e=this._tx.toUint8Array();return this._rawTx=e,Array.from(e)}}get rawTxUint8Array(){return null!=this._rawTx?this._rawTx:null!=this._tx?(this._rawTx=this._tx.toUint8Array(),this._rawTx):void 0}constructor(e,t){if("string"==typeof e)this._txid=e;else if(e instanceof Uint8Array)this._rawTx=e;else if(Array.isArray(e))this._rawTx=new Uint8Array(e);else if(e instanceof i3)this._tx=e;else throw Error("Invalid transaction data type");this.bumpIndex=t,this.updateInputTxids()}static fromTx(e,t){return new iQ(e,t)}static fromRawTx(e,t){return new iQ(e,t)}static fromTxid(e,t){return new iQ(e,t)}updateInputTxids(){if(this.hasProof||null==this.tx)this.inputTxids=[];else{let e=new Set;for(let t of this.tx.inputs)void 0!==t.sourceTXID&&null!==t.sourceTXID&&""!==t.sourceTXID&&e.add(t.sourceTXID);this.inputTxids=Array.from(e)}}toWriter(e,t){let i=t=>{e.writeUInt8(t)},r=()=>{if(null==this._txid)throw Error("Transaction ID (_txid) is undefined");e.writeReverse(ti(this._txid,"hex"))},n=()=>{let t=this.rawTxUint8Array;if(null==t)throw Error("a valid serialized Transaction is expected");e.write(t)},a=()=>{void 0===this.bumpIndex?i(l.RAWTX):(i(l.RAWTX_AND_BUMP_INDEX),e.writeVarIntNum(this.bumpIndex))};t===i1?this.isTxidOnly?(i(l.TXID_ONLY),r()):(void 0!==this.bumpIndex?(i(l.RAWTX_AND_BUMP_INDEX),e.writeVarIntNum(this.bumpIndex)):i(l.RAWTX),n()):(n(),a())}static fromReader(e,t){let i,r,n;if(t===i1){let t=e.readUInt8();t===l.TXID_ONLY?n=iQ.fromTxid(te(e.readReverse(32))):(t===l.RAWTX_AND_BUMP_INDEX&&(r=e.readVarIntNum()),i=i3.fromReader(e),n=iQ.fromTx(i,r))}else i=i3.fromReader(e),r=0!==e.readUInt8()?e.readVarIntNum():void 0,n=iQ.fromTx(i,r);return n}}let i0=0xefbe0001,i1=0xefbe0002,i2=0x1010101;(a=l||(l={}))[a.RAWTX=0]="RAWTX",a[a.RAWTX_AND_BUMP_INDEX=1]="RAWTX_AND_BUMP_INDEX",a[a.TXID_ONLY=2]="TXID_ONLY";class i8{bumps=[];txs=[];version=i1;atomicTxid=void 0;txidIndex=void 0;rawBytesCache;hexCache;needsSort=!0;constructor(e=i1){this.version=e}invalidateSerializationCaches(){this.rawBytesCache=void 0,this.hexCache=void 0}markMutated(e=!0){this.invalidateSerializationCaches(),e&&(this.needsSort=!0)}ensureSerializableState(){for(let e of this.txs)e.txid}ensureSortedForSerialization(){this.needsSort&&this.sortTxs()}getSerializedBytes(){if(this.ensureSerializableState(),null==this.rawBytesCache){this.ensureSortedForSerialization();let e=new e8;this.toWriter(e),this.rawBytesCache=e.toUint8Array()}return this.rawBytesCache}getBeefForAtomic(e){this.needsSort&&this.sortTxs();let t=this.findTxid(e);if(null==t)throw Error(`${e} does not exist in this Beef`);let i=this.txs[this.txs.length-1]===t?this:this.clone();if(i!==this){let t=this.txs.findIndex(t=>t.txid===e);i.txs.splice(t+1)}let r=new e8;return r.writeUInt32LE(i2),r.writeReverse(ti(e,"hex")),{beef:i,writer:r}}findTxid(e){return this.ensureTxidIndex().get(e)}ensureTxidIndex(){if(null==this.txidIndex)for(let e of(this.txidIndex=new Map,this.txs))this.txidIndex.set(e.txid,e);return this.txidIndex}deleteFromIndex(e){this.txidIndex?.delete(e)}addToIndex(e){this.txidIndex?.set(e.txid,e)}makeTxidOnly(e){let t=this.txs.findIndex(t=>t.txid===e);if(-1===t)return;let i=this.txs[t];return i.isTxidOnly?i:(this.deleteFromIndex(e),this.txs.splice(t,1),this.markMutated(!0),i=this.mergeTxidOnly(e))}findBump(e){return this.bumps.find(t=>t.path[0].some(t=>t.hash===e))}findTransactionForSigning(e){let t=this.findTxid(e);if(null!=t&&null!=t.tx){for(let e of t.tx.inputs)if(null==e.sourceTransaction){let t=this.findTxid(tw(e.sourceTXID,"sourceTXID must be valid"));null!=t&&(e.sourceTransaction=t.tx)}return t.tx}}findAtomicTransaction(e){let t=this.findTxid(e);if(null==t||null==t.tx)return;let i=(e,t)=>{let r=e.findBump(t.id("hex"));if(null!=r)t.merklePath=r;else for(let r of t.inputs){if(null==r.sourceTransaction){let t=e.findTxid(tw(r.sourceTXID,"sourceTXID must be valid"));null!=t&&(r.sourceTransaction=t.tx)}if(null!=r.sourceTransaction){let t=e.findBump(r.sourceTransaction.id("hex"));null!=t?r.sourceTransaction.merklePath=t:i(e,r.sourceTransaction)}}};return i(this,t.tx),t.tx}mergeBump(e){let t;this.markMutated(!1);for(let i=0;i<this.bumps.length;i++){let r=this.bumps[i];if(r===e)return i;if(r.blockHeight===e.blockHeight&&r.computeRoot()===e.computeRoot()){r.combine(e),t=i;break}}void 0===t&&(t=this.bumps.length,this.bumps.push(e));let i=this.bumps[t];for(let e of this.txs){let r=e.txid;if(null==e.bumpIndex){for(let n of i.path[0])if(n.hash===r){e.bumpIndex=t,n.txid=!0;break}}}return t}mergeRawTx(e,t){this.markMutated(!0);let i=new iQ(e,t);return this.removeExistingTxid(i.txid),this.txs.push(i),this.addToIndex(i),this.tryToValidateBumpIndex(i),i}mergeTransaction(e){let t;this.markMutated(!0);let i=e.id("hex");this.removeExistingTxid(i),null!=e.merklePath&&(t=this.mergeBump(e.merklePath));let r=new iQ(e,t);if(this.txs.push(r),this.addToIndex(r),this.tryToValidateBumpIndex(r),void 0===(t=r.bumpIndex))for(let t of e.inputs)null!=t.sourceTransaction&&this.mergeTransaction(t.sourceTransaction);return r}removeExistingTxid(e){let t=this.txs.findIndex(t=>t.txid===e);t>=0&&(this.deleteFromIndex(e),this.txs.splice(t,1),this.markMutated(!0))}mergeTxidOnly(e){let t=this.findTxid(e);return null==t&&(t=new iQ(e),this.txs.push(t),this.addToIndex(t),this.tryToValidateBumpIndex(t),this.markMutated(!0)),t}mergeBeefTx(e){let t=this.findTxid(e.txid);if(e.isTxidOnly&&null==t?t=this.mergeTxidOnly(e.txid):null!=e._tx&&(null==t||t.isTxidOnly)?t=this.mergeTransaction(e._tx):null!=e._rawTx&&(null==t||t.isTxidOnly)&&(t=this.mergeRawTx(e._rawTx)),null==t)throw Error(`Failed to merge BeefTx for txid: ${e.txid}`);return t}mergeBeef(e){let t=e instanceof i8?e:i8.fromBinary(e);for(let e of t.bumps)this.mergeBump(e);for(let e of t.txs)this.mergeBeefTx(e)}isValid(e){return this.verifyValid(e).valid}async verify(e,t){let i=this.verifyValid(t);if(!i.valid)return!1;for(let t of Object.keys(i.roots))if(!await e.isValidRootForHeight(i.roots[t],Number(t)))return!1;return!0}verifyValid(e){let t={valid:!1,roots:{}},i=this.sortTxs();if(i.missingInputs.length>0||i.notValid.length>0||i.txidOnly.length>0&&!0!==e||i.withMissingInputs.length>0)return t;let r={};for(let i of this.txs)if(i.isTxidOnly){if(!0!==e)return t;r[i.txid]=!0}let n=(e,i)=>{let r=e.computeRoot(i);return(void 0===t.roots[e.blockHeight]||""===t.roots[e.blockHeight])&&(t.roots[e.blockHeight]=r),t.roots[e.blockHeight]===r};for(let e of this.bumps)for(let i of e.path[0])if(!0===i.txid&&"string"==typeof i.hash&&i.hash.length>0&&(r[i.hash]=!0,!n(e,i.hash)))return t;for(let e of this.txs)if(void 0!==e.bumpIndex&&null==this.bumps[e.bumpIndex].path[0].find(t=>t.hash===e.txid))return t;for(let e of this.txs){for(let i of e.inputTxids)if(!r[i])return t;r[e.txid]=!0}return t.valid=!0,t}toWriter(e){for(let t of(e.writeUInt32LE(this.version),e.writeVarIntNum(this.bumps.length),this.bumps))e.write(t.toBinary());for(let t of(e.writeVarIntNum(this.txs.length),this.txs))t.toWriter(e,this.version)}toBinary(){return Array.from(this.getSerializedBytes())}toUint8Array(){return this.getSerializedBytes()}toBinaryAtomic(e){let{beef:t,writer:i}=this.getBeefForAtomic(e);return t.toWriter(i),i.toArray()}toUint8ArrayAtomic(e){let{beef:t,writer:i}=this.getBeefForAtomic(e),r=t.getSerializedBytes(),n=i.toUint8Array(),a=new Uint8Array(n.length+r.length);return a.set(n,0),a.set(r,n.length),a}toHex(){if(null!=this.hexCache)return this.hexCache;let e=te(this.getSerializedBytes());return this.hexCache=e,e}static fromReader(e){let t,i=e.readUInt32LE();if(i===i2&&(t=te(e.readReverse(32)),i=e.readUInt32LE()),i!==i0&&i!==i1)throw Error(`Serialized BEEF must start with ${i0} or ${i1} but starts with ${i}`);let r=new i8(i),n=e.readVarIntNum();for(let t=0;t<n;t++){let t=iZ.fromReader(e,!1);r.bumps.push(t)}let a=e.readVarIntNum();for(let t=0;t<a;t++){let t=iQ.fromReader(e,i);r.txs.push(t)}return r.atomicTxid=t,r}static fromBinary(e){let t=e3.makeReader(e);return i8.fromReader(t)}static fromString(e,t="hex"){let i=new e3(tt(e,t));return i8.fromReader(i)}tryToValidateBumpIndex(e){if(void 0!==e.bumpIndex)return!0;let t=e.txid;for(let i=0;i<this.bumps.length;i++){let r=this.bumps[i].path[0].findIndex(e=>e.hash===t);if(r>=0)return e.bumpIndex=i,this.bumps[i].path[0][r].txid=!0,!0}return!1}sortTxs(){let e={},t={},i=[],r=[],n=[];for(let a of this.txs)t[a.txid]=a,a.isValid=a.hasProof,a.isValid?(e[a.txid]=!0,r.push(a)):a.isTxidOnly&&0===a.inputTxids.length?(e[a.txid]=!0,n.push(a)):i.push(a);let a={},s=[],o=i;for(let e of(i=[],o)){let r=!1;for(let i of e.inputTxids)void 0===t[i]&&(a[i]=!0,r=!0);r?s.push(e):i.push(e)}for(;i.length>0;){let t=i;for(let n of(i=[],t))n.inputTxids.every(t=>e[t])?(e[n.txid]=!0,r.push(n)):i.push(n);if(t.length===i.length)break}let c=i;return this.txs=s.concat(c).concat(n).concat(r),this.needsSort=!1,this.invalidateSerializationCaches(),{missingInputs:Object.keys(a),notValid:c.map(e=>e.txid),valid:Object.keys(e),withMissingInputs:s.map(e=>e.txid),txidOnly:n.map(e=>e.txid)}}clone(){let e=new i8;return e.version=this.version,e.bumps=Array.from(this.bumps),e.txs=Array.from(this.txs),e.txidIndex=void 0,e.needsSort=this.needsSort,e.hexCache=this.hexCache,e.rawBytesCache=this.rawBytesCache,e}trimKnownTxids(e){let t=!1;for(let i=0;i<this.txs.length;){let r=this.txs[i];r.isTxidOnly&&e.includes(r.txid)?(this.deleteFromIndex(r.txid),this.txs.splice(i,1),t=!0):i++}let i=new Set;for(let e of this.txs)void 0!==e.bumpIndex&&i.add(e.bumpIndex);if(i.size<this.bumps.length){let e=new Map,r=0;for(let t=0;t<this.bumps.length;t++)i.has(t)&&(e.set(t,r),r++);for(let t of(this.bumps=this.bumps.filter((e,t)=>i.has(t)),this.txs))if(void 0!==t.bumpIndex){let i=e.get(t.bumpIndex);if(void 0===i)throw Error(`Internal error: bumpIndex ${t.bumpIndex} not found in indexMap`);t.bumpIndex=i}t=!0}t&&this.markMutated(!0)}getValidTxids(){return this.sortTxs().valid}toLogString(){let e="";e+=`BEEF with ${this.bumps.length} BUMPS and ${this.txs.length} Transactions, isValid ${this.isValid().toString()}
|
|
6
|
+
${s}`),this.name=this.constructor.name,this.txid=e.txid,this.outputIndex=e.outputIndex,this.context=e.context,this.programCounter=e.programCounter,this.stackState=e.stackState.map(e=>e.slice()),this.altStackState=e.altStackState.map(e=>e.slice()),this.ifStackState=e.ifStackState.slice(),this.stackMem=e.stackMem,this.altStackMem=e.altStackMem}}let iC=BigInt(0x7fffffff),iB=Object.freeze(new P(-1).toScriptNum()),iU=Object.freeze(Array.from({length:17},(e,t)=>Object.freeze(new P(t).toScriptNum())));function iV(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}class iD{sourceTXID;sourceOutputIndex;sourceSatoshis;lockingScript;transactionVersion;otherInputs;outputs;inputIndex;unlockingScript;inputSequence;lockTime;context;programCounter;lastCodeSeparator;stack;altStack;ifStack;memoryLimit;stackMem;altStackMem;isRelaxedOverride;sigHashCache;constructor(e){this.sourceTXID=e.sourceTXID,this.sourceOutputIndex=e.sourceOutputIndex,this.sourceSatoshis=e.sourceSatoshis,this.lockingScript=e.lockingScript,this.transactionVersion=e.transactionVersion,this.otherInputs=e.otherInputs,this.outputs=e.outputs,this.inputIndex=e.inputIndex,this.unlockingScript=e.unlockingScript,this.inputSequence=e.inputSequence,this.lockTime=e.lockTime,this.memoryLimit=e.memoryLimit??32e6,this.isRelaxedOverride=!0===e.isRelaxed,this.stack=[],this.altStack=[],this.ifStack=[],this.stackMem=0,this.altStackMem=0,this.sigHashCache={hashOutputsSingle:new Map},this.reset()}isRelaxed(){return this.isRelaxedOverride||this.transactionVersion>1}reset(){this.context="UnlockingScript",this.programCounter=0,this.lastCodeSeparator=null,this.stack=[],this.altStack=[],this.ifStack=[],this.stackMem=0,this.altStackMem=0,this.sigHashCache={hashOutputsSingle:new Map}}ensureStackMem(e){this.stackMem+e>this.memoryLimit&&this.scriptEvaluationError("Stack memory usage has exceeded "+String(this.memoryLimit)+" bytes")}ensureAltStackMem(e){this.altStackMem+e>this.memoryLimit&&this.scriptEvaluationError("Alt stack memory usage has exceeded "+String(this.memoryLimit)+" bytes")}pushStack(e){this.ensureStackMem(e.length),this.stack.push(e),this.stackMem+=e.length}pushStackCopy(e){this.ensureStackMem(e.length);let t=e.slice();this.stack.push(t),this.stackMem+=t.length}popStack(){0===this.stack.length&&this.scriptEvaluationError("Attempted to pop from an empty stack.");let e=this.stack.pop();return this.stackMem-=e.length,e}stackTop(e=-1){return(0===this.stack.length||this.stack.length<Math.abs(e)||e>=0&&e>=this.stack.length)&&this.scriptEvaluationError(`Stack underflow accessing element at index ${e}. Stack length is ${this.stack.length}.`),this.stack[this.stack.length+e]}pushAltStack(e){this.ensureAltStackMem(e.length),this.altStack.push(e),this.altStackMem+=e.length}popAltStack(){0===this.altStack.length&&this.scriptEvaluationError("Attempted to pop from an empty alt stack.");let e=this.altStack.pop();return this.altStackMem-=e.length,e}checkSignatureEncoding(e){if(0===e.length)return!0;if(!function(e){if(e.length<9||e.length>73||48!==e[0]||e[1]!==e.length-3)return!1;let t=e[2],i=e[3];if(2!==t||0===i||5+i>=e.length)return!1;let r=4+i,n=e[r],a=e[r+1];if(2!==n||0===a||(128&e[4])!=0||i>1&&0===e[4]&&(128&e[5])==0)return!1;let s=r+2;return(128&e[s])==0&&(!(a>1)||0!==e[s]||(128&e[s+1])!=0)&&i+a+7===e.length}(e))return this.scriptEvaluationError("The signature format is invalid."),!1;try{let t=iv.fromChecksigFormat(e);if(!this.isRelaxed()&&!t.hasLowS())return this.scriptEvaluationError("The signature must have a low S value."),!1}catch(e){return this.scriptEvaluationError("The signature format is invalid."),!1}return!0}checkPublicKeyEncoding(e){if(0===e.length)return this.scriptEvaluationError("Public key is empty."),!1;if(e.length<33)return this.scriptEvaluationError("The public key is too short, it must be at least 33 bytes."),!1;if(4===e[0]){if(65!==e.length)return this.scriptEvaluationError("The non-compressed public key must be 65 bytes."),!1}else if(2!==e[0]&&3!==e[0])return this.scriptEvaluationError("The public key is in an unknown format."),!1;else if(33!==e.length)return this.scriptEvaluationError("The compressed public key must be 33 bytes."),!1;try{tJ.fromDER(e)}catch(e){return this.scriptEvaluationError("The public key is in an unknown format."),!1}return!0}verifySignature(e,t,i){return tY(new P(eo(iv.formatBytes({sourceTXID:this.sourceTXID,sourceOutputIndex:this.sourceOutputIndex,sourceSatoshis:this.sourceSatoshis,transactionVersion:this.transactionVersion,otherInputs:this.otherInputs,outputs:this.outputs,inputIndex:this.inputIndex,subscript:i,inputSequence:this.inputSequence,lockTime:this.lockTime,scope:e.scope,cache:this.sigHashCache}))),e,t)}step(){if(this.stackMem>this.memoryLimit)return this.scriptEvaluationError("Stack memory usage has exceeded "+String(this.memoryLimit)+" bytes"),!1;if(this.altStackMem>this.memoryLimit)return this.scriptEvaluationError("Alt stack memory usage has exceeded "+String(this.memoryLimit)+" bytes"),!1;"UnlockingScript"===this.context&&this.programCounter>=this.unlockingScript.chunks.length&&(this.context="LockingScript",this.programCounter=0);let e="UnlockingScript"===this.context?this.unlockingScript:this.lockingScript;if(this.programCounter>=e.chunks.length)return!1;let t=e.chunks[this.programCounter],i=t.op;void 0===i&&this.scriptEvaluationError(`Missing opcode in ${this.context} at pc=${this.programCounter}.`),Array.isArray(t.data)&&t.data.length>0x40000000&&this.scriptEvaluationError(`Data push > 1073741824 bytes (pc=${this.programCounter}).`);let r=!this.ifStack.includes(!1);if(r&&i>=0&&i<=im.OP_PUSHDATA4){let e,i;!this.isRelaxed()&&(e=t.data,i=t.op,Array.isArray(e)&&(0===e.length?i!==im.OP_0:1===e.length&&e[0]>=1&&e[0]<=16?i!==im.OP_1+(e[0]-1):1===e.length&&129===e[0]?i!==im.OP_1NEGATE:e.length<=75?i!==e.length:e.length<=255?i!==im.OP_PUSHDATA1:e.length<=65535&&i!==im.OP_PUSHDATA2))&&this.scriptEvaluationError(`This data is not minimally-encoded. (PC: ${this.programCounter})`),this.pushStack(Array.isArray(t.data)?t.data:[])}else if(r||i>=im.OP_IF&&i<=im.OP_ENDIF){let e,t,n,a,s,o,c,l,h,d,u,f,p,g,m,y,b,w,v,I,k,S,E,x,A,N;switch(i){case im.OP_VER:this.pushStackCopy(new P(this.transactionVersion).toScriptNum());break;case im.OP_SUBSTR:{this.stack.length<3&&this.scriptEvaluationError("OP_SUBSTR requires at least three items to be on the stack.");let t=P.fromScriptNum(this.popStack(),!this.isRelaxed()).toNumber(),i=P.fromScriptNum(this.popStack(),!this.isRelaxed()).toNumber(),r=(e=this.popStack()).length;(i<0||i>=r||t<0||t>r-i)&&this.scriptEvaluationError(`OP_SUBSTR offset (${i}) must be in range [0, ${r}) and length (${t}) must be in range [0, ${r-i}]`),this.pushStack(e.slice(i,i+t));break}case im.OP_LEFT:{this.stack.length<2&&this.scriptEvaluationError("OP_LEFT requires at least two items to be on the stack.");let t=P.fromScriptNum(this.popStack(),!this.isRelaxed()).toNumber(),i=(e=this.popStack()).length;(t<0||t>i)&&this.scriptEvaluationError(`OP_LEFT length (${t}) must be in range [0, ${i}]`),this.pushStack(e.slice(0,t));break}case im.OP_RIGHT:{this.stack.length<2&&this.scriptEvaluationError("OP_RIGHT requires at least two items to be on the stack.");let t=P.fromScriptNum(this.popStack(),!this.isRelaxed()).toNumber(),i=(e=this.popStack()).length;(t<0||t>i)&&this.scriptEvaluationError(`OP_RIGHT length (${t}) must be in range [0, ${i}]`),this.pushStack(e.slice(i-t,t));break}case im.OP_LSHIFTNUM:{this.stack.length<2&&this.scriptEvaluationError("OP_LSHIFTNUM requires at least two items to be on the stack.");let e=P.fromScriptNum(this.popStack(),!this.isRelaxed()).toBigInt();e<0&&this.scriptEvaluationError("OP_LSHIFTNUM bits to shift must not be negative.");let t=P.fromScriptNum(this.popStack(),!this.isRelaxed()).toBigInt(),i=new P(t<<e);this.pushStack(i.toScriptNum());break}case im.OP_RSHIFTNUM:{let e;this.stack.length<2&&this.scriptEvaluationError("OP_RSHIFTNUM requires at least two items to be on the stack.");let t=P.fromScriptNum(this.popStack(),!this.isRelaxed()).toBigInt();t<0&&this.scriptEvaluationError("OP_RSHIFTNUM bits to shift must not be negative.");let i=P.fromScriptNum(this.popStack(),!this.isRelaxed()).toBigInt();e=new P(i<0?-(-i>>t):i>>t),this.pushStack(e.toScriptNum());break}case im.OP_1NEGATE:this.pushStackCopy(iB);break;case im.OP_0:this.pushStackCopy(iU[0]);break;case im.OP_1:case im.OP_2:case im.OP_3:case im.OP_4:case im.OP_5:case im.OP_6:case im.OP_7:case im.OP_8:case im.OP_9:case im.OP_10:case im.OP_11:case im.OP_12:case im.OP_13:case im.OP_14:case im.OP_15:case im.OP_16:f=i-(im.OP_1-1),this.pushStackCopy(iU[f]);break;case im.OP_NOP:case im.OP_NOP1:case im.OP_NOP2:case im.OP_NOP3:case im.OP_NOP7:case im.OP_NOP8:case im.OP_NOP9:case im.OP_NOP10:case im.OP_NOP11:case im.OP_NOP12:case im.OP_NOP13:case im.OP_NOP14:case im.OP_NOP15:case im.OP_NOP16:case im.OP_NOP17:case im.OP_NOP18:case im.OP_NOP19:case im.OP_NOP20:case im.OP_NOP21:case im.OP_NOP22:case im.OP_NOP23:case im.OP_NOP24:case im.OP_NOP25:case im.OP_NOP26:case im.OP_NOP27:case im.OP_NOP28:case im.OP_NOP29:case im.OP_NOP30:case im.OP_NOP31:case im.OP_NOP32:case im.OP_NOP33:case im.OP_NOP34:case im.OP_NOP35:case im.OP_NOP36:case im.OP_NOP37:case im.OP_NOP38:case im.OP_NOP39:case im.OP_NOP40:case im.OP_NOP41:case im.OP_NOP42:case im.OP_NOP43:case im.OP_NOP44:case im.OP_NOP45:case im.OP_NOP46:case im.OP_NOP47:case im.OP_NOP48:case im.OP_NOP49:case im.OP_NOP50:case im.OP_NOP51:case im.OP_NOP52:case im.OP_NOP53:case im.OP_NOP54:case im.OP_NOP55:case im.OP_NOP56:case im.OP_NOP57:case im.OP_NOP58:case im.OP_NOP59:case im.OP_NOP60:case im.OP_NOP61:case im.OP_NOP62:case im.OP_NOP63:case im.OP_NOP64:case im.OP_NOP65:case im.OP_NOP66:case im.OP_NOP67:case im.OP_NOP68:case im.OP_NOP69:case im.OP_NOP70:case im.OP_NOP71:case im.OP_NOP72:case im.OP_NOP73:case im.OP_NOP77:break;case im.OP_VERIF:case im.OP_VERNOTIF:g=!1,r&&(this.stack.length<1&&this.scriptEvaluationError("OP_VERIF and OP_VERNOTIF require at least one item on the stack when they are used!"),n=new P(this.transactionVersion).toScriptNum(),g=iV(t=this.popStack(),n),i===im.OP_VERNOTIF&&(g=!g)),this.ifStack.push(g);break;case im.OP_IF:case im.OP_NOTIF:g=!1,r&&(this.stack.length<1&&this.scriptEvaluationError("OP_IF and OP_NOTIF require at least one item on the stack when they are used!"),e=this.popStack(),g=this.castToBool(e),i===im.OP_NOTIF&&(g=!g)),this.ifStack.push(g);break;case im.OP_ELSE:0===this.ifStack.length&&this.scriptEvaluationError("OP_ELSE requires a preceeding OP_IF."),this.ifStack[this.ifStack.length-1]=!this.ifStack[this.ifStack.length-1];break;case im.OP_ENDIF:0===this.ifStack.length&&this.scriptEvaluationError("OP_ENDIF requires a preceeding OP_IF."),this.ifStack.pop();break;case im.OP_VERIFY:this.stack.length<1&&this.scriptEvaluationError("OP_VERIFY requires at least one item to be on the stack."),t=this.stackTop(),(g=this.castToBool(t))||this.scriptEvaluationError("OP_VERIFY requires the top stack value to be truthy."),this.popStack();break;case im.OP_RETURN:"UnlockingScript"===this.context?this.programCounter=this.unlockingScript.chunks.length:this.programCounter=this.lockingScript.chunks.length,this.ifStack=[],this.programCounter--;break;case im.OP_TOALTSTACK:this.stack.length<1&&this.scriptEvaluationError("OP_TOALTSTACK requires at oeast one item to be on the stack."),this.pushAltStack(this.popStack());break;case im.OP_FROMALTSTACK:this.altStack.length<1&&this.scriptEvaluationError("OP_FROMALTSTACK requires at least one item to be on the stack."),this.pushStack(this.popAltStack());break;case im.OP_2DROP:this.stack.length<2&&this.scriptEvaluationError("OP_2DROP requires at least two items to be on the stack."),this.popStack(),this.popStack();break;case im.OP_2DUP:this.stack.length<2&&this.scriptEvaluationError("OP_2DUP requires at least two items to be on the stack."),t=this.stackTop(-2),n=this.stackTop(-1),this.pushStackCopy(t),this.pushStackCopy(n);break;case im.OP_3DUP:this.stack.length<3&&this.scriptEvaluationError("OP_3DUP requires at least three items to be on the stack."),t=this.stackTop(-3),n=this.stackTop(-2),a=this.stackTop(-1),this.pushStackCopy(t),this.pushStackCopy(n),this.pushStackCopy(a);break;case im.OP_2OVER:this.stack.length<4&&this.scriptEvaluationError("OP_2OVER requires at least four items to be on the stack."),t=this.stackTop(-4),n=this.stackTop(-3),this.pushStackCopy(t),this.pushStackCopy(n);break;case im.OP_2ROT:{this.stack.length<6&&this.scriptEvaluationError("OP_2ROT requires at least six items to be on the stack.");let e=this.popStack(),t=this.popStack(),i=this.popStack(),r=this.popStack(),n=this.popStack(),a=this.popStack();this.pushStack(r),this.pushStack(i),this.pushStack(t),this.pushStack(e),this.pushStack(a),this.pushStack(n);break}case im.OP_2SWAP:{this.stack.length<4&&this.scriptEvaluationError("OP_2SWAP requires at least four items to be on the stack.");let e=this.popStack(),t=this.popStack(),i=this.popStack(),r=this.popStack();this.pushStack(t),this.pushStack(e),this.pushStack(r),this.pushStack(i);break}case im.OP_IFDUP:this.stack.length<1&&this.scriptEvaluationError("OP_IFDUP requires at least one item to be on the stack."),t=this.stackTop(),this.castToBool(t)&&this.pushStackCopy(t);break;case im.OP_DEPTH:this.pushStack(new P(this.stack.length).toScriptNum());break;case im.OP_DROP:this.stack.length<1&&this.scriptEvaluationError("OP_DROP requires at least one item to be on the stack."),this.popStack();break;case im.OP_DUP:this.stack.length<1&&this.scriptEvaluationError("OP_DUP requires at least one item to be on the stack."),this.pushStackCopy(this.stackTop());break;case im.OP_NIP:this.stack.length<2&&this.scriptEvaluationError("OP_NIP requires at least two items to be on the stack."),n=this.popStack(),this.popStack(),this.pushStack(n);break;case im.OP_OVER:this.stack.length<2&&this.scriptEvaluationError("OP_OVER requires at least two items to be on the stack."),this.pushStackCopy(this.stackTop(-2));break;case im.OP_PICK:case im.OP_ROLL:{this.stack.length<2&&this.scriptEvaluationError(`${im[i]} requires at least two items to be on the stack.`);let e=(l=P.fromScriptNum(this.popStack(),!this.isRelaxed())).toBigInt();(e<0n||e>=BigInt(this.stack.length))&&this.scriptEvaluationError(`${im[i]} requires the top stack element to be 0 or a positive number less than the current size of the stack.`);let t=Number(e),r=this.stack[this.stack.length-1-t];i===im.OP_ROLL?(this.stack.splice(this.stack.length-1-t,1),this.stackMem-=r.length,this.pushStack(r)):this.pushStackCopy(r);break}case im.OP_ROT:this.stack.length<3&&this.scriptEvaluationError("OP_ROT requires at least three items to be on the stack."),c=this.popStack(),o=this.popStack(),s=this.popStack(),this.pushStack(o),this.pushStack(c),this.pushStack(s);break;case im.OP_SWAP:this.stack.length<2&&this.scriptEvaluationError("OP_SWAP requires at least two items to be on the stack."),o=this.popStack(),s=this.popStack(),this.pushStack(o),this.pushStack(s);break;case im.OP_TUCK:this.stack.length<2&&this.scriptEvaluationError("OP_TUCK requires at least two items to be on the stack."),t=this.stackTop(-1),this.ensureStackMem(t.length),this.stack.splice(this.stack.length-2,0,t.slice()),this.stackMem+=t.length;break;case im.OP_SIZE:this.stack.length<1&&this.scriptEvaluationError("OP_SIZE requires at least one item to be on the stack."),this.pushStack(new P(this.stackTop().length).toScriptNum());break;case im.OP_AND:case im.OP_OR:case im.OP_XOR:{this.stack.length<2&&this.scriptEvaluationError(`${im[i]} requires at least two items on the stack.`),n=this.popStack(),(t=this.popStack()).length!==n.length&&this.scriptEvaluationError(`${im[i]} requires the top two stack items to be the same size.`);let e=Array(t.length);for(let r=0;r<t.length;r++)i===im.OP_AND?e[r]=t[r]&n[r]:i===im.OP_OR?e[r]=t[r]|n[r]:e[r]=t[r]^n[r];this.pushStack(e);break}case im.OP_INVERT:{this.stack.length<1&&this.scriptEvaluationError("OP_INVERT requires at least one item to be on the stack.");let t=Array((e=this.popStack()).length);for(let i=0;i<e.length;i++)t[i]=255&~e[i];this.pushStack(t);break}case im.OP_LSHIFT:case im.OP_RSHIFT:{let e;this.stack.length<2&&this.scriptEvaluationError(`${im[i]} requires at least two items to be on the stack.`),d=P.fromScriptNum(this.popStack(),!this.isRelaxed()),t=this.popStack();let r=d.toBigInt();if(r<0n&&this.scriptEvaluationError(`${im[i]} requires the top item on the stack not to be negative.`),0===t.length){this.pushStack([]);break}if(h=new P(t),i===im.OP_LSHIFT){e=h.ushln(r);let i=new P(1).ushln(8*t.length).isubn(1);e=e.iand(i)}else e=h.ushrn(r);let n=e.toArray("be",t.length);this.pushStack(n);break}case im.OP_EQUAL:case im.OP_EQUALVERIFY:this.stack.length<2&&this.scriptEvaluationError(`${im[i]} requires at least two items to be on the stack.`),n=this.popStack(),g=iV(t=this.popStack(),n),this.pushStack(g?[1]:[]),i===im.OP_EQUALVERIFY&&(g||this.scriptEvaluationError("OP_EQUALVERIFY requires the top two stack items to be equal."),this.popStack());break;case im.OP_1ADD:case im.OP_1SUB:case im.OP_2MUL:case im.OP_2DIV:case im.OP_NEGATE:case im.OP_ABS:case im.OP_NOT:case im.OP_0NOTEQUAL:switch(this.stack.length<1&&this.scriptEvaluationError(`${im[i]} requires at least one item to be on the stack.`),l=P.fromScriptNum(this.popStack(),!this.isRelaxed()),i){case im.OP_1ADD:l=l.add(new P(1));break;case im.OP_1SUB:l=l.sub(new P(1));break;case im.OP_2MUL:l=l.mul(new P(2));break;case im.OP_2DIV:l=l.div(new P(2));break;case im.OP_NEGATE:l=l.neg();break;case im.OP_ABS:l.isNeg()&&(l=l.neg());break;case im.OP_NOT:l=new P(+(0===l.cmpn(0)));break;case im.OP_0NOTEQUAL:l=new P(+(0!==l.cmpn(0)))}this.pushStack(l.toScriptNum());break;case im.OP_ADD:case im.OP_SUB:case im.OP_MUL:case im.OP_DIV:case im.OP_MOD:case im.OP_BOOLAND:case im.OP_BOOLOR:case im.OP_NUMEQUAL:case im.OP_NUMEQUALVERIFY:case im.OP_NUMNOTEQUAL:case im.OP_LESSTHAN:case im.OP_GREATERTHAN:case im.OP_LESSTHANOREQUAL:case im.OP_GREATERTHANOREQUAL:case im.OP_MIN:case im.OP_MAX:{this.stack.length<2&&this.scriptEvaluationError(`${im[i]} requires at least two items to be on the stack.`),n=this.popStack(),t=this.popStack(),d=P.fromScriptNum(n,!this.isRelaxed()),h=P.fromScriptNum(t,!this.isRelaxed());let e=0;switch(i){case im.OP_MUL:e=h.byteLength()+d.byteLength();break;case im.OP_ADD:case im.OP_SUB:e=Math.max(h.byteLength(),d.byteLength())+1;break;default:e=Math.max(h.byteLength(),d.byteLength())}this.ensureStackMem(e);let r=new P(0);switch(i){case im.OP_ADD:r=h.add(d);break;case im.OP_SUB:r=h.sub(d);break;case im.OP_MUL:r=h.mul(d);break;case im.OP_DIV:0===d.cmpn(0)&&this.scriptEvaluationError("OP_DIV cannot divide by zero!"),r=h.div(d);break;case im.OP_MOD:0===d.cmpn(0)&&this.scriptEvaluationError("OP_MOD cannot divide by zero!"),r=h.mod(d);break;case im.OP_BOOLAND:r=new P(+(0!==h.cmpn(0)&&0!==d.cmpn(0)));break;case im.OP_BOOLOR:r=new P(+(0!==h.cmpn(0)||0!==d.cmpn(0)));break;case im.OP_NUMEQUAL:case im.OP_NUMEQUALVERIFY:r=new P(+(0===h.cmp(d)));break;case im.OP_NUMNOTEQUAL:r=new P(+(0!==h.cmp(d)));break;case im.OP_LESSTHAN:r=new P(+(0>h.cmp(d)));break;case im.OP_GREATERTHAN:r=new P(+(h.cmp(d)>0));break;case im.OP_LESSTHANOREQUAL:r=new P(+(0>=h.cmp(d)));break;case im.OP_GREATERTHANOREQUAL:r=new P(+(h.cmp(d)>=0));break;case im.OP_MIN:r=0>h.cmp(d)?h:d;break;case im.OP_MAX:r=h.cmp(d)>0?h:d}this.pushStack(r.toScriptNum()),i===im.OP_NUMEQUALVERIFY&&(this.castToBool(this.stackTop())||this.scriptEvaluationError("OP_NUMEQUALVERIFY requires the top stack item to be truthy."),this.popStack());break}case im.OP_WITHIN:this.stack.length<3&&this.scriptEvaluationError("OP_WITHIN requires at least three items to be on the stack."),u=P.fromScriptNum(this.popStack(),!this.isRelaxed()),d=P.fromScriptNum(this.popStack(),!this.isRelaxed()),g=(h=P.fromScriptNum(this.popStack(),!this.isRelaxed())).cmp(d)>=0&&0>h.cmp(u),this.pushStack(g?[1]:[]);break;case im.OP_RIPEMD160:case im.OP_SHA1:case im.OP_SHA256:case im.OP_HASH160:case im.OP_HASH256:{this.stack.length<1&&this.scriptEvaluationError(`${im[i]} requires at least one item to be on the stack.`),e=this.popStack();let t=[];i===im.OP_RIPEMD160?t=er(e):i===im.OP_SHA1?t=en(e):i===im.OP_SHA256?t=ea(e):i===im.OP_HASH160?t=ec(e):i===im.OP_HASH256&&(t=eo(e)),this.pushStack(t);break}case im.OP_CODESEPARATOR:this.lastCodeSeparator=this.programCounter;break;case im.OP_CHECKSIG:case im.OP_CHECKSIGVERIFY:if(this.stack.length<2&&this.scriptEvaluationError(`${im[i]} requires at least two items to be on the stack.`),w=this.popStack(),b=this.popStack(),this.checkSignatureEncoding(b)&&this.checkPublicKeyEncoding(w)||this.scriptEvaluationError(`${im[i]} requires correct encoding for the public key and signature.`),m=!1,b.length>0)try{v=iv.fromChecksigFormat(b);let e=("UnlockingScript"===this.context?this.unlockingScript:this.lockingScript).chunks.slice(null===this.lastCodeSeparator?0:this.lastCodeSeparator+1);(y=new ib(e)).findAndDelete(new ib().writeBin(b)),I=tJ.fromDER(w),m=this.verifySignature(v,I,y)}catch(e){m=!1}this.pushStack(m?[1]:[]),i===im.OP_CHECKSIGVERIFY&&(m||this.scriptEvaluationError("OP_CHECKSIGVERIFY requires that a valid signature is provided."),this.popStack());break;case im.OP_CHECKMULTISIG:case im.OP_CHECKMULTISIGVERIFY:{k=1,this.stack.length<k&&this.scriptEvaluationError(`${im[i]} requires at least 1 item for nKeys.`);let e=P.fromScriptNum(this.stackTop(-k),!this.isRelaxed()).toBigInt();(e<0n||e>iC)&&this.scriptEvaluationError(`${im[i]} requires a key count between 0 and 2147483647.`);let t=x=Number(e);S=++k,k+=x,this.stack.length<k&&this.scriptEvaluationError(`${im[i]} stack too small for nKeys and keys. Need ${k}, have ${this.stack.length}.`);let r=P.fromScriptNum(this.stackTop(-k),!this.isRelaxed()).toBigInt();(r<0n||r>BigInt(x))&&this.scriptEvaluationError(`${im[i]} requires the number of signatures to be no greater than the number of keys.`);let n=A=Number(r);E=++k,k+=A,this.stack.length<k&&this.scriptEvaluationError(`${im[i]} stack too small for N, keys, M, sigs, and dummy. Need ${k}, have ${this.stack.length}.`),y=new ib(("UnlockingScript"===this.context?this.unlockingScript:this.lockingScript).chunks.slice(null===this.lastCodeSeparator?0:this.lastCodeSeparator+1));for(let e=0;e<A;e++)b=this.stackTop(-E-e),y.findAndDelete(new ib().writeBin(b));for(m=!0;m&&A>0;){if(0===x){m=!1;break}if(b=this.stackTop(-E),w=this.stackTop(-S),this.checkSignatureEncoding(b)&&this.checkPublicKeyEncoding(w)||this.scriptEvaluationError(`${im[i]} requires correct encoding for the public key and signature.`),N=!1,b.length>0)try{v=iv.fromChecksigFormat(b),I=tJ.fromDER(w),N=this.verifySignature(v,I,y)}catch(e){N=!1}N&&(E++,A--),S++,A>--x&&(m=!1)}let a=1+t+1+n+1-1;for(;a>0;)this.popStack(),a--;this.stack.length<1&&this.scriptEvaluationError(`${im[i]} requires an extra item (dummy) to be on the stack.`);let s=this.popStack();!this.isRelaxed()&&s.length>0&&this.scriptEvaluationError(`${im[i]} requires the extra stack item (dummy) to be empty.`),this.pushStack(m?[1]:[]),i===im.OP_CHECKMULTISIGVERIFY&&(m||this.scriptEvaluationError("OP_CHECKMULTISIGVERIFY requires that a sufficient number of valid signatures are provided."),this.popStack());break}case im.OP_CAT:{this.stack.length<2&&this.scriptEvaluationError("OP_CAT requires at least two items to be on the stack."),n=this.popStack();let e=(t=this.popStack()).concat(n);e.length>0x40000000&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes."),this.pushStack(e);break}case im.OP_SPLIT:{this.stack.length<2&&this.scriptEvaluationError("OP_SPLIT requires at least two items to be on the stack.");let e=this.popStack(),t=this.popStack(),i=P.fromScriptNum(e,!this.isRelaxed()).toBigInt();(i<0n||i>BigInt(t.length))&&this.scriptEvaluationError("OP_SPLIT requires the first stack item to be a non-negative number less than or equal to the size of the second-from-top stack item.");let r=Number(i);this.pushStack(t.slice(0,r)),this.pushStack(t.slice(r));break}case im.OP_NUM2BIN:{this.stack.length<2&&this.scriptEvaluationError("OP_NUM2BIN requires at least two items to be on the stack.");let e=P.fromScriptNum(this.popStack(),!this.isRelaxed()).toBigInt();(e>BigInt(0x40000000)||e<0n)&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes or negative size."),p=Number(e);let t=this.popStack();if((t=tm(t)).length>p&&this.scriptEvaluationError("OP_NUM2BIN requires that the size expressed in the top stack item is large enough to hold the value expressed in the second-from-top stack item."),t.length===p){this.pushStack(t);break}let i=Array(p).fill(0),r=0;t.length>0&&(r=128&t[t.length-1],t[t.length-1]&=127);for(let e=0;e<t.length;e++)i[e]=t[e];0!==r&&(i[p-1]|=128),this.pushStack(i);break}case im.OP_BIN2NUM:{this.stack.length<1&&this.scriptEvaluationError("OP_BIN2NUM requires at least one item to be on the stack.");let e=tm(t=this.popStack());!function(e,t=Number.MAX_SAFE_INTEGER){return!(e.length>t)&&(!(e.length>0)||(127&e[e.length-1])!=0||!(e.length<=1)&&(128&e[e.length-2])!=0)}(e)&&this.scriptEvaluationError("OP_BIN2NUM requires that the resulting number is valid."),this.pushStack(e);break}default:this.scriptEvaluationError(`Invalid opcode ${i} (pc=${this.programCounter}).`)}}return this.programCounter++,!0}validate(){for(this.isRelaxed()||this.unlockingScript.isPushOnly()||this.scriptEvaluationError("Unlocking scripts can only contain push operations, and no other opcodes.");this.step()&&("LockingScript"!==this.context||!(this.programCounter>=this.lockingScript.chunks.length)););return this.ifStack.length>0&&this.scriptEvaluationError("Every OP_IF, OP_NOTIF, or OP_ELSE must be terminated with OP_ENDIF prior to the end of the script."),this.isRelaxed()||1===this.stack.length||this.scriptEvaluationError(`The clean stack rule requires exactly one item to be on the stack after script execution, found ${this.stack.length}.`),0===this.stack.length?this.scriptEvaluationError("The top stack element must be truthy after script evaluation (stack is empty)."):this.castToBool(this.stackTop())||this.scriptEvaluationError("The top stack element must be truthy after script evaluation."),!0}castToBool(e){if(0===e.length)return!1;for(let t=0;t<e.length;t++)if(0!==e[t])return t!==e.length-1||128!==e[t];return!1}scriptEvaluationError(e){throw new iR({message:e,txid:this.sourceTXID,outputIndex:this.sourceOutputIndex,context:this.context,programCounter:this.programCounter,stackState:this.stack,altStackState:this.altStack,ifStackState:this.ifStack,stackMem:this.stackMem,altStackMem:this.altStackMem})}}class iL{lock(e){let t;if("string"==typeof e){let i=tf(e);if(0!==i.prefix[0]&&111!==i.prefix[0])throw Error("only P2PKH is supported");t=i.data}else t=e;if(20!==t.length)throw Error("P2PKH hash length must be 20 bytes");return new iT([{op:im.OP_DUP},{op:im.OP_HASH160},{op:t.length,data:t},{op:im.OP_EQUALVERIFY},{op:im.OP_CHECKSIG}])}unlock(e,t="all",i=!1,r,n){return{sign:async(a,s)=>{let o=iv.SIGHASH_FORKID;"all"===t&&(o|=iv.SIGHASH_ALL),"none"===t&&(o|=iv.SIGHASH_NONE),"single"===t&&(o|=iv.SIGHASH_SINGLE),i&&(o|=iv.SIGHASH_ANYONECANPAY);let c=a.inputs[s],l=a.inputs.filter((e,t)=>t!==s),h=c.sourceTXID??c.sourceTransaction?.id("hex");if(null==h||void 0===h||""===h)throw Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(null==(r||=c.sourceTransaction?.outputs[c.sourceOutputIndex].satoshis)||void 0===r)throw Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");if(null==(n||=c.sourceTransaction?.outputs[c.sourceOutputIndex].lockingScript))throw Error("The lockingScript or input sourceTransaction is required for transaction signing.");let d=iv.format({sourceTXID:h,sourceOutputIndex:tw(c.sourceOutputIndex,"input.sourceOutputIndex must have value"),sourceSatoshis:r,transactionVersion:a.version,otherInputs:l,inputIndex:s,outputs:a.outputs,inputSequence:tw(c.sequence,"input.sequence must have value"),subscript:n,lockTime:a.lockTime,scope:o}),u=e.sign(ea(d)),f=new iv(u.r,u.s,o).toChecksigFormat(),p=e.toPublicKey().encode(!0);return new i_([{op:f.length,data:f},{op:p.length,data:p}])},estimateLength:async()=>108}}}class iF{type="raw";constructor(e="raw"){this.type=e}lock(e){let t=[{op:im.OP_OVER},{op:im.OP_3},{op:im.OP_SPLIT},{op:im.OP_NIP},{op:im.OP_1},{op:im.OP_SPLIT},{op:im.OP_SWAP},{op:im.OP_SPLIT},{op:im.OP_DROP}];return"raw"!==this.type&&t.push({op:im["OP_"+this.type]}),t.push({op:e.length,data:e}),t.push({op:im.OP_EQUALVERIFY}),t.push({op:im.OP_CHECKSIG}),new iT(t)}unlock(e,t,i="all",r=!1){return{sign:async(n,a)=>{void 0===t&&(t=t3.fromRandom());let s=iv.SIGHASH_FORKID;"all"===i&&(s|=iv.SIGHASH_ALL),"none"===i&&(s|=iv.SIGHASH_NONE),"single"===i&&(s|=iv.SIGHASH_SINGLE),r&&(s|=iv.SIGHASH_ANYONECANPAY);let o=[...n.inputs],[c]=o.splice(a,1);if("object"!=typeof c.sourceTransaction)throw Error("The source transaction is needed for transaction signing.");let l=iv.format({sourceTXID:c.sourceTransaction?.id("hex")??"",sourceOutputIndex:c.sourceOutputIndex??0,sourceSatoshis:c.sourceTransaction?.outputs[c.sourceOutputIndex]?.satoshis??0,transactionVersion:n.version,otherInputs:o,inputIndex:a,outputs:n.outputs,inputSequence:c.sequence??0xffffffff,subscript:c.sourceTransaction?.outputs[c.sourceOutputIndex]?.lockingScript??new ib,lockTime:n.lockTime,scope:s}),h=t.sign(ea(l),void 0,!0,e),d=new iv(h.r,h.s,s).toChecksigFormat(),u=t.toPublicKey().encode(!0);return new i_([{op:d.length,data:d},{op:u.length,data:u}])},estimateLength:async()=>108}}}let iH=e=>0===e.length||1===e.length&&0===e[0]?{op:0}:1===e.length&&e[0]>0&&e[0]<=16?{op:80+e[0]}:1===e.length&&129===e[0]?{op:79}:e.length<=75?{op:e.length,data:e}:e.length<=255?{op:76,data:e}:e.length<=65535?{op:77,data:e}:{op:78,data:e};class iK{wallet;originator;static decode(e,t="before"){let i,r;if("before"===t)i=tJ.fromString(te(tw(e.chunks[0].data,"script.chunks[0].data must have value"))),r=2;else{let t=e.chunks.length-1;if(e.chunks[t].op!==im.OP_CHECKSIG)throw Error("Expected OP_CHECKSIG at the end of the script");i=tJ.fromString(te(tw(e.chunks[t-1].data,"public key chunk data must have value"))),r=0}let n=[];for(let t=r;t<e.chunks.length;t++){let i=e.chunks[t+1]?.op,r=e.chunks[t].data??[];if(0===r.length&&(e.chunks[t].op>=80&&e.chunks[t].op<=95?r=[e.chunks[t].op-80]:0===e.chunks[t].op?r=[0]:79===e.chunks[t].op&&(r=[129])),n.push(r),i===im.OP_DROP||i===im.OP_2DROP)break}return{fields:n,lockingPublicKey:i}}constructor(e,t){this.wallet=e,this.originator=t}async lock(e,t,i,r,n=!1,a=!0,s="before"){let{publicKey:o}=await this.wallet.getPublicKey({protocolID:t,keyID:i,counterparty:r,forSelf:n},this.originator),c=[],l=[];if(c.push({op:o.length/2,data:ti(o,"hex")}),c.push({op:im.OP_CHECKSIG}),a){let n=e.reduce((e,t)=>[...e,...t],[]),{signature:a}=await this.wallet.createSignature({data:n,protocolID:t,keyID:i,counterparty:r},this.originator);e.push(a)}for(let t of e)l.push(iH(t));let h=e.length;for(;h>1;)l.push({op:im.OP_2DROP}),h-=2;return new iT((0!==h&&l.push({op:im.OP_DROP}),"before"===s)?[...c,...l]:[...l,...c])}unlock(e,t,i,r="all",n=!1,a,s){return{sign:async(o,c)=>{let l=iv.SIGHASH_FORKID;"all"===r&&(l|=iv.SIGHASH_ALL),"none"===r&&(l|=iv.SIGHASH_NONE),"single"===r&&(l|=iv.SIGHASH_SINGLE),n&&(l|=iv.SIGHASH_ANYONECANPAY);let h=o.inputs[c],d=o.inputs.filter((e,t)=>t!==c),u=h.sourceTXID??h.sourceTransaction?.id("hex");if(null==u||void 0===u)throw Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(null==(a||=h.sourceTransaction?.outputs[h.sourceOutputIndex].satoshis)||void 0===a)throw Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");if(null==(s||=h.sourceTransaction?.outputs[h.sourceOutputIndex].lockingScript))throw Error("The lockingScript or input sourceTransaction is required for transaction signing.");let f=ea(iv.format({sourceTXID:u,sourceOutputIndex:tw(h.sourceOutputIndex,"input.sourceOutputIndex must have value"),sourceSatoshis:a,transactionVersion:o.version,otherInputs:d,inputIndex:c,outputs:o.outputs,inputSequence:h.sequence??0xffffffff,subscript:s,lockTime:o.lockTime,scope:l})),{signature:p}=await this.wallet.createSignature({data:f,protocolID:e,keyID:t,counterparty:i},this.originator),g=tK.fromDER([...p]),m=new iv(g.r,g.s,l).toChecksigFormat();return new i_([{op:m.length,data:m}])},estimateLength:async()=>73}}}class iM{value;constructor(e){this.value=e}async computeFee(e){let t,i=e=>e>0x100000000?9:e>65536?5:e>253?3:1;t=4+i(e.inputs.length);for(let r=0;r<e.inputs.length;r++){let n,a=e.inputs[r];if(t+=40,"object"==typeof a.unlockingScript)n=a.unlockingScript.toBinary().length;else if("object"==typeof a.unlockingScriptTemplate)n=await a.unlockingScriptTemplate.estimateLength(e,r);else throw Error("All inputs must have an unlocking script or an unlocking script template for sat/kb fee computation.");t+=i(n),t+=n}for(let r of(t+=i(e.outputs.length),e.outputs)){t+=8;let e=r.lockingScript.toBinary().length;t+=i(e),t+=e}return Math.ceil((t+=4)/1e3*this.value)}}class iq extends iM{static ARC_POLICY_URL="https://arc.gorillapool.io/v1/policy";static instance=null;cachedRate=null;cacheTimestamp=0;cacheValidityMs;constructor(e=3e5){super(100),this.cacheValidityMs=e}static getInstance(e=3e5){return iq.instance||(iq.instance=new iq(e)),iq.instance}async fetchFeeRate(){let e=Date.now();if(null!==this.cachedRate&&e-this.cacheTimestamp<this.cacheValidityMs)return this.cachedRate;try{let t=await fetch(iq.ARC_POLICY_URL);if(!t.ok)throw Error(`HTTP ${t.status}: ${t.statusText}`);let i=await t.json();if(!i.policy?.miningFee||"number"!=typeof i.policy.miningFee.satoshis||"number"!=typeof i.policy.miningFee.bytes)throw Error("Invalid policy response format");let r=i.policy.miningFee.satoshis/i.policy.miningFee.bytes*1e3;return this.cachedRate=r,this.cacheTimestamp=e,r}catch(e){if(null!==this.cachedRate)return console.warn("Failed to fetch live fee rate, using cached value:",e),this.cachedRate;return console.warn("Failed to fetch live fee rate, using default 100 sat/kb:",e),100}}async computeFee(e){let t=await this.fetchFeeRate();return this.value=t,super.computeFee(e)}}class i${https;constructor(e){this.https=e}async request(e,t){return await new Promise((i,r)=>{let n=this.https.request(e,t,e=>{let t="";e.on("data",e=>{t+=e}),e.on("end",()=>{let r=e.statusCode>=200&&e.statusCode<=299,n=e.headers["content-type"],a=""!==t&&"string"==typeof n&&n.startsWith("application/json")?JSON.parse(t):t;i({status:e.statusCode,statusText:e.statusMessage,ok:r,data:a})})});n.on("error",e=>{r(e)}),null!==t.data&&void 0!==t.data&&n.write(JSON.stringify(t.data)),n.end()})}}class iz{fetch;constructor(e){this.fetch=e}async request(e,t){let i={method:t.method,headers:t.headers,body:JSON.stringify(t.data)},r=await this.fetch(e,i),n=r.headers.get("Content-Type"),a=n?.startsWith("application/json")?await r.json():await r.text();return{ok:r.ok,status:r.status,statusText:r.statusText,data:a}}}function iW(){let e={async request(){throw Error("No method available to perform HTTP request")}};if("u">typeof window&&"function"==typeof window.fetch)return new iz(window.fetch.bind(window));if(!("u">typeof require))return e;try{let e=require("https");return new i$(e)}catch(t){return e}}function ij(){return`ts-sdk-${te(t0(16))}`}class iX{URL;apiKey;deploymentId;callbackUrl;callbackToken;headers;httpClient;constructor(e,t){if(this.URL=e,"string"==typeof t)this.apiKey=t,this.httpClient=iW(),this.deploymentId=ij(),this.callbackToken=void 0,this.callbackUrl=void 0;else{const{apiKey:e,deploymentId:i,httpClient:r,callbackToken:n,callbackUrl:a,headers:s}=t??{};this.apiKey=e,this.httpClient=r??iW(),this.deploymentId=i??ij(),this.callbackToken=n,this.callbackUrl=a,this.headers=s}}requestHeaders(){let e={"Content-Type":"application/json","XDeployment-ID":this.deploymentId};if(null!=this.apiKey&&""!==this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),null!=this.callbackUrl&&""!==this.callbackUrl&&(e["X-CallbackUrl"]=this.callbackUrl),null!=this.callbackToken&&""!==this.callbackToken&&(e["X-CallbackToken"]=this.callbackToken),null!=this.headers)for(let t in this.headers)e[t]=this.headers[t];return e}async broadcast(e){let t;try{t=e.toHexEF()}catch(i){if("All inputs must have source transactions when serializing to EF format"===i.message)t=e.toHex();else throw i}let i={method:"POST",headers:this.requestHeaders(),data:{rawTx:t}};try{let e=await this.httpClient.request(`${this.URL}/v1/tx`,i);if(e.ok){let{txid:t,extraInfo:i,txStatus:r,competingTxs:n}=e.data,a=i?.toUpperCase().includes("ORPHAN")||r?.toUpperCase().includes("ORPHAN");if(["DOUBLE_SPEND_ATTEMPTED","REJECTED","INVALID","MALFORMED","MINED_IN_STALE_BLOCK"].includes(r?.toUpperCase())||a){let e={status:"error",code:r??"UNKNOWN",txid:t,description:`${r??""} ${i??""}`.trim()};return null!=n&&(e.more={competingTxs:n}),e}let s={status:"success",txid:t,message:`${r} ${i}`};return null!=n&&(s.competingTxs=n),s}{let t=typeof e.status,i={status:"error",code:"number"===t||"string"===t?e.status.toString():"ERR_UNKNOWN",description:"Unknown error"},r=e.data;if("string"==typeof r)try{r=JSON.parse(e.data)}catch{}return"object"==typeof r&&(null!==r&&(i.more=r),null!=r&&"string"==typeof r.txid&&(i.txid=r.txid),null!=r&&"detail"in r&&"string"==typeof r.detail&&(i.description=r.detail)),i}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}async broadcastMany(e){let t=e.map(e=>{try{return{rawTx:e.toHexEF()}}catch(t){if("All inputs must have source transactions when serializing to EF format"===t.message)return{rawTx:e.toHex()};throw t}}),i={method:"POST",headers:this.requestHeaders(),data:t};try{return(await this.httpClient.request(`${this.URL}/v1/txs`,i)).data}catch(i){let t={status:"error",code:"500",description:"string"==typeof i.message?i.message:"Internal Server Error"};return e.map(()=>t)}}}function iG(e=!1,t={}){return new iX(e?"https://testnet.arc.gorillapool.io":"https://arc.gorillapool.io",t)}class iY{network;apiKey;URL;httpClient;constructor(e="main",t={}){const{apiKey:i,httpClient:r}=t;this.network=e,this.URL=`https://api.whatsonchain.com/v1/bsv/${e}`,this.httpClient=r??iW(),this.apiKey=i??""}async isValidRootForHeight(e,t){let i={method:"GET",headers:this.getHttpHeaders()},r=await this.httpClient.request(`${this.URL}/block/${t}/header`,i);if(r.ok){let{merkleroot:t}=r.data;return t===e}if(404===r.status)return!1;throw Error(`Failed to verify merkleroot for height ${t} because of an error: ${JSON.stringify(r.data)} `)}async currentHeight(){try{let e={method:"GET",headers:this.getHttpHeaders()},t=await this.httpClient.request(`${this.URL}/block/headers`,e);if(t.ok)return t.data[0].height;throw Error(`Failed to get current height because of an error: ${JSON.stringify(t.data)} `)}catch(e){throw Error(`Failed to get current height because of an error: ${e instanceof Error?e.message:String(e)}`)}}getHttpHeaders(){let e={Accept:"application/json"};return"string"==typeof this.apiKey&&""!==this.apiKey.trim()&&(e.Authorization=this.apiKey),e}}function iJ(){return new iY}class iZ{blockHeight;path;static fromHex(e){return iZ.fromBinary(ti(e,"hex"))}static fromReader(e,t=!0){let i,r,n,a=e.readVarIntNum(),s=e.readUInt8(),o=Array(s).fill(null).map(()=>[]);for(let t=0;t<s;t++){for(n=e.readVarIntNum();n>0;){r=e.readVarIntNum(),i=e.readUInt8();let a={offset:r};(1&i)!=0?a.duplicate=!0:((2&i)!=0&&(a.txid=!0),a.hash=te(e.read(32).reverse())),Array.isArray(o[t])&&0!==o[t].length||(o[t]=[]),o[t].push(a),n--}o[t].sort((e,t)=>e.offset-t.offset)}return new iZ(a,o,t)}static fromBinary(e){let t=new e3(e);return iZ.fromReader(t)}static fromCoinbaseTxidAndHeight(e,t){return new iZ(t,[[{offset:0,hash:e,txid:!0}]])}constructor(e,t,i=!0){let r;this.blockHeight=e,this.path=t;const n=Array(this.path.length).fill(0).map(()=>new Set);this.path.forEach((e,t)=>{if(0===e.length&&0===t)throw Error(`Empty level at height: ${t}`);let r=new Set;e.forEach(e=>{if(r.has(e.offset))throw Error(`Duplicate offset: ${e.offset}, at height: ${t}`);if(r.add(e.offset),0===t){if(!0!==e.duplicate)for(let t=1;t<this.path.length;t++)n[t].add(e.offset>>t^1)}else if(i&&!n[t].has(e.offset))throw Error(`Invalid offset: ${e.offset}, at height: ${t}, with legal offsets: ${Array.from(n[t]).join(", ")}`)})}),this.path[0].forEach((e,t)=>{if(0===t&&(r=this.computeRoot(e.hash)),r!==this.computeRoot(e.hash))throw Error("Mismatched roots")})}toWriter(e){e.writeVarIntNum(this.blockHeight);let t=this.path.length;e.writeUInt8(t);for(let i=0;i<t;i++){let t=Object.keys(this.path[i]).length;for(let r of(e.writeVarIntNum(t),this.path[i])){e.writeVarIntNum(r.offset);let t=0;r?.duplicate===!0&&(t|=1),r?.txid!==void 0&&null!==r.txid&&(t|=2),e.writeUInt8(t),(1&t)==0&&e.write(ti(r.hash,"hex").reverse())}}}toBinary(){let e=new tp;return this.toWriter(e),e.toArray()}toBinaryUint8Array(){let e=new e8;return this.toWriter(e),e.toUint8Array()}toHex(){return te(this.toBinaryUint8Array())}indexOf(e){let t=this.path[0].find(t=>t.hash===e);if(null==t)throw Error(`Transaction ID ${e} not found in the Merkle Path`);return t.offset}computeRoot(e){if("string"!=typeof e){let t=this.path[0].find(e=>!!e?.hash);if(null==t)throw Error("No valid leaf found in the Merkle Path");e=t.hash}if("string"!=typeof e)throw Error("Transaction ID is undefined");let t=this.indexOf(e);if("number"!=typeof t)throw Error(`This proof does not contain the txid: ${e??"undefined"}`);let i=e=>te(eo(ti(e,"hex").reverse()).reverse()),r=e;if(1===this.path.length&&1===this.path[0].length)return r;for(let e=0;e<this.path.length;e++){this.path[e];let n=t>>e^1,a=this.findOrComputeLeaf(e,n);if("object"!=typeof a)throw Error(`Missing hash for index ${t} at height ${e}`);r=i(!0===a.duplicate?(r??"")+(r??""):n%2!=0?(a.hash??"")+(r??""):(r??"")+(a.hash??""))}return r}findOrComputeLeaf(e,t){let i=e=>te(eo(ti(e,"hex").reverse()).reverse()),r=this.path[e].find(e=>e.offset===t);if(null!=r)return r;if(0===e)return;let n=e-1,a=t<<1,s=this.findOrComputeLeaf(n,a);if(null==s||null==s.hash||""===s.hash)return;let o=this.findOrComputeLeaf(n,a+1);if(null!=o)return{offset:t,hash:i(!0===o.duplicate?s.hash+s.hash:(o.hash??"")+(s.hash??""))}}async verify(e,t){let i=this.computeRoot(e);if(0===this.indexOf(e)){let e=await t.currentHeight();if(this.blockHeight+100<e)return!1}return await t.isValidRootForHeight(i,this.blockHeight)}combine(e){if(this.blockHeight!==e.blockHeight)throw Error("You cannot combine paths which do not have the same block height.");if(this.computeRoot()!==e.computeRoot())throw Error("You cannot combine paths which do not have the same root.");let t=[];for(let i=0;i<this.path.length;i++){t.push([]);for(let e=0;e<this.path[i].length;e++)t[i].push(this.path[i][e]);for(let r=0;r<e.path[i].length;r++)if(void 0===t[i].find(t=>t.offset===e.path[i][r].offset))t[i].push(e.path[i][r]);else if(e.path[i][r]?.txid!==void 0&&e.path[i][r]?.txid!==null){let n=t[i].find(t=>t.offset===e.path[i][r].offset);null!=n&&(n.txid=!0)}}this.path=t,this.trim()}trim(){let e=(e,t)=>{(0===t.length||t.slice(-1)[0]!==e)&&t.push(e)},t=(e,t)=>{for(let i=e.length;i>=0;i--){let r=this.path[t].findIndex(t=>t.offset===e[i]);r>=0&&this.path[t].splice(r,1)}},i=t=>{let i=[];for(let r of t)e(r>>1,i);return i},r=[],n=[];for(let e=0;e<this.path.length;e++)this.path[e].sort((e,t)=>e.offset-t.offset);for(let t=0;t<this.path[0].length;t++){let i=this.path[0][t];if(!0===i.txid)e(i.offset>>1,r);else{let r=i.offset%2==1,a=this.path[0][t+(r?-1:1)];void 0!==a.txid&&null!==a.txid&&a.txid||e(a.offset,n)}}t(n,0);for(let e=1;e<this.path.length;e++)n=r,r=i(r),t(n,e)}}class iQ{_bumpIndex;_tx;_rawTx;_txid;inputTxids=[];isValid=void 0;get bumpIndex(){return this._bumpIndex}set bumpIndex(e){this._bumpIndex=e,this.updateInputTxids()}get hasProof(){return void 0!==this._bumpIndex}get isTxidOnly(){return void 0!==this._txid&&null!==this._txid&&null==this._rawTx&&null==this._tx}get txid(){if(void 0!==this._txid&&null!==this._txid&&""!==this._txid)return this._txid;if(null!=this._tx)return this._txid=this._tx.id("hex"),this._txid;if(null!=this._rawTx)return this._txid=te(eo(this._rawTx)),this._txid;throw Error("Internal")}get tx(){return null!=this._tx?this._tx:null!=this._rawTx?(this._tx=i3.fromBinary(this._rawTx),this._tx):void 0}get rawTx(){if(null!=this._rawTx)return Array.from(this._rawTx);if(null!=this._tx){let e=this._tx.toUint8Array();return this._rawTx=e,Array.from(e)}}get rawTxUint8Array(){return null!=this._rawTx?this._rawTx:null!=this._tx?(this._rawTx=this._tx.toUint8Array(),this._rawTx):void 0}constructor(e,t){if("string"==typeof e)this._txid=e;else if(e instanceof Uint8Array)this._rawTx=e;else if(Array.isArray(e))this._rawTx=new Uint8Array(e);else if(e instanceof i3)this._tx=e;else throw Error("Invalid transaction data type");this.bumpIndex=t,this.updateInputTxids()}static fromTx(e,t){return new iQ(e,t)}static fromRawTx(e,t){return new iQ(e,t)}static fromTxid(e,t){return new iQ(e,t)}updateInputTxids(){if(this.hasProof||null==this.tx)this.inputTxids=[];else{let e=new Set;for(let t of this.tx.inputs)void 0!==t.sourceTXID&&null!==t.sourceTXID&&""!==t.sourceTXID&&e.add(t.sourceTXID);this.inputTxids=Array.from(e)}}toWriter(e,t){let i=t=>{e.writeUInt8(t)},r=()=>{if(null==this._txid)throw Error("Transaction ID (_txid) is undefined");e.writeReverse(ti(this._txid,"hex"))},n=()=>{let t=this.rawTxUint8Array;if(null==t)throw Error("a valid serialized Transaction is expected");e.write(t)},a=()=>{void 0===this.bumpIndex?i(l.RAWTX):(i(l.RAWTX_AND_BUMP_INDEX),e.writeVarIntNum(this.bumpIndex))};t===i1?this.isTxidOnly?(i(l.TXID_ONLY),r()):(void 0!==this.bumpIndex?(i(l.RAWTX_AND_BUMP_INDEX),e.writeVarIntNum(this.bumpIndex)):i(l.RAWTX),n()):(n(),a())}static fromReader(e,t){let i,r,n;if(t===i1){let t=e.readUInt8();t===l.TXID_ONLY?n=iQ.fromTxid(te(e.readReverse(32))):(t===l.RAWTX_AND_BUMP_INDEX&&(r=e.readVarIntNum()),i=i3.fromReader(e),n=iQ.fromTx(i,r))}else i=i3.fromReader(e),r=0!==e.readUInt8()?e.readVarIntNum():void 0,n=iQ.fromTx(i,r);return n}}let i0=0xefbe0001,i1=0xefbe0002,i2=0x1010101;(a=l||(l={}))[a.RAWTX=0]="RAWTX",a[a.RAWTX_AND_BUMP_INDEX=1]="RAWTX_AND_BUMP_INDEX",a[a.TXID_ONLY=2]="TXID_ONLY";class i8{bumps=[];txs=[];version=i1;atomicTxid=void 0;txidIndex=void 0;rawBytesCache;hexCache;needsSort=!0;constructor(e=i1){this.version=e}invalidateSerializationCaches(){this.rawBytesCache=void 0,this.hexCache=void 0}markMutated(e=!0){this.invalidateSerializationCaches(),e&&(this.needsSort=!0)}ensureSerializableState(){for(let e of this.txs)e.txid}ensureSortedForSerialization(){this.needsSort&&this.sortTxs()}getSerializedBytes(){if(this.ensureSerializableState(),null==this.rawBytesCache){this.ensureSortedForSerialization();let e=new e8;this.toWriter(e),this.rawBytesCache=e.toUint8Array()}return this.rawBytesCache}getBeefForAtomic(e){this.needsSort&&this.sortTxs();let t=this.findTxid(e);if(null==t)throw Error(`${e} does not exist in this Beef`);let i=this.txs[this.txs.length-1]===t?this:this.clone();if(i!==this){let t=this.txs.findIndex(t=>t.txid===e);i.txs.splice(t+1)}let r=new e8;return r.writeUInt32LE(i2),r.writeReverse(ti(e,"hex")),{beef:i,writer:r}}findTxid(e){return this.ensureTxidIndex().get(e)}ensureTxidIndex(){if(null==this.txidIndex)for(let e of(this.txidIndex=new Map,this.txs))this.txidIndex.set(e.txid,e);return this.txidIndex}deleteFromIndex(e){this.txidIndex?.delete(e)}addToIndex(e){this.txidIndex?.set(e.txid,e)}makeTxidOnly(e){let t=this.txs.findIndex(t=>t.txid===e);if(-1===t)return;let i=this.txs[t];return i.isTxidOnly?i:(this.deleteFromIndex(e),this.txs.splice(t,1),this.markMutated(!0),i=this.mergeTxidOnly(e))}findBump(e){return this.bumps.find(t=>t.path[0].some(t=>t.hash===e))}findTransactionForSigning(e){let t=this.findTxid(e);if(null!=t&&null!=t.tx){for(let e of t.tx.inputs)if(null==e.sourceTransaction){let t=this.findTxid(tw(e.sourceTXID,"sourceTXID must be valid"));null!=t&&(e.sourceTransaction=t.tx)}return t.tx}}findAtomicTransaction(e){let t=this.findTxid(e);if(null==t||null==t.tx)return;let i=(e,t)=>{let r=e.findBump(t.id("hex"));if(null!=r)t.merklePath=r;else for(let r of t.inputs){if(null==r.sourceTransaction){let t=e.findTxid(tw(r.sourceTXID,"sourceTXID must be valid"));null!=t&&(r.sourceTransaction=t.tx)}if(null!=r.sourceTransaction){let t=e.findBump(r.sourceTransaction.id("hex"));null!=t?r.sourceTransaction.merklePath=t:i(e,r.sourceTransaction)}}};return i(this,t.tx),t.tx}mergeBump(e){let t;this.markMutated(!1);for(let i=0;i<this.bumps.length;i++){let r=this.bumps[i];if(r===e)return i;if(r.blockHeight===e.blockHeight&&r.computeRoot()===e.computeRoot()){r.combine(e),t=i;break}}void 0===t&&(t=this.bumps.length,this.bumps.push(e));let i=this.bumps[t];for(let e of this.txs){let r=e.txid;if(null==e.bumpIndex){for(let n of i.path[0])if(n.hash===r){e.bumpIndex=t,n.txid=!0;break}}}return t}mergeRawTx(e,t){this.markMutated(!0);let i=new iQ(e,t);return this.removeExistingTxid(i.txid),this.txs.push(i),this.addToIndex(i),this.tryToValidateBumpIndex(i),i}mergeTransaction(e){let t;this.markMutated(!0);let i=e.id("hex");this.removeExistingTxid(i),null!=e.merklePath&&(t=this.mergeBump(e.merklePath));let r=new iQ(e,t);if(this.txs.push(r),this.addToIndex(r),this.tryToValidateBumpIndex(r),void 0===(t=r.bumpIndex))for(let t of e.inputs)null!=t.sourceTransaction&&this.mergeTransaction(t.sourceTransaction);return r}removeExistingTxid(e){let t=this.txs.findIndex(t=>t.txid===e);t>=0&&(this.deleteFromIndex(e),this.txs.splice(t,1),this.markMutated(!0))}mergeTxidOnly(e){let t=this.findTxid(e);return null==t&&(t=new iQ(e),this.txs.push(t),this.addToIndex(t),this.tryToValidateBumpIndex(t),this.markMutated(!0)),t}mergeBeefTx(e){let t=this.findTxid(e.txid);if(e.isTxidOnly&&null==t?t=this.mergeTxidOnly(e.txid):null!=e._tx&&(null==t||t.isTxidOnly)?t=this.mergeTransaction(e._tx):null!=e._rawTx&&(null==t||t.isTxidOnly)&&(t=this.mergeRawTx(e._rawTx)),null==t)throw Error(`Failed to merge BeefTx for txid: ${e.txid}`);return t}mergeBeef(e){let t=e instanceof i8?e:i8.fromBinary(e);for(let e of t.bumps)this.mergeBump(e);for(let e of t.txs)this.mergeBeefTx(e)}isValid(e){return this.verifyValid(e).valid}async verify(e,t){let i=this.verifyValid(t);if(!i.valid)return!1;for(let t of Object.keys(i.roots))if(!await e.isValidRootForHeight(i.roots[t],Number(t)))return!1;return!0}verifyValid(e){let t={valid:!1,roots:{}},i=this.sortTxs();if(i.missingInputs.length>0||i.notValid.length>0||i.txidOnly.length>0&&!0!==e||i.withMissingInputs.length>0)return t;let r={};for(let i of this.txs)if(i.isTxidOnly){if(!0!==e)return t;r[i.txid]=!0}let n=(e,i)=>{let r=e.computeRoot(i);return(void 0===t.roots[e.blockHeight]||""===t.roots[e.blockHeight])&&(t.roots[e.blockHeight]=r),t.roots[e.blockHeight]===r};for(let e of this.bumps)for(let i of e.path[0])if(!0===i.txid&&"string"==typeof i.hash&&i.hash.length>0&&(r[i.hash]=!0,!n(e,i.hash)))return t;for(let e of this.txs)if(void 0!==e.bumpIndex&&null==this.bumps[e.bumpIndex].path[0].find(t=>t.hash===e.txid))return t;for(let e of this.txs){for(let i of e.inputTxids)if(!r[i])return t;r[e.txid]=!0}return t.valid=!0,t}toWriter(e){for(let t of(e.writeUInt32LE(this.version),e.writeVarIntNum(this.bumps.length),this.bumps))e.write(t.toBinary());for(let t of(e.writeVarIntNum(this.txs.length),this.txs))t.toWriter(e,this.version)}toBinary(){return Array.from(this.getSerializedBytes())}toUint8Array(){return this.getSerializedBytes()}toBinaryAtomic(e){let{beef:t,writer:i}=this.getBeefForAtomic(e);return t.toWriter(i),i.toArray()}toUint8ArrayAtomic(e){let{beef:t,writer:i}=this.getBeefForAtomic(e),r=t.getSerializedBytes(),n=i.toUint8Array(),a=new Uint8Array(n.length+r.length);return a.set(n,0),a.set(r,n.length),a}toHex(){if(null!=this.hexCache)return this.hexCache;let e=te(this.getSerializedBytes());return this.hexCache=e,e}static fromReader(e){let t,i=e.readUInt32LE();if(i===i2&&(t=te(e.readReverse(32)),i=e.readUInt32LE()),i!==i0&&i!==i1)throw Error(`Serialized BEEF must start with ${i0} or ${i1} but starts with ${i}`);let r=new i8(i),n=e.readVarIntNum();for(let t=0;t<n;t++){let t=iZ.fromReader(e,!1);r.bumps.push(t)}let a=e.readVarIntNum();for(let t=0;t<a;t++){let t=iQ.fromReader(e,i);r.txs.push(t)}return r.atomicTxid=t,r}static fromBinary(e){let t=e3.makeReader(e);return i8.fromReader(t)}static fromString(e,t="hex"){let i=new e3(tt(e,t));return i8.fromReader(i)}tryToValidateBumpIndex(e){if(void 0!==e.bumpIndex)return!0;let t=e.txid;for(let i=0;i<this.bumps.length;i++){let r=this.bumps[i].path[0].findIndex(e=>e.hash===t);if(r>=0)return e.bumpIndex=i,this.bumps[i].path[0][r].txid=!0,!0}return!1}sortTxs(){let e={},t={},i=[],r=[],n=[];for(let a of this.txs)t[a.txid]=a,a.isValid=a.hasProof,a.isValid?(e[a.txid]=!0,r.push(a)):a.isTxidOnly&&0===a.inputTxids.length?(e[a.txid]=!0,n.push(a)):i.push(a);let a={},s=[],o=i;for(let e of(i=[],o)){let r=!1;for(let i of e.inputTxids)void 0===t[i]&&(a[i]=!0,r=!0);r?s.push(e):i.push(e)}for(;i.length>0;){let t=i;for(let n of(i=[],t))n.inputTxids.every(t=>e[t])?(e[n.txid]=!0,r.push(n)):i.push(n);if(t.length===i.length)break}let c=i;return this.txs=s.concat(c).concat(n).concat(r),this.needsSort=!1,this.invalidateSerializationCaches(),{missingInputs:Object.keys(a),notValid:c.map(e=>e.txid),valid:Object.keys(e),withMissingInputs:s.map(e=>e.txid),txidOnly:n.map(e=>e.txid)}}clone(){let e=new i8;return e.version=this.version,e.bumps=Array.from(this.bumps),e.txs=Array.from(this.txs),e.txidIndex=void 0,e.needsSort=this.needsSort,e.hexCache=this.hexCache,e.rawBytesCache=this.rawBytesCache,e}trimKnownTxids(e){let t=!1;for(let i=0;i<this.txs.length;){let r=this.txs[i];r.isTxidOnly&&e.includes(r.txid)?(this.deleteFromIndex(r.txid),this.txs.splice(i,1),t=!0):i++}let i=new Set;for(let e of this.txs)void 0!==e.bumpIndex&&i.add(e.bumpIndex);if(i.size<this.bumps.length){let e=new Map,r=0;for(let t=0;t<this.bumps.length;t++)i.has(t)&&(e.set(t,r),r++);for(let t of(this.bumps=this.bumps.filter((e,t)=>i.has(t)),this.txs))if(void 0!==t.bumpIndex){let i=e.get(t.bumpIndex);if(void 0===i)throw Error(`Internal error: bumpIndex ${t.bumpIndex} not found in indexMap`);t.bumpIndex=i}t=!0}t&&this.markMutated(!0)}getValidTxids(){return this.sortTxs().valid}toLogString(){let e="";e+=`BEEF with ${this.bumps.length} BUMPS and ${this.txs.length} Transactions, isValid ${this.isValid().toString()}
|
|
7
7
|
`;let t=-1;for(let i of this.bumps)t++,e+=` BUMP ${t}
|
|
8
8
|
block: ${i.blockHeight}
|
|
9
9
|
txids: [
|