gamegold 4.0.7 → 4.0.8

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.
@@ -37,7 +37,7 @@ const path = require('path');var gpath = path.join(__dirname, '../../../', 'node
37
37
  /*!
38
38
  * script.js - script interpreter for vallnet
39
39
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
40
- */const i=Buffer.alloc(0),s=r(0),n=r(247),a=r(169),o=r(130),c=r(114),u=r(101),h=r(21),l=h.opcodes,p=h.types,d=h.outputLockType,f=r(7),m=r(27),g=r(6),y=r(146),v=r(28),b=r(3),w=r(330),x=r(1),k=r(20),S=r(2),E=r(4),_=r(12),{ContractType:A,ContractStatus:R}=r(5),I=r(170),j={199:{len:11,list:[6,8]},197:{len:22,list:[9,18]},198:{len:19,list:[6,15]}},C=2;class P{constructor(t){this.raw=i,this.code=[],this.indicator=w.inst(0),t&&this.fromOptions(t)}createScript(t,e=p.PUBKEYHASH){switch(this.clear(),e){case p.PUBKEY:this.$fromPubkey(t);break;case p.PUBKEYHASH:this.$fromPubkeyhash(t);break;case p.PROPEXTEND:this.$fromPkhExtend(t);break;case p.MULTISIG:var[r,i,s]=t;this.$fromMultisig(r,i,s);break;case p.SCRIPTHASH:this.$fromScripthash(t);break;case p.NULLDATA:this.$fromNulldata(t);break;case p.WITNESS:var[r,i,s]=t;this.$fromProgram(r,i,s)}return 0<this.code.length&&this.compile(),this}static createScript(t,e=p.PUBKEYHASH){return(new P).createScript(t,e)}$fromNulldata(t){s(Buffer.isBuffer(t)),s(t.length<=m.MAX_OP_RETURN,"Nulldata too large."),this.pushOp(l.OP_RETURN),this.pushData(t)}$fromPubkey(t){s(Buffer.isBuffer(t)&&(33===t.length||65===t.length)),this.code.push(a.fromPush(t)),this.code.push(a.fromOp(l.OP_CHECKSIG))}$fromPubkeyhash(t){s(Buffer.isBuffer(t)&&20===t.length),this.code.push(a.fromOp(l.OP_DUP)),this.code.push(a.fromOp(l.OP_HASH160)),this.code.push(a.fromPush(t)),this.code.push(a.fromOp(l.OP_EQUALVERIFY)),this.code.push(a.fromOp(l.OP_CHECKSIG))}$fromPkhExtend(t){s(Buffer.isBuffer(t.info)&&t.info.length<=m.MAX_OP_INFO),s(Buffer.isBuffer(t.hash)&&20===t.hash.length),this.code.push(a.fromOp(t.opcode)),this.code.push(a.fromPush(t.info)),this.code.push(a.fromOp(l.OP_DROP)),this.code.push(a.fromOp(l.OP_DUP)),this.code.push(a.fromOp(l.OP_HASH160)),this.code.push(a.fromPush(t.hash)),this.code.push(a.fromOp(l.OP_EQUALVERIFY)),this.code.push(a.fromOp(l.OP_CHECKSIG))}$fromMultisig(t,e,r){s(x.isU8(t)&&x.isU8(e)),s(Array.isArray(r)),s(r.length===e,"`n` keys are required for multisig."),s(1<=t&&t<=e),s(1<=e&&e<=15),this.clear(),this.pushSmall(t);for(const t of r.slice().sort((t,e)=>t.compare(e)))this.pushData(t);this.pushSmall(e),this.pushOp(l.OP_CHECKMULTISIG)}$fromScripthash(t){s(Buffer.isBuffer(t)&&20===t.length),this.code.push(a.fromOp(l.OP_HASH160)),this.code.push(a.fromPush(t)),this.code.push(a.fromOp(l.OP_EQUAL))}$fromProgram(t,e,r){var i;s(x.isU8(t)&&0<=t&&t<=16),s(Buffer.isBuffer(e)&&2<=e.length&&e.length<=40),r&&(i=Buffer.from(JSON.stringify(r)),s(Buffer.isBuffer(i)&&i.length<=m.MAX_OP_INFO),h.OperCodeFromType[r.oper]&&(this.code.push(a.fromOp(h.OperCodeFromType[r.oper])),this.code.push(a.fromPush(i)),this.code.push(a.fromOp(l.OP_DROP)))),this.code.push(a.fromSmall(t)),this.code.push(a.fromPush(e))}get length(){return this.code.length}set length(t){return this.code.length=t,this.code.length}fromOptions(t){if(s(t,"Script data is required."),Buffer.isBuffer(t))return this.fromRaw(t);if(Array.isArray(t))return this.fromArray(t);if(t.raw){if(!t.code)return this.fromRaw(t.raw);s(Buffer.isBuffer(t.raw),"Raw must be a Buffer."),this.raw=t.raw}if(t.code){if(!t.raw)return this.fromArray(t.code);s(Array.isArray(t.code),"Code must be an array."),this.code=t.code}return this}static fromOptions(t){return(new P).fromOptions(t)}entries(){return this.code.entries()}[Symbol.iterator](){return this.code[Symbol.iterator]()}toArray(){return this.code.slice()}fromArray(t){s(Array.isArray(t)),this.clear();for(const e of t)this.push(e);return this.compile()}static fromArray(t){return(new P).fromArray(t)}toItems(){const t=[];for(const r of this.code){var e=r.toPush();if(!e)throw new Error("Non-push opcode in script.");t.push(e)}return t}fromItems(t,e=!0){s(Array.isArray(t));let r=[];if(e)this.clear();else{let t=this.shift();for(;t;)r.push(t),t=this.shift()}for(const e of t)this.pushData(e);for(const t of r)this.push(t);return this.compile()}static fromItems(t){return(new P).fromItems(t)}toStack(){return new o(this.toItems())}fromStack(t,e=!0){return this.fromItems(t.items,e)}static fromStack(t){return(new P).fromStack(t)}clone(){return(new P).inject(this)}inject(t){return this.raw=t.raw,this.code=t.code.slice(),this}equals(t){return s(P.isScript(t)),this.raw.equals(t.raw)}compare(t){return s(P.isScript(t)),this.raw.compare(t.raw)}clear(){return this.raw=i,this.code.length=0,this}inspect(){return`<Script: ${this.toString()}>`}toString(){const t=[];for(const e of this.code)t.push(e.toFormat());return t.join(" ")}toASM(t){this.isNulldata()&&(t=!1);const e=[];for(const r of this.code)e.push(r.toASM(t));return e.join(" ")}compile(){if(0===this.code.length)return this.clear();let t=0;for(const e of this.code)t+=e.getSize();const e=new E(t);for(const t of this.code)t.toWriter(e);return this.raw=e.render(),this}toWriter(t){return t.writeVarBytes(this.raw),t}toRaw(){return this.raw}toJSON(){return this.toRaw().toString("hex")}fromJSON(t){return s("string"==typeof t,"Code must be a string."),this.fromRaw(Buffer.from(t,"hex"))}static fromJSON(t){return(new P).fromJSON(t)}getSubscript(t){if(0===t)return this.clone();const e=new P;for(let i=t;i<this.code.length;i++){var r=this.code[i];if(-1===r.value)break;e.code.push(r)}return e.compile()}removeSeparators(){let t=!1;for(const e of this.code){if(-1===e.value)break;if(e.value===l.OP_CODESEPARATOR){t=!0;break}}if(!t)return this;const e=new P;for(const t of this.code){if(-1===t.value)break;t.value!==l.OP_CODESEPARATOR&&e.code.push(t)}return e.compile()}getLocktime(){return 2<=this.code.length&&this.getOp(1)==l.OP_CHECKLOCKTIMEVERIFY?this.getInt(0,!1,5):-1}getSequence(){return 2<=this.code.length&&this.getOp(1)==l.OP_CHECKSEQUENCEVERIFY?this.getInt(0,!1,5):-1}getLockStatus(){let t=d.NOCHECK,e=-1,r=-1;var i,s;return 2<=this.code.length&&this.getOp(1)==l.OP_CHECKLOCKTIMEVERIFY&&((i=this.getInt(0,!1,5))<f.LOCKTIME_THRESHOLD?(t=d.CHECKABSOLUTEBLOCK,e=i):(t=d.CHECKABSOLUTETIME,r=i)),2<=this.code.length&&this.getOp(1)==l.OP_CHECKSEQUENCEVERIFY&&((i=this.getInt(0,!1,5))&f.SEQUENCE_DISABLE_FLAG||(s=i&f.SEQUENCE_MASK,i&f.SEQUENCE_TYPE_FLAG?(t=d.CHECKRELATIVETIME,r=s):(t=d.CHECKRELATIVEBLOCK,e=s))),[t,e,r]}execute(t,e,r,i,n,a,o){if(null==e&&(e=P.flags.STANDARD_VERIFY_FLAGS),null==o&&(o=0),this.raw.length>f.MAX_SCRIPT_SIZE)throw new c("SCRIPT_SIZE");const h=[],p=[];let d=0,m=0,y=0,v=!1;e&P.flags.VERIFY_MINIMALDATA&&(v=!0);for(let U=0;U<this.code.length;U++){const q=this.code[U];if(-1===q.value)throw new c("BAD_OPCODE",q,U);if(q.data&&q.data.length>f.MAX_SCRIPT_PUSH)throw new c("PUSH_SIZE",q,U);if(q.value>l.OP_16&&++m>f.MAX_SCRIPT_OPS)throw new c("OP_COUNT",q,U);if(q.isDisabled())throw new c("DISABLED_OPCODE",q,U);if(y&&!q.isBranch()){if(t.length+p.length>f.MAX_SCRIPT_STACK)throw new c("STACK_SIZE",q,U)}else if(q.data){if(v&&!q.isMinimal())throw new c("MINIMALDATA",q,U);if(t.push(q.data),t.length+p.length>f.MAX_SCRIPT_STACK)throw new c("STACK_SIZE",q,U)}else{switch(q.value){case l.OP_PROPCREATE:case l.OP_PROPEXCHANGE:case l.OP_CPREGISTER:case l.OP_CPCHANGE:case l.OP_HTLCSUGGEST:case l.OP_HTLCASSENT:case l.OP_COMMENT:case l.OP_COINBASE:break;case l.OP_PROMISE:this.indicator.set(C);break;case l.OP_RETURN:throw new c("OP_RETURN",q,U);case l.OP_0:t.pushInt(0);break;case l.OP_1NEGATE:t.pushInt(-1);break;case l.OP_1:case l.OP_2:case l.OP_3:case l.OP_4:case l.OP_5:case l.OP_6:case l.OP_7:case l.OP_8:case l.OP_9:case l.OP_10:case l.OP_11:case l.OP_12:case l.OP_13:case l.OP_14:case l.OP_15:case l.OP_16:t.pushInt(q.value-80);break;case l.OP_NOP:break;case l.OP_CHECKLOCKTIMEVERIFY:{if(!(e&P.flags.VERIFY_CHECKLOCKTIMEVERIFY)){if(e&P.flags.VERIFY_DISCOURAGE_UPGRADABLE_NOPS)throw new c("DISCOURAGE_UPGRADABLE_NOPS",q,U);break}if(!r)throw new c("UNKNOWN_ERROR","No TX passed in.");if(0===t.length)throw new c("INVALID_STACK_OPERATION",q,U);const s=t.getNum(-1,v,5);if(s.isNeg())throw new c("NEGATIVE_LOCKTIME",q,U);var b=s.toDouble();if(r.verifyLocktime(i,b))break;throw new c("UNSATISFIED_LOCKTIME",q,U)}case l.OP_CHECKSEQUENCEVERIFY:{if(!(e&P.flags.VERIFY_CHECKSEQUENCEVERIFY)){if(e&P.flags.VERIFY_DISCOURAGE_UPGRADABLE_NOPS)throw new c("DISCOURAGE_UPGRADABLE_NOPS",q,U);break}if(!r)throw new c("UNKNOWN_ERROR","No TX passed in.");if(0===t.length)throw new c("INVALID_STACK_OPERATION",q,U);const s=t.getNum(-1,v,5);if(s.isNeg())throw new c("NEGATIVE_LOCKTIME",q,U);if(b=s.toDouble(),r.verifySequence(i,b))break;throw new c("UNSATISFIED_LOCKTIME",q,U)}case l.OP_NOP1:case l.OP_NOP4:case l.OP_NOP5:case l.OP_NOP6:case l.OP_NOP7:case l.OP_NOP8:case l.OP_NOP9:case l.OP_NOP10:if(e&P.flags.VERIFY_DISCOURAGE_UPGRADABLE_NOPS)throw new c("DISCOURAGE_UPGRADABLE_NOPS",q,U);break;case l.OP_IF:case l.OP_NOTIF:{let r=!1;if(!y){if(t.length<1)throw new c("UNBALANCED_CONDITIONAL",q,U);if(1===o&&e&P.flags.VERIFY_MINIMALIF){if(1<(w=t.get(-1)).length)throw new c("MINIMALIF");if(1===w.length&&1!==w[0])throw new c("MINIMALIF")}r=t.getBool(-1),q.value===l.OP_NOTIF&&(r=!r),t.pop()}h.push(r),r||(y+=1);break}case l.OP_ELSE:if(0===h.length)throw new c("UNBALANCED_CONDITIONAL",q,U);h[h.length-1]=!h[h.length-1],h[h.length-1]?--y:y+=1;break;case l.OP_ENDIF:if(0===h.length)throw new c("UNBALANCED_CONDITIONAL",q,U);h.pop()||--y;break;case l.OP_VERIFY:if(0===t.length)throw new c("INVALID_STACK_OPERATION",q,U);if(!t.getBool(-1))throw new c("VERIFY",q,U);t.pop();break;case l.OP_TOALTSTACK:if(0===t.length)throw new c("INVALID_STACK_OPERATION",q,U);p.push(t.pop());break;case l.OP_FROMALTSTACK:if(0===p.length)throw new c("INVALID_ALTSTACK_OPERATION",q,U);t.push(p.pop());break;case l.OP_2DROP:if(t.length<2)throw new c("INVALID_STACK_OPERATION",q,U);t.pop(),t.pop();break;case l.OP_2DUP:if(t.length<2)throw new c("INVALID_STACK_OPERATION",q,U);var w=t.get(-2),x=t.get(-1);t.push(w),t.push(x);break;case l.OP_3DUP:if(t.length<3)throw new c("INVALID_STACK_OPERATION",q,U);x=t.get(-3);var k=t.get(-2),S=t.get(-1);t.push(x),t.push(k),t.push(S);break;case l.OP_2OVER:if(t.length<4)throw new c("INVALID_STACK_OPERATION",q,U);k=t.get(-4),S=t.get(-3),t.push(k),t.push(S);break;case l.OP_2ROT:if(t.length<6)throw new c("INVALID_STACK_OPERATION",q,U);var E=t.get(-6),_=t.get(-5);t.erase(-6,-4),t.push(E),t.push(_);break;case l.OP_2SWAP:if(t.length<4)throw new c("INVALID_STACK_OPERATION",q,U);t.swap(-4,-2),t.swap(-3,-1);break;case l.OP_IFDUP:if(0===t.length)throw new c("INVALID_STACK_OPERATION",q,U);t.getBool(-1)&&(E=t.get(-1),t.push(E));break;case l.OP_DEPTH:t.pushInt(t.length);break;case l.OP_DROP:{if(0===t.length)throw new c("INVALID_STACK_OPERATION",q,U);let e=t.pop();if(this.indicator.check(C)){this.indicator.unSet(C);try{var A=JSON.parse(e.toString());new I(A,a).run(t)}catch(p){}}break}case l.OP_DUP:if(0===t.length)throw new c("INVALID_STACK_OPERATION",q,U);t.push(t.get(-1));break;case l.OP_NIP:if(t.length<2)throw new c("INVALID_STACK_OPERATION",q,U);t.remove(-2);break;case l.OP_OVER:if(t.length<2)throw new c("INVALID_STACK_OPERATION",q,U);t.push(t.get(-2));break;case l.OP_PICK:case l.OP_ROLL:if(t.length<2)throw new c("INVALID_STACK_OPERATION",q,U);if(_=t.getInt(-1,v,4),t.pop(),_<0||_>=t.length)throw new c("INVALID_STACK_OPERATION",q,U);var R=t.get(-_-1);q.value===l.OP_ROLL&&t.remove(-_-1),t.push(R);break;case l.OP_ROT:if(t.length<3)throw new c("INVALID_STACK_OPERATION",q,U);t.swap(-3,-2),t.swap(-2,-1);break;case l.OP_SWAP:if(t.length<2)throw new c("INVALID_STACK_OPERATION",q,U);t.swap(-2,-1);break;case l.OP_TUCK:if(t.length<2)throw new c("INVALID_STACK_OPERATION",q,U);t.insert(-2,t.get(-1));break;case l.OP_SIZE:if(t.length<1)throw new c("INVALID_STACK_OPERATION",q,U);t.pushInt(t.get(-1).length);break;case l.OP_EQUAL:case l.OP_EQUALVERIFY:{if(t.length<2)throw new c("INVALID_STACK_OPERATION",q,U);const e=t.get(-2);R=t.get(-1);var j=e.equals(R);if(t.pop(),t.pop(),t.pushBool(j),q.value===l.OP_EQUALVERIFY){if(!j)throw new c("EQUALVERIFY",q,U);t.pop()}break}case l.OP_1ADD:case l.OP_1SUB:case l.OP_NEGATE:case l.OP_ABS:case l.OP_NOT:case l.OP_0NOTEQUAL:{if(t.length<1)throw new c("INVALID_STACK_OPERATION",q,U);let e,r=t.getNum(-1,v,4);switch(q.value){case l.OP_1ADD:r.iaddn(1);break;case l.OP_1SUB:r.isubn(1);break;case l.OP_NEGATE:r.ineg();break;case l.OP_ABS:r.iabs();break;case l.OP_NOT:e=r.isZero(),r=u.fromBool(e);break;case l.OP_0NOTEQUAL:e=!r.isZero(),r=u.fromBool(e);break;default:s(!1,"Fatal script error.")}t.pop(),t.pushNum(r);break}case l.OP_ADD:case l.OP_SUB:case l.OP_BOOLAND:case l.OP_BOOLOR:case l.OP_NUMEQUAL:case l.OP_NUMEQUALVERIFY:case l.OP_NUMNOTEQUAL:case l.OP_LESSTHAN:case l.OP_GREATERTHAN:case l.OP_LESSTHANOREQUAL:case l.OP_GREATERTHANOREQUAL:case l.OP_MIN:case l.OP_MAX:{if(t.length<2)throw new c("INVALID_STACK_OPERATION",q,U);const e=t.getNum(-2,v,4),r=t.getNum(-1,v,4);let i,n;switch(q.value){case l.OP_ADD:i=e.iadd(r);break;case l.OP_SUB:i=e.isub(r);break;case l.OP_BOOLAND:n=e.toBool()&&r.toBool(),i=u.fromBool(n);break;case l.OP_BOOLOR:n=e.toBool()||r.toBool(),i=u.fromBool(n);break;case l.OP_NUMEQUAL:case l.OP_NUMEQUALVERIFY:n=e.eq(r),i=u.fromBool(n);break;case l.OP_NUMNOTEQUAL:n=!e.eq(r),i=u.fromBool(n);break;case l.OP_LESSTHAN:n=e.lt(r),i=u.fromBool(n);break;case l.OP_GREATERTHAN:n=e.gt(r),i=u.fromBool(n);break;case l.OP_LESSTHANOREQUAL:n=e.lte(r),i=u.fromBool(n);break;case l.OP_GREATERTHANOREQUAL:n=e.gte(r),i=u.fromBool(n);break;case l.OP_MIN:i=u.min(e,r);break;case l.OP_MAX:i=u.max(e,r);break;default:s(!1,"Fatal script error.")}if(t.pop(),t.pop(),t.pushNum(i),q.value===l.OP_NUMEQUALVERIFY){if(!t.getBool(-1))throw new c("NUMEQUALVERIFY",q,U);t.pop()}break}case l.OP_WITHIN:{if(t.length<3)throw new c("INVALID_STACK_OPERATION",q,U);const e=t.getNum(-3,v,4),r=t.getNum(-2,v,4);j=t.getNum(-1,v,4);var B=r.lte(e)&&e.lt(j);t.pop(),t.pop(),t.pop(),t.pushBool(B);break}case l.OP_RIPEMD160:if(0===t.length)throw new c("INVALID_STACK_OPERATION",q,U);t.push(g.ripemd160(t.pop()));break;case l.OP_SHA1:if(0===t.length)throw new c("INVALID_STACK_OPERATION",q,U);t.push(g.sha1(t.pop()));break;case l.OP_SHA256:if(0===t.length)throw new c("INVALID_STACK_OPERATION",q,U);t.push(g.sha256(t.pop()));break;case l.OP_HASH160:if(0===t.length)throw new c("INVALID_STACK_OPERATION",q,U);t.push(g.hash160(t.pop()));break;case l.OP_HASH256:if(0===t.length)throw new c("INVALID_STACK_OPERATION",q,U);t.push(g.hash256(t.pop()));break;case l.OP_CODESEPARATOR:d=U+1;break;case l.OP_CHECKSIG:case l.OP_CHECKSIGVERIFY:{if(!r)throw new c("UNKNOWN_ERROR","No TX passed in.");if(t.length<2)throw new c("INVALID_STACK_OPERATION",q,U);B=t.get(-2);var N,D=t.get(-1);const s=this.getSubscript(d);0===o&&s.findAndDelete(B),T(B,e),O(D,e,o);let a=!1;if(0<B.length&&(N=B[B.length-1],a=F(N=r.signatureHash(i,s,n,N,o),B,D)),!a&&e&P.flags.VERIFY_NULLFAIL&&0!==B.length)throw new c("NULLFAIL",q,U);if(t.pop(),t.pop(),t.pushBool(a),q.value===l.OP_CHECKSIGVERIFY){if(!a)throw new c("CHECKSIGVERIFY",q,U);t.pop()}break}case l.OP_CHECKMULTISIG:case l.OP_CHECKMULTISIGVERIFY:{if(!r)throw new c("UNKNOWN_ERROR","No TX passed in.");let s=1;if(t.length<s)throw new c("INVALID_STACK_OPERATION",q,U);let a,u,h=t.getInt(-s,v,4),p=h+2;if(h<0||h>f.MAX_MULTISIG_PUBKEYS)throw new c("PUBKEY_COUNT",q,U);if((m+=h)>f.MAX_SCRIPT_OPS)throw new c("OP_COUNT",q,U);if(s+=1,a=s,s+=h,t.length<s)throw new c("INVALID_STACK_OPERATION",q,U);let g=t.getInt(-s,v,4);if(g<0||g>h)throw new c("SIG_COUNT",q,U);if(s+=1,u=s,s+=g,t.length<s)throw new c("INVALID_STACK_OPERATION",q,U);const y=this.getSubscript(d);for(let e=0;e<g;e++){var L=t.get(-u-e);0===o&&y.findAndDelete(L)}let b=!0;for(;b&&0<g;){var H,z=t.get(-u),M=t.get(-a);T(z,e),O(M,e,o),0<z.length&&(H=z[z.length-1],F(r.signatureHash(i,y,n,H,o),z,M)&&(u+=1,--g)),a+=1,--h,g>h&&(b=!1)}for(;1<s;){if(!b&&e&P.flags.VERIFY_NULLFAIL&&0===p&&0!==t.get(-1).length)throw new c("NULLFAIL",q,U);0<p&&--p,t.pop(),--s}if(t.length<1)throw new c("INVALID_STACK_OPERATION",q,U);if(e&P.flags.VERIFY_NULLDUMMY&&0!==t.get(-1).length)throw new c("SIG_NULLDUMMY",q,U);if(t.pop(),t.pushBool(b),q.value===l.OP_CHECKMULTISIGVERIFY){if(!b)throw new c("CHECKMULTISIGVERIFY",q,U);t.pop()}break}default:throw new c("BAD_OPCODE",q,U)}if(t.length+p.length>f.MAX_SCRIPT_STACK)throw new c("STACK_SIZE",q,U)}}if(0!==h.length)throw new c("UNBALANCED_CONDITIONAL")}findAndDelete(t){const e=a.fromPush(t);if(this.raw.length<e.getSize())return 0;let r=!1;for(const t of this.code){if(-1===t.value)break;if(t.equals(e)){r=!0;break}}if(!r)return 0;const i=[];let s=0;for(const t of this.code){if(-1===t.value)break;t.equals(e)?s+=1:i.push(t)}return this.code=i,this.compile(),s}indexOf(t){for(let e=0;e<this.code.length;e++){const r=this.code[e];if(-1===r.value)break;if(r.data&&r.data.equals(t))return e}return-1}isCode(){for(const t of this.code){if(-1===t.value)return!1;if(t.isDisabled())return!1;switch(t.value){case l.OP_RESERVED:case l.OP_NOP:case l.OP_VER:case l.OP_VERIF:case l.OP_VERNOTIF:case l.OP_RESERVED1:case l.OP_RESERVED2:case l.OP_NOP1:return!1}if(t.value>l.OP_PROPMAX)return!1}return!0}fromAddress(t,e){"string"==typeof t&&(t=_.fromString(t)),s(t instanceof _,"Not an address.");let r=!1;if(t.isPubkeyhash())if(e&&e.oper)switch(e.oper){case A.cpRegister:this.createScript({opcode:P.opcodes.OP_CPREGISTER,hash:t.hash,info:Buffer.from(JSON.stringify(e))},P.types.PROPEXTEND);break;case A.cpChange:this.createScript({opcode:P.opcodes.OP_CPCHANGE,hash:t.hash,info:Buffer.from(JSON.stringify(e))},P.types.PROPEXTEND);break;case A.propCreate:this.createScript({opcode:P.opcodes.OP_PROPCREATE,hash:t.hash,info:Buffer.from(JSON.stringify(e))},P.types.PROPEXTEND);break;case A.propExchange:this.createScript({opcode:P.opcodes.OP_PROPEXCHANGE,hash:t.hash,info:Buffer.from(JSON.stringify(e))},P.types.PROPEXTEND);break;case A.coinbase:this.createScript({opcode:P.opcodes.OP_COINBASE,hash:t.hash,info:Buffer.from(JSON.stringify(e))},P.types.PROPEXTEND)}else this.createScript(t.hash);else t.isScripthash()?this.createScript(t.hash,P.types.SCRIPTHASH):t.isProgram()&&this.createScript([t.version,t.hash,e],P.types.WITNESS);if(e&&e.locktype&&(!e.oper||h.unspendableCodes.indexOf(e.oper)<0))switch(e.locktype){case d.CHECKABSOLUTEBLOCK:case d.CHECKABSOLUTETIME:this.code.unshift(a.fromOp(l.OP_DROP)),this.code.unshift(a.fromOp(l.OP_CHECKLOCKTIMEVERIFY)),this.code.unshift(a.fromInt(e.locktime)),r=!0;break;case d.CHECKRELATIVEBLOCK:case d.CHECKRELATIVETIME:e.locktype===d.CHECKRELATIVETIME&&(e.locktime=e.locktime|f.SEQUENCE_TYPE_FLAG),this.code.unshift(a.fromOp(l.OP_DROP)),this.code.unshift(a.fromOp(l.OP_CHECKSEQUENCEVERIFY)),this.code.unshift(a.fromInt(e.locktime)),r=!0}if(r&&this.compile(),0<this.code.length)return this;throw new Error("Unknown address type.")}static fromAddress(t,e){return(new P).fromAddress(t,e)}fromCommitment(t,e){const r=new E(36);return r.writeU32BE(2854332909),r.writeHash(t),this.clear(),this.pushOp(l.OP_RETURN),this.pushData(r.render()),e&&this.pushData(e),this.compile()}static fromCommitment(t,e){return(new P).fromCommitment(t,e)}getRedeem(){let t=null;for(const e of this.code){if(-1===e.value)return null;if(e.value>l.OP_16)return null;t=e.data}return t?P.fromRaw(t):null}getType(){return this.isPubkey()?p.PUBKEY:this.isPubkeyhash()?p.PUBKEYHASH:this.isScripthash()?p.SCRIPTHASH:this.isWitnessPubkeyhash()?p.WITNESSPUBKEYHASH:this.isWitnessScripthash()?p.WITNESSSCRIPTHASH:this.isWitnessMasthash()?p.WITNESSMASTHASH:this.isMultisig()?p.MULTISIG:this.isNulldata()?p.NULLDATA:p.NONSTANDARD}isPubkey(t){return t?35<=this.raw.length&&(33===this.raw[0]||65===this.raw[0])&&this.raw[0]+2===this.raw.length&&this.raw[this.raw.length-1]===l.OP_CHECKSIG:2===this.code.length&&(33===(t=this.getLength(0))||65===t)&&this.getOp(1)===l.OP_CHECKSIG}isPubkeyhash(t){if(t||25===this.raw.length)return 25===this.raw.length&&this.raw[0]===l.OP_DUP&&this.raw[1]===l.OP_HASH160&&20===this.raw[2]&&this.raw[23]===l.OP_EQUALVERIFY&&this.raw[24]===l.OP_CHECKSIG;let e=0;for(var r of this.code)if(r.value==l.OP_DUP){e=this.code.indexOf(r);break}return this.getOp(0+e)===l.OP_DUP&&this.getOp(1+e)===l.OP_HASH160&&20===this.getLength(2+e)&&this.getOp(3+e)===l.OP_EQUALVERIFY&&this.getOp(4+e)===l.OP_CHECKSIG}isMultisig(t){if(this.code.length<4||19<this.code.length)return!1;if(this.getOp(-1)!==l.OP_CHECKMULTISIG)return!1;var e=this.getSmall(0);if(e<1)return!1;var r=this.getSmall(-2);if(r<1||r<e)return!1;if(this.code.length!==r+3)return!1;for(let e=1;e<r+1;e++){const r=this.code[e];var i=r.toLength();if(33!==i&&65!==i)return!1;if(t&&!r.isMinimal())return!1}return!0}isUnknown(){return this.getType()===p.NONSTANDARD}isStandard(){var[t,e]=this.getMultisig();return-1!==t?!(e<1||3<e||t<1||e<t):this.isNulldata()?this.raw.length<=m.MAX_OP_RETURN_BYTES:this.getType()!==p.NONSTANDARD}isScripthash(){return 23===this.raw.length&&this.raw[0]===l.OP_HASH160&&20===this.raw[1]&&this.raw[22]===l.OP_EQUAL}isNulldata(t){if(0===this.code.length)return!1;if(this.getOp(0)!==l.OP_RETURN)return!1;if(1!==this.code.length){if(t&&this.raw.length>m.MAX_OP_RETURN_BYTES)return!1;for(let e=1;e<this.code.length;e++){const r=this.code[e];if(-1===r.value)return!1;if(r.value>l.OP_16)return!1;if(t&&!r.isMinimal())return!1}}return!0}isCommitment(){return 38<=this.raw.length&&this.raw[0]===l.OP_RETURN&&36===this.raw[1]&&2854332909===this.raw.readUInt32BE(2,!0)}isWitnessPubkeyhash(){return 22===this.raw.length&&this.raw[0]===l.OP_0&&20===this.raw[1]||5==this.code.length&&this.code[2].value==l.OP_DROP&&this.code[3].value==l.OP_0&&20==this.code[4].value}getWitnessPubkeyhash(){return this.isWitnessPubkeyhash()?5==this.code.length?this.getData(4):this.getData(1):null}isWitnessScripthash(){return 34===this.raw.length&&this.raw[0]===l.OP_0&&32===this.raw[1]}getWitnessScripthash(){return this.isWitnessScripthash()?this.getData(1):null}isProgram(){if(2==this.code.length){if(4<=this.raw.length&&this.raw.length<=42&&(this.raw[0]==l.OP_0||this.raw[0]>=l.OP_1&&this.raw[0]<=l.OP_16)&&this.raw[1]+2==this.raw.length)return!0}else if(5==this.code.length&&4<=this.raw.length&&this.code[2].value==l.OP_DROP&&(this.code[3].value==l.OP_0||this.code[3].value>=l.OP_1&&this.code[3].value<=l.OP_16))return!0;return!1}isWitnessMasthash(){return 34===this.raw.length&&this.raw[0]===l.OP_1&&32===this.raw[1]}isUnspendable(){return this.raw.length>f.MAX_SCRIPT_SIZE||0<this.raw.length&&this.raw[0]===l.OP_RETURN}getSize(){return this.raw.length}getVarSize(){return b.sizeVarBytes(this.raw)}getReturnData(t){if(!(this.code&&this.code[0]&&this.code[1]&&this.code[1].data))return null;if(t)if(Array.isArray(t)){let r=!1;for(var e of t)if(this.code[0].value===e){r=!0;break}if(!r)return null}else if(this.code[0].value!==t)return null;try{return x.parseJson(this.code[1].data.toString())}catch(t){return null}}getReturnType(t){if(!this.code||!this.code[0])return null;if(t)if(Array.isArray(t)){let r=!1;for(var e of t)if(this.code[0].value===e){r=!0;break}if(!r)return null}else if(this.code[0].value!==t)return null;return this.code[0].value}hash160(t){let e=g.hash160(this.toRaw());return"hex"===t?e.toString("hex"):e}sha256(t){let e=g.sha256(this.toRaw());return"hex"===t?e.toString("hex"):e}getPubkey(t){return this.isPubkey(t)?t?this.raw.slice(1,1+this.raw[0]):this.getData(0):null}getMultiPubkeyhash(){let t=j[this.getOp(0)];return t&&this.code.length==t.len?t.list.map(t=>this.getData(t)):null}getPubkeyhash(t){if(this.isPubkeyhash(t)){if(t)return this.raw.slice(3,23);for(var e of this.code)if(e.value==l.OP_CHECKSIG)return this.getData(this.code.indexOf(e)-2)}return null}getMultisig(t){return this.isMultisig(t)?[this.getSmall(0),this.getSmall(-2)]:[-1,-1]}getScripthash(){return this.isScripthash()?this.getData(1):null}getNulldata(t){if(!this.isNulldata(t))return null;for(let t=1;t<this.code.length;t++){var e=this.code[t].toPush();if(e)return e}return i}getCommitment(){return this.isCommitment()?this.raw.slice(6,38):null}getProgram(){return this.isProgram()?2==this.code.length?new n(this.getSmall(0),this.getData(1)):5==this.code.length?new n(this.getSmall(3),this.getData(4)):null:null}forWitness(){var t;return this.isProgram()?this.clone():(t=this.getPubkey())?(t=g.hash160(t),P.createScript([0,t],P.types.WITNESS)):(t=this.getPubkeyhash())?P.createScript([0,t],P.types.WITNESS):P.createScript([0,this.sha256()],P.types.WITNESS)}getWitnessMasthash(){return this.isWitnessMasthash()?this.getData(1):null}getInputType(){return this.isPubkeyInput()?p.PUBKEY:this.isPubkeyhashInput()?p.PUBKEYHASH:this.isScripthashInput()?p.SCRIPTHASH:this.isMultisigInput()?p.MULTISIG:p.NONSTANDARD}isPubkeyhashInput(){var t,e;return 2===this.code.length&&(t=this.getLength(0),e=this.getLength(1),9<=t&&t<=73&&(33===e||65===e))}isUnknownInput(){return this.getInputType()===p.NONSTANDARD}isPubkeyInput(){var t;return 1===this.code.length&&9<=(t=this.getLength(0))&&t<=73}isScripthashInput(){if(this.code.length<2)return!1;var t=this.getData(-1);if(!t)return!1;if(0===t.length)return!1;if(h.isSignatureEncoding(t))return!1;if(h.isKeyEncoding(t))return!1;const e=P.fromRaw(t);return!!e.isCode()&&!e.isUnspendable()&&!!this.isPushOnly()}isMultisigInput(){if(this.code.length<2)return!1;if(this.getOp(0)!==l.OP_0)return!1;if(this.getOp(1)>l.OP_PUSHDATA4)return!1;if(this.isScripthashInput())return!1;for(let e=1;e<this.code.length;e++){var t=this.getLength(e);if(t<9||73<t)return!1}return!0}getPubkeyInput(){return this.isPubkeyInput()?this.getData(0):null}getPubkeyhashInput(){return this.isPubkeyhashInput()?[this.getData(0),this.getData(1)]:[null,null]}getMultisigInput(){if(!this.isMultisigInput())return null;const t=[];for(let e=1;e<this.code.length;e++)t.push(this.getData(e));return t}getScripthashInput(){return this.isScripthashInput()?this.getData(-1):null}getCoinbaseHeight(){return P.getCoinbaseHeight(this.raw)}static getCoinbaseHeight(t){if(0===t.length)return-1;if(t[0]>=l.OP_1&&t[0]<=l.OP_16)return t[0]-80;if(6<t[0])return-1;const e=a.fromRaw(t),r=e.toNum();return r?!r.isNeg()&&e.equals(a.fromNum(r))?r.toDouble():-1:1}test(t){for(const e of this.code){if(-1===e.value)break;if(e.data&&0!==e.data.length){if(t.test(e.data))return!0;if(33==e.data.length&&t.test(g.hash160(e.data)))return!0}}return!1}isPushOnly(){for(const t of this.code){if(-1===t.value)return!1;if(t.value>l.OP_16)return!1}return!0}getSigops(t){let e=0,r=-1;for(const i of this.code){if(-1===i.value)break;switch(i.value){case l.OP_CHECKSIG:case l.OP_CHECKSIGVERIFY:e+=1;break;case l.OP_CHECKMULTISIG:case l.OP_CHECKMULTISIGVERIFY:t&&r>=l.OP_1&&r<=l.OP_16?e+=r-80:e+=f.MAX_MULTISIG_PUBKEYS}r=i.value}return e}getScripthashSigops(t){if(!this.isScripthash())return this.getSigops(!0);const e=t.getRedeem();return e?e.getSigops(!0):0}getWitnessSigops(t,e){let r=this.getProgram();if(!r&&this.isScripthash()){const e=t.getRedeem();e&&(r=e.getProgram())}if(r&&0===r.version){if(20===r.data.length)return 1;if(32===r.data.length&&0<e.items.length){return e.getRedeem().getSigops(!0)}}return 0}get(t){return t<0&&(t+=this.code.length),t<0||t>=this.code.length?null:this.code[t]}pop(){return this.code.pop()||null}shift(){return this.code.shift()||null}remove(t){return t<0&&(t+=this.code.length),t<0||t>=this.code.length||0===(t=this.code.splice(t,1)).length?null:t[0]}set(t,e){return t<0&&(t+=this.code.length),s(a.isOpcode(e)),s(0<=t&&t<=this.code.length),this.code[t]=e,this}push(t){return s(a.isOpcode(t)),this.code.push(t),this}unshift(t){return s(a.isOpcode(t)),this.code.unshift(t),this}insert(t,e){return t<0&&(t+=this.code.length),s(a.isOpcode(e)),s(0<=t&&t<=this.code.length),this.code.splice(t,0,e),this}getOp(t){return(t=this.get(t))?t.value:-1}popOp(){var t=this.pop();return t?t.value:-1}shiftOp(){var t=this.shift();return t?t.value:-1}removeOp(t){return(t=this.remove(t))?t.value:-1}setOp(t,e){return this.set(t,a.fromOp(e))}pushOp(t){return this.push(a.fromOp(t))}unshiftOp(t){return this.unshift(a.fromOp(t))}insertOp(t,e){return this.insert(t,a.fromOp(e))}getData(t){return(t=this.get(t))?t.data:null}popData(){var t=this.pop();return t?t.data:null}shiftData(){var t=this.shift();return t?t.data:null}removeData(t){return(t=this.remove(t))?t.data:null}setData(t,e){return this.set(t,a.fromData(e))}pushData(t){return this.push(a.fromData(t))}unshiftData(t){return this.unshift(a.fromData(t))}insertData(t,e){return this.insert(t,a.fromData(e))}getLength(t){const e=this.get(t);return e?e.toLength():-1}getPush(t){const e=this.get(t);return e?e.toPush():null}popPush(){const t=this.pop();return t?t.toPush():null}shiftPush(){const t=this.shift();return t?t.toPush():null}removePush(t){const e=this.remove(t);return e?e.toPush():null}setPush(t,e){return this.set(t,a.fromPush(e))}pushPush(t){return this.push(a.fromPush(t))}unshiftPush(t){return this.unshift(a.fromPush(t))}insertPush(t,e){return this.insert(t,a.fromPush(e))}getString(t,e){const r=this.get(t);return r?r.toString(e):null}popString(t){const e=this.pop();return e?e.toString(t):null}shiftString(t){const e=this.shift();return e?e.toString(t):null}removeString(t,e){const r=this.remove(t);return r?r.toString(e):null}setString(t,e,r){return this.set(t,a.fromString(e,r))}pushString(t,e){return this.push(a.fromString(t,e))}unshiftString(t,e){return this.unshift(a.fromString(t,e))}insertString(t,e,r){return this.insert(t,a.fromString(e,r))}getSmall(t){const e=this.get(t);return e?e.toSmall():-1}popSmall(){const t=this.pop();return t?t.toSmall():-1}shiftSmall(){const t=this.shift();return t?t.toSmall():-1}removeSmall(t){const e=this.remove(t);return e?e.toSmall():-1}setSmall(t,e){return this.set(t,a.fromSmall(e))}pushSmall(t){return this.push(a.fromSmall(t))}unshiftSmall(t){return this.unshift(a.fromSmall(t))}insertSmall(t,e){return this.insert(t,a.fromSmall(e))}getNum(t,e,r){const i=this.get(t);return i?i.toNum(e,r):null}popNum(t,e){const r=this.pop();return r?r.toNum(t,e):null}shiftNum(t,e){const r=this.shift();return r?r.toNum(t,e):null}removeNum(t,e,r){const i=this.remove(t);return i?i.toNum(e,r):null}setNum(t,e){return this.set(t,a.fromNum(e))}pushNum(t){return this.push(a.fromNum(t))}unshiftNum(t){return this.unshift(a.fromNum(t))}insertNum(t,e){return this.insert(t,a.fromNum(e))}getInt(t,e,r){const i=this.get(t);return i?i.toInt(e,r):-1}popInt(t,e){const r=this.pop();return r?r.toInt(t,e):-1}shiftInt(t,e){const r=this.shift();return r?r.toInt(t,e):-1}removeInt(t,e,r){const i=this.remove(t);return i?i.toInt(e,r):-1}setInt(t,e){return this.set(t,a.fromInt(e))}pushInt(t){return this.push(a.fromInt(t))}unshiftInt(t){return this.unshift(a.fromInt(t))}insertInt(t,e){return this.insert(t,a.fromInt(e))}getBool(t){const e=this.get(t);return!!e&&e.toBool()}popBool(){const t=this.pop();return!!t&&t.toBool()}shiftBool(){const t=this.shift();return!!t&&t.toBool()}removeBool(t){const e=this.remove(t);return!!e&&e.toBool()}setBool(t,e){return this.set(t,a.fromBool(e))}pushBool(t){return this.push(a.fromBool(t))}unshiftBool(t){return this.unshift(a.fromBool(t))}insertBool(t,e){return this.insert(t,a.fromBool(e))}getSym(t){const e=this.get(t);return e?e.toSymbol():null}popSym(){const t=this.pop();return t?t.toSymbol():null}shiftSym(){const t=this.shift();return t?t.toSymbol():null}removeSym(t){const e=this.remove(t);return e?e.toSymbol():null}setSym(t,e){return this.set(t,a.fromSymbol(e))}pushSym(t){return this.push(a.fromSymbol(t))}unshiftSym(t){return this.unshift(a.fromSymbol(t))}insertSym(t,e){return this.insert(t,a.fromSymbol(e))}fromString(t){if(s("string"==typeof t),0===(t=t.trim()).length)return this;t=t.split(/\s+/);const e=new k;for(const c of t){let t=c;x.isUpperCase(t)||(t=t.toUpperCase()),x.startsWith(t,"OP_")||(t="OP_"+t);var r=l[t];if(null==r)if("'"===c[0]){s("'"===c[c.length-1],"Invalid string.");var i=c.slice(1,-1);const t=a.fromString(i);e.writeBytes(t.toRaw())}else if(/^-?\d+$/.test(c)){i=u.fromString(c,10);const t=a.fromNum(i);e.writeBytes(t.toRaw())}else{s(0===c.indexOf("0x"),"Unknown opcode.");var n=c.substring(2),o=Buffer.from(n,"hex");s(o.length===n.length/2,"Invalid hex string."),e.writeBytes(o)}else e.writeU8(r)}return this.fromRaw(e.render())}static fromString(t){return(new P).fromString(t)}static verifyScript(t,e,r,i,n,u,h,l){if((h=null==h?P.flags.STANDARD_VERIFY_FLAGS:h)&P.flags.VERIFY_SIGPUSHONLY&&!t.isPushOnly())throw new c("SIG_PUSHONLY");null==l&&(l=R.None);let p,d=new o;if(t.execute(d,h,i,n,u,l,0),h&P.flags.VERIFY_P2SH&&(p=d.clone()),r.execute(d,h,i,n,u,l,0),0===d.length||!d.getBool(-1))throw new c("EVAL_FALSE");let f=!1;if(h&P.flags.VERIFY_WITNESS&&r.isProgram()){if(f=!0,0!==t.raw.length)throw new c("WITNESS_MALLEATED");P.verifyProgram(e,r,h,i,n,u,l),d.length=1}if(h&P.flags.VERIFY_P2SH&&r.isScripthash()){if(!t.isPushOnly())throw new c("SIG_PUSHONLY");if(0===(d=p).length)throw new c("EVAL_FALSE");r=d.pop();const s=P.fromRaw(r);if(s.execute(d,h,i,n,u,l,0),0===d.length||!d.getBool(-1))throw new c("EVAL_FALSE");if(h&P.flags.VERIFY_WITNESS&&s.isProgram()){if(f=!0,!t.raw.equals(a.fromPush(r).toRaw()))throw new c("WITNESS_MALLEATED_P2SH");P.verifyProgram(e,s,h,i,n,u,l),d.length=1}}if(h&P.flags.VERIFY_CLEANSTACK&&(s(0!=(h&P.flags.VERIFY_P2SH)),1!==d.length))throw new c("CLEANSTACK");if(h&P.flags.VERIFY_WITNESS&&(s(0!=(h&P.flags.VERIFY_P2SH)),!f&&0<e.items.length))throw new c("WITNESS_UNEXPECTED")}static verifyProgram(t,e,r,i,n,a,o){var u=e.getProgram();s(u,"verifyProgram called on non-witness-program."),s(0!=(r&P.flags.VERIFY_WITNESS));const h=t.toStack();let l;if(0!==u.version){if(r&P.flags.VERIFY_MAST&&1===u.version)P.verifyMast(u,h,e,r,i,n,o);else if(r&P.flags.VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM)throw new c("DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM")}else{if(32===u.data.length){if(0===h.length)throw new c("WITNESS_PROGRAM_WITNESS_EMPTY");if(t=h.pop(),!g.sha256(t).equals(u.data))throw new c("WITNESS_PROGRAM_MISMATCH");l=P.fromRaw(t)}else{if(20!==u.data.length)throw new c("WITNESS_PROGRAM_WRONG_LENGTH");if(2!==h.length)throw new c("WITNESS_PROGRAM_MISMATCH");l=P.createScript(u.data)}for(let t=0;t<h.length;t++)if(h.get(t).length>f.MAX_SCRIPT_PUSH)throw new c("PUSH_SIZE");if(l.execute(h,r,i,n,a,o,1),1!==h.length||!h.getBool(-1))throw new c("EVAL_FALSE")}}static verifyMast(t,e,r,i,n,a,o,u){if(s(1===t.version),s(0!=(i&P.flags.VERIFY_MAST)),e.length<4)throw new c("INVALID_MAST_STACK");var h=e.get(-1);if(h.length<1||5<h.length)throw new c("INVALID_MAST_STACK");var l=h[0];if(0===l||e.length<l+3)throw new c("INVALID_MAST_STACK");var p=l;let d=new k;if(d.writeU8(l),0===h[h.length-1])throw new c("INVALID_MAST_STACK");let m=0;for(let t=1;t<h.length;t++)m|=h[t]<<8*(t-1);if(m<0&&(m+=4294967296),0<m&&i&P.flags.DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM)throw new c("DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM");let v=new k;v.writeU32(m);const b=e.get(-2);if(31&b.length)throw new c("INVALID_MAST_STACK");var w=b.length>>>5;if(32<w)throw new c("INVALID_MAST_STACK");if(0===m&&(p+=w)>f.MAX_SCRIPT_OPS)throw new c("OP_COUNT");const x=[];for(let t=0;t<w;t++)x.push(b.slice(32*t,32*t+32));var S=e.get(-3);if(4<S.length)throw new c("INVALID_MAST_STACK");let E=0;if(0<S.length){if(0===S[S.length-1])throw new c("INVALID_MAST_STACK");for(let t=0;t<S.length;t++)E|=S[t]<<8*t;E<0&&(E+=4294967296)}if(w<32&&E>=1<<w>>>0)throw new c("INVALID_MAST_STACK");let _=new k;_.writeBytes(r.raw);for(let t=0;t<l;t++){var A=e.get(-(4+t));if(0===m&&_.offset+A.length>f.MAX_SCRIPT_SIZE)throw new c("SCRIPT_SIZE");d.writeBytes(g.hash256(A)),_.writeBytes(A)}if(d=g.hash256(d.render()),d=y.verifyBranch(d,x,E),v.writeBytes(d),!(v=g.hash256(v.render())).equals(t.data))throw new c("WITNESS_PROGRAM_MISMATCH");if(0===m){e.length-=3+l;for(let t=0;t<e.length;t++)if(e.get(t).length>f.MAX_SCRIPT_PUSH)throw new c("PUSH_SIZE");if(_=_.render(),(r=P.fromRaw(_)).execute(e,i,n,a,o,u,1),0!==e.length)throw new c("EVAL_FALSE")}}fromReader(t){return this.fromRaw(t.readVarBytes())}fromRaw(t){const e=new S(t,!0);for(this.raw=t;e.left();)this.code.push(a.fromReader(e));return this}static fromReader(t){return(new P).fromReader(t)}static fromRaw(t,e){return"string"==typeof t&&(t=Buffer.from(t,e)),(new P).fromRaw(t)}static isScript(t){return t instanceof P}}function O(t,e,r){if(s(Buffer.isBuffer(t)),s("number"==typeof e),s("number"==typeof r),e&P.flags.VERIFY_STRICTENC&&!h.isKeyEncoding(t))throw new c("PUBKEYTYPE");if(1===r&&e&P.flags.VERIFY_WITNESS_PUBKEYTYPE&&!h.isCompressedEncoding(t))throw new c("WITNESS_PUBKEYTYPE")}function T(t,e){if(s(Buffer.isBuffer(t)),s("number"==typeof e),0!==t.length){if((e&P.flags.VERIFY_DERSIG||e&P.flags.VERIFY_LOW_S||e&P.flags.VERIFY_STRICTENC)&&!h.isSignatureEncoding(t))throw new c("SIG_DER");if(e&P.flags.VERIFY_LOW_S&&!h.isLowDER(t))throw new c("SIG_HIGH_S");if(e&P.flags.VERIFY_STRICTENC&&!h.isHashType(t))throw new c("SIG_HASHTYPE")}}function F(t,e,r){return v.verify(t,e.slice(0,-1),r)}P.opcodes=h.opcodes,P.opcodesByVal=h.opcodesByVal,P.flags=h.flags,P.hashType=h.hashType,P.hashTypeByVal=h.hashTypeByVal,P.types=h.types,P.typesByVal=h.typesByVal,P.outputLockType=h.outputLockType,P.unspendableCodes=h.unspendableCodes,P.TradeType={btc:1},t.exports=P},function(t,e,r){"use strict";
40
+ */const i=Buffer.alloc(0),s=r(0),n=r(247),a=r(169),o=r(130),c=r(114),u=r(101),h=r(21),l=h.opcodes,p=h.types,d=h.outputLockType,f=r(7),m=r(27),g=r(6),y=r(146),v=r(29),b=r(3),w=r(330),x=r(1),k=r(20),S=r(2),E=r(4),_=r(12),{ContractType:A,ContractStatus:R}=r(5),I=r(170),j={199:{len:11,list:[6,8]},197:{len:22,list:[9,18]},198:{len:19,list:[6,15]}},C=2;class P{constructor(t){this.raw=i,this.code=[],this.indicator=w.inst(0),t&&this.fromOptions(t)}createScript(t,e=p.PUBKEYHASH){switch(this.clear(),e){case p.PUBKEY:this.$fromPubkey(t);break;case p.PUBKEYHASH:this.$fromPubkeyhash(t);break;case p.PROPEXTEND:this.$fromPkhExtend(t);break;case p.MULTISIG:var[r,i,s]=t;this.$fromMultisig(r,i,s);break;case p.SCRIPTHASH:this.$fromScripthash(t);break;case p.NULLDATA:this.$fromNulldata(t);break;case p.WITNESS:var[r,i,s]=t;this.$fromProgram(r,i,s)}return 0<this.code.length&&this.compile(),this}static createScript(t,e=p.PUBKEYHASH){return(new P).createScript(t,e)}$fromNulldata(t){s(Buffer.isBuffer(t)),s(t.length<=m.MAX_OP_RETURN,"Nulldata too large."),this.pushOp(l.OP_RETURN),this.pushData(t)}$fromPubkey(t){s(Buffer.isBuffer(t)&&(33===t.length||65===t.length)),this.code.push(a.fromPush(t)),this.code.push(a.fromOp(l.OP_CHECKSIG))}$fromPubkeyhash(t){s(Buffer.isBuffer(t)&&20===t.length),this.code.push(a.fromOp(l.OP_DUP)),this.code.push(a.fromOp(l.OP_HASH160)),this.code.push(a.fromPush(t)),this.code.push(a.fromOp(l.OP_EQUALVERIFY)),this.code.push(a.fromOp(l.OP_CHECKSIG))}$fromPkhExtend(t){s(Buffer.isBuffer(t.info)&&t.info.length<=m.MAX_OP_INFO),s(Buffer.isBuffer(t.hash)&&20===t.hash.length),this.code.push(a.fromOp(t.opcode)),this.code.push(a.fromPush(t.info)),this.code.push(a.fromOp(l.OP_DROP)),this.code.push(a.fromOp(l.OP_DUP)),this.code.push(a.fromOp(l.OP_HASH160)),this.code.push(a.fromPush(t.hash)),this.code.push(a.fromOp(l.OP_EQUALVERIFY)),this.code.push(a.fromOp(l.OP_CHECKSIG))}$fromMultisig(t,e,r){s(x.isU8(t)&&x.isU8(e)),s(Array.isArray(r)),s(r.length===e,"`n` keys are required for multisig."),s(1<=t&&t<=e),s(1<=e&&e<=15),this.clear(),this.pushSmall(t);for(const t of r.slice().sort((t,e)=>t.compare(e)))this.pushData(t);this.pushSmall(e),this.pushOp(l.OP_CHECKMULTISIG)}$fromScripthash(t){s(Buffer.isBuffer(t)&&20===t.length),this.code.push(a.fromOp(l.OP_HASH160)),this.code.push(a.fromPush(t)),this.code.push(a.fromOp(l.OP_EQUAL))}$fromProgram(t,e,r){var i;s(x.isU8(t)&&0<=t&&t<=16),s(Buffer.isBuffer(e)&&2<=e.length&&e.length<=40),r&&(i=Buffer.from(JSON.stringify(r)),s(Buffer.isBuffer(i)&&i.length<=m.MAX_OP_INFO),h.OperCodeFromType[r.oper]&&(this.code.push(a.fromOp(h.OperCodeFromType[r.oper])),this.code.push(a.fromPush(i)),this.code.push(a.fromOp(l.OP_DROP)))),this.code.push(a.fromSmall(t)),this.code.push(a.fromPush(e))}get length(){return this.code.length}set length(t){return this.code.length=t,this.code.length}fromOptions(t){if(s(t,"Script data is required."),Buffer.isBuffer(t))return this.fromRaw(t);if(Array.isArray(t))return this.fromArray(t);if(t.raw){if(!t.code)return this.fromRaw(t.raw);s(Buffer.isBuffer(t.raw),"Raw must be a Buffer."),this.raw=t.raw}if(t.code){if(!t.raw)return this.fromArray(t.code);s(Array.isArray(t.code),"Code must be an array."),this.code=t.code}return this}static fromOptions(t){return(new P).fromOptions(t)}entries(){return this.code.entries()}[Symbol.iterator](){return this.code[Symbol.iterator]()}toArray(){return this.code.slice()}fromArray(t){s(Array.isArray(t)),this.clear();for(const e of t)this.push(e);return this.compile()}static fromArray(t){return(new P).fromArray(t)}toItems(){const t=[];for(const r of this.code){var e=r.toPush();if(!e)throw new Error("Non-push opcode in script.");t.push(e)}return t}fromItems(t,e=!0){s(Array.isArray(t));let r=[];if(e)this.clear();else{let t=this.shift();for(;t;)r.push(t),t=this.shift()}for(const e of t)this.pushData(e);for(const t of r)this.push(t);return this.compile()}static fromItems(t){return(new P).fromItems(t)}toStack(){return new o(this.toItems())}fromStack(t,e=!0){return this.fromItems(t.items,e)}static fromStack(t){return(new P).fromStack(t)}clone(){return(new P).inject(this)}inject(t){return this.raw=t.raw,this.code=t.code.slice(),this}equals(t){return s(P.isScript(t)),this.raw.equals(t.raw)}compare(t){return s(P.isScript(t)),this.raw.compare(t.raw)}clear(){return this.raw=i,this.code.length=0,this}inspect(){return`<Script: ${this.toString()}>`}toString(){const t=[];for(const e of this.code)t.push(e.toFormat());return t.join(" ")}toASM(t){this.isNulldata()&&(t=!1);const e=[];for(const r of this.code)e.push(r.toASM(t));return e.join(" ")}compile(){if(0===this.code.length)return this.clear();let t=0;for(const e of this.code)t+=e.getSize();const e=new E(t);for(const t of this.code)t.toWriter(e);return this.raw=e.render(),this}toWriter(t){return t.writeVarBytes(this.raw),t}toRaw(){return this.raw}toJSON(){return this.toRaw().toString("hex")}fromJSON(t){return s("string"==typeof t,"Code must be a string."),this.fromRaw(Buffer.from(t,"hex"))}static fromJSON(t){return(new P).fromJSON(t)}getSubscript(t){if(0===t)return this.clone();const e=new P;for(let i=t;i<this.code.length;i++){var r=this.code[i];if(-1===r.value)break;e.code.push(r)}return e.compile()}removeSeparators(){let t=!1;for(const e of this.code){if(-1===e.value)break;if(e.value===l.OP_CODESEPARATOR){t=!0;break}}if(!t)return this;const e=new P;for(const t of this.code){if(-1===t.value)break;t.value!==l.OP_CODESEPARATOR&&e.code.push(t)}return e.compile()}getLocktime(){return 2<=this.code.length&&this.getOp(1)==l.OP_CHECKLOCKTIMEVERIFY?this.getInt(0,!1,5):-1}getSequence(){return 2<=this.code.length&&this.getOp(1)==l.OP_CHECKSEQUENCEVERIFY?this.getInt(0,!1,5):-1}getLockStatus(){let t=d.NOCHECK,e=-1,r=-1;var i,s;return 2<=this.code.length&&this.getOp(1)==l.OP_CHECKLOCKTIMEVERIFY&&((i=this.getInt(0,!1,5))<f.LOCKTIME_THRESHOLD?(t=d.CHECKABSOLUTEBLOCK,e=i):(t=d.CHECKABSOLUTETIME,r=i)),2<=this.code.length&&this.getOp(1)==l.OP_CHECKSEQUENCEVERIFY&&((i=this.getInt(0,!1,5))&f.SEQUENCE_DISABLE_FLAG||(s=i&f.SEQUENCE_MASK,i&f.SEQUENCE_TYPE_FLAG?(t=d.CHECKRELATIVETIME,r=s):(t=d.CHECKRELATIVEBLOCK,e=s))),[t,e,r]}execute(t,e,r,i,n,a,o){if(null==e&&(e=P.flags.STANDARD_VERIFY_FLAGS),null==o&&(o=0),this.raw.length>f.MAX_SCRIPT_SIZE)throw new c("SCRIPT_SIZE");const h=[],p=[];let d=0,m=0,y=0,v=!1;e&P.flags.VERIFY_MINIMALDATA&&(v=!0);for(let U=0;U<this.code.length;U++){const q=this.code[U];if(-1===q.value)throw new c("BAD_OPCODE",q,U);if(q.data&&q.data.length>f.MAX_SCRIPT_PUSH)throw new c("PUSH_SIZE",q,U);if(q.value>l.OP_16&&++m>f.MAX_SCRIPT_OPS)throw new c("OP_COUNT",q,U);if(q.isDisabled())throw new c("DISABLED_OPCODE",q,U);if(y&&!q.isBranch()){if(t.length+p.length>f.MAX_SCRIPT_STACK)throw new c("STACK_SIZE",q,U)}else if(q.data){if(v&&!q.isMinimal())throw new c("MINIMALDATA",q,U);if(t.push(q.data),t.length+p.length>f.MAX_SCRIPT_STACK)throw new c("STACK_SIZE",q,U)}else{switch(q.value){case l.OP_PROPCREATE:case l.OP_PROPEXCHANGE:case l.OP_CPREGISTER:case l.OP_CPCHANGE:case l.OP_HTLCSUGGEST:case l.OP_HTLCASSENT:case l.OP_COMMENT:case l.OP_COINBASE:break;case l.OP_PROMISE:this.indicator.set(C);break;case l.OP_RETURN:throw new c("OP_RETURN",q,U);case l.OP_0:t.pushInt(0);break;case l.OP_1NEGATE:t.pushInt(-1);break;case l.OP_1:case l.OP_2:case l.OP_3:case l.OP_4:case l.OP_5:case l.OP_6:case l.OP_7:case l.OP_8:case l.OP_9:case l.OP_10:case l.OP_11:case l.OP_12:case l.OP_13:case l.OP_14:case l.OP_15:case l.OP_16:t.pushInt(q.value-80);break;case l.OP_NOP:break;case l.OP_CHECKLOCKTIMEVERIFY:{if(!(e&P.flags.VERIFY_CHECKLOCKTIMEVERIFY)){if(e&P.flags.VERIFY_DISCOURAGE_UPGRADABLE_NOPS)throw new c("DISCOURAGE_UPGRADABLE_NOPS",q,U);break}if(!r)throw new c("UNKNOWN_ERROR","No TX passed in.");if(0===t.length)throw new c("INVALID_STACK_OPERATION",q,U);const s=t.getNum(-1,v,5);if(s.isNeg())throw new c("NEGATIVE_LOCKTIME",q,U);var b=s.toDouble();if(r.verifyLocktime(i,b))break;throw new c("UNSATISFIED_LOCKTIME",q,U)}case l.OP_CHECKSEQUENCEVERIFY:{if(!(e&P.flags.VERIFY_CHECKSEQUENCEVERIFY)){if(e&P.flags.VERIFY_DISCOURAGE_UPGRADABLE_NOPS)throw new c("DISCOURAGE_UPGRADABLE_NOPS",q,U);break}if(!r)throw new c("UNKNOWN_ERROR","No TX passed in.");if(0===t.length)throw new c("INVALID_STACK_OPERATION",q,U);const s=t.getNum(-1,v,5);if(s.isNeg())throw new c("NEGATIVE_LOCKTIME",q,U);if(b=s.toDouble(),r.verifySequence(i,b))break;throw new c("UNSATISFIED_LOCKTIME",q,U)}case l.OP_NOP1:case l.OP_NOP4:case l.OP_NOP5:case l.OP_NOP6:case l.OP_NOP7:case l.OP_NOP8:case l.OP_NOP9:case l.OP_NOP10:if(e&P.flags.VERIFY_DISCOURAGE_UPGRADABLE_NOPS)throw new c("DISCOURAGE_UPGRADABLE_NOPS",q,U);break;case l.OP_IF:case l.OP_NOTIF:{let r=!1;if(!y){if(t.length<1)throw new c("UNBALANCED_CONDITIONAL",q,U);if(1===o&&e&P.flags.VERIFY_MINIMALIF){if(1<(w=t.get(-1)).length)throw new c("MINIMALIF");if(1===w.length&&1!==w[0])throw new c("MINIMALIF")}r=t.getBool(-1),q.value===l.OP_NOTIF&&(r=!r),t.pop()}h.push(r),r||(y+=1);break}case l.OP_ELSE:if(0===h.length)throw new c("UNBALANCED_CONDITIONAL",q,U);h[h.length-1]=!h[h.length-1],h[h.length-1]?--y:y+=1;break;case l.OP_ENDIF:if(0===h.length)throw new c("UNBALANCED_CONDITIONAL",q,U);h.pop()||--y;break;case l.OP_VERIFY:if(0===t.length)throw new c("INVALID_STACK_OPERATION",q,U);if(!t.getBool(-1))throw new c("VERIFY",q,U);t.pop();break;case l.OP_TOALTSTACK:if(0===t.length)throw new c("INVALID_STACK_OPERATION",q,U);p.push(t.pop());break;case l.OP_FROMALTSTACK:if(0===p.length)throw new c("INVALID_ALTSTACK_OPERATION",q,U);t.push(p.pop());break;case l.OP_2DROP:if(t.length<2)throw new c("INVALID_STACK_OPERATION",q,U);t.pop(),t.pop();break;case l.OP_2DUP:if(t.length<2)throw new c("INVALID_STACK_OPERATION",q,U);var w=t.get(-2),x=t.get(-1);t.push(w),t.push(x);break;case l.OP_3DUP:if(t.length<3)throw new c("INVALID_STACK_OPERATION",q,U);x=t.get(-3);var k=t.get(-2),S=t.get(-1);t.push(x),t.push(k),t.push(S);break;case l.OP_2OVER:if(t.length<4)throw new c("INVALID_STACK_OPERATION",q,U);k=t.get(-4),S=t.get(-3),t.push(k),t.push(S);break;case l.OP_2ROT:if(t.length<6)throw new c("INVALID_STACK_OPERATION",q,U);var E=t.get(-6),_=t.get(-5);t.erase(-6,-4),t.push(E),t.push(_);break;case l.OP_2SWAP:if(t.length<4)throw new c("INVALID_STACK_OPERATION",q,U);t.swap(-4,-2),t.swap(-3,-1);break;case l.OP_IFDUP:if(0===t.length)throw new c("INVALID_STACK_OPERATION",q,U);t.getBool(-1)&&(E=t.get(-1),t.push(E));break;case l.OP_DEPTH:t.pushInt(t.length);break;case l.OP_DROP:{if(0===t.length)throw new c("INVALID_STACK_OPERATION",q,U);let e=t.pop();if(this.indicator.check(C)){this.indicator.unSet(C);try{var A=JSON.parse(e.toString());new I(A,a).run(t)}catch(p){}}break}case l.OP_DUP:if(0===t.length)throw new c("INVALID_STACK_OPERATION",q,U);t.push(t.get(-1));break;case l.OP_NIP:if(t.length<2)throw new c("INVALID_STACK_OPERATION",q,U);t.remove(-2);break;case l.OP_OVER:if(t.length<2)throw new c("INVALID_STACK_OPERATION",q,U);t.push(t.get(-2));break;case l.OP_PICK:case l.OP_ROLL:if(t.length<2)throw new c("INVALID_STACK_OPERATION",q,U);if(_=t.getInt(-1,v,4),t.pop(),_<0||_>=t.length)throw new c("INVALID_STACK_OPERATION",q,U);var R=t.get(-_-1);q.value===l.OP_ROLL&&t.remove(-_-1),t.push(R);break;case l.OP_ROT:if(t.length<3)throw new c("INVALID_STACK_OPERATION",q,U);t.swap(-3,-2),t.swap(-2,-1);break;case l.OP_SWAP:if(t.length<2)throw new c("INVALID_STACK_OPERATION",q,U);t.swap(-2,-1);break;case l.OP_TUCK:if(t.length<2)throw new c("INVALID_STACK_OPERATION",q,U);t.insert(-2,t.get(-1));break;case l.OP_SIZE:if(t.length<1)throw new c("INVALID_STACK_OPERATION",q,U);t.pushInt(t.get(-1).length);break;case l.OP_EQUAL:case l.OP_EQUALVERIFY:{if(t.length<2)throw new c("INVALID_STACK_OPERATION",q,U);const e=t.get(-2);R=t.get(-1);var j=e.equals(R);if(t.pop(),t.pop(),t.pushBool(j),q.value===l.OP_EQUALVERIFY){if(!j)throw new c("EQUALVERIFY",q,U);t.pop()}break}case l.OP_1ADD:case l.OP_1SUB:case l.OP_NEGATE:case l.OP_ABS:case l.OP_NOT:case l.OP_0NOTEQUAL:{if(t.length<1)throw new c("INVALID_STACK_OPERATION",q,U);let e,r=t.getNum(-1,v,4);switch(q.value){case l.OP_1ADD:r.iaddn(1);break;case l.OP_1SUB:r.isubn(1);break;case l.OP_NEGATE:r.ineg();break;case l.OP_ABS:r.iabs();break;case l.OP_NOT:e=r.isZero(),r=u.fromBool(e);break;case l.OP_0NOTEQUAL:e=!r.isZero(),r=u.fromBool(e);break;default:s(!1,"Fatal script error.")}t.pop(),t.pushNum(r);break}case l.OP_ADD:case l.OP_SUB:case l.OP_BOOLAND:case l.OP_BOOLOR:case l.OP_NUMEQUAL:case l.OP_NUMEQUALVERIFY:case l.OP_NUMNOTEQUAL:case l.OP_LESSTHAN:case l.OP_GREATERTHAN:case l.OP_LESSTHANOREQUAL:case l.OP_GREATERTHANOREQUAL:case l.OP_MIN:case l.OP_MAX:{if(t.length<2)throw new c("INVALID_STACK_OPERATION",q,U);const e=t.getNum(-2,v,4),r=t.getNum(-1,v,4);let i,n;switch(q.value){case l.OP_ADD:i=e.iadd(r);break;case l.OP_SUB:i=e.isub(r);break;case l.OP_BOOLAND:n=e.toBool()&&r.toBool(),i=u.fromBool(n);break;case l.OP_BOOLOR:n=e.toBool()||r.toBool(),i=u.fromBool(n);break;case l.OP_NUMEQUAL:case l.OP_NUMEQUALVERIFY:n=e.eq(r),i=u.fromBool(n);break;case l.OP_NUMNOTEQUAL:n=!e.eq(r),i=u.fromBool(n);break;case l.OP_LESSTHAN:n=e.lt(r),i=u.fromBool(n);break;case l.OP_GREATERTHAN:n=e.gt(r),i=u.fromBool(n);break;case l.OP_LESSTHANOREQUAL:n=e.lte(r),i=u.fromBool(n);break;case l.OP_GREATERTHANOREQUAL:n=e.gte(r),i=u.fromBool(n);break;case l.OP_MIN:i=u.min(e,r);break;case l.OP_MAX:i=u.max(e,r);break;default:s(!1,"Fatal script error.")}if(t.pop(),t.pop(),t.pushNum(i),q.value===l.OP_NUMEQUALVERIFY){if(!t.getBool(-1))throw new c("NUMEQUALVERIFY",q,U);t.pop()}break}case l.OP_WITHIN:{if(t.length<3)throw new c("INVALID_STACK_OPERATION",q,U);const e=t.getNum(-3,v,4),r=t.getNum(-2,v,4);j=t.getNum(-1,v,4);var B=r.lte(e)&&e.lt(j);t.pop(),t.pop(),t.pop(),t.pushBool(B);break}case l.OP_RIPEMD160:if(0===t.length)throw new c("INVALID_STACK_OPERATION",q,U);t.push(g.ripemd160(t.pop()));break;case l.OP_SHA1:if(0===t.length)throw new c("INVALID_STACK_OPERATION",q,U);t.push(g.sha1(t.pop()));break;case l.OP_SHA256:if(0===t.length)throw new c("INVALID_STACK_OPERATION",q,U);t.push(g.sha256(t.pop()));break;case l.OP_HASH160:if(0===t.length)throw new c("INVALID_STACK_OPERATION",q,U);t.push(g.hash160(t.pop()));break;case l.OP_HASH256:if(0===t.length)throw new c("INVALID_STACK_OPERATION",q,U);t.push(g.hash256(t.pop()));break;case l.OP_CODESEPARATOR:d=U+1;break;case l.OP_CHECKSIG:case l.OP_CHECKSIGVERIFY:{if(!r)throw new c("UNKNOWN_ERROR","No TX passed in.");if(t.length<2)throw new c("INVALID_STACK_OPERATION",q,U);B=t.get(-2);var N,D=t.get(-1);const s=this.getSubscript(d);0===o&&s.findAndDelete(B),T(B,e),O(D,e,o);let a=!1;if(0<B.length&&(N=B[B.length-1],a=F(N=r.signatureHash(i,s,n,N,o),B,D)),!a&&e&P.flags.VERIFY_NULLFAIL&&0!==B.length)throw new c("NULLFAIL",q,U);if(t.pop(),t.pop(),t.pushBool(a),q.value===l.OP_CHECKSIGVERIFY){if(!a)throw new c("CHECKSIGVERIFY",q,U);t.pop()}break}case l.OP_CHECKMULTISIG:case l.OP_CHECKMULTISIGVERIFY:{if(!r)throw new c("UNKNOWN_ERROR","No TX passed in.");let s=1;if(t.length<s)throw new c("INVALID_STACK_OPERATION",q,U);let a,u,h=t.getInt(-s,v,4),p=h+2;if(h<0||h>f.MAX_MULTISIG_PUBKEYS)throw new c("PUBKEY_COUNT",q,U);if((m+=h)>f.MAX_SCRIPT_OPS)throw new c("OP_COUNT",q,U);if(s+=1,a=s,s+=h,t.length<s)throw new c("INVALID_STACK_OPERATION",q,U);let g=t.getInt(-s,v,4);if(g<0||g>h)throw new c("SIG_COUNT",q,U);if(s+=1,u=s,s+=g,t.length<s)throw new c("INVALID_STACK_OPERATION",q,U);const y=this.getSubscript(d);for(let e=0;e<g;e++){var L=t.get(-u-e);0===o&&y.findAndDelete(L)}let b=!0;for(;b&&0<g;){var H,z=t.get(-u),M=t.get(-a);T(z,e),O(M,e,o),0<z.length&&(H=z[z.length-1],F(r.signatureHash(i,y,n,H,o),z,M)&&(u+=1,--g)),a+=1,--h,g>h&&(b=!1)}for(;1<s;){if(!b&&e&P.flags.VERIFY_NULLFAIL&&0===p&&0!==t.get(-1).length)throw new c("NULLFAIL",q,U);0<p&&--p,t.pop(),--s}if(t.length<1)throw new c("INVALID_STACK_OPERATION",q,U);if(e&P.flags.VERIFY_NULLDUMMY&&0!==t.get(-1).length)throw new c("SIG_NULLDUMMY",q,U);if(t.pop(),t.pushBool(b),q.value===l.OP_CHECKMULTISIGVERIFY){if(!b)throw new c("CHECKMULTISIGVERIFY",q,U);t.pop()}break}default:throw new c("BAD_OPCODE",q,U)}if(t.length+p.length>f.MAX_SCRIPT_STACK)throw new c("STACK_SIZE",q,U)}}if(0!==h.length)throw new c("UNBALANCED_CONDITIONAL")}findAndDelete(t){const e=a.fromPush(t);if(this.raw.length<e.getSize())return 0;let r=!1;for(const t of this.code){if(-1===t.value)break;if(t.equals(e)){r=!0;break}}if(!r)return 0;const i=[];let s=0;for(const t of this.code){if(-1===t.value)break;t.equals(e)?s+=1:i.push(t)}return this.code=i,this.compile(),s}indexOf(t){for(let e=0;e<this.code.length;e++){const r=this.code[e];if(-1===r.value)break;if(r.data&&r.data.equals(t))return e}return-1}isCode(){for(const t of this.code){if(-1===t.value)return!1;if(t.isDisabled())return!1;switch(t.value){case l.OP_RESERVED:case l.OP_NOP:case l.OP_VER:case l.OP_VERIF:case l.OP_VERNOTIF:case l.OP_RESERVED1:case l.OP_RESERVED2:case l.OP_NOP1:return!1}if(t.value>l.OP_PROPMAX)return!1}return!0}fromAddress(t,e){"string"==typeof t&&(t=_.fromString(t)),s(t instanceof _,"Not an address.");let r=!1;if(t.isPubkeyhash())if(e&&e.oper)switch(e.oper){case A.cpRegister:this.createScript({opcode:P.opcodes.OP_CPREGISTER,hash:t.hash,info:Buffer.from(JSON.stringify(e))},P.types.PROPEXTEND);break;case A.cpChange:this.createScript({opcode:P.opcodes.OP_CPCHANGE,hash:t.hash,info:Buffer.from(JSON.stringify(e))},P.types.PROPEXTEND);break;case A.propCreate:this.createScript({opcode:P.opcodes.OP_PROPCREATE,hash:t.hash,info:Buffer.from(JSON.stringify(e))},P.types.PROPEXTEND);break;case A.propExchange:this.createScript({opcode:P.opcodes.OP_PROPEXCHANGE,hash:t.hash,info:Buffer.from(JSON.stringify(e))},P.types.PROPEXTEND);break;case A.coinbase:this.createScript({opcode:P.opcodes.OP_COINBASE,hash:t.hash,info:Buffer.from(JSON.stringify(e))},P.types.PROPEXTEND)}else this.createScript(t.hash);else t.isScripthash()?this.createScript(t.hash,P.types.SCRIPTHASH):t.isProgram()&&this.createScript([t.version,t.hash,e],P.types.WITNESS);if(e&&e.locktype&&(!e.oper||h.unspendableCodes.indexOf(e.oper)<0))switch(e.locktype){case d.CHECKABSOLUTEBLOCK:case d.CHECKABSOLUTETIME:this.code.unshift(a.fromOp(l.OP_DROP)),this.code.unshift(a.fromOp(l.OP_CHECKLOCKTIMEVERIFY)),this.code.unshift(a.fromInt(e.locktime)),r=!0;break;case d.CHECKRELATIVEBLOCK:case d.CHECKRELATIVETIME:e.locktype===d.CHECKRELATIVETIME&&(e.locktime=e.locktime|f.SEQUENCE_TYPE_FLAG),this.code.unshift(a.fromOp(l.OP_DROP)),this.code.unshift(a.fromOp(l.OP_CHECKSEQUENCEVERIFY)),this.code.unshift(a.fromInt(e.locktime)),r=!0}if(r&&this.compile(),0<this.code.length)return this;throw new Error("Unknown address type.")}static fromAddress(t,e){return(new P).fromAddress(t,e)}fromCommitment(t,e){const r=new E(36);return r.writeU32BE(2854332909),r.writeHash(t),this.clear(),this.pushOp(l.OP_RETURN),this.pushData(r.render()),e&&this.pushData(e),this.compile()}static fromCommitment(t,e){return(new P).fromCommitment(t,e)}getRedeem(){let t=null;for(const e of this.code){if(-1===e.value)return null;if(e.value>l.OP_16)return null;t=e.data}return t?P.fromRaw(t):null}getType(){return this.isPubkey()?p.PUBKEY:this.isPubkeyhash()?p.PUBKEYHASH:this.isScripthash()?p.SCRIPTHASH:this.isWitnessPubkeyhash()?p.WITNESSPUBKEYHASH:this.isWitnessScripthash()?p.WITNESSSCRIPTHASH:this.isWitnessMasthash()?p.WITNESSMASTHASH:this.isMultisig()?p.MULTISIG:this.isNulldata()?p.NULLDATA:p.NONSTANDARD}isPubkey(t){return t?35<=this.raw.length&&(33===this.raw[0]||65===this.raw[0])&&this.raw[0]+2===this.raw.length&&this.raw[this.raw.length-1]===l.OP_CHECKSIG:2===this.code.length&&(33===(t=this.getLength(0))||65===t)&&this.getOp(1)===l.OP_CHECKSIG}isPubkeyhash(t){if(t||25===this.raw.length)return 25===this.raw.length&&this.raw[0]===l.OP_DUP&&this.raw[1]===l.OP_HASH160&&20===this.raw[2]&&this.raw[23]===l.OP_EQUALVERIFY&&this.raw[24]===l.OP_CHECKSIG;let e=0;for(var r of this.code)if(r.value==l.OP_DUP){e=this.code.indexOf(r);break}return this.getOp(0+e)===l.OP_DUP&&this.getOp(1+e)===l.OP_HASH160&&20===this.getLength(2+e)&&this.getOp(3+e)===l.OP_EQUALVERIFY&&this.getOp(4+e)===l.OP_CHECKSIG}isMultisig(t){if(this.code.length<4||19<this.code.length)return!1;if(this.getOp(-1)!==l.OP_CHECKMULTISIG)return!1;var e=this.getSmall(0);if(e<1)return!1;var r=this.getSmall(-2);if(r<1||r<e)return!1;if(this.code.length!==r+3)return!1;for(let e=1;e<r+1;e++){const r=this.code[e];var i=r.toLength();if(33!==i&&65!==i)return!1;if(t&&!r.isMinimal())return!1}return!0}isUnknown(){return this.getType()===p.NONSTANDARD}isStandard(){var[t,e]=this.getMultisig();return-1!==t?!(e<1||3<e||t<1||e<t):this.isNulldata()?this.raw.length<=m.MAX_OP_RETURN_BYTES:this.getType()!==p.NONSTANDARD}isScripthash(){return 23===this.raw.length&&this.raw[0]===l.OP_HASH160&&20===this.raw[1]&&this.raw[22]===l.OP_EQUAL}isNulldata(t){if(0===this.code.length)return!1;if(this.getOp(0)!==l.OP_RETURN)return!1;if(1!==this.code.length){if(t&&this.raw.length>m.MAX_OP_RETURN_BYTES)return!1;for(let e=1;e<this.code.length;e++){const r=this.code[e];if(-1===r.value)return!1;if(r.value>l.OP_16)return!1;if(t&&!r.isMinimal())return!1}}return!0}isCommitment(){return 38<=this.raw.length&&this.raw[0]===l.OP_RETURN&&36===this.raw[1]&&2854332909===this.raw.readUInt32BE(2,!0)}isWitnessPubkeyhash(){return 22===this.raw.length&&this.raw[0]===l.OP_0&&20===this.raw[1]||5==this.code.length&&this.code[2].value==l.OP_DROP&&this.code[3].value==l.OP_0&&20==this.code[4].value}getWitnessPubkeyhash(){return this.isWitnessPubkeyhash()?5==this.code.length?this.getData(4):this.getData(1):null}isWitnessScripthash(){return 34===this.raw.length&&this.raw[0]===l.OP_0&&32===this.raw[1]}getWitnessScripthash(){return this.isWitnessScripthash()?this.getData(1):null}isProgram(){if(2==this.code.length){if(4<=this.raw.length&&this.raw.length<=42&&(this.raw[0]==l.OP_0||this.raw[0]>=l.OP_1&&this.raw[0]<=l.OP_16)&&this.raw[1]+2==this.raw.length)return!0}else if(5==this.code.length&&4<=this.raw.length&&this.code[2].value==l.OP_DROP&&(this.code[3].value==l.OP_0||this.code[3].value>=l.OP_1&&this.code[3].value<=l.OP_16))return!0;return!1}isWitnessMasthash(){return 34===this.raw.length&&this.raw[0]===l.OP_1&&32===this.raw[1]}isUnspendable(){return this.raw.length>f.MAX_SCRIPT_SIZE||0<this.raw.length&&this.raw[0]===l.OP_RETURN}getSize(){return this.raw.length}getVarSize(){return b.sizeVarBytes(this.raw)}getReturnData(t){if(!(this.code&&this.code[0]&&this.code[1]&&this.code[1].data))return null;if(t)if(Array.isArray(t)){let r=!1;for(var e of t)if(this.code[0].value===e){r=!0;break}if(!r)return null}else if(this.code[0].value!==t)return null;try{return x.parseJson(this.code[1].data.toString())}catch(t){return null}}getReturnType(t){if(!this.code||!this.code[0])return null;if(t)if(Array.isArray(t)){let r=!1;for(var e of t)if(this.code[0].value===e){r=!0;break}if(!r)return null}else if(this.code[0].value!==t)return null;return this.code[0].value}hash160(t){let e=g.hash160(this.toRaw());return"hex"===t?e.toString("hex"):e}sha256(t){let e=g.sha256(this.toRaw());return"hex"===t?e.toString("hex"):e}getPubkey(t){return this.isPubkey(t)?t?this.raw.slice(1,1+this.raw[0]):this.getData(0):null}getMultiPubkeyhash(){let t=j[this.getOp(0)];return t&&this.code.length==t.len?t.list.map(t=>this.getData(t)):null}getPubkeyhash(t){if(this.isPubkeyhash(t)){if(t)return this.raw.slice(3,23);for(var e of this.code)if(e.value==l.OP_CHECKSIG)return this.getData(this.code.indexOf(e)-2)}return null}getMultisig(t){return this.isMultisig(t)?[this.getSmall(0),this.getSmall(-2)]:[-1,-1]}getScripthash(){return this.isScripthash()?this.getData(1):null}getNulldata(t){if(!this.isNulldata(t))return null;for(let t=1;t<this.code.length;t++){var e=this.code[t].toPush();if(e)return e}return i}getCommitment(){return this.isCommitment()?this.raw.slice(6,38):null}getProgram(){return this.isProgram()?2==this.code.length?new n(this.getSmall(0),this.getData(1)):5==this.code.length?new n(this.getSmall(3),this.getData(4)):null:null}forWitness(){var t;return this.isProgram()?this.clone():(t=this.getPubkey())?(t=g.hash160(t),P.createScript([0,t],P.types.WITNESS)):(t=this.getPubkeyhash())?P.createScript([0,t],P.types.WITNESS):P.createScript([0,this.sha256()],P.types.WITNESS)}getWitnessMasthash(){return this.isWitnessMasthash()?this.getData(1):null}getInputType(){return this.isPubkeyInput()?p.PUBKEY:this.isPubkeyhashInput()?p.PUBKEYHASH:this.isScripthashInput()?p.SCRIPTHASH:this.isMultisigInput()?p.MULTISIG:p.NONSTANDARD}isPubkeyhashInput(){var t,e;return 2===this.code.length&&(t=this.getLength(0),e=this.getLength(1),9<=t&&t<=73&&(33===e||65===e))}isUnknownInput(){return this.getInputType()===p.NONSTANDARD}isPubkeyInput(){var t;return 1===this.code.length&&9<=(t=this.getLength(0))&&t<=73}isScripthashInput(){if(this.code.length<2)return!1;var t=this.getData(-1);if(!t)return!1;if(0===t.length)return!1;if(h.isSignatureEncoding(t))return!1;if(h.isKeyEncoding(t))return!1;const e=P.fromRaw(t);return!!e.isCode()&&!e.isUnspendable()&&!!this.isPushOnly()}isMultisigInput(){if(this.code.length<2)return!1;if(this.getOp(0)!==l.OP_0)return!1;if(this.getOp(1)>l.OP_PUSHDATA4)return!1;if(this.isScripthashInput())return!1;for(let e=1;e<this.code.length;e++){var t=this.getLength(e);if(t<9||73<t)return!1}return!0}getPubkeyInput(){return this.isPubkeyInput()?this.getData(0):null}getPubkeyhashInput(){return this.isPubkeyhashInput()?[this.getData(0),this.getData(1)]:[null,null]}getMultisigInput(){if(!this.isMultisigInput())return null;const t=[];for(let e=1;e<this.code.length;e++)t.push(this.getData(e));return t}getScripthashInput(){return this.isScripthashInput()?this.getData(-1):null}getCoinbaseHeight(){return P.getCoinbaseHeight(this.raw)}static getCoinbaseHeight(t){if(0===t.length)return-1;if(t[0]>=l.OP_1&&t[0]<=l.OP_16)return t[0]-80;if(6<t[0])return-1;const e=a.fromRaw(t),r=e.toNum();return r?!r.isNeg()&&e.equals(a.fromNum(r))?r.toDouble():-1:1}test(t){for(const e of this.code){if(-1===e.value)break;if(e.data&&0!==e.data.length){if(t.test(e.data))return!0;if(33==e.data.length&&t.test(g.hash160(e.data)))return!0}}return!1}isPushOnly(){for(const t of this.code){if(-1===t.value)return!1;if(t.value>l.OP_16)return!1}return!0}getSigops(t){let e=0,r=-1;for(const i of this.code){if(-1===i.value)break;switch(i.value){case l.OP_CHECKSIG:case l.OP_CHECKSIGVERIFY:e+=1;break;case l.OP_CHECKMULTISIG:case l.OP_CHECKMULTISIGVERIFY:t&&r>=l.OP_1&&r<=l.OP_16?e+=r-80:e+=f.MAX_MULTISIG_PUBKEYS}r=i.value}return e}getScripthashSigops(t){if(!this.isScripthash())return this.getSigops(!0);const e=t.getRedeem();return e?e.getSigops(!0):0}getWitnessSigops(t,e){let r=this.getProgram();if(!r&&this.isScripthash()){const e=t.getRedeem();e&&(r=e.getProgram())}if(r&&0===r.version){if(20===r.data.length)return 1;if(32===r.data.length&&0<e.items.length){return e.getRedeem().getSigops(!0)}}return 0}get(t){return t<0&&(t+=this.code.length),t<0||t>=this.code.length?null:this.code[t]}pop(){return this.code.pop()||null}shift(){return this.code.shift()||null}remove(t){return t<0&&(t+=this.code.length),t<0||t>=this.code.length||0===(t=this.code.splice(t,1)).length?null:t[0]}set(t,e){return t<0&&(t+=this.code.length),s(a.isOpcode(e)),s(0<=t&&t<=this.code.length),this.code[t]=e,this}push(t){return s(a.isOpcode(t)),this.code.push(t),this}unshift(t){return s(a.isOpcode(t)),this.code.unshift(t),this}insert(t,e){return t<0&&(t+=this.code.length),s(a.isOpcode(e)),s(0<=t&&t<=this.code.length),this.code.splice(t,0,e),this}getOp(t){return(t=this.get(t))?t.value:-1}popOp(){var t=this.pop();return t?t.value:-1}shiftOp(){var t=this.shift();return t?t.value:-1}removeOp(t){return(t=this.remove(t))?t.value:-1}setOp(t,e){return this.set(t,a.fromOp(e))}pushOp(t){return this.push(a.fromOp(t))}unshiftOp(t){return this.unshift(a.fromOp(t))}insertOp(t,e){return this.insert(t,a.fromOp(e))}getData(t){return(t=this.get(t))?t.data:null}popData(){var t=this.pop();return t?t.data:null}shiftData(){var t=this.shift();return t?t.data:null}removeData(t){return(t=this.remove(t))?t.data:null}setData(t,e){return this.set(t,a.fromData(e))}pushData(t){return this.push(a.fromData(t))}unshiftData(t){return this.unshift(a.fromData(t))}insertData(t,e){return this.insert(t,a.fromData(e))}getLength(t){const e=this.get(t);return e?e.toLength():-1}getPush(t){const e=this.get(t);return e?e.toPush():null}popPush(){const t=this.pop();return t?t.toPush():null}shiftPush(){const t=this.shift();return t?t.toPush():null}removePush(t){const e=this.remove(t);return e?e.toPush():null}setPush(t,e){return this.set(t,a.fromPush(e))}pushPush(t){return this.push(a.fromPush(t))}unshiftPush(t){return this.unshift(a.fromPush(t))}insertPush(t,e){return this.insert(t,a.fromPush(e))}getString(t,e){const r=this.get(t);return r?r.toString(e):null}popString(t){const e=this.pop();return e?e.toString(t):null}shiftString(t){const e=this.shift();return e?e.toString(t):null}removeString(t,e){const r=this.remove(t);return r?r.toString(e):null}setString(t,e,r){return this.set(t,a.fromString(e,r))}pushString(t,e){return this.push(a.fromString(t,e))}unshiftString(t,e){return this.unshift(a.fromString(t,e))}insertString(t,e,r){return this.insert(t,a.fromString(e,r))}getSmall(t){const e=this.get(t);return e?e.toSmall():-1}popSmall(){const t=this.pop();return t?t.toSmall():-1}shiftSmall(){const t=this.shift();return t?t.toSmall():-1}removeSmall(t){const e=this.remove(t);return e?e.toSmall():-1}setSmall(t,e){return this.set(t,a.fromSmall(e))}pushSmall(t){return this.push(a.fromSmall(t))}unshiftSmall(t){return this.unshift(a.fromSmall(t))}insertSmall(t,e){return this.insert(t,a.fromSmall(e))}getNum(t,e,r){const i=this.get(t);return i?i.toNum(e,r):null}popNum(t,e){const r=this.pop();return r?r.toNum(t,e):null}shiftNum(t,e){const r=this.shift();return r?r.toNum(t,e):null}removeNum(t,e,r){const i=this.remove(t);return i?i.toNum(e,r):null}setNum(t,e){return this.set(t,a.fromNum(e))}pushNum(t){return this.push(a.fromNum(t))}unshiftNum(t){return this.unshift(a.fromNum(t))}insertNum(t,e){return this.insert(t,a.fromNum(e))}getInt(t,e,r){const i=this.get(t);return i?i.toInt(e,r):-1}popInt(t,e){const r=this.pop();return r?r.toInt(t,e):-1}shiftInt(t,e){const r=this.shift();return r?r.toInt(t,e):-1}removeInt(t,e,r){const i=this.remove(t);return i?i.toInt(e,r):-1}setInt(t,e){return this.set(t,a.fromInt(e))}pushInt(t){return this.push(a.fromInt(t))}unshiftInt(t){return this.unshift(a.fromInt(t))}insertInt(t,e){return this.insert(t,a.fromInt(e))}getBool(t){const e=this.get(t);return!!e&&e.toBool()}popBool(){const t=this.pop();return!!t&&t.toBool()}shiftBool(){const t=this.shift();return!!t&&t.toBool()}removeBool(t){const e=this.remove(t);return!!e&&e.toBool()}setBool(t,e){return this.set(t,a.fromBool(e))}pushBool(t){return this.push(a.fromBool(t))}unshiftBool(t){return this.unshift(a.fromBool(t))}insertBool(t,e){return this.insert(t,a.fromBool(e))}getSym(t){const e=this.get(t);return e?e.toSymbol():null}popSym(){const t=this.pop();return t?t.toSymbol():null}shiftSym(){const t=this.shift();return t?t.toSymbol():null}removeSym(t){const e=this.remove(t);return e?e.toSymbol():null}setSym(t,e){return this.set(t,a.fromSymbol(e))}pushSym(t){return this.push(a.fromSymbol(t))}unshiftSym(t){return this.unshift(a.fromSymbol(t))}insertSym(t,e){return this.insert(t,a.fromSymbol(e))}fromString(t){if(s("string"==typeof t),0===(t=t.trim()).length)return this;t=t.split(/\s+/);const e=new k;for(const c of t){let t=c;x.isUpperCase(t)||(t=t.toUpperCase()),x.startsWith(t,"OP_")||(t="OP_"+t);var r=l[t];if(null==r)if("'"===c[0]){s("'"===c[c.length-1],"Invalid string.");var i=c.slice(1,-1);const t=a.fromString(i);e.writeBytes(t.toRaw())}else if(/^-?\d+$/.test(c)){i=u.fromString(c,10);const t=a.fromNum(i);e.writeBytes(t.toRaw())}else{s(0===c.indexOf("0x"),"Unknown opcode.");var n=c.substring(2),o=Buffer.from(n,"hex");s(o.length===n.length/2,"Invalid hex string."),e.writeBytes(o)}else e.writeU8(r)}return this.fromRaw(e.render())}static fromString(t){return(new P).fromString(t)}static verifyScript(t,e,r,i,n,u,h,l){if((h=null==h?P.flags.STANDARD_VERIFY_FLAGS:h)&P.flags.VERIFY_SIGPUSHONLY&&!t.isPushOnly())throw new c("SIG_PUSHONLY");null==l&&(l=R.None);let p,d=new o;if(t.execute(d,h,i,n,u,l,0),h&P.flags.VERIFY_P2SH&&(p=d.clone()),r.execute(d,h,i,n,u,l,0),0===d.length||!d.getBool(-1))throw new c("EVAL_FALSE");let f=!1;if(h&P.flags.VERIFY_WITNESS&&r.isProgram()){if(f=!0,0!==t.raw.length)throw new c("WITNESS_MALLEATED");P.verifyProgram(e,r,h,i,n,u,l),d.length=1}if(h&P.flags.VERIFY_P2SH&&r.isScripthash()){if(!t.isPushOnly())throw new c("SIG_PUSHONLY");if(0===(d=p).length)throw new c("EVAL_FALSE");r=d.pop();const s=P.fromRaw(r);if(s.execute(d,h,i,n,u,l,0),0===d.length||!d.getBool(-1))throw new c("EVAL_FALSE");if(h&P.flags.VERIFY_WITNESS&&s.isProgram()){if(f=!0,!t.raw.equals(a.fromPush(r).toRaw()))throw new c("WITNESS_MALLEATED_P2SH");P.verifyProgram(e,s,h,i,n,u,l),d.length=1}}if(h&P.flags.VERIFY_CLEANSTACK&&(s(0!=(h&P.flags.VERIFY_P2SH)),1!==d.length))throw new c("CLEANSTACK");if(h&P.flags.VERIFY_WITNESS&&(s(0!=(h&P.flags.VERIFY_P2SH)),!f&&0<e.items.length))throw new c("WITNESS_UNEXPECTED")}static verifyProgram(t,e,r,i,n,a,o){var u=e.getProgram();s(u,"verifyProgram called on non-witness-program."),s(0!=(r&P.flags.VERIFY_WITNESS));const h=t.toStack();let l;if(0!==u.version){if(r&P.flags.VERIFY_MAST&&1===u.version)P.verifyMast(u,h,e,r,i,n,o);else if(r&P.flags.VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM)throw new c("DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM")}else{if(32===u.data.length){if(0===h.length)throw new c("WITNESS_PROGRAM_WITNESS_EMPTY");if(t=h.pop(),!g.sha256(t).equals(u.data))throw new c("WITNESS_PROGRAM_MISMATCH");l=P.fromRaw(t)}else{if(20!==u.data.length)throw new c("WITNESS_PROGRAM_WRONG_LENGTH");if(2!==h.length)throw new c("WITNESS_PROGRAM_MISMATCH");l=P.createScript(u.data)}for(let t=0;t<h.length;t++)if(h.get(t).length>f.MAX_SCRIPT_PUSH)throw new c("PUSH_SIZE");if(l.execute(h,r,i,n,a,o,1),1!==h.length||!h.getBool(-1))throw new c("EVAL_FALSE")}}static verifyMast(t,e,r,i,n,a,o,u){if(s(1===t.version),s(0!=(i&P.flags.VERIFY_MAST)),e.length<4)throw new c("INVALID_MAST_STACK");var h=e.get(-1);if(h.length<1||5<h.length)throw new c("INVALID_MAST_STACK");var l=h[0];if(0===l||e.length<l+3)throw new c("INVALID_MAST_STACK");var p=l;let d=new k;if(d.writeU8(l),0===h[h.length-1])throw new c("INVALID_MAST_STACK");let m=0;for(let t=1;t<h.length;t++)m|=h[t]<<8*(t-1);if(m<0&&(m+=4294967296),0<m&&i&P.flags.DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM)throw new c("DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM");let v=new k;v.writeU32(m);const b=e.get(-2);if(31&b.length)throw new c("INVALID_MAST_STACK");var w=b.length>>>5;if(32<w)throw new c("INVALID_MAST_STACK");if(0===m&&(p+=w)>f.MAX_SCRIPT_OPS)throw new c("OP_COUNT");const x=[];for(let t=0;t<w;t++)x.push(b.slice(32*t,32*t+32));var S=e.get(-3);if(4<S.length)throw new c("INVALID_MAST_STACK");let E=0;if(0<S.length){if(0===S[S.length-1])throw new c("INVALID_MAST_STACK");for(let t=0;t<S.length;t++)E|=S[t]<<8*t;E<0&&(E+=4294967296)}if(w<32&&E>=1<<w>>>0)throw new c("INVALID_MAST_STACK");let _=new k;_.writeBytes(r.raw);for(let t=0;t<l;t++){var A=e.get(-(4+t));if(0===m&&_.offset+A.length>f.MAX_SCRIPT_SIZE)throw new c("SCRIPT_SIZE");d.writeBytes(g.hash256(A)),_.writeBytes(A)}if(d=g.hash256(d.render()),d=y.verifyBranch(d,x,E),v.writeBytes(d),!(v=g.hash256(v.render())).equals(t.data))throw new c("WITNESS_PROGRAM_MISMATCH");if(0===m){e.length-=3+l;for(let t=0;t<e.length;t++)if(e.get(t).length>f.MAX_SCRIPT_PUSH)throw new c("PUSH_SIZE");if(_=_.render(),(r=P.fromRaw(_)).execute(e,i,n,a,o,u,1),0!==e.length)throw new c("EVAL_FALSE")}}fromReader(t){return this.fromRaw(t.readVarBytes())}fromRaw(t){const e=new S(t,!0);for(this.raw=t;e.left();)this.code.push(a.fromReader(e));return this}static fromReader(t){return(new P).fromReader(t)}static fromRaw(t,e){return"string"==typeof t&&(t=Buffer.from(t,e)),(new P).fromRaw(t)}static isScript(t){return t instanceof P}}function O(t,e,r){if(s(Buffer.isBuffer(t)),s("number"==typeof e),s("number"==typeof r),e&P.flags.VERIFY_STRICTENC&&!h.isKeyEncoding(t))throw new c("PUBKEYTYPE");if(1===r&&e&P.flags.VERIFY_WITNESS_PUBKEYTYPE&&!h.isCompressedEncoding(t))throw new c("WITNESS_PUBKEYTYPE")}function T(t,e){if(s(Buffer.isBuffer(t)),s("number"==typeof e),0!==t.length){if((e&P.flags.VERIFY_DERSIG||e&P.flags.VERIFY_LOW_S||e&P.flags.VERIFY_STRICTENC)&&!h.isSignatureEncoding(t))throw new c("SIG_DER");if(e&P.flags.VERIFY_LOW_S&&!h.isLowDER(t))throw new c("SIG_HIGH_S");if(e&P.flags.VERIFY_STRICTENC&&!h.isHashType(t))throw new c("SIG_HASHTYPE")}}function F(t,e,r){return v.verify(t,e.slice(0,-1),r)}P.opcodes=h.opcodes,P.opcodesByVal=h.opcodesByVal,P.flags=h.flags,P.hashType=h.hashType,P.hashTypeByVal=h.hashTypeByVal,P.types=h.types,P.typesByVal=h.typesByVal,P.outputLockType=h.outputLockType,P.unspendableCodes=h.unspendableCodes,P.TradeType={btc:1},t.exports=P},function(t,e,r){"use strict";
41
41
  /*!
42
42
  * packetTypes.js - worker packets for vallnet
43
43
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -47,7 +47,7 @@ const path = require('path');var gpath = path.join(__dirname, '../../../', 'node
47
47
  * tx.js - transaction object for vallnet
48
48
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
49
49
  * https://github.com/bookmansoft/gamegold
50
- */const i=r(0),s=r(1),n=r(3),a=r(6),o=r(28),c=r(34),u=r(15),h=r(17),l=r(2),p=r(4),d=r(115),f=r(26),m=r(46),g=r(64),y=r(102),v=r(7),b=r(27),w=r(114),{opcodes:x,hashType:k}=r(21);function S(t,e){this.data=null,this.size=t,this.witness=e}r(61),t.exports=class t{constructor(t){t=t||{},this.version=1,this.inputs=t.inputs||[],this.outputs=t.outputs||[],this.locktime=0,this.mutable=!1,this._hash=null,this._hhash=null,this._whash=null,this._raw=null,this._size=-1,this._witness=-1,this._sigops=-1,this._hashPrevouts=null,this._hashSequence=null,this._hashOutputs=null,t&&this.fromOptions(t)}fromOptions(t){if(i(t,"TX data is required."),null!=t.version&&(i(s.isU32(t.version),"Version must be a uint32."),this.version=t.version),t.inputs){this.inputs=[],i(Array.isArray(t.inputs),"Inputs must be an array.");for(const e of t.inputs)this.inputs.push(new d(e))}if(t.outputs){this.outputs=[],i(Array.isArray(t.outputs),"Outputs must be an array.");for(const e of t.outputs)this.outputs.push(new f(e))}return null!=t.locktime&&(i(s.isU32(t.locktime),"Locktime must be a uint32."),this.locktime=t.locktime),this}static fromOptions(e){return(new t).fromOptions(e)}clone(){return(new t).inject(this)}inject(t,e=0){this.version=t.version;for(const r of t.inputs)if(this.inputs.push(r.clone()),0!=e&&this.inputs.length>=e)break;for(const r of t.outputs)if(this.outputs.push(r.clone()),0!=e&&this.outputs.length>=e)break;return this.locktime=t.locktime,this}refresh(){this._hash=null,this._hhash=null,this._whash=null,this._raw=null,this._size=-1,this._witness=-1,this._sigops=-1,this._hashPrevouts=null,this._hashSequence=null,this._hashOutputs=null}hash(t){let e=this._hash;if(e||(e=a.hash256(this.toNormal()),this.mutable||(this._hash=e)),"hex"===t){let t=this._hhash;t||(t=e.toString("hex"),this.mutable||(this._hhash=t)),e=t}return e}witnessHash(t){if(!this.hasWitness())return this.hash(t);let e=this._whash;return e||(e=a.hash256(this.toRaw()),this.mutable||(this._whash=e)),"hex"===t?e.toString("hex"):e}toRaw(){return this.frame().data}toNormal(){return this.hasWitness()?this.frameNormal().data:this.toRaw()}toWriter(t){return this.mutable?this.hasWitness()?this.writeWitness(t):this.writeNormal(t):(t.writeBytes(this.toRaw()),t)}toNormalWriter(t){return this.hasWitness()?(this.writeNormal(t),t):this.toWriter(t)}frame(){if(this.mutable)return i(!this._raw),this.hasWitness()?this.frameWitness():this.frameNormal();if(this._raw){i(0<=this._size),i(0<=this._witness);const t=new S(this._size,this._witness);return t.data=this._raw,t}let t;return t=this.hasWitness()?this.frameWitness():this.frameNormal(),this._raw=t.data,this._size=t.size,this._witness=t.witness,t}getSizes(){return this.mutable?this.hasWitness()?this.getWitnessSizes():this.getNormalSizes():this.frame()}getVirtualSize(){var t=v.WITNESS_SCALE_FACTOR;return(this.getWeight()+t-1)/t|0}getSigopsSize(t){var e=v.WITNESS_SCALE_FACTOR,r=b.BYTES_PER_SIGOP;return(Math.max(this.getWeight(),t*r)+e-1)/e|0}getWeight(){var t=this.getSizes();return(t.size-t.witness)*(v.WITNESS_SCALE_FACTOR-1)+t.size}getSize(){return this.getSizes().size}getBaseSize(){var t=this.getSizes();return t.size-t.witness}hasWitness(){if(-1!==this._witness)return 0!==this._witness;for(const t of this.inputs)if(0<t.witness.items.length)return!0;return!1}signatureHash(t,e,r,s,n){if(i(0<=t&&t<this.inputs.length),i(e instanceof h),i("number"==typeof r),i("number"==typeof s),0===n)return this.signatureHashV0(t,e,s);if(1===n)return this.signatureHashV1(t,e,r,s);throw new Error("Unknown sighash version.")}get opr(){let t={};return 0<this.outputs.length&&(t.data=this.outputs[0].getReturnData([x.OP_RETURN]),t.data&&"inner"==t.data.$tag&&(t.isDerived=!0)),t}signatureHashV0(t,e,r){if((31&r)===k.SINGLE){if(t>=this.outputs.length)return Buffer.from(n.ONE_HASH)}else if((31&r)===k.ZERO&&0==this.outputs.length)return Buffer.from(n.ONE_HASH);e=e.removeSeparators();var i=this.hashSize(t,e,r);const s=p.pool(i);if(s.writeU32(this.version),r&k.ANYONECANPAY){const r=this.inputs[t];s.writeVarint(1),r.prevout.toWriter(s),s.writeVarBytes(e.toRaw()),s.writeU32(r.sequence)}else{s.writeVarint(this.inputs.length);for(let i=0;i<this.inputs.length;i++){const n=this.inputs[i];if(n.prevout.toWriter(s),i===t)s.writeVarBytes(e.toRaw()),s.writeU32(n.sequence);else switch(s.writeVarint(0),31&r){case k.NONE:case k.SINGLE:case k.ZERO:s.writeU32(0);break;default:s.writeU32(n.sequence)}}}switch(31&r){case k.NONE:s.writeVarint(0);break;case k.SINGLE:{const e=this.outputs[t];s.writeVarint(t+1);for(let e=0;e<t;e++)s.writeI64(-1),s.writeVarint(0);e.toWriter(s);break}case k.ZERO:{const t=this.outputs[0];s.writeVarint(1),t.toWriter(s);break}default:s.writeVarint(this.outputs.length);for(const t of this.outputs)t.toWriter(s)}return s.writeU32(this.locktime),s.writeU32(r),a.hash256(s.render())}hashSize(t,e,r){let i=0;switch(i+=4,i=r&k.ANYONECANPAY?(i=i+1+36)+e.getVarSize()+4:(i=(i+=n.sizeVarint(this.inputs.length))+41*(this.inputs.length-1)+36)+e.getVarSize()+4,31&r){case k.NONE:i+=1;break;case k.SINGLE:i=(i=i+n.sizeVarint(t+1)+9*t)+this.outputs[t].getSize();break;case k.ZERO:0<this.outputs.length?i=(i+=n.sizeVarint(1))+this.outputs[0].getSize():i+=1;break;default:i+=n.sizeVarint(this.outputs.length);for(const t of this.outputs)i+=t.getSize()}return i+8}signatureHashV1(t,e,r,i){const s=this.inputs[t];let o=n.ZERO_HASH,c=n.ZERO_HASH,u=n.ZERO_HASH;if(!(i&k.ANYONECANPAY))if(this._hashPrevouts)o=this._hashPrevouts;else{const t=p.pool(36*this.inputs.length);for(const e of this.inputs)e.prevout.toWriter(t);o=a.hash256(t.render()),this.mutable||(this._hashPrevouts=o)}if(!(i&k.ANYONECANPAY)&&(31&i)!==k.ZERO&&(31&i)!==k.SINGLE&&(31&i)!==k.NONE)if(this._hashSequence)c=this._hashSequence;else{const t=p.pool(4*this.inputs.length);for(const e of this.inputs)t.writeU32(e.sequence);c=a.hash256(t.render()),this.mutable||(this._hashSequence=c)}if((31&i)!==k.SINGLE&&(31&i)!==k.ZERO&&(31&i)!==k.NONE)if(this._hashOutputs)u=this._hashOutputs;else{let t=0;for(const e of this.outputs)t+=e.getSize();const e=p.pool(t);for(const t of this.outputs)t.toWriter(e);u=a.hash256(e.render()),this.mutable||(this._hashOutputs=u)}else if((31&i)===k.SINGLE){if(t<this.outputs.length){const e=this.outputs[t];u=a.hash256(e.toRaw())}}else if((31&i)===k.ZERO&&0<this.outputs.length){const t=this.outputs[0];u=a.hash256(t.toRaw())}t=156+e.getVarSize();const h=p.pool(t);return h.writeU32(this.version),h.writeBytes(o),h.writeBytes(c),h.writeHash(s.prevout.hash),h.writeU32(s.prevout.index),h.writeVarBytes(e.toRaw()),h.writeI64(r),h.writeU32(s.sequence),h.writeBytes(u),h.writeU32(this.locktime),h.writeU32(i),a.hash256(h.render())}checksig(t,e,r,i,s,n){var a;return 0!==i.length&&(a=i[i.length-1],t=this.signatureHash(t,e,r,a,n),o.verify(t,i.slice(0,-1),s))}signature(t,e,r,i,s,n){null==s&&(s=k.ALL),t=this.signatureHash(t,e,r,s,n=null==n?0:n),e=o.sign(t,i);const a=new p(e.length+1);return a.writeBytes(e),a.writeU8(s),a.render()}check(t,e,r){if(0===this.inputs.length)throw new w("UNKNOWN_ERROR","No inputs.");if(!this.isCoinbase())for(let s=0;s<this.inputs.length;s++){var i=this.inputs[s].prevout;if(!(i=t.getOutput(i)))throw new w("UNKNOWN_ERROR","No coin available.");this.checkInput(s,i,e,r)}}checkInput(t,e,r,s){var n=this.inputs[t];i(n,"Input does not exist."),i(e,"No coin passed.");try{h.verifyScript(n.script,n.witness,e.script,this,t,e.value,r,s)}catch(t){throw t}}async checkAsync(t,e,r,i){if(0===this.inputs.length)throw new w("UNKNOWN_ERROR","No inputs.");this.isCoinbase()||(i&&i.enabled?await i.check(this,t,e,r):this.check(t,e,r))}verify(t,e,r){try{this.check(t,e,r)}catch(t){if("ScriptError"===t.type)return!1;throw t}return!0}verifyInputs(t,e){var[t]=this.checkInputs(t,e);return-1!==t}verifyInput(t,e,r,i){try{this.checkInput(t,e,r,i)}catch(t){if("ScriptError"===t.type)return!1;throw t}return!0}async verifyAsync(t,e,r,i){try{await this.checkAsync(t,e,r,i)}catch(t){if("ScriptError"===t.type)return!1;throw t}return!0}isCoinbase(){return 1===this.inputs.length&&this.inputs[0].prevout.isNull()}isRBF(){if(2!==this.version)for(const t of this.inputs)if(t.isRBF())return!0;return!1}getFee(t){return this.hasCoins(t)?this.getInputValue(t)-this.getOutputValue():0}getInputValue(t){let e=0;for(var{prevout:r}of this.inputs){if(!(r=t.getOutput(r)))return 0;e+=r.value}return e}getOutputValue(){let t=0;for(const e of this.outputs)t+=e.value;return t}_getInputAddresses(t){const e=Object.create(null),r=[];if(!this.isCoinbase())for(const s of this.inputs){var i=t?t.getOutputFor(s):null;const n=s.getAddress(i);n&&(e[i=n.getHash("hex")]||(e[i]=!0,r.push(n)))}return[r,e]}_getOutputAddresses(){const t=Object.create(null),e=[];for(const i of this.outputs){const s=i.getAddress();var r;s&&(t[r=s.getHash("hex")]||(t[r]=!0,e.push(s)))}return[e,t]}_getAddresses(t){const[e,r]=this._getInputAddresses(t);for(const t of this.getOutputAddresses()){var i=t.getHash("hex");r[i]||(r[i]=!0,e.push(t))}return[e,r]}getInputAddresses(t){var[t]=this._getInputAddresses(t);return t}getOutputAddresses(){var[t]=this._getOutputAddresses();return t}getAddresses(t){var[t]=this._getAddresses(t);return t}getInputHashes(t,e){if("hex"===e)return[,e]=this._getInputAddresses(t),Object.keys(e);const r=[];for(const e of this.getInputAddresses(t))r.push(e.getHash());return r}getOutputHashes(t){if("hex"===t)return[,t]=this._getOutputAddresses(),Object.keys(t);const e=[];for(const t of this.getOutputAddresses())e.push(t.getHash());return e}getHashes(t,e){if("hex"===e)return[,e]=this._getAddresses(t),Object.keys(e);const r=[];for(const e of this.getAddresses(t))r.push(e.getHash());return r}hasCoins(t){if(0===this.inputs.length)return!1;for(var{prevout:e}of this.inputs)if(!t.hasEntry(e))return!1;return!0}isFinal(t,e){var r=v.LOCKTIME_THRESHOLD;if(0!==this.locktime&&!(this.locktime<(this.locktime<r?t:e)))for(const t of this.inputs)if(4294967295!==t.sequence)return!1;return!0}static mergeOrder(t){return i(Array.isArray(t)),t.reduce((t,e)=>null==t||1==t.outputs.length||1<e.outputs.length&&e.outputs[1].value>t.outputs[1].value?e:t,null)}verifyLocktime(t,e){var r=v.LOCKTIME_THRESHOLD;t=this.inputs[t];return i(t,"Input does not exist."),i(0<=e,"Locktime must be non-negative."),this.locktime<r==e<r&&!(e>this.locktime)&&4294967295!==t.sequence}verifySequence(t,e){var r=v.SEQUENCE_DISABLE_FLAG,s=v.SEQUENCE_TYPE_FLAG,n=v.SEQUENCE_MASK;t=this.inputs[t];return i(t,"Input does not exist."),i(0<=e,"Locktime must be non-negative."),!(!(e&r)&&(this.version<2||t.sequence&r||(t.sequence&s)!=(e&s)||(e&n)>(t.sequence&n)))}getLegacySigops(){if(-1!==this._sigops)return this._sigops;let t=0;for(const e of this.inputs)t+=e.script.getSigops(!1);for(const e of this.outputs)t+=e.script.getSigops(!1);return this.mutable||(this._sigops=t),t}getScripthashSigops(t){if(this.isCoinbase())return 0;let e=0;for(const r of this.inputs){const i=t.getOutputFor(r);i&&i.script.isScripthash()&&(e+=i.script.getScripthashSigops(r.script))}return e}getWitnessSigops(t){if(this.isCoinbase())return 0;let e=0;for(const r of this.inputs){const i=t.getOutputFor(r);i&&(e+=i.script.getWitnessSigops(r.script,r.witness))}return e}getSigopsCost(t,e){null==e&&(e=h.flags.STANDARD_VERIFY_FLAGS);var r=v.WITNESS_SCALE_FACTOR;let i=this.getLegacySigops()*r;return e&h.flags.VERIFY_P2SH&&(i+=this.getScripthashSigops(t)*r),e&h.flags.VERIFY_WITNESS&&(i+=this.getWitnessSigops(t)),i}getSigops(t,e){var r=v.WITNESS_SCALE_FACTOR;return(this.getSigopsCost(t,e)+r-1)/r|0}isSane(){var[t]=this.checkSanity();return t}checkSanity(){if(0===this.inputs.length)return[!1,"bad-txns-vin-empty",100];if(0===this.outputs.length)return[!1,"bad-txns-vout-empty",100];if(this.getBaseSize()>v.MAX_BLOCK_SIZE)return[!1,"bad-txns-oversize",100];let t=0;for(const e of this.outputs){if(e.value<0)return[!1,"bad-txns-vout-negative",100];if(e.value>v.MAX_MONEY)return[!1,"bad-txns-vout-toolarge",100];if((t+=e.value)<0||t>v.MAX_MONEY)return[!1,"bad-txns-txouttotal-toolarge",100]}const e=new Set;for(const t of this.inputs){var r=t.prevout.toKey();if(e.has(r))return[!1,"bad-txns-inputs-duplicate",100];e.add(r)}if(this.isCoinbase()){var i=this.inputs[0].script.getSize();if(i<2||100<i)return[!1,"bad-cb-length",100]}else for(const t of this.inputs)if(t.prevout.isNull())return[!1,"bad-txns-prevout-null",10];return[!0,"valid",0]}isStandard(){var[t]=this.checkStandard();return t}checkStandard(){if(this.version<1||this.version>b.MAX_TX_VERSION)return[!1,"version",0];if(this.getWeight()>=b.MAX_TX_WEIGHT)return[!1,"tx-size",0];for(const t of this.inputs){if(1650<t.script.getSize())return[!1,"scriptsig-size",0];if(!t.script.isPushOnly())return[!1,"scriptsig-not-pushonly",0]}let t=0;for(const e of this.outputs){if(!e.script.isStandard())return[!1,"scriptpubkey",0];if(e.script.isNulldata())t++;else{if(e.script.isMultisig()&&!b.BARE_MULTISIG)return[!1,"bare-multisig",0];if(e.isDust())return[!1,"dust",0]}}return 1<t?[!1,"multi-op-return",0]:[!0,"valid",0]}hasStandardInputs(t){if(!this.isCoinbase())for(const e of this.inputs){const r=t.getOutputFor(e);if(!r)return!1;if(!r.script.isPubkeyhash())if(r.script.isScripthash()){const t=e.script.getRedeem();if(!t)return!1;if(t.getSigops(!0)>b.MAX_P2SH_SIGOPS)return!1}else if(r.script.isUnknown())return!1}return!0}hasStandardWitness(t){if(!this.isCoinbase())for(const i of this.inputs){var e,r=i.witness;if((e=t.getOutputFor(i))&&0!==r.items.length){let t=e.script;if(t.isScripthash()&&!(t=i.script.getRedeem()))return!1;if(!t.isProgram())return!1;if(t.isWitnessPubkeyhash()){if(2!==r.items.length)return!1;if(73<r.items[0].length)return!1;if(65<r.items[1].length)return!1}else if(t.isWitnessScripthash()){if(r.items.length-1>b.MAX_P2WSH_STACK)return!1;for(let t=0;t<r.items.length-1;t++)if(r.items[t].length>b.MAX_P2WSH_PUSH)return!1;if((e=r.items[r.items.length-1]).length>b.MAX_P2WSH_SIZE)return!1;const t=h.fromRaw(e);if(t.isPubkey()){if(r.items.length-1!=1)return!1;if(73<r.items[0].length)return!1}else if(t.isPubkeyhash()){if(i.witness.items.length-1!=2)return!1;if(73<r.items[0].length)return!1;if(65<r.items[1].length)return!1}else{var[e]=t.getMultisig();if(-1!==e){if(r.items.length-1!==e+1)return!1;if(0!==r.items[0].length)return!1;for(let t=1;t<r.items.length-1;t++)if(73<r.items[t].length)return!1}}}else{if(r.items.length>b.MAX_P2WSH_STACK)return!1;for(const t of r.items)if(t.length>b.MAX_P2WSH_PUSH)return!1}}}return!0}checkInputs(t,e){i("number"==typeof e);let r=0;for(var{prevout:s}of this.inputs){var n=t.getEntry(s);if(!n)return[-1,"bad-txns-inputs-missingorspent",0];if(n.coinbase&&0<n.height&&e<n.height+v.COINBASE_MATURITY)return[-1,"bad-txns-premature-spend-of-coinbase",0];if(n=t.getOutput(s),i(n),n.value<0||n.value>v.MAX_MONEY)return[-1,"bad-txns-inputvalues-outofrange",100];if((r+=n.value)<0||r>v.MAX_MONEY)return[-1,"bad-txns-inputvalues-outofrange",100]}var a=this.getOutputValue();return r<a?[-1,"bad-txns-in-belowout",100]:(a=r-a)<0?[-1,"bad-txns-fee-negative",100]:a>v.MAX_MONEY?[-1,"bad-txns-fee-outofrange",100]:[a,"valid",0]}getModifiedSize(t){null==t&&(t=this.getVirtualSize());for(const r of this.inputs){var e=41+Math.min(110,r.script.getSize());e<t&&(t-=e)}return t}getPriority(t,e,r){if(i("number"==typeof e,"Must pass in height."),this.isCoinbase())return 0;null==r&&(r=this.getVirtualSize());let s=0;for(var{prevout:n}of this.inputs){var a=t.getOutput(n);a&&-1!==(n=t.getHeight(n))&&n<=e&&(s+=a.value*(e-n))}return Math.floor(s/r)}getChainValue(t){if(this.isCoinbase())return 0;let e=0;for(var{prevout:r}of this.inputs){var i=t.getOutput(r);i&&-1!==t.getHeight(r)&&(e+=i.value)}return e}isFree(t,e,r){return this.getPriority(t,e,r)>b.FREE_THRESHOLD}getMinFee(t,e){return null==t&&(t=this.getVirtualSize()),b.getMinFee(t,e)}getRoundFee(t,e){return null==t&&(t=this.getVirtualSize()),b.getRoundFee(t,e)}getRate(t,e){return(t=this.getFee(t))<0?0:(null==e&&(e=this.getVirtualSize()),b.getRate(e,t))}getPrevout(){if(this.isCoinbase())return[];const t=Object.create(null);for(const e of this.inputs)t[e.prevout.hash]=!0;return Object.keys(t)}isWatched(t){let e=!1;t.test(this.hash())&&(e=!0);for(let r=0;r<this.outputs.length;r++){const i=this.outputs[r];if(i.script.test(t)){if(t.update===y.flags.ALL){const e=m.fromTX(this,r);t.add(e.toRaw())}else if(t.update===y.flags.PUBKEY_ONLY&&(i.script.isPubkey()||i.script.isMultisig())){const e=m.fromTX(this,r);t.add(e.toRaw())}e=!0}}if(e)return e;for(const e of this.inputs){const r=e.prevout;if(t.test(r.toRaw()))return!0;if(e.script.test(t))return!0}return!1}rhash(){return s.revHex(this.hash("hex"))}rwhash(){return s.revHex(this.witnessHash("hex"))}txid(){return this.rhash()}wtxid(){return this.rwhash()}toInv(){return new g(g.types.TX,this.hash("hex"))}inspect(){return this.format()}format(t,e,r){let i=0,n=0,a=-1,o=null,u=0,h=null;return t&&(n=this.getFee(t),i=this.getRate(t),Number.isSafeInteger(i)||(i=0)),e&&(a=e.height,o=s.revHex(e.hash),u=e.time,h=s.date(u)),null==r&&(r=-1),{hash:this.txid(),witnessHash:this.wtxid(),size:this.getSize(),virtualSize:this.getVirtualSize(),value:c.btc(this.getOutputValue()),fee:c.btc(n),rate:c.btc(i),minFee:c.btc(this.getMinFee()),height:a,block:o,time:u,date:h,index:r,version:this.version,inputs:this.inputs.map(e=>{var r=t?t.getOutputFor(e):null;return e.format(r)}),outputs:this.outputs,locktime:this.locktime}}formatInsight(t,e=0){return null==t&&(t=-1),{hash:this.hash("hex"),rhash:this.txid(),witnessHash:this.wtxid(),txid:function(){return this.rhash},ps:e,index:t,version:this.version,flag:1,locktime:this.locktime,raw:this.toRaw(),inputs:this.inputs.map(t=>t.formatInsight()),outputs:this.outputs.map(t=>t.formatInsight())}}static EncodeSpenderValue(t,e,r,i){const s=Buffer.allocUnsafe(72);return s.write(t,0,"hex"),s.writeUInt32BE(e,32,!0),s.writeUInt32BE(r,36,!0),s.write(i,40,"hex"),s}static DecodeSpenderValue(t){return i(Buffer.isBuffer(t)),i(72===t.length),{txid:t.toString("hex",0,32),inputIndex:t.readUInt32BE(32,!0),blockHeight:t.readUInt32BE(36,!0),blockHash:t.toString("hex",40,32)}}toJSON(){return this.getJSON()}getJSON(t,e,r,i){let n,a,o,c,h,l;return e&&(a=this.getFee(e),n=this.getRate(e),Number.isSafeInteger(n)||(n=0)),r&&(o=r.height,c=s.revHex(r.hash),h=r.time,l=s.date(h)),t=u.get(t),{hash:this.txid(),witnessHash:this.wtxid(),fee:a,rate:n,mtime:s.now(),height:o,block:c,time:h,date:l,index:i,version:this.version,inputs:this.inputs.map(r=>{var i=e?e.getCoinFor(r):null;return r.getJSON(t,i)}),outputs:this.outputs.map(e=>e.getJSON(t)),locktime:this.locktime,hex:this.toRaw().toString("hex")}}fromJSON(t){i(t,"TX data is required."),i(s.isU32(t.version),"Version must be a uint32."),i(Array.isArray(t.inputs),"Inputs must be an array."),i(Array.isArray(t.outputs),"Outputs must be an array."),i(s.isU32(t.locktime),"Locktime must be a uint32."),this.version=t.version;for(const e of t.inputs)this.inputs.push(d.fromJSON(e));for(const e of t.outputs)this.outputs.push(f.fromJSON(e));return this.locktime=t.locktime,this}static fromJSON(e){return(new t).fromJSON(e)}static fromRaw(e,r){return"string"==typeof e&&(e=Buffer.from(e,r)),(new t).fromRaw(e)}static fromReader(e){return(new t).fromReader(e)}fromRaw(t){return this.fromReader(new l(t))}fromReader(t){if(!((e=t).left()<6)&&0===e.data[e.offset+4]&&0!==e.data[e.offset+5])return this.fromWitnessReader(t);t.start(),this.version=t.readU32();var e,r=t.readVarint();for(let e=0;e<r;e++)this.inputs.push(d.fromReader(t));var i=t.readVarint();for(let e=0;e<i;e++)this.outputs.push(f.fromReader(t));return this.locktime=t.readU32(),this.mutable?t.end():(this._raw=t.endData(),this._size=this._raw.length,this._witness=0),this}fromWitnessReader(t){t.start(),this.version=t.readU32(),i(0===t.readU8(),"Non-zero marker.");let e=t.readU8();i(0!==e,"Flags byte is zero.");var r=t.readVarint();for(let e=0;e<r;e++)this.inputs.push(d.fromReader(t));var s=t.readVarint();for(let e=0;e<s;e++)this.outputs.push(f.fromReader(t));let n=0,a=!1;if(1&e){e^=1,n=t.offset;for(const e of this.inputs)e.witness.fromReader(t),0<e.witness.items.length&&(a=!0);n=t.offset-n+2}if(0!==e)throw new Error("Unknown witness flag.");if(0===this.inputs.length&&0!==this.outputs.length)throw new Error("Zero input witness tx.");return this.locktime=t.readU32(),!this.mutable&&a?(this._raw=t.endData(),this._size=this._raw.length,this._witness=n):t.end(),this}frameNormal(){const t=this.getNormalSizes(),e=new p(t.size);return this.writeNormal(e),t.data=e.render(),t}frameWitness(){const t=this.getWitnessSizes(),e=new p(t.size);return this.writeWitness(e),t.data=e.render(),t}writeNormal(t){if(0===this.inputs.length&&0!==this.outputs.length)throw new Error("Cannot serialize zero-input tx.");t.writeU32(this.version),t.writeVarint(this.inputs.length);for(const e of this.inputs)e.toWriter(t);t.writeVarint(this.outputs.length);for(const e of this.outputs)e.toWriter(t);return t.writeU32(this.locktime),t}writeWitness(t){if(0===this.inputs.length&&0!==this.outputs.length)throw new Error("Cannot serialize zero-input tx.");t.writeU32(this.version),t.writeU8(0),t.writeU8(1),t.writeVarint(this.inputs.length);for(const e of this.inputs)e.toWriter(t);t.writeVarint(this.outputs.length);for(const e of this.outputs)e.toWriter(t);var e=t.offset;for(const e of this.inputs)e.witness.toWriter(t);if(e=t.offset-e,t.writeU32(this.locktime),e===this.inputs.length)throw new Error("Cannot serialize empty-witness tx.");return t}getNormalSizes(){let t=0;t=(t+=4)+n.sizeVarint(this.inputs.length);for(const e of this.inputs)t+=e.getSize();t+=n.sizeVarint(this.outputs.length);for(const e of this.outputs)t+=e.getSize();return new S(t+=4,0)}getWitnessSizes(){let t=0,e=0;t+=4,e+=2,t+=n.sizeVarint(this.inputs.length);for(const r of this.inputs)t+=r.getSize(),e+=r.witness.getVarSize();t+=n.sizeVarint(this.outputs.length);for(const e of this.outputs)t+=e.getSize();return new S((t+=4)+e,e)}static isTX(e){return e instanceof t}}},function(t,e,r){"use strict";
50
+ */const i=r(0),s=r(1),n=r(3),a=r(6),o=r(29),c=r(34),u=r(15),h=r(17),l=r(2),p=r(4),d=r(115),f=r(26),m=r(46),g=r(64),y=r(102),v=r(7),b=r(27),w=r(114),{opcodes:x,hashType:k}=r(21);function S(t,e){this.data=null,this.size=t,this.witness=e}r(61),t.exports=class t{constructor(t){t=t||{},this.version=1,this.inputs=t.inputs||[],this.outputs=t.outputs||[],this.locktime=0,this.mutable=!1,this._hash=null,this._hhash=null,this._whash=null,this._raw=null,this._size=-1,this._witness=-1,this._sigops=-1,this._hashPrevouts=null,this._hashSequence=null,this._hashOutputs=null,t&&this.fromOptions(t)}fromOptions(t){if(i(t,"TX data is required."),null!=t.version&&(i(s.isU32(t.version),"Version must be a uint32."),this.version=t.version),t.inputs){this.inputs=[],i(Array.isArray(t.inputs),"Inputs must be an array.");for(const e of t.inputs)this.inputs.push(new d(e))}if(t.outputs){this.outputs=[],i(Array.isArray(t.outputs),"Outputs must be an array.");for(const e of t.outputs)this.outputs.push(new f(e))}return null!=t.locktime&&(i(s.isU32(t.locktime),"Locktime must be a uint32."),this.locktime=t.locktime),this}static fromOptions(e){return(new t).fromOptions(e)}clone(){return(new t).inject(this)}inject(t,e=0){this.version=t.version;for(const r of t.inputs)if(this.inputs.push(r.clone()),0!=e&&this.inputs.length>=e)break;for(const r of t.outputs)if(this.outputs.push(r.clone()),0!=e&&this.outputs.length>=e)break;return this.locktime=t.locktime,this}refresh(){this._hash=null,this._hhash=null,this._whash=null,this._raw=null,this._size=-1,this._witness=-1,this._sigops=-1,this._hashPrevouts=null,this._hashSequence=null,this._hashOutputs=null}hash(t){let e=this._hash;if(e||(e=a.hash256(this.toNormal()),this.mutable||(this._hash=e)),"hex"===t){let t=this._hhash;t||(t=e.toString("hex"),this.mutable||(this._hhash=t)),e=t}return e}witnessHash(t){if(!this.hasWitness())return this.hash(t);let e=this._whash;return e||(e=a.hash256(this.toRaw()),this.mutable||(this._whash=e)),"hex"===t?e.toString("hex"):e}toRaw(){return this.frame().data}toNormal(){return this.hasWitness()?this.frameNormal().data:this.toRaw()}toWriter(t){return this.mutable?this.hasWitness()?this.writeWitness(t):this.writeNormal(t):(t.writeBytes(this.toRaw()),t)}toNormalWriter(t){return this.hasWitness()?(this.writeNormal(t),t):this.toWriter(t)}frame(){if(this.mutable)return i(!this._raw),this.hasWitness()?this.frameWitness():this.frameNormal();if(this._raw){i(0<=this._size),i(0<=this._witness);const t=new S(this._size,this._witness);return t.data=this._raw,t}let t;return t=this.hasWitness()?this.frameWitness():this.frameNormal(),this._raw=t.data,this._size=t.size,this._witness=t.witness,t}getSizes(){return this.mutable?this.hasWitness()?this.getWitnessSizes():this.getNormalSizes():this.frame()}getVirtualSize(){var t=v.WITNESS_SCALE_FACTOR;return(this.getWeight()+t-1)/t|0}getSigopsSize(t){var e=v.WITNESS_SCALE_FACTOR,r=b.BYTES_PER_SIGOP;return(Math.max(this.getWeight(),t*r)+e-1)/e|0}getWeight(){var t=this.getSizes();return(t.size-t.witness)*(v.WITNESS_SCALE_FACTOR-1)+t.size}getSize(){return this.getSizes().size}getBaseSize(){var t=this.getSizes();return t.size-t.witness}hasWitness(){if(-1!==this._witness)return 0!==this._witness;for(const t of this.inputs)if(0<t.witness.items.length)return!0;return!1}signatureHash(t,e,r,s,n){if(i(0<=t&&t<this.inputs.length),i(e instanceof h),i("number"==typeof r),i("number"==typeof s),0===n)return this.signatureHashV0(t,e,s);if(1===n)return this.signatureHashV1(t,e,r,s);throw new Error("Unknown sighash version.")}get opr(){let t={};return 0<this.outputs.length&&(t.data=this.outputs[0].getReturnData([x.OP_RETURN]),t.data&&"inner"==t.data.$tag&&(t.isDerived=!0)),t}signatureHashV0(t,e,r){if((31&r)===k.SINGLE){if(t>=this.outputs.length)return Buffer.from(n.ONE_HASH)}else if((31&r)===k.ZERO&&0==this.outputs.length)return Buffer.from(n.ONE_HASH);e=e.removeSeparators();var i=this.hashSize(t,e,r);const s=p.pool(i);if(s.writeU32(this.version),r&k.ANYONECANPAY){const r=this.inputs[t];s.writeVarint(1),r.prevout.toWriter(s),s.writeVarBytes(e.toRaw()),s.writeU32(r.sequence)}else{s.writeVarint(this.inputs.length);for(let i=0;i<this.inputs.length;i++){const n=this.inputs[i];if(n.prevout.toWriter(s),i===t)s.writeVarBytes(e.toRaw()),s.writeU32(n.sequence);else switch(s.writeVarint(0),31&r){case k.NONE:case k.SINGLE:case k.ZERO:s.writeU32(0);break;default:s.writeU32(n.sequence)}}}switch(31&r){case k.NONE:s.writeVarint(0);break;case k.SINGLE:{const e=this.outputs[t];s.writeVarint(t+1);for(let e=0;e<t;e++)s.writeI64(-1),s.writeVarint(0);e.toWriter(s);break}case k.ZERO:{const t=this.outputs[0];s.writeVarint(1),t.toWriter(s);break}default:s.writeVarint(this.outputs.length);for(const t of this.outputs)t.toWriter(s)}return s.writeU32(this.locktime),s.writeU32(r),a.hash256(s.render())}hashSize(t,e,r){let i=0;switch(i+=4,i=r&k.ANYONECANPAY?(i=i+1+36)+e.getVarSize()+4:(i=(i+=n.sizeVarint(this.inputs.length))+41*(this.inputs.length-1)+36)+e.getVarSize()+4,31&r){case k.NONE:i+=1;break;case k.SINGLE:i=(i=i+n.sizeVarint(t+1)+9*t)+this.outputs[t].getSize();break;case k.ZERO:0<this.outputs.length?i=(i+=n.sizeVarint(1))+this.outputs[0].getSize():i+=1;break;default:i+=n.sizeVarint(this.outputs.length);for(const t of this.outputs)i+=t.getSize()}return i+8}signatureHashV1(t,e,r,i){const s=this.inputs[t];let o=n.ZERO_HASH,c=n.ZERO_HASH,u=n.ZERO_HASH;if(!(i&k.ANYONECANPAY))if(this._hashPrevouts)o=this._hashPrevouts;else{const t=p.pool(36*this.inputs.length);for(const e of this.inputs)e.prevout.toWriter(t);o=a.hash256(t.render()),this.mutable||(this._hashPrevouts=o)}if(!(i&k.ANYONECANPAY)&&(31&i)!==k.ZERO&&(31&i)!==k.SINGLE&&(31&i)!==k.NONE)if(this._hashSequence)c=this._hashSequence;else{const t=p.pool(4*this.inputs.length);for(const e of this.inputs)t.writeU32(e.sequence);c=a.hash256(t.render()),this.mutable||(this._hashSequence=c)}if((31&i)!==k.SINGLE&&(31&i)!==k.ZERO&&(31&i)!==k.NONE)if(this._hashOutputs)u=this._hashOutputs;else{let t=0;for(const e of this.outputs)t+=e.getSize();const e=p.pool(t);for(const t of this.outputs)t.toWriter(e);u=a.hash256(e.render()),this.mutable||(this._hashOutputs=u)}else if((31&i)===k.SINGLE){if(t<this.outputs.length){const e=this.outputs[t];u=a.hash256(e.toRaw())}}else if((31&i)===k.ZERO&&0<this.outputs.length){const t=this.outputs[0];u=a.hash256(t.toRaw())}t=156+e.getVarSize();const h=p.pool(t);return h.writeU32(this.version),h.writeBytes(o),h.writeBytes(c),h.writeHash(s.prevout.hash),h.writeU32(s.prevout.index),h.writeVarBytes(e.toRaw()),h.writeI64(r),h.writeU32(s.sequence),h.writeBytes(u),h.writeU32(this.locktime),h.writeU32(i),a.hash256(h.render())}checksig(t,e,r,i,s,n){var a;return 0!==i.length&&(a=i[i.length-1],t=this.signatureHash(t,e,r,a,n),o.verify(t,i.slice(0,-1),s))}signature(t,e,r,i,s,n){null==s&&(s=k.ALL),t=this.signatureHash(t,e,r,s,n=null==n?0:n),e=o.sign(t,i);const a=new p(e.length+1);return a.writeBytes(e),a.writeU8(s),a.render()}check(t,e,r){if(0===this.inputs.length)throw new w("UNKNOWN_ERROR","No inputs.");if(!this.isCoinbase())for(let s=0;s<this.inputs.length;s++){var i=this.inputs[s].prevout;if(!(i=t.getOutput(i)))throw new w("UNKNOWN_ERROR","No coin available.");this.checkInput(s,i,e,r)}}checkInput(t,e,r,s){var n=this.inputs[t];i(n,"Input does not exist."),i(e,"No coin passed.");try{h.verifyScript(n.script,n.witness,e.script,this,t,e.value,r,s)}catch(t){throw t}}async checkAsync(t,e,r,i){if(0===this.inputs.length)throw new w("UNKNOWN_ERROR","No inputs.");this.isCoinbase()||(i&&i.enabled?await i.check(this,t,e,r):this.check(t,e,r))}verify(t,e,r){try{this.check(t,e,r)}catch(t){if("ScriptError"===t.type)return!1;throw t}return!0}verifyInputs(t,e){var[t]=this.checkInputs(t,e);return-1!==t}verifyInput(t,e,r,i){try{this.checkInput(t,e,r,i)}catch(t){if("ScriptError"===t.type)return!1;throw t}return!0}async verifyAsync(t,e,r,i){try{await this.checkAsync(t,e,r,i)}catch(t){if("ScriptError"===t.type)return!1;throw t}return!0}isCoinbase(){return 1===this.inputs.length&&this.inputs[0].prevout.isNull()}isRBF(){if(2!==this.version)for(const t of this.inputs)if(t.isRBF())return!0;return!1}getFee(t){return this.hasCoins(t)?this.getInputValue(t)-this.getOutputValue():0}getInputValue(t){let e=0;for(var{prevout:r}of this.inputs){if(!(r=t.getOutput(r)))return 0;e+=r.value}return e}getOutputValue(){let t=0;for(const e of this.outputs)t+=e.value;return t}_getInputAddresses(t){const e=Object.create(null),r=[];if(!this.isCoinbase())for(const s of this.inputs){var i=t?t.getOutputFor(s):null;const n=s.getAddress(i);n&&(e[i=n.getHash("hex")]||(e[i]=!0,r.push(n)))}return[r,e]}_getOutputAddresses(){const t=Object.create(null),e=[];for(const i of this.outputs){const s=i.getAddress();var r;s&&(t[r=s.getHash("hex")]||(t[r]=!0,e.push(s)))}return[e,t]}_getAddresses(t){const[e,r]=this._getInputAddresses(t);for(const t of this.getOutputAddresses()){var i=t.getHash("hex");r[i]||(r[i]=!0,e.push(t))}return[e,r]}getInputAddresses(t){var[t]=this._getInputAddresses(t);return t}getOutputAddresses(){var[t]=this._getOutputAddresses();return t}getAddresses(t){var[t]=this._getAddresses(t);return t}getInputHashes(t,e){if("hex"===e)return[,e]=this._getInputAddresses(t),Object.keys(e);const r=[];for(const e of this.getInputAddresses(t))r.push(e.getHash());return r}getOutputHashes(t){if("hex"===t)return[,t]=this._getOutputAddresses(),Object.keys(t);const e=[];for(const t of this.getOutputAddresses())e.push(t.getHash());return e}getHashes(t,e){if("hex"===e)return[,e]=this._getAddresses(t),Object.keys(e);const r=[];for(const e of this.getAddresses(t))r.push(e.getHash());return r}hasCoins(t){if(0===this.inputs.length)return!1;for(var{prevout:e}of this.inputs)if(!t.hasEntry(e))return!1;return!0}isFinal(t,e){var r=v.LOCKTIME_THRESHOLD;if(0!==this.locktime&&!(this.locktime<(this.locktime<r?t:e)))for(const t of this.inputs)if(4294967295!==t.sequence)return!1;return!0}static mergeOrder(t){return i(Array.isArray(t)),t.reduce((t,e)=>null==t||1==t.outputs.length||1<e.outputs.length&&e.outputs[1].value>t.outputs[1].value?e:t,null)}verifyLocktime(t,e){var r=v.LOCKTIME_THRESHOLD;t=this.inputs[t];return i(t,"Input does not exist."),i(0<=e,"Locktime must be non-negative."),this.locktime<r==e<r&&!(e>this.locktime)&&4294967295!==t.sequence}verifySequence(t,e){var r=v.SEQUENCE_DISABLE_FLAG,s=v.SEQUENCE_TYPE_FLAG,n=v.SEQUENCE_MASK;t=this.inputs[t];return i(t,"Input does not exist."),i(0<=e,"Locktime must be non-negative."),!(!(e&r)&&(this.version<2||t.sequence&r||(t.sequence&s)!=(e&s)||(e&n)>(t.sequence&n)))}getLegacySigops(){if(-1!==this._sigops)return this._sigops;let t=0;for(const e of this.inputs)t+=e.script.getSigops(!1);for(const e of this.outputs)t+=e.script.getSigops(!1);return this.mutable||(this._sigops=t),t}getScripthashSigops(t){if(this.isCoinbase())return 0;let e=0;for(const r of this.inputs){const i=t.getOutputFor(r);i&&i.script.isScripthash()&&(e+=i.script.getScripthashSigops(r.script))}return e}getWitnessSigops(t){if(this.isCoinbase())return 0;let e=0;for(const r of this.inputs){const i=t.getOutputFor(r);i&&(e+=i.script.getWitnessSigops(r.script,r.witness))}return e}getSigopsCost(t,e){null==e&&(e=h.flags.STANDARD_VERIFY_FLAGS);var r=v.WITNESS_SCALE_FACTOR;let i=this.getLegacySigops()*r;return e&h.flags.VERIFY_P2SH&&(i+=this.getScripthashSigops(t)*r),e&h.flags.VERIFY_WITNESS&&(i+=this.getWitnessSigops(t)),i}getSigops(t,e){var r=v.WITNESS_SCALE_FACTOR;return(this.getSigopsCost(t,e)+r-1)/r|0}isSane(){var[t]=this.checkSanity();return t}checkSanity(){if(0===this.inputs.length)return[!1,"bad-txns-vin-empty",100];if(0===this.outputs.length)return[!1,"bad-txns-vout-empty",100];if(this.getBaseSize()>v.MAX_BLOCK_SIZE)return[!1,"bad-txns-oversize",100];let t=0;for(const e of this.outputs){if(e.value<0)return[!1,"bad-txns-vout-negative",100];if(e.value>v.MAX_MONEY)return[!1,"bad-txns-vout-toolarge",100];if((t+=e.value)<0||t>v.MAX_MONEY)return[!1,"bad-txns-txouttotal-toolarge",100]}const e=new Set;for(const t of this.inputs){var r=t.prevout.toKey();if(e.has(r))return[!1,"bad-txns-inputs-duplicate",100];e.add(r)}if(this.isCoinbase()){var i=this.inputs[0].script.getSize();if(i<2||100<i)return[!1,"bad-cb-length",100]}else for(const t of this.inputs)if(t.prevout.isNull())return[!1,"bad-txns-prevout-null",10];return[!0,"valid",0]}isStandard(){var[t]=this.checkStandard();return t}checkStandard(){if(this.version<1||this.version>b.MAX_TX_VERSION)return[!1,"version",0];if(this.getWeight()>=b.MAX_TX_WEIGHT)return[!1,"tx-size",0];for(const t of this.inputs){if(1650<t.script.getSize())return[!1,"scriptsig-size",0];if(!t.script.isPushOnly())return[!1,"scriptsig-not-pushonly",0]}let t=0;for(const e of this.outputs){if(!e.script.isStandard())return[!1,"scriptpubkey",0];if(e.script.isNulldata())t++;else{if(e.script.isMultisig()&&!b.BARE_MULTISIG)return[!1,"bare-multisig",0];if(e.isDust())return[!1,"dust",0]}}return 1<t?[!1,"multi-op-return",0]:[!0,"valid",0]}hasStandardInputs(t){if(!this.isCoinbase())for(const e of this.inputs){const r=t.getOutputFor(e);if(!r)return!1;if(!r.script.isPubkeyhash())if(r.script.isScripthash()){const t=e.script.getRedeem();if(!t)return!1;if(t.getSigops(!0)>b.MAX_P2SH_SIGOPS)return!1}else if(r.script.isUnknown())return!1}return!0}hasStandardWitness(t){if(!this.isCoinbase())for(const i of this.inputs){var e,r=i.witness;if((e=t.getOutputFor(i))&&0!==r.items.length){let t=e.script;if(t.isScripthash()&&!(t=i.script.getRedeem()))return!1;if(!t.isProgram())return!1;if(t.isWitnessPubkeyhash()){if(2!==r.items.length)return!1;if(73<r.items[0].length)return!1;if(65<r.items[1].length)return!1}else if(t.isWitnessScripthash()){if(r.items.length-1>b.MAX_P2WSH_STACK)return!1;for(let t=0;t<r.items.length-1;t++)if(r.items[t].length>b.MAX_P2WSH_PUSH)return!1;if((e=r.items[r.items.length-1]).length>b.MAX_P2WSH_SIZE)return!1;const t=h.fromRaw(e);if(t.isPubkey()){if(r.items.length-1!=1)return!1;if(73<r.items[0].length)return!1}else if(t.isPubkeyhash()){if(i.witness.items.length-1!=2)return!1;if(73<r.items[0].length)return!1;if(65<r.items[1].length)return!1}else{var[e]=t.getMultisig();if(-1!==e){if(r.items.length-1!==e+1)return!1;if(0!==r.items[0].length)return!1;for(let t=1;t<r.items.length-1;t++)if(73<r.items[t].length)return!1}}}else{if(r.items.length>b.MAX_P2WSH_STACK)return!1;for(const t of r.items)if(t.length>b.MAX_P2WSH_PUSH)return!1}}}return!0}checkInputs(t,e){i("number"==typeof e);let r=0;for(var{prevout:s}of this.inputs){var n=t.getEntry(s);if(!n)return[-1,"bad-txns-inputs-missingorspent",0];if(n.coinbase&&0<n.height&&e<n.height+v.COINBASE_MATURITY)return[-1,"bad-txns-premature-spend-of-coinbase",0];if(n=t.getOutput(s),i(n),n.value<0||n.value>v.MAX_MONEY)return[-1,"bad-txns-inputvalues-outofrange",100];if((r+=n.value)<0||r>v.MAX_MONEY)return[-1,"bad-txns-inputvalues-outofrange",100]}var a=this.getOutputValue();return r<a?[-1,"bad-txns-in-belowout",100]:(a=r-a)<0?[-1,"bad-txns-fee-negative",100]:a>v.MAX_MONEY?[-1,"bad-txns-fee-outofrange",100]:[a,"valid",0]}getModifiedSize(t){null==t&&(t=this.getVirtualSize());for(const r of this.inputs){var e=41+Math.min(110,r.script.getSize());e<t&&(t-=e)}return t}getPriority(t,e,r){if(i("number"==typeof e,"Must pass in height."),this.isCoinbase())return 0;null==r&&(r=this.getVirtualSize());let s=0;for(var{prevout:n}of this.inputs){var a=t.getOutput(n);a&&-1!==(n=t.getHeight(n))&&n<=e&&(s+=a.value*(e-n))}return Math.floor(s/r)}getChainValue(t){if(this.isCoinbase())return 0;let e=0;for(var{prevout:r}of this.inputs){var i=t.getOutput(r);i&&-1!==t.getHeight(r)&&(e+=i.value)}return e}isFree(t,e,r){return this.getPriority(t,e,r)>b.FREE_THRESHOLD}getMinFee(t,e){return null==t&&(t=this.getVirtualSize()),b.getMinFee(t,e)}getRoundFee(t,e){return null==t&&(t=this.getVirtualSize()),b.getRoundFee(t,e)}getRate(t,e){return(t=this.getFee(t))<0?0:(null==e&&(e=this.getVirtualSize()),b.getRate(e,t))}getPrevout(){if(this.isCoinbase())return[];const t=Object.create(null);for(const e of this.inputs)t[e.prevout.hash]=!0;return Object.keys(t)}isWatched(t){let e=!1;t.test(this.hash())&&(e=!0);for(let r=0;r<this.outputs.length;r++){const i=this.outputs[r];if(i.script.test(t)){if(t.update===y.flags.ALL){const e=m.fromTX(this,r);t.add(e.toRaw())}else if(t.update===y.flags.PUBKEY_ONLY&&(i.script.isPubkey()||i.script.isMultisig())){const e=m.fromTX(this,r);t.add(e.toRaw())}e=!0}}if(e)return e;for(const e of this.inputs){const r=e.prevout;if(t.test(r.toRaw()))return!0;if(e.script.test(t))return!0}return!1}rhash(){return s.revHex(this.hash("hex"))}rwhash(){return s.revHex(this.witnessHash("hex"))}txid(){return this.rhash()}wtxid(){return this.rwhash()}toInv(){return new g(g.types.TX,this.hash("hex"))}inspect(){return this.format()}format(t,e,r){let i=0,n=0,a=-1,o=null,u=0,h=null;return t&&(n=this.getFee(t),i=this.getRate(t),Number.isSafeInteger(i)||(i=0)),e&&(a=e.height,o=s.revHex(e.hash),u=e.time,h=s.date(u)),null==r&&(r=-1),{hash:this.txid(),witnessHash:this.wtxid(),size:this.getSize(),virtualSize:this.getVirtualSize(),value:c.btc(this.getOutputValue()),fee:c.btc(n),rate:c.btc(i),minFee:c.btc(this.getMinFee()),height:a,block:o,time:u,date:h,index:r,version:this.version,inputs:this.inputs.map(e=>{var r=t?t.getOutputFor(e):null;return e.format(r)}),outputs:this.outputs,locktime:this.locktime}}formatInsight(t,e=0){return null==t&&(t=-1),{hash:this.hash("hex"),rhash:this.txid(),witnessHash:this.wtxid(),txid:function(){return this.rhash},ps:e,index:t,version:this.version,flag:1,locktime:this.locktime,raw:this.toRaw(),inputs:this.inputs.map(t=>t.formatInsight()),outputs:this.outputs.map(t=>t.formatInsight())}}static EncodeSpenderValue(t,e,r,i){const s=Buffer.allocUnsafe(72);return s.write(t,0,"hex"),s.writeUInt32BE(e,32,!0),s.writeUInt32BE(r,36,!0),s.write(i,40,"hex"),s}static DecodeSpenderValue(t){return i(Buffer.isBuffer(t)),i(72===t.length),{txid:t.toString("hex",0,32),inputIndex:t.readUInt32BE(32,!0),blockHeight:t.readUInt32BE(36,!0),blockHash:t.toString("hex",40,32)}}toJSON(){return this.getJSON()}getJSON(t,e,r,i){let n,a,o,c,h,l;return e&&(a=this.getFee(e),n=this.getRate(e),Number.isSafeInteger(n)||(n=0)),r&&(o=r.height,c=s.revHex(r.hash),h=r.time,l=s.date(h)),t=u.get(t),{hash:this.txid(),witnessHash:this.wtxid(),fee:a,rate:n,mtime:s.now(),height:o,block:c,time:h,date:l,index:i,version:this.version,inputs:this.inputs.map(r=>{var i=e?e.getCoinFor(r):null;return r.getJSON(t,i)}),outputs:this.outputs.map(e=>e.getJSON(t)),locktime:this.locktime,hex:this.toRaw().toString("hex")}}fromJSON(t){i(t,"TX data is required."),i(s.isU32(t.version),"Version must be a uint32."),i(Array.isArray(t.inputs),"Inputs must be an array."),i(Array.isArray(t.outputs),"Outputs must be an array."),i(s.isU32(t.locktime),"Locktime must be a uint32."),this.version=t.version;for(const e of t.inputs)this.inputs.push(d.fromJSON(e));for(const e of t.outputs)this.outputs.push(f.fromJSON(e));return this.locktime=t.locktime,this}static fromJSON(e){return(new t).fromJSON(e)}static fromRaw(e,r){return"string"==typeof e&&(e=Buffer.from(e,r)),(new t).fromRaw(e)}static fromReader(e){return(new t).fromReader(e)}fromRaw(t){return this.fromReader(new l(t))}fromReader(t){if(!((e=t).left()<6)&&0===e.data[e.offset+4]&&0!==e.data[e.offset+5])return this.fromWitnessReader(t);t.start(),this.version=t.readU32();var e,r=t.readVarint();for(let e=0;e<r;e++)this.inputs.push(d.fromReader(t));var i=t.readVarint();for(let e=0;e<i;e++)this.outputs.push(f.fromReader(t));return this.locktime=t.readU32(),this.mutable?t.end():(this._raw=t.endData(),this._size=this._raw.length,this._witness=0),this}fromWitnessReader(t){t.start(),this.version=t.readU32(),i(0===t.readU8(),"Non-zero marker.");let e=t.readU8();i(0!==e,"Flags byte is zero.");var r=t.readVarint();for(let e=0;e<r;e++)this.inputs.push(d.fromReader(t));var s=t.readVarint();for(let e=0;e<s;e++)this.outputs.push(f.fromReader(t));let n=0,a=!1;if(1&e){e^=1,n=t.offset;for(const e of this.inputs)e.witness.fromReader(t),0<e.witness.items.length&&(a=!0);n=t.offset-n+2}if(0!==e)throw new Error("Unknown witness flag.");if(0===this.inputs.length&&0!==this.outputs.length)throw new Error("Zero input witness tx.");return this.locktime=t.readU32(),!this.mutable&&a?(this._raw=t.endData(),this._size=this._raw.length,this._witness=n):t.end(),this}frameNormal(){const t=this.getNormalSizes(),e=new p(t.size);return this.writeNormal(e),t.data=e.render(),t}frameWitness(){const t=this.getWitnessSizes(),e=new p(t.size);return this.writeWitness(e),t.data=e.render(),t}writeNormal(t){if(0===this.inputs.length&&0!==this.outputs.length)throw new Error("Cannot serialize zero-input tx.");t.writeU32(this.version),t.writeVarint(this.inputs.length);for(const e of this.inputs)e.toWriter(t);t.writeVarint(this.outputs.length);for(const e of this.outputs)e.toWriter(t);return t.writeU32(this.locktime),t}writeWitness(t){if(0===this.inputs.length&&0!==this.outputs.length)throw new Error("Cannot serialize zero-input tx.");t.writeU32(this.version),t.writeU8(0),t.writeU8(1),t.writeVarint(this.inputs.length);for(const e of this.inputs)e.toWriter(t);t.writeVarint(this.outputs.length);for(const e of this.outputs)e.toWriter(t);var e=t.offset;for(const e of this.inputs)e.witness.toWriter(t);if(e=t.offset-e,t.writeU32(this.locktime),e===this.inputs.length)throw new Error("Cannot serialize empty-witness tx.");return t}getNormalSizes(){let t=0;t=(t+=4)+n.sizeVarint(this.inputs.length);for(const e of this.inputs)t+=e.getSize();t+=n.sizeVarint(this.outputs.length);for(const e of this.outputs)t+=e.getSize();return new S(t+=4,0)}getWitnessSizes(){let t=0,e=0;t+=4,e+=2,t+=n.sizeVarint(this.inputs.length);for(const r of this.inputs)t+=r.getSize(),e+=r.witness.getVarSize();t+=n.sizeVarint(this.outputs.length);for(const e of this.outputs)t+=e.getSize();return new S((t+=4)+e,e)}static isTX(e){return e instanceof t}}},function(t,e,r){"use strict";
51
51
  /*!
52
52
  * writer.js - buffer writer for vallnet
53
53
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -56,7 +56,7 @@ const path = require('path');var gpath = path.join(__dirname, '../../../', 'node
56
56
  * common.js - common script functions for vallnet
57
57
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
58
58
  * https://github.com/bookmansoft/gamegold
59
- */const i=r(0),s=r(1),n=r(28),a=r(101);r=r(5).ContractType,e.opcodes={OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_LEFT:128,OP_RIGHT:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_CHECKLOCKTIMEVERIFY:177,OP_CHECKSEQUENCEVERIFY:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_PROPCREATE:192,OP_PROPEXCHANGE:193,OP_PROPSALE:194,OP_CPREGISTER:195,OP_CPCHANGE:196,OP_HTLCSUGGEST:197,OP_HTLCASSENT:198,OP_PROMISE:199,OP_COINBASE:200,OP_COMMENT:201,OP_PROPMAX:207,OP_SMALLDATA:249,OP_SMALLINTEGER:250,OP_PUBKEYS:251,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255},e.opcodesByVal=s.reverse(e.opcodes),e.small=[Buffer.from([129]),Buffer.from([]),Buffer.from([1]),Buffer.from([2]),Buffer.from([3]),Buffer.from([4]),Buffer.from([5]),Buffer.from([6]),Buffer.from([7]),Buffer.from([8]),Buffer.from([9]),Buffer.from([10]),Buffer.from([11]),Buffer.from([12]),Buffer.from([13]),Buffer.from([14]),Buffer.from([15]),Buffer.from([16])],e.flags={VERIFY_NONE:0,VERIFY_P2SH:1,VERIFY_STRICTENC:2,VERIFY_DERSIG:4,VERIFY_LOW_S:8,VERIFY_NULLDUMMY:16,VERIFY_SIGPUSHONLY:32,VERIFY_MINIMALDATA:64,VERIFY_DISCOURAGE_UPGRADABLE_NOPS:128,VERIFY_CLEANSTACK:256,VERIFY_CHECKLOCKTIMEVERIFY:512,VERIFY_CHECKSEQUENCEVERIFY:1024,VERIFY_WITNESS:2048,VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM:4096,VERIFY_MINIMALIF:8192,VERIFY_NULLFAIL:16384,VERIFY_WITNESS_PUBKEYTYPE:32768,VERIFY_MAST:65536},e.flags.MANDATORY_VERIFY_FLAGS=e.flags.VERIFY_P2SH,e.flags.STANDARD_VERIFY_FLAGS=0|e.flags.MANDATORY_VERIFY_FLAGS|e.flags.VERIFY_DERSIG|e.flags.VERIFY_STRICTENC|e.flags.VERIFY_MINIMALDATA|e.flags.VERIFY_NULLDUMMY|e.flags.VERIFY_DISCOURAGE_UPGRADABLE_NOPS|e.flags.VERIFY_CLEANSTACK|e.flags.VERIFY_MINIMALIF|e.flags.VERIFY_NULLFAIL|e.flags.VERIFY_CHECKLOCKTIMEVERIFY|e.flags.VERIFY_CHECKSEQUENCEVERIFY|e.flags.VERIFY_LOW_S|e.flags.VERIFY_WITNESS|e.flags.VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM|e.flags.VERIFY_WITNESS_PUBKEYTYPE,e.flags.ONLY_STANDARD_VERIFY_FLAGS=e.flags.STANDARD_VERIFY_FLAGS&~e.flags.MANDATORY_VERIFY_FLAGS,e.hashType={ALL:1,NONE:2,SINGLE:3,ZERO:4,ANYONECANPAY:128},e.hashTypeByVal=s.reverse(e.hashType),e.types={NONSTANDARD:0,PUBKEY:1,PUBKEYHASH:2,SCRIPTHASH:3,MULTISIG:4,NULLDATA:5,WITNESS:9,PROPEXTEND:114,WITNESSMALFORMED:128,WITNESSSCRIPTHASH:129,WITNESSPUBKEYHASH:130,WITNESSMASTHASH:131},e.typesByVal=s.reverse(e.types),e.isHashType=function(t){return i(Buffer.isBuffer(t)),0!==t.length&&(t=t[t.length-1]&~e.hashType.ANYONECANPAY)>=e.hashType.ALL&&t<=e.hashType.ZERO},e.isLowDER=function(t){return!!e.isSignatureEncoding(t)&&n.isLowS(t.slice(0,-1))},e.isKeyEncoding=function(t){if(i(Buffer.isBuffer(t)),t.length<33)return!1;if(4===t[0]){if(65!==t.length)return!1}else{if(2!==t[0]&&3!==t[0])return!1;if(33!==t.length)return!1}return!0},e.isCompressedEncoding=function(t){return i(Buffer.isBuffer(t)),33===t.length&&(2===t[0]||3===t[0])},e.isSignatureEncoding=function(t){var e,r;return i(Buffer.isBuffer(t)),!(t.length<9||73<t.length||48!==t[0]||t[1]!==t.length-3||5+(e=t[3])>=t.length||e+(r=t[5+e])+7!==t.length||2!==t[2]||0===e||128&t[4]||1<e&&0===t[4]&&!(128&t[5])||2!==t[e+4]||0===r||128&t[e+6]||1<r&&0===t[e+6]&&!(128&t[e+7]))},e.toASM=function(t,r){if(t.length<=4){return a.decode(t).toString(10)}if(r&&e.isSignatureEncoding(t)){r=t[t.length-1];let i=e.hashTypeByVal[31&r]||"";return i&&(r&e.hashType.ANYONECANPAY&&(i+="|ANYONECANPAY"),i=`[${i}]`),t.slice(0,-1).toString("hex")+i}return t.toString("hex")},e.outputLockType={NOCHECK:"no",CHECKABSOLUTEBLOCK:"clb",CHECKABSOLUTETIME:"clt",CHECKRELATIVEBLOCK:"csb",CHECKRELATIVETIME:"cst"},e.nestingCodes=[e.opcodes.OP_PROPCREATE,e.opcodes.OP_PROPEXCHANGE,e.opcodes.OP_HTLCSUGGEST,e.opcodes.OP_HTLCASSENT,e.opcodes.OP_COMMENT],e.espicalCodes=[e.opcodes.OP_RETURN,e.opcodes.OP_CPREGISTER,e.opcodes.OP_CPCHANGE,e.opcodes.OP_PROMISE,e.opcodes.OP_COINBASE],e.unspendableCodes=[e.opcodes.OP_RETURN,e.opcodes.OP_CPREGISTER,e.opcodes.OP_CPCHANGE,e.opcodes.OP_PROMISE].concat(e.nestingCodes);let o={},c=(o[r.propCreate]=e.opcodes.OP_PROPCREATE,o[r.propExchange]=e.opcodes.OP_PROPEXCHANGE,o[r.propSale]=e.opcodes.OP_PROPSALE,o[r.coinbase]=e.opcodes.OP_COINBASE,o[r.cpRegister]=e.opcodes.OP_CPREGISTER,o[r.cpChange]=e.opcodes.OP_CPCHANGE,o[r.contractPromise]=e.opcodes.OP_PROMISE,o[r.htlcSuggest]=e.opcodes.OP_HTLCSUGGEST,o[r.htlcAssent]=e.opcodes.OP_HTLCASSENT,o[r.comment]=e.opcodes.OP_COMMENT,e.OperCodeFromType=o,{});c[e.opcodes.OP_PROPCREATE]=r.propCreate,c[e.opcodes.OP_PROPEXCHANGE]=r.propExchange,c[e.opcodes.OP_PROPSALE]=r.propSale,c[e.opcodes.OP_COINBASE]=r.coinbase,c[e.opcodes.OP_CPREGISTER]=r.cpRegister,c[e.opcodes.OP_CPCHANGE]=r.cpChange,c[e.opcodes.OP_PROMISE]=r.contractPromise,c[e.opcodes.OP_HTLCASSENT]=r.htlcAssent,c[e.opcodes.OP_COMMENT]=r.comment,e.ContractTypeFromCode=c},function(t,e,r){"use strict";
59
+ */const i=r(0),s=r(1),n=r(29),a=r(101);r=r(5).ContractType,e.opcodes={OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_LEFT:128,OP_RIGHT:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_CHECKLOCKTIMEVERIFY:177,OP_CHECKSEQUENCEVERIFY:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_PROPCREATE:192,OP_PROPEXCHANGE:193,OP_PROPSALE:194,OP_CPREGISTER:195,OP_CPCHANGE:196,OP_HTLCSUGGEST:197,OP_HTLCASSENT:198,OP_PROMISE:199,OP_COINBASE:200,OP_COMMENT:201,OP_PROPMAX:207,OP_SMALLDATA:249,OP_SMALLINTEGER:250,OP_PUBKEYS:251,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255},e.opcodesByVal=s.reverse(e.opcodes),e.small=[Buffer.from([129]),Buffer.from([]),Buffer.from([1]),Buffer.from([2]),Buffer.from([3]),Buffer.from([4]),Buffer.from([5]),Buffer.from([6]),Buffer.from([7]),Buffer.from([8]),Buffer.from([9]),Buffer.from([10]),Buffer.from([11]),Buffer.from([12]),Buffer.from([13]),Buffer.from([14]),Buffer.from([15]),Buffer.from([16])],e.flags={VERIFY_NONE:0,VERIFY_P2SH:1,VERIFY_STRICTENC:2,VERIFY_DERSIG:4,VERIFY_LOW_S:8,VERIFY_NULLDUMMY:16,VERIFY_SIGPUSHONLY:32,VERIFY_MINIMALDATA:64,VERIFY_DISCOURAGE_UPGRADABLE_NOPS:128,VERIFY_CLEANSTACK:256,VERIFY_CHECKLOCKTIMEVERIFY:512,VERIFY_CHECKSEQUENCEVERIFY:1024,VERIFY_WITNESS:2048,VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM:4096,VERIFY_MINIMALIF:8192,VERIFY_NULLFAIL:16384,VERIFY_WITNESS_PUBKEYTYPE:32768,VERIFY_MAST:65536},e.flags.MANDATORY_VERIFY_FLAGS=e.flags.VERIFY_P2SH,e.flags.STANDARD_VERIFY_FLAGS=0|e.flags.MANDATORY_VERIFY_FLAGS|e.flags.VERIFY_DERSIG|e.flags.VERIFY_STRICTENC|e.flags.VERIFY_MINIMALDATA|e.flags.VERIFY_NULLDUMMY|e.flags.VERIFY_DISCOURAGE_UPGRADABLE_NOPS|e.flags.VERIFY_CLEANSTACK|e.flags.VERIFY_MINIMALIF|e.flags.VERIFY_NULLFAIL|e.flags.VERIFY_CHECKLOCKTIMEVERIFY|e.flags.VERIFY_CHECKSEQUENCEVERIFY|e.flags.VERIFY_LOW_S|e.flags.VERIFY_WITNESS|e.flags.VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM|e.flags.VERIFY_WITNESS_PUBKEYTYPE,e.flags.ONLY_STANDARD_VERIFY_FLAGS=e.flags.STANDARD_VERIFY_FLAGS&~e.flags.MANDATORY_VERIFY_FLAGS,e.hashType={ALL:1,NONE:2,SINGLE:3,ZERO:4,ANYONECANPAY:128},e.hashTypeByVal=s.reverse(e.hashType),e.types={NONSTANDARD:0,PUBKEY:1,PUBKEYHASH:2,SCRIPTHASH:3,MULTISIG:4,NULLDATA:5,WITNESS:9,PROPEXTEND:114,WITNESSMALFORMED:128,WITNESSSCRIPTHASH:129,WITNESSPUBKEYHASH:130,WITNESSMASTHASH:131},e.typesByVal=s.reverse(e.types),e.isHashType=function(t){return i(Buffer.isBuffer(t)),0!==t.length&&(t=t[t.length-1]&~e.hashType.ANYONECANPAY)>=e.hashType.ALL&&t<=e.hashType.ZERO},e.isLowDER=function(t){return!!e.isSignatureEncoding(t)&&n.isLowS(t.slice(0,-1))},e.isKeyEncoding=function(t){if(i(Buffer.isBuffer(t)),t.length<33)return!1;if(4===t[0]){if(65!==t.length)return!1}else{if(2!==t[0]&&3!==t[0])return!1;if(33!==t.length)return!1}return!0},e.isCompressedEncoding=function(t){return i(Buffer.isBuffer(t)),33===t.length&&(2===t[0]||3===t[0])},e.isSignatureEncoding=function(t){var e,r;return i(Buffer.isBuffer(t)),!(t.length<9||73<t.length||48!==t[0]||t[1]!==t.length-3||5+(e=t[3])>=t.length||e+(r=t[5+e])+7!==t.length||2!==t[2]||0===e||128&t[4]||1<e&&0===t[4]&&!(128&t[5])||2!==t[e+4]||0===r||128&t[e+6]||1<r&&0===t[e+6]&&!(128&t[e+7]))},e.toASM=function(t,r){if(t.length<=4){return a.decode(t).toString(10)}if(r&&e.isSignatureEncoding(t)){r=t[t.length-1];let i=e.hashTypeByVal[31&r]||"";return i&&(r&e.hashType.ANYONECANPAY&&(i+="|ANYONECANPAY"),i=`[${i}]`),t.slice(0,-1).toString("hex")+i}return t.toString("hex")},e.outputLockType={NOCHECK:"no",CHECKABSOLUTEBLOCK:"clb",CHECKABSOLUTETIME:"clt",CHECKRELATIVEBLOCK:"csb",CHECKRELATIVETIME:"cst"},e.nestingCodes=[e.opcodes.OP_PROPCREATE,e.opcodes.OP_PROPEXCHANGE,e.opcodes.OP_HTLCSUGGEST,e.opcodes.OP_HTLCASSENT,e.opcodes.OP_COMMENT],e.espicalCodes=[e.opcodes.OP_RETURN,e.opcodes.OP_CPREGISTER,e.opcodes.OP_CPCHANGE,e.opcodes.OP_PROMISE,e.opcodes.OP_COINBASE],e.unspendableCodes=[e.opcodes.OP_RETURN,e.opcodes.OP_CPREGISTER,e.opcodes.OP_CPCHANGE,e.opcodes.OP_PROMISE].concat(e.nestingCodes);let o={},c=(o[r.propCreate]=e.opcodes.OP_PROPCREATE,o[r.propExchange]=e.opcodes.OP_PROPEXCHANGE,o[r.propSale]=e.opcodes.OP_PROPSALE,o[r.coinbase]=e.opcodes.OP_COINBASE,o[r.cpRegister]=e.opcodes.OP_CPREGISTER,o[r.cpChange]=e.opcodes.OP_CPCHANGE,o[r.contractPromise]=e.opcodes.OP_PROMISE,o[r.htlcSuggest]=e.opcodes.OP_HTLCSUGGEST,o[r.htlcAssent]=e.opcodes.OP_HTLCASSENT,o[r.comment]=e.opcodes.OP_COMMENT,e.OperCodeFromType=o,{});c[e.opcodes.OP_PROPCREATE]=r.propCreate,c[e.opcodes.OP_PROPEXCHANGE]=r.propExchange,c[e.opcodes.OP_PROPSALE]=r.propSale,c[e.opcodes.OP_COINBASE]=r.coinbase,c[e.opcodes.OP_CPREGISTER]=r.cpRegister,c[e.opcodes.OP_CPCHANGE]=r.cpChange,c[e.opcodes.OP_PROMISE]=r.contractPromise,c[e.opcodes.OP_HTLCASSENT]=r.htlcAssent,c[e.opcodes.OP_COMMENT]=r.comment,e.ContractTypeFromCode=c},function(t,e,r){"use strict";
60
60
  /*!
61
61
  * Packet.js - worker packets for vallnet
62
62
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -70,16 +70,16 @@ const path = require('path');var gpath = path.join(__dirname, '../../../', 'node
70
70
  * policy.js - bitcoin constants for vallnet
71
71
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
72
72
  * https://github.com/bookmansoft/gamegold
73
- */const i=r(0);r=r(7),e.BASE_PORT=2e3,e.setPort=function(t,r=0){t.port=r+100*t.typeId+e.BASE_PORT,t.httpPort=r+100*t.typeId+e.BASE_PORT+2,t.publicPort=r+100*t.typeId+e.BASE_PORT+3,t.wsport=r+100*t.typeId+e.BASE_PORT+4,t.stratumPort=r+100*t.typeId+e.BASE_PORT+5},e.MAX_TX_VERSION=2,e.MAX_TX_SIZE=r.MAX_BLOCK_SIZE/10,e.MAX_TX_WEIGHT=r.MAX_BLOCK_WEIGHT/10,e.MAX_TX_SIGOPS=r.MAX_BLOCK_SIGOPS/5,e.MAX_TX_SIGOPS_COST=r.MAX_BLOCK_SIGOPS_COST/5,e.BYTES_PER_SIGOP=20,e.MIN_RELAY=1e3,e.BARE_MULTISIG=!0,e.FREE_THRESHOLD=144*r.COIN/250,e.MAX_P2SH_SIGOPS=15,e.MAX_OP_RETURN=2048,e.MAX_OP_INFO=2048,e.MAX_OP_RETURN_BYTES=e.MAX_OP_RETURN+3,e.MAX_P2WSH_STACK=100,e.MAX_P2WSH_PUSH=80,e.MAX_P2WSH_SIZE=3600,e.MEMPOOL_MAX_ANCESTORS=2e4,e.MEMPOOL_MAX_SIZE=1e3,e.MEMPOOL_EXPIRY_TIME=259200,e.MEMPOOL_MAX_ORPHANS=5e4,e.MIN_BLOCK_WEIGHT=8192,e.MAX_BLOCK_WEIGHT=1e7*r.WITNESS_SCALE_FACTOR,e.BLOCK_PRIORITY_WEIGHT=0,e.BLOCK_PRIORITY_THRESHOLD=e.FREE_THRESHOLD,e.getMinFee=function(t,r){if(null==r&&(r=e.MIN_RELAY),i(0<=t),i(0<=r),0===t)return 0;let s=Math.floor(r*t/1e3);return 0===s&&0<r?r:s},e.getRoundFee=function(t,r){if(null==r&&(r=e.MIN_RELAY),i(0<=t),i(0<=r),0===t)return 0;let s=r*Math.ceil(t/1e3);return 0===s&&0<r?r:s},e.getRate=function(t,e){return i(0<=t),i(0<=e),0===t?0:Math.floor(1e3*e/t)}},function(t,e,r){"use strict";
73
+ */const i=r(0);r=r(7),e.BASE_PORT=2e3,e.setPort=function(t,r=0){t.port=r+100*t.typeId+e.BASE_PORT,t.httpPort=r+100*t.typeId+e.BASE_PORT+2,t.publicPort=r+100*t.typeId+e.BASE_PORT+3,t.wsport=r+100*t.typeId+e.BASE_PORT+4,t.stratumPort=r+100*t.typeId+e.BASE_PORT+5},e.MAX_TX_VERSION=2,e.MAX_TX_SIZE=r.MAX_BLOCK_SIZE/10,e.MAX_TX_WEIGHT=r.MAX_BLOCK_WEIGHT/10,e.MAX_TX_SIGOPS=r.MAX_BLOCK_SIGOPS/5,e.MAX_TX_SIGOPS_COST=r.MAX_BLOCK_SIGOPS_COST/5,e.BYTES_PER_SIGOP=20,e.MIN_RELAY=1e3,e.BARE_MULTISIG=!0,e.FREE_THRESHOLD=144*r.COIN/250,e.MAX_P2SH_SIGOPS=15,e.MAX_OP_RETURN=2048,e.MAX_OP_INFO=2048,e.MAX_OP_RETURN_BYTES=e.MAX_OP_RETURN+3,e.MAX_P2WSH_STACK=100,e.MAX_P2WSH_PUSH=80,e.MAX_P2WSH_SIZE=3600,e.MEMPOOL_MAX_ANCESTORS=2e4,e.MEMPOOL_MAX_SIZE=1e3,e.MEMPOOL_EXPIRY_TIME=259200,e.MEMPOOL_MAX_ORPHANS=5e4,e.MIN_BLOCK_WEIGHT=8192,e.MAX_BLOCK_WEIGHT=1e7*r.WITNESS_SCALE_FACTOR,e.BLOCK_PRIORITY_WEIGHT=0,e.BLOCK_PRIORITY_THRESHOLD=e.FREE_THRESHOLD,e.getMinFee=function(t,r){if(null==r&&(r=e.MIN_RELAY),i(0<=t),i(0<=r),0===t)return 0;let s=Math.floor(r*t/1e3);return 0===s&&0<r?r:s},e.getRoundFee=function(t,r){if(null==r&&(r=e.MIN_RELAY),i(0<=t),i(0<=r),0===t)return 0;let s=r*Math.ceil(t/1e3);return 0===s&&0<r?r:s},e.getRate=function(t,e){return i(0<=t),i(0<=e),0===t?0:Math.floor(1e3*e/t)}},function(t,e){Array.prototype.array_diff=function(...t){return this.reduce((e,r)=>{let i=!1;for(let e=0;e<t.length;e++)-1!=t[e].indexOf(r)&&(i=!0);return i||e.push(r),e},[])},t.exports=class t{constructor(t){this.$dirty=!0,this.items=null,this.data=new Map,this.account=new Map,t&&this.load(t)}merge(t){for(var e of(this.$dirty=!0,this.items=null,t.data.keys()))this.data.set(e,t.data.get(e));for(var r of t.account.keys())this.account.set(r,t.account.get(r));return this}query(e,r,i){e=e||[];let s,n,a=10,o=1,c=[];for(let t=0;t<e.length;t++){var u=e[t];u&&Array.isArray(u)?"size"==u[0]?(a=u[1],delete e[t]):"page"==u[0]?(o=u[1],delete e[t]):"@total"==u[0]||"@sum"==u[0]?(c.push(["sum",u[1]]),a=4294967295,delete e[t]):"@max"==u[0]?(c.push(["max",u[1]]),a=4294967295,delete e[t]):"@min"==u[0]?(c.push(["min",u[1]]),a=4294967295,delete e[t]):"@average"==u[0]?(c.push(["average",u[1]]),a=4294967295,delete e[t]):"wid"==u[0]?(s=u[1],delete e[t]):"account"==u[0]&&(n=u[1],delete e[t],s=s||1):delete e[t]}let h=this;if(s&&void 0!==n&&null!=n){let e=this.account.get(s+"."+n);if(!e)return{list:[],count:0,page:0,cur:0};h=new t(e.entries())}let l=h.where(e);return(l=Array.isArray(r)&&2<r.length?l.orderby(r[0],r[1]):l).paginate(a,o,c).result(i)}get dirty(){return this.$dirty}set dirty(t){this.$dirty=t}orderby(t,e){switch(this.items||(this.items=this.ToArray()),e){case"desc":this.items=this.items.sort((e,r)=>r[t]-e[t]);break;case"asc":this.items=this.items.sort((e,r)=>e[t]-r[t])}return this}paginate(t,e,r){return this.items||(this.items=this.ToArray()),e=e||1,this.pageSize=t||10,0<this.pageSize?this.items.length%this.pageSize==0?this.pageNum=this.items.length/this.pageSize|0:this.pageNum=1+(this.items.length/this.pageSize|0):(this.pageNum=1,this.pageSize=this.items.length),this.count=this.items.length,this.pageCur=e,this.statistic=r,this}result(t){let e={list:this.records(t||null),count:this.count,page:this.pageNum,cur:this.pageCur,countCur:this.countCur};return Array.isArray(this.statistic)&&this.statistic.map(t=>{e[t[1]]=this[t[1]]}),e}records(t){if(this.items||(this.items=this.ToArray()),0==this.items.length)return[];this.pageSize||(this.pageSize=this.items.length,this.pageNum=1,this.pageCur=1);let e=[],r=this;if(!(this.pageCur>this.pageNum)){this.countCur=0;for(let i=this.pageSize*(this.pageCur-1);i<this.pageSize*this.pageCur&&this.items[i];i++){this.countCur++;let s=null;s=Array.isArray(t)?t.reduce((t,e)=>(t[e]=r.items[i][e],t),{}):this.items[i],Array.isArray(this.statistic)&&0<this.statistic.length?this.statistic.map(t=>{r[t[1]]=r[t[1]]||null;let e=null;var s;for(s of t[1].split("."))if(void 0===(e=(e||r.items[i])[s]))break;if(e)switch(t[0]){case"sum":r[t[1]]||(r[t[1]]=0),r[t[1]]+=e;break;case"max":(!r[t[1]]||r[t[1]]<e)&&(r[t[1]]=e);break;case"min":(!r[t[1]]||r[t[1]]>e)&&(r[t[1]]=e)}}):e.push(s)}}return e}async predict(e){var r,i;let s=[];for([r,i]of[...this.data])await e(r,i)&&s.push([r,i]);return new t(s)}where(e){let r=[...this.data];for(var i of e)if(i&&Array.isArray(i)&&!(i.length<2)){let t={k:i[0],sign:2==i.length?"==":i[1],v:2==i.length?i[1]:i[2]};t.k&&void 0!==t.v&&(r=r.filter(([,e])=>{let r=null;var i;for(i of t.k.split("."))if(void 0===(r=(r||e)[i]))return!1;switch(t.sign){case"==":return r==t.v;case">":return r>t.v;case"<":return r<t.v;case"!=":return r!=t.v;case">=":return r>=t.v;case"<=":return r<=t.v;case"like":return"string"==typeof t.v&&"string"==typeof r&&(-1!=r.indexOf(t.v)||-1!=t.v.indexOf(r));case"include":return!("string"!=typeof t.v&&!Array.isArray(t.v)||!r||-1==t.v.indexOf(r));case"exclude":return"string"!=typeof t.v&&!Array.isArray(t.v)||!r||-1==t.v.indexOf(r);default:return!1}}))}return new t(r)}excludeCids(t){return t=t||[],Array.isArray(t)?(t=Array.from(new Set(t))).reduce((t,e)=>(this.has(e)||t.push(e),t),[]):[]}diff(...t){return[...this.data.keys()].array_diff(...t.map(t=>[...t.data.keys()]))}has(t){return"object"==typeof t&&Buffer.isBuffer(t)&&(t=t.toString("hex")),this.data.has(t)}set(t,e){var r;e&&("object"==typeof t&&Buffer.isBuffer(t)&&(t=t.toString("hex")),e.wid&&void 0!==e.account&&null!=e.account&&(r=e.wid+"."+e.account,this.account.get(r)||this.account.set(r,new Map),this.account.get(r).set(t,e)),this.data.set(t,e),this.items=null)}get(t,e){return"object"==typeof t&&Buffer.isBuffer(t)&&(t=t.toString("hex")),e&&(t+=e),this.data.get(t)}getAccount(t,e){let r=this.account.get(t+"."+e);return r?[...r.values()]:[]}remove(t){return this.delete(t)}delete(t){"object"==typeof t&&Buffer.isBuffer(t)&&(t=t.toString("hex"));var e=this.get(t);if(e&&e.wid&&void 0!==e.account&&null!=e.account){let r=this.account.get(e.wid+"."+e.account);r&&r.delete(t)}return e=this.data.delete(t),this.items=null,e}deletes(t){var e;for(e of this.where(t).getKeys())this.data.delete(e);this.items=null}load(t,e=!0){for(var r of(e&&(this.data.clear(),this.items=null),t))this.set(r[0],r[1])}clear(){this.data.clear(),this.items=null}forEach(t,e){this.data.forEach(t,e||this)}ToArray(){return[...this.data.values()]}getKeys(){return[...this.data.keys()]}getSize(){return this.data.size}}},function(t,e,r){"use strict";
74
74
  /*!
75
75
  * secp256k1.js - ecdsa wrapper for secp256k1 and elliptic
76
76
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
77
77
  * https://github.com/bookmansoft/gamegold
78
- */let i;if(1!==Number(process.env.GAMEGOLD_NO_SECP256K1))try{i=r(371)}catch(t){i=r(255)}else i=r(255);t.exports=i},function(t,e){Array.prototype.array_diff=function(...t){return this.reduce((e,r)=>{let i=!1;for(let e=0;e<t.length;e++)-1!=t[e].indexOf(r)&&(i=!0);return i||e.push(r),e},[])},t.exports=class t{constructor(t){this.$dirty=!0,this.items=null,this.data=new Map,this.account=new Map,t&&this.load(t)}merge(t){for(var e of(this.$dirty=!0,this.items=null,t.data.keys()))this.data.set(e,t.data.get(e));for(var r of t.account.keys())this.account.set(r,t.account.get(r));return this}query(e,r,i){e=e||[];let s,n,a=10,o=1,c=[];for(let t=0;t<e.length;t++){var u=e[t];u&&Array.isArray(u)?"size"==u[0]?(a=u[1],delete e[t]):"page"==u[0]?(o=u[1],delete e[t]):"@total"==u[0]||"@sum"==u[0]?(c.push(["sum",u[1]]),a=4294967295,delete e[t]):"@max"==u[0]?(c.push(["max",u[1]]),a=4294967295,delete e[t]):"@min"==u[0]?(c.push(["min",u[1]]),a=4294967295,delete e[t]):"@average"==u[0]?(c.push(["average",u[1]]),a=4294967295,delete e[t]):"wid"==u[0]?(s=u[1],delete e[t]):"account"==u[0]&&(n=u[1],delete e[t],s=s||1):delete e[t]}let h=this;if(s&&void 0!==n&&null!=n){let e=this.account.get(s+"."+n);if(!e)return{list:[],count:0,page:0,cur:0};h=new t(e.entries())}let l=h.where(e);return(l=Array.isArray(r)&&2<r.length?l.orderby(r[0],r[1]):l).paginate(a,o,c).result(i)}get dirty(){return this.$dirty}set dirty(t){this.$dirty=t}orderby(t,e){switch(this.items||(this.items=this.ToArray()),e){case"desc":this.items=this.items.sort((e,r)=>r[t]-e[t]);break;case"asc":this.items=this.items.sort((e,r)=>e[t]-r[t])}return this}paginate(t,e,r){return this.items||(this.items=this.ToArray()),e=e||1,this.pageSize=t||10,0<this.pageSize?this.items.length%this.pageSize==0?this.pageNum=this.items.length/this.pageSize|0:this.pageNum=1+(this.items.length/this.pageSize|0):(this.pageNum=1,this.pageSize=this.items.length),this.count=this.items.length,this.pageCur=e,this.statistic=r,this}result(t){let e={list:this.records(t||null),count:this.count,page:this.pageNum,cur:this.pageCur,countCur:this.countCur};return Array.isArray(this.statistic)&&this.statistic.map(t=>{e[t[1]]=this[t[1]]}),e}records(t){if(this.items||(this.items=this.ToArray()),0==this.items.length)return[];this.pageSize||(this.pageSize=this.items.length,this.pageNum=1,this.pageCur=1);let e=[],r=this;if(!(this.pageCur>this.pageNum)){this.countCur=0;for(let i=this.pageSize*(this.pageCur-1);i<this.pageSize*this.pageCur&&this.items[i];i++){this.countCur++;let s=null;s=Array.isArray(t)?t.reduce((t,e)=>(t[e]=r.items[i][e],t),{}):this.items[i],Array.isArray(this.statistic)&&0<this.statistic.length?this.statistic.map(t=>{r[t[1]]=r[t[1]]||null;let e=null;var s;for(s of t[1].split("."))if(void 0===(e=(e||r.items[i])[s]))break;if(e)switch(t[0]){case"sum":r[t[1]]||(r[t[1]]=0),r[t[1]]+=e;break;case"max":(!r[t[1]]||r[t[1]]<e)&&(r[t[1]]=e);break;case"min":(!r[t[1]]||r[t[1]]>e)&&(r[t[1]]=e)}}):e.push(s)}}return e}async predict(e){var r,i;let s=[];for([r,i]of[...this.data])await e(r,i)&&s.push([r,i]);return new t(s)}where(e){let r=[...this.data];for(var i of e)if(i&&Array.isArray(i)&&!(i.length<2)){let t={k:i[0],sign:2==i.length?"==":i[1],v:2==i.length?i[1]:i[2]};t.k&&void 0!==t.v&&(r=r.filter(([,e])=>{let r=null;var i;for(i of t.k.split("."))if(void 0===(r=(r||e)[i]))return!1;switch(t.sign){case"==":return r==t.v;case">":return r>t.v;case"<":return r<t.v;case"!=":return r!=t.v;case">=":return r>=t.v;case"<=":return r<=t.v;case"like":return"string"==typeof t.v&&"string"==typeof r&&(-1!=r.indexOf(t.v)||-1!=t.v.indexOf(r));case"include":return!("string"!=typeof t.v&&!Array.isArray(t.v)||!r||-1==t.v.indexOf(r));case"exclude":return"string"!=typeof t.v&&!Array.isArray(t.v)||!r||-1==t.v.indexOf(r);default:return!1}}))}return new t(r)}excludeCids(t){return t=t||[],Array.isArray(t)?(t=Array.from(new Set(t))).reduce((t,e)=>(this.has(e)||t.push(e),t),[]):[]}diff(...t){return[...this.data.keys()].array_diff(...t.map(t=>[...t.data.keys()]))}has(t){return"object"==typeof t&&Buffer.isBuffer(t)&&(t=t.toString("hex")),this.data.has(t)}set(t,e){var r;e&&("object"==typeof t&&Buffer.isBuffer(t)&&(t=t.toString("hex")),e.wid&&void 0!==e.account&&null!=e.account&&(r=e.wid+"."+e.account,this.account.get(r)||this.account.set(r,new Map),this.account.get(r).set(t,e)),this.data.set(t,e),this.items=null)}get(t,e){return"object"==typeof t&&Buffer.isBuffer(t)&&(t=t.toString("hex")),e&&(t+=e),this.data.get(t)}getAccount(t,e){let r=this.account.get(t+"."+e);return r?[...r.values()]:[]}remove(t){return this.delete(t)}delete(t){"object"==typeof t&&Buffer.isBuffer(t)&&(t=t.toString("hex"));var e=this.get(t);if(e&&e.wid&&void 0!==e.account&&null!=e.account){let r=this.account.get(e.wid+"."+e.account);r&&r.delete(t)}return e=this.data.delete(t),this.items=null,e}deletes(t){var e;for(e of this.where(t).getKeys())this.data.delete(e);this.items=null}load(t,e=!0){for(var r of(e&&(this.data.clear(),this.items=null),t))this.set(r[0],r[1])}clear(){this.data.clear(),this.items=null}forEach(t,e){this.data.forEach(t,e||this)}ToArray(){return[...this.data.values()]}getKeys(){return[...this.data.keys()]}getSize(){return this.data.size}}},,function(t,e,r){r=r(14).Buffer;var i={dsa:{parts:["p","q","g","y"],sizePart:"p"},rsa:{parts:["e","n"],sizePart:"n"},ecdsa:{parts:["curve","Q"],sizePart:"Q"},ed25519:{parts:["A"],sizePart:"A"}},s=(i.curve25519=i.ed25519,{dsa:{parts:["p","q","g","y","x"]},rsa:{parts:["n","e","d","iqmp","p","q"]},ecdsa:{parts:["curve","Q","d"]},ed25519:{parts:["A","k"]}});s.curve25519=s.ed25519,r={nistp256:{size:256,pkcs8oid:"1.2.840.10045.3.1.7",p:r.from("00ffffffff 00000001 00000000 0000000000000000 ffffffff ffffffff ffffffff".replace(/ /g,""),"hex"),a:r.from("00FFFFFFFF 00000001 00000000 0000000000000000 FFFFFFFF FFFFFFFF FFFFFFFC".replace(/ /g,""),"hex"),b:r.from("5ac635d8 aa3a93e7 b3ebbd55 769886bc651d06b0 cc53b0f6 3bce3c3e 27d2604b".replace(/ /g,""),"hex"),s:r.from("00c49d3608 86e70493 6a6678e1 139d26b7819f7e90".replace(/ /g,""),"hex"),n:r.from("00ffffffff 00000000 ffffffff ffffffffbce6faad a7179e84 f3b9cac2 fc632551".replace(/ /g,""),"hex"),G:r.from("046b17d1f2 e12c4247 f8bce6e5 63a440f277037d81 2deb33a0 f4a13945 d898c2964fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e162bce3357 6b315ece cbb64068 37bf51f5".replace(/ /g,""),"hex")},nistp384:{size:384,pkcs8oid:"1.3.132.0.34",p:r.from("00ffffffff ffffffff ffffffff ffffffffffffffff ffffffff ffffffff fffffffeffffffff 00000000 00000000 ffffffff".replace(/ /g,""),"hex"),a:r.from("00FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFFFFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFEFFFFFFFF 00000000 00000000 FFFFFFFC".replace(/ /g,""),"hex"),b:r.from("b3312fa7 e23ee7e4 988e056b e3f82d19181d9c6e fe814112 0314088f 5013875ac656398d 8a2ed19d 2a85c8ed d3ec2aef".replace(/ /g,""),"hex"),s:r.from("00a335926a a319a27a 1d00896a 6773a4827acdac73".replace(/ /g,""),"hex"),n:r.from("00ffffffff ffffffff ffffffff ffffffffffffffff ffffffff c7634d81 f4372ddf581a0db2 48b0a77a ecec196a ccc52973".replace(/ /g,""),"hex"),G:r.from("04aa87ca22 be8b0537 8eb1c71e f320ad746e1d3b62 8ba79b98 59f741e0 82542a385502f25d bf55296c 3a545e38 72760ab73617de4a 96262c6f 5d9e98bf 9292dc29f8f41dbd 289a147c e9da3113 b5f0b8c00a60b1ce 1d7e819d 7a431d7c 90ea0e5f".replace(/ /g,""),"hex")},nistp521:{size:521,pkcs8oid:"1.3.132.0.35",p:r.from("01ffffff ffffffff ffffffff ffffffffffffffff ffffffff ffffffff ffffffffffffffff ffffffff ffffffff ffffffffffffffff ffffffff ffffffff ffffffffffff".replace(/ /g,""),"hex"),a:r.from("01FFFFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFFFFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFFFFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFFFFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFC".replace(/ /g,""),"hex"),b:r.from("51953eb961 8e1c9a1f 929a21a0 b68540eea2da725b 99b315f3 b8b48991 8ef109e156193951 ec7e937b 1652c0bd 3bb1bf073573df88 3d2c34f1 ef451fd4 6b503f00".replace(/ /g,""),"hex"),s:r.from("00d09e8800 291cb853 96cc6717 393284aaa0da64ba".replace(/ /g,""),"hex"),n:r.from("01ffffffffff ffffffff ffffffff ffffffffffffffff ffffffff ffffffff fffffffa51868783 bf2f966b 7fcc0148 f709a5d03bb5c9b8 899c47ae bb6fb71e 91386409".replace(/ /g,""),"hex"),G:r.from("0400c6 858e06b7 0404e9cd 9e3ecb66 2395b4429c648139 053fb521 f828af60 6b4d3dbaa14b5e77 efe75928 fe1dc127 a2ffa8de3348b3c1 856a429b f97e7e31 c2e5bd660118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd998f54449 579b4468 17afbd17 273e662c97ee7299 5ef42640 c550b901 3fad0761353c7086 a272c240 88be9476 9fd16650".replace(/ /g,""),"hex")}};t.exports={info:i,privInfo:s,hashAlgs:{md5:!0,sha1:!0,sha256:!0,sha384:!0,sha512:!0},curves:r}},function(t,e,r){"use strict";
78
+ */let i;if(1!==Number(process.env.GAMEGOLD_NO_SECP256K1))try{i=r(371)}catch(t){i=r(255)}else i=r(255);t.exports=i},,function(t,e,r){r=r(14).Buffer;var i={dsa:{parts:["p","q","g","y"],sizePart:"p"},rsa:{parts:["e","n"],sizePart:"n"},ecdsa:{parts:["curve","Q"],sizePart:"Q"},ed25519:{parts:["A"],sizePart:"A"}},s=(i.curve25519=i.ed25519,{dsa:{parts:["p","q","g","y","x"]},rsa:{parts:["n","e","d","iqmp","p","q"]},ecdsa:{parts:["curve","Q","d"]},ed25519:{parts:["A","k"]}});s.curve25519=s.ed25519,r={nistp256:{size:256,pkcs8oid:"1.2.840.10045.3.1.7",p:r.from("00ffffffff 00000001 00000000 0000000000000000 ffffffff ffffffff ffffffff".replace(/ /g,""),"hex"),a:r.from("00FFFFFFFF 00000001 00000000 0000000000000000 FFFFFFFF FFFFFFFF FFFFFFFC".replace(/ /g,""),"hex"),b:r.from("5ac635d8 aa3a93e7 b3ebbd55 769886bc651d06b0 cc53b0f6 3bce3c3e 27d2604b".replace(/ /g,""),"hex"),s:r.from("00c49d3608 86e70493 6a6678e1 139d26b7819f7e90".replace(/ /g,""),"hex"),n:r.from("00ffffffff 00000000 ffffffff ffffffffbce6faad a7179e84 f3b9cac2 fc632551".replace(/ /g,""),"hex"),G:r.from("046b17d1f2 e12c4247 f8bce6e5 63a440f277037d81 2deb33a0 f4a13945 d898c2964fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e162bce3357 6b315ece cbb64068 37bf51f5".replace(/ /g,""),"hex")},nistp384:{size:384,pkcs8oid:"1.3.132.0.34",p:r.from("00ffffffff ffffffff ffffffff ffffffffffffffff ffffffff ffffffff fffffffeffffffff 00000000 00000000 ffffffff".replace(/ /g,""),"hex"),a:r.from("00FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFFFFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFEFFFFFFFF 00000000 00000000 FFFFFFFC".replace(/ /g,""),"hex"),b:r.from("b3312fa7 e23ee7e4 988e056b e3f82d19181d9c6e fe814112 0314088f 5013875ac656398d 8a2ed19d 2a85c8ed d3ec2aef".replace(/ /g,""),"hex"),s:r.from("00a335926a a319a27a 1d00896a 6773a4827acdac73".replace(/ /g,""),"hex"),n:r.from("00ffffffff ffffffff ffffffff ffffffffffffffff ffffffff c7634d81 f4372ddf581a0db2 48b0a77a ecec196a ccc52973".replace(/ /g,""),"hex"),G:r.from("04aa87ca22 be8b0537 8eb1c71e f320ad746e1d3b62 8ba79b98 59f741e0 82542a385502f25d bf55296c 3a545e38 72760ab73617de4a 96262c6f 5d9e98bf 9292dc29f8f41dbd 289a147c e9da3113 b5f0b8c00a60b1ce 1d7e819d 7a431d7c 90ea0e5f".replace(/ /g,""),"hex")},nistp521:{size:521,pkcs8oid:"1.3.132.0.35",p:r.from("01ffffff ffffffff ffffffff ffffffffffffffff ffffffff ffffffff ffffffffffffffff ffffffff ffffffff ffffffffffffffff ffffffff ffffffff ffffffffffff".replace(/ /g,""),"hex"),a:r.from("01FFFFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFFFFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFFFFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFFFFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFC".replace(/ /g,""),"hex"),b:r.from("51953eb961 8e1c9a1f 929a21a0 b68540eea2da725b 99b315f3 b8b48991 8ef109e156193951 ec7e937b 1652c0bd 3bb1bf073573df88 3d2c34f1 ef451fd4 6b503f00".replace(/ /g,""),"hex"),s:r.from("00d09e8800 291cb853 96cc6717 393284aaa0da64ba".replace(/ /g,""),"hex"),n:r.from("01ffffffffff ffffffff ffffffff ffffffffffffffff ffffffff ffffffff fffffffa51868783 bf2f966b 7fcc0148 f709a5d03bb5c9b8 899c47ae bb6fb71e 91386409".replace(/ /g,""),"hex"),G:r.from("0400c6 858e06b7 0404e9cd 9e3ecb66 2395b4429c648139 053fb521 f828af60 6b4d3dbaa14b5e77 efe75928 fe1dc127 a2ffa8de3348b3c1 856a429b f97e7e31 c2e5bd660118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd998f54449 579b4468 17afbd17 273e662c97ee7299 5ef42640 c550b901 3fad0761353c7086 a272c240 88be9476 9fd16650".replace(/ /g,""),"hex")}};t.exports={info:i,privInfo:s,hashAlgs:{md5:!0,sha1:!0,sha256:!0,sha384:!0,sha512:!0},curves:r}},function(t,e,r){"use strict";
79
79
  /*!
80
80
  * keyring.js - keyring object for vallnet
81
81
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
82
- */const i=r(0),s=r(3),n=r(6),a=r(15),o=r(2),c=r(4),u=r(70),h=r(17),l=r(12),p=r(26),d=r(28),f=r(1);function m(t){return t&&(t.privateKey||t.publicKey||t)}t.exports=class t{constructor(t,e){this.network=a.primary,this.witness=!1,this.nested=!1,this.publicKey=s.ZERO_KEY,this.privateKey=null,this.script=null,this._keyHash=null,this._keyAddress=null,this._program=null,this._nestedHash=null,this._nestedAddress=null,this._scriptHash160=null,this._scriptHash256=null,this._scriptAddress=null,t&&this.fromOptions(t,e)}fromOptions(t,e){e=e||t.network;let r=m(t);if(null!=t.witness&&(i("boolean"==typeof t.witness),this.witness=t.witness),null!=t.nested&&(i("boolean"==typeof t.nested),this.nested=t.nested),Buffer.isBuffer(r))return this.fromKey(r,e);r=m(t.key),t.publicKey&&(r=m(t.publicKey)),t.privateKey&&(r=m(t.privateKey));var s=t.script;t=t.compressed;return s?this.fromScript(r,s,t,e):this.fromKey(r,t,e)}static fromOptions(e){return(new t).fromOptions(e)}refresh(){this._keyHash=null,this._keyAddress=null,this._program=null,this._nestedHash=null,this._nestedAddress=null,this._scriptHash160=null,this._scriptHash256=null,this._scriptAddress=null}fromPrivate(t,e,r){return i(Buffer.isBuffer(t),"Private key must be a buffer."),i(d.privateKeyVerify(t),"Not a valid private key."),"boolean"!=typeof e&&(r=e,e=null),this.network=a.get(r),this.privateKey=t,this.publicKey=d.publicKeyCreate(t,!1!==e),this}static fromPrivate(e,r,i){return(new t).fromPrivate(e,r,i)}fromPublic(t,e){return i(Buffer.isBuffer(t),"Public key must be a buffer."),i(d.publicKeyVerify(t),"Not a valid public key."),this.network=a.get(e),this.publicKey=t,this}generate(t,e){"boolean"!=typeof t&&(e=t,t=null);var r=d.generatePrivateKey();return this.fromKey(r,t,e)}static generate(e,r){return(new t).generate(e,r)}static fromPublic(e,r){return(new t).fromPublic(e,r)}fromKey(t,e,r){return i(Buffer.isBuffer(t),"Key must be a buffer."),"boolean"!=typeof e&&(r=e,e=null),32===t.length?this.fromPrivate(t,!1!==e,r):this.fromPublic(t,r)}static fromKey(e,r,i){return(new t).fromKey(e,r,i)}fromScript(t,e,r,s){return i(e instanceof h,"Non-script passed into KeyRing."),"boolean"!=typeof r&&(s=r,r=null),this.fromKey(t,r,s),this.script=e,this}static fromScript(e,r,i,s){return(new t).fromScript(e,r,i,s)}getSecretSize(){let t=0;return t=(t+=1)+this.privateKey.length,33===this.publicKey.length&&(t+=1),t+4}toSecret(t){var e=this.getSecretSize();const r=new c(e);return i(this.privateKey,"Cannot serialize without private key."),t=t||this.network,t=a.get(t),r.writeU8(t.keyPrefix.privkey),r.writeBytes(this.privateKey),33===this.publicKey.length&&r.writeU8(1),r.writeChecksum(),u.encode(r.render())}fromSecret(t,e){const r=new o(u.decode(t),!0);t=r.readU8(),e=a.fromWIF(t,e),t=r.readBytes(32);let s=!1;return 4<r.left()&&(i(1===r.readU8(),"Bad compression flag."),s=!0),r.verifyChecksum(),this.fromPrivate(t,s,e)}static fromSecret(e,r){return(new t).fromSecret(e,r)}getPrivateKey(t){return this.privateKey?"base58"===t?this.toSecret():"hex"===t?this.privateKey.toString("hex"):this.privateKey:null}getPublicKey(t){return"base58"===t?u.encode(this.publicKey):"hex"===t?this.publicKey.toString("hex"):this.publicKey}getScript(){return this.script}getProgram(){if(!this.witness)return null;if(!this._program){let t;t=this.script?this.script.sha256():n.hash160(this.publicKey),this._program=h.createScript([0,t],h.types.WITNESS)}return this._program}getNestedHash(t){return this.witness?(this._nestedHash||(this._nestedHash=this.getProgram().hash160()),"hex"===t?this._nestedHash.toString("hex"):this._nestedHash):null}getNestedAddress(t){var e;return this.witness?(this._nestedAddress||(e=this.getNestedHash(),e=l.fromScripthash(e,this.network),this._nestedAddress=e),"base58"===t?this._nestedAddress.toBase58():"string"===t?this._nestedAddress.toString():this._nestedAddress):null}getScriptHash(t){return this.witness?this.getScriptHash256(t):this.getScriptHash160(t)}getScriptHash160(t){return this.script?(this._scriptHash160||(this._scriptHash160=this.script.hash160()),"hex"===t?this._scriptHash160.toString("hex"):this._scriptHash160):null}getScriptHash256(t){return this.script?(this._scriptHash256||(this._scriptHash256=this.script.sha256()),"hex"===t?this._scriptHash256.toString("hex"):this._scriptHash256):null}getScriptAddress(t){if(!this.script)return null;if(!this._scriptAddress){let t;var e;t=this.witness?(e=this.getScriptHash256(),l.fromWitnessScripthash(e,this.network)):(e=this.getScriptHash160(),l.fromScripthash(e,this.network)),this._scriptAddress=t}return"base58"===t?this._scriptAddress.toBase58():"string"===t?this._scriptAddress.toString():this._scriptAddress}getKeyHash(t){return this._keyHash||(this._keyHash=n.hash160(this.publicKey)),"hex"===t?this._keyHash.toString("hex"):this._keyHash}getKeyAddress(t){if(!this._keyAddress){var e=this.getKeyHash();let t;t=this.witness?l.fromWitnessPubkeyhash(e,this.network):l.fromPubkeyhash(e,this.network),this._keyAddress=t}return"base58"===t?this._keyAddress.toBase58():"string"===t?this._keyAddress.toString():this._keyAddress}getHash(t){return this.nested?this.getNestedHash(t):this.script?this.getScriptHash(t):this.getKeyHash(t)}getAddress(t){return this.nested?this.getNestedAddress(t):this.script?this.getScriptAddress(t):this.getKeyAddress(t)}ownHash(t){if(!t)return!1;let e=!1;if(Array.isArray(t)){for(var r of t)e=e||this.ownHash(r);return e}return!!t.equals(this.getKeyHash())||!(!this.script||!t.equals(this.getScriptHash()))||!(!this.witness||!t.equals(this.getNestedHash()))}ownOutput(t,e){let r;return t instanceof p?r=t:(r=t.outputs[e],i(r,"Output does not exist.")),this.ownHash(r.getHashs())}getRedeem(t){if(this.witness&&t.equals(this.getNestedHash()))return this.getProgram();if(this.script){if(t.equals(this.getScriptHash160()))return this.script;if(t.equals(this.getScriptHash256()))return this.script}return null}sign(t){return i(this.privateKey,"Cannot sign without private key."),d.sign(t,this.privateKey)}verify(t,e){return d.verify(t,e,this.publicKey)}signData(t,e="bookman"){(t=t||{}).cid||(t.cid=e),t.time&&(t.time=f.now()/300|0),t.addr=this.getAddress("string"),t.pubkey=this.publicKey.toString("hex");let r={data:t};return e=n.hash256(Buffer.from(f.stringify(r.data))),r.sig=this.sign(e).toString("hex"),r}getVersion(){return!this.witness||this.nested?-1:0}getType(){return this.nested?l.types.SCRIPTHASH:this.witness?l.types.WITNESS:this.script?l.types.SCRIPTHASH:l.types.PUBKEYHASH}inspect(){return this.toJSON()}toJSON(){return{network:this.network.type,witness:this.witness,nested:this.nested,publicKey:this.publicKey.toString("hex"),script:this.script?this.script.toRaw().toString("hex"):null,program:this.witness?this.getProgram().toRaw().toString("hex"):null,type:l.typesByVal[this.getType()].toLowerCase(),address:this.getAddress("string")}}fromJSON(t){return i(t),i("string"==typeof t.network),i("boolean"==typeof t.witness),i("boolean"==typeof t.nested),i("string"==typeof t.publicKey),i(!t.script||"string"==typeof t.script),this.nework=a.get(t.network),this.witness=t.witness,this.nested=t.nested,this.publicKey=Buffer.from(t.publicKey,"hex"),t.script&&(this.script=Buffer.from(t.script,"hex")),this}static fromJSON(e){return(new t).fromJSON(e)}getSize(){let t=0;return t+=1,this.privateKey?t=t+s.sizeVarBytes(this.privateKey)+1:t+=s.sizeVarBytes(this.publicKey),t+(this.script?this.script.getVarSize():1)}toWriter(t){let e=0;return this.witness&&(e|=1),this.nested&&(e|=2),t.writeU8(e),this.privateKey?(t.writeVarBytes(this.privateKey),t.writeU8(33===this.publicKey.length)):t.writeVarBytes(this.publicKey),this.script?t.writeVarBytes(this.script.toRaw()):t.writeVarint(0),t}toRaw(){var t=this.getSize();return this.toWriter(new c(t)).render()}fromReader(t,e){this.network=a.get(e),e=t.readU8(),this.witness=0!=(1&e),this.nested=0!=(2&e),32===(e=t.readVarBytes()).length?(r=1===t.readU8(),this.privateKey=e,this.publicKey=d.publicKeyCreate(e,r)):(this.publicKey=e,i(d.publicKeyVerify(e),"Invalid public key."));var r=t.readVarBytes();return 0<r.length&&(this.script=h.fromRaw(r)),this}fromRaw(t,e){return this.fromReader(new o(t),e)}static fromReader(e){return(new t).fromReader(e)}static fromRaw(e){return(new t).fromRaw(e)}static isKeyRing(e){return e instanceof t}}},,function(t,e,r){"use strict";
82
+ */const i=r(0),s=r(3),n=r(6),a=r(15),o=r(2),c=r(4),u=r(70),h=r(17),l=r(12),p=r(26),d=r(29),f=r(1);function m(t){return t&&(t.privateKey||t.publicKey||t)}t.exports=class t{constructor(t,e){this.network=a.primary,this.witness=!1,this.nested=!1,this.publicKey=s.ZERO_KEY,this.privateKey=null,this.script=null,this._keyHash=null,this._keyAddress=null,this._program=null,this._nestedHash=null,this._nestedAddress=null,this._scriptHash160=null,this._scriptHash256=null,this._scriptAddress=null,t&&this.fromOptions(t,e)}fromOptions(t,e){e=e||t.network;let r=m(t);if(null!=t.witness&&(i("boolean"==typeof t.witness),this.witness=t.witness),null!=t.nested&&(i("boolean"==typeof t.nested),this.nested=t.nested),Buffer.isBuffer(r))return this.fromKey(r,e);r=m(t.key),t.publicKey&&(r=m(t.publicKey)),t.privateKey&&(r=m(t.privateKey));var s=t.script;t=t.compressed;return s?this.fromScript(r,s,t,e):this.fromKey(r,t,e)}static fromOptions(e){return(new t).fromOptions(e)}refresh(){this._keyHash=null,this._keyAddress=null,this._program=null,this._nestedHash=null,this._nestedAddress=null,this._scriptHash160=null,this._scriptHash256=null,this._scriptAddress=null}fromPrivate(t,e,r){return i(Buffer.isBuffer(t),"Private key must be a buffer."),i(d.privateKeyVerify(t),"Not a valid private key."),"boolean"!=typeof e&&(r=e,e=null),this.network=a.get(r),this.privateKey=t,this.publicKey=d.publicKeyCreate(t,!1!==e),this}static fromPrivate(e,r,i){return(new t).fromPrivate(e,r,i)}fromPublic(t,e){return i(Buffer.isBuffer(t),"Public key must be a buffer."),i(d.publicKeyVerify(t),"Not a valid public key."),this.network=a.get(e),this.publicKey=t,this}generate(t,e){"boolean"!=typeof t&&(e=t,t=null);var r=d.generatePrivateKey();return this.fromKey(r,t,e)}static generate(e,r){return(new t).generate(e,r)}static fromPublic(e,r){return(new t).fromPublic(e,r)}fromKey(t,e,r){return i(Buffer.isBuffer(t),"Key must be a buffer."),"boolean"!=typeof e&&(r=e,e=null),32===t.length?this.fromPrivate(t,!1!==e,r):this.fromPublic(t,r)}static fromKey(e,r,i){return(new t).fromKey(e,r,i)}fromScript(t,e,r,s){return i(e instanceof h,"Non-script passed into KeyRing."),"boolean"!=typeof r&&(s=r,r=null),this.fromKey(t,r,s),this.script=e,this}static fromScript(e,r,i,s){return(new t).fromScript(e,r,i,s)}getSecretSize(){let t=0;return t=(t+=1)+this.privateKey.length,33===this.publicKey.length&&(t+=1),t+4}toSecret(t){var e=this.getSecretSize();const r=new c(e);return i(this.privateKey,"Cannot serialize without private key."),t=t||this.network,t=a.get(t),r.writeU8(t.keyPrefix.privkey),r.writeBytes(this.privateKey),33===this.publicKey.length&&r.writeU8(1),r.writeChecksum(),u.encode(r.render())}fromSecret(t,e){const r=new o(u.decode(t),!0);t=r.readU8(),e=a.fromWIF(t,e),t=r.readBytes(32);let s=!1;return 4<r.left()&&(i(1===r.readU8(),"Bad compression flag."),s=!0),r.verifyChecksum(),this.fromPrivate(t,s,e)}static fromSecret(e,r){return(new t).fromSecret(e,r)}getPrivateKey(t){return this.privateKey?"base58"===t?this.toSecret():"hex"===t?this.privateKey.toString("hex"):this.privateKey:null}getPublicKey(t){return"base58"===t?u.encode(this.publicKey):"hex"===t?this.publicKey.toString("hex"):this.publicKey}getScript(){return this.script}getProgram(){if(!this.witness)return null;if(!this._program){let t;t=this.script?this.script.sha256():n.hash160(this.publicKey),this._program=h.createScript([0,t],h.types.WITNESS)}return this._program}getNestedHash(t){return this.witness?(this._nestedHash||(this._nestedHash=this.getProgram().hash160()),"hex"===t?this._nestedHash.toString("hex"):this._nestedHash):null}getNestedAddress(t){var e;return this.witness?(this._nestedAddress||(e=this.getNestedHash(),e=l.fromScripthash(e,this.network),this._nestedAddress=e),"base58"===t?this._nestedAddress.toBase58():"string"===t?this._nestedAddress.toString():this._nestedAddress):null}getScriptHash(t){return this.witness?this.getScriptHash256(t):this.getScriptHash160(t)}getScriptHash160(t){return this.script?(this._scriptHash160||(this._scriptHash160=this.script.hash160()),"hex"===t?this._scriptHash160.toString("hex"):this._scriptHash160):null}getScriptHash256(t){return this.script?(this._scriptHash256||(this._scriptHash256=this.script.sha256()),"hex"===t?this._scriptHash256.toString("hex"):this._scriptHash256):null}getScriptAddress(t){if(!this.script)return null;if(!this._scriptAddress){let t;var e;t=this.witness?(e=this.getScriptHash256(),l.fromWitnessScripthash(e,this.network)):(e=this.getScriptHash160(),l.fromScripthash(e,this.network)),this._scriptAddress=t}return"base58"===t?this._scriptAddress.toBase58():"string"===t?this._scriptAddress.toString():this._scriptAddress}getKeyHash(t){return this._keyHash||(this._keyHash=n.hash160(this.publicKey)),"hex"===t?this._keyHash.toString("hex"):this._keyHash}getKeyAddress(t){if(!this._keyAddress){var e=this.getKeyHash();let t;t=this.witness?l.fromWitnessPubkeyhash(e,this.network):l.fromPubkeyhash(e,this.network),this._keyAddress=t}return"base58"===t?this._keyAddress.toBase58():"string"===t?this._keyAddress.toString():this._keyAddress}getHash(t){return this.nested?this.getNestedHash(t):this.script?this.getScriptHash(t):this.getKeyHash(t)}getAddress(t){return this.nested?this.getNestedAddress(t):this.script?this.getScriptAddress(t):this.getKeyAddress(t)}ownHash(t){if(!t)return!1;let e=!1;if(Array.isArray(t)){for(var r of t)e=e||this.ownHash(r);return e}return!!t.equals(this.getKeyHash())||!(!this.script||!t.equals(this.getScriptHash()))||!(!this.witness||!t.equals(this.getNestedHash()))}ownOutput(t,e){let r;return t instanceof p?r=t:(r=t.outputs[e],i(r,"Output does not exist.")),this.ownHash(r.getHashs())}getRedeem(t){if(this.witness&&t.equals(this.getNestedHash()))return this.getProgram();if(this.script){if(t.equals(this.getScriptHash160()))return this.script;if(t.equals(this.getScriptHash256()))return this.script}return null}sign(t){return i(this.privateKey,"Cannot sign without private key."),d.sign(t,this.privateKey)}verify(t,e){return d.verify(t,e,this.publicKey)}signData(t,e="bookman"){(t=t||{}).cid||(t.cid=e),t.time&&(t.time=f.now()/300|0),t.addr=this.getAddress("string"),t.pubkey=this.publicKey.toString("hex");let r={data:t};return e=n.hash256(Buffer.from(f.stringify(r.data))),r.sig=this.sign(e).toString("hex"),r}getVersion(){return!this.witness||this.nested?-1:0}getType(){return this.nested?l.types.SCRIPTHASH:this.witness?l.types.WITNESS:this.script?l.types.SCRIPTHASH:l.types.PUBKEYHASH}inspect(){return this.toJSON()}toJSON(){return{network:this.network.type,witness:this.witness,nested:this.nested,publicKey:this.publicKey.toString("hex"),script:this.script?this.script.toRaw().toString("hex"):null,program:this.witness?this.getProgram().toRaw().toString("hex"):null,type:l.typesByVal[this.getType()].toLowerCase(),address:this.getAddress("string")}}fromJSON(t){return i(t),i("string"==typeof t.network),i("boolean"==typeof t.witness),i("boolean"==typeof t.nested),i("string"==typeof t.publicKey),i(!t.script||"string"==typeof t.script),this.nework=a.get(t.network),this.witness=t.witness,this.nested=t.nested,this.publicKey=Buffer.from(t.publicKey,"hex"),t.script&&(this.script=Buffer.from(t.script,"hex")),this}static fromJSON(e){return(new t).fromJSON(e)}getSize(){let t=0;return t+=1,this.privateKey?t=t+s.sizeVarBytes(this.privateKey)+1:t+=s.sizeVarBytes(this.publicKey),t+(this.script?this.script.getVarSize():1)}toWriter(t){let e=0;return this.witness&&(e|=1),this.nested&&(e|=2),t.writeU8(e),this.privateKey?(t.writeVarBytes(this.privateKey),t.writeU8(33===this.publicKey.length)):t.writeVarBytes(this.publicKey),this.script?t.writeVarBytes(this.script.toRaw()):t.writeVarint(0),t}toRaw(){var t=this.getSize();return this.toWriter(new c(t)).render()}fromReader(t,e){this.network=a.get(e),e=t.readU8(),this.witness=0!=(1&e),this.nested=0!=(2&e),32===(e=t.readVarBytes()).length?(r=1===t.readU8(),this.privateKey=e,this.publicKey=d.publicKeyCreate(e,r)):(this.publicKey=e,i(d.publicKeyVerify(e),"Invalid public key."));var r=t.readVarBytes();return 0<r.length&&(this.script=h.fromRaw(r)),this}fromRaw(t,e){return this.fromReader(new o(t),e)}static fromReader(e){return(new t).fromReader(e)}static fromRaw(e){return(new t).fromRaw(e)}static isKeyRing(e){return e instanceof t}}},,function(t,e,r){"use strict";
83
83
  /*!
84
84
  * amount.js - amount object for vallnet
85
85
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -143,7 +143,7 @@ let i=[];[r(567),r(568),r(569),r(570),r(571),r(572),r(573),r(574),r(575),r(576),
143
143
  /*!
144
144
  * coinview.js - coin viewpoint object for vallnet
145
145
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
146
- */const i=r(331),s=r(256),n=r(148);t.exports=class t{constructor(){this.map=new Map,this.undo=new s}clone(){let e=new t;for(var[r,i]of this.map)e.map.set(r,i.clone());return e.undo=s.fromRaw(this.undo.toRaw()),e}get(t){return this.map.get(t)}has(t){return this.map.has(t)}add(t,e){return this.map.set(t,e),e}ensure(t){return this.map.get(t)||this.add(t,new i)}remove(t){var e=this.map.get(t);return e?(this.map.delete(t),e):null}addTX(t,e,r){var s=t.hash("hex");t=i.fromTX(t,e,r);return this.add(s,t)}removeTX(t,e,r){var s=t.hash("hex");const n=i.fromTX(t,e,r);for(const t of n.outputs.values())t.spent=!0;return this.add(s,n)}addEntry(t,e){var{hash:t,index:r}=t;return this.ensure(t).add(r,e)}addIndex(t,e,r,i){var s=t.hash("hex");return this.ensure(s).add(e,n.fromTX(t,e,r,i))}addCoin(t){return this.ensure(t.hash).addCoin(t)}addOutput(t,e){var{hash:t,index:r}=t;return this.ensure(t).addOutput(r,e)}spendEntry(t){var{hash:t,index:e}=t;const r=this.get(t);return r&&(t=r.spend(e))?(this.undo.push(t),t):null}removeEntry(t){var{hash:t,index:e}=t;const r=this.get(t);return r?r.remove(e):null}hasEntry(t){var{hash:t,index:e}=t;const r=this.get(t);return!!r&&r.has(e)}getEntry(t){var{hash:t,index:e}=t;const r=this.get(t);return r?r.get(e):null}isUnspent(t){var{hash:t,index:e}=t;const r=this.get(t);return!!r&&r.isUnspent(e)}getCoin(t){const e=this.get(t.hash);return e?e.getCoin(t):null}getOutput(t){var{hash:t,index:e}=t;const r=this.get(t);return r?r.getOutput(e):null}getHeight(t){return(t=this.getEntry(t))?t.height:-1}isCoinbase(t){return!!(t=this.getEntry(t))&&t.coinbase}hasEntryFor(t){return this.hasEntry(t.prevout)}getEntryFor(t){return this.getEntry(t.prevout)}isUnspentFor(t){return this.isUnspent(t.prevout)}getCoinFor(t){return this.getCoin(t.prevout)}getOutputFor(t){return this.getOutput(t.prevout)}getHeightFor(t){return this.getHeight(t.prevout)}isCoinbaseFor(t){return this.isCoinbase(t.prevout)}async readCoin(t,e){var r=this.getEntry(e);return r||((r=await t.readCoin(e))?this.addEntry(e,r):null)}async readInputs(t,e){let r=!0;for(var{prevout:i}of e.inputs)await this.readCoin(t,i)||(r=!1);return r}async spendInputs(t,e){let r=0;for(;r<e.inputs.length;){var i=Math.min(r+4,e.inputs.length);const n=[];for(;r<i;r++){var s=e.inputs[r].prevout;n.push(this.readCoin(t,s))}for(const t of await Promise.all(n)){if(!t||t.spent)return!1;t.spent=!0,this.undo.push(t)}}return!0}getSize(t){let e=0;for(var{prevout:r}of(e+=t.inputs.length,t.inputs)){const t=this.getEntry(r);t&&(e+=t.getSize())}return e}toWriter(t,e){for(var{prevout:r}of e.inputs){const e=this.getEntry(r);e?(t.writeU8(1),e.toWriter(t)):t.writeU8(0)}return t}fromReader(t,e){for(var{prevout:r}of e.inputs){var i;0!==t.readU8()&&(i=n.fromReader(t),this.addEntry(r,i))}return this}static fromReader(e,r){return(new t).fromReader(e,r)}}},function(t,e){t.exports=require("http")},function(t,e,r){const i=r(1),s=r(28),n=r(6),a=r(12);t.exports={verifyData:function(t){try{var e=Buffer.from(t.data.pubkey,"hex"),r=Buffer.from(i.stringify(t.data));if(s.verify(n.hash256(r),Buffer.from(t.sig,"hex"),e)&&a.fromString(t.data.addr).hash.toString("hex")==n.hash160(e).toString("hex"))return!0}catch(t){}return!1},generateKey:function(t){"string"==typeof(t=t||s.generatePrivateKey())&&(t=Buffer.from(t,"hex"));let e=s.publicKeyCreate(t,!0);return{private:t.toString("hex"),public:e.toString("hex")}},signObj:function(t,e){return"string"==typeof e&&(e=Buffer.from(e,"hex")),t=Buffer.isBuffer(t)?n.hash256(t):n.hash256(Buffer.from(i.stringify(t))),s.sign(t,e).toString("hex")},verifyObj:function(t,e,r){return t=Buffer.isBuffer(t)?n.hash256(t):n.hash256(Buffer.from(i.stringify(t))),"string"==typeof e&&(e=Buffer.from(e,"hex")),"string"==typeof r&&(r=Buffer.from(r,"hex")),s.verify(t,e,r)}}},function(t,e,r){"use strict";
146
+ */const i=r(331),s=r(256),n=r(148);t.exports=class t{constructor(){this.map=new Map,this.undo=new s}clone(){let e=new t;for(var[r,i]of this.map)e.map.set(r,i.clone());return e.undo=s.fromRaw(this.undo.toRaw()),e}get(t){return this.map.get(t)}has(t){return this.map.has(t)}add(t,e){return this.map.set(t,e),e}ensure(t){return this.map.get(t)||this.add(t,new i)}remove(t){var e=this.map.get(t);return e?(this.map.delete(t),e):null}addTX(t,e,r){var s=t.hash("hex");t=i.fromTX(t,e,r);return this.add(s,t)}removeTX(t,e,r){var s=t.hash("hex");const n=i.fromTX(t,e,r);for(const t of n.outputs.values())t.spent=!0;return this.add(s,n)}addEntry(t,e){var{hash:t,index:r}=t;return this.ensure(t).add(r,e)}addIndex(t,e,r,i){var s=t.hash("hex");return this.ensure(s).add(e,n.fromTX(t,e,r,i))}addCoin(t){return this.ensure(t.hash).addCoin(t)}addOutput(t,e){var{hash:t,index:r}=t;return this.ensure(t).addOutput(r,e)}spendEntry(t){var{hash:t,index:e}=t;const r=this.get(t);return r&&(t=r.spend(e))?(this.undo.push(t),t):null}removeEntry(t){var{hash:t,index:e}=t;const r=this.get(t);return r?r.remove(e):null}hasEntry(t){var{hash:t,index:e}=t;const r=this.get(t);return!!r&&r.has(e)}getEntry(t){var{hash:t,index:e}=t;const r=this.get(t);return r?r.get(e):null}isUnspent(t){var{hash:t,index:e}=t;const r=this.get(t);return!!r&&r.isUnspent(e)}getCoin(t){const e=this.get(t.hash);return e?e.getCoin(t):null}getOutput(t){var{hash:t,index:e}=t;const r=this.get(t);return r?r.getOutput(e):null}getHeight(t){return(t=this.getEntry(t))?t.height:-1}isCoinbase(t){return!!(t=this.getEntry(t))&&t.coinbase}hasEntryFor(t){return this.hasEntry(t.prevout)}getEntryFor(t){return this.getEntry(t.prevout)}isUnspentFor(t){return this.isUnspent(t.prevout)}getCoinFor(t){return this.getCoin(t.prevout)}getOutputFor(t){return this.getOutput(t.prevout)}getHeightFor(t){return this.getHeight(t.prevout)}isCoinbaseFor(t){return this.isCoinbase(t.prevout)}async readCoin(t,e){var r=this.getEntry(e);return r||((r=await t.readCoin(e))?this.addEntry(e,r):null)}async readInputs(t,e){let r=!0;for(var{prevout:i}of e.inputs)await this.readCoin(t,i)||(r=!1);return r}async spendInputs(t,e){let r=0;for(;r<e.inputs.length;){var i=Math.min(r+4,e.inputs.length);const n=[];for(;r<i;r++){var s=e.inputs[r].prevout;n.push(this.readCoin(t,s))}for(const t of await Promise.all(n)){if(!t||t.spent)return!1;t.spent=!0,this.undo.push(t)}}return!0}getSize(t){let e=0;for(var{prevout:r}of(e+=t.inputs.length,t.inputs)){const t=this.getEntry(r);t&&(e+=t.getSize())}return e}toWriter(t,e){for(var{prevout:r}of e.inputs){const e=this.getEntry(r);e?(t.writeU8(1),e.toWriter(t)):t.writeU8(0)}return t}fromReader(t,e){for(var{prevout:r}of e.inputs){var i;0!==t.readU8()&&(i=n.fromReader(t),this.addEntry(r,i))}return this}static fromReader(e,r){return(new t).fromReader(e,r)}}},function(t,e){t.exports=require("http")},function(t,e,r){const i=r(1),s=r(29),n=r(6),a=r(12);t.exports={verifyData:function(t){try{var e=Buffer.from(t.data.pubkey,"hex"),r=Buffer.from(i.stringify(t.data));if(s.verify(n.hash256(r),Buffer.from(t.sig,"hex"),e)&&a.fromString(t.data.addr).hash.toString("hex")==n.hash160(e).toString("hex"))return!0}catch(t){}return!1},generateKey:function(t){"string"==typeof(t=t||s.generatePrivateKey())&&(t=Buffer.from(t,"hex"));let e=s.publicKeyCreate(t,!0);return{private:t.toString("hex"),public:e.toString("hex")}},signObj:function(t,e){return"string"==typeof e&&(e=Buffer.from(e,"hex")),t=Buffer.isBuffer(t)?n.hash256(t):n.hash256(Buffer.from(i.stringify(t))),s.sign(t,e).toString("hex")},verifyObj:function(t,e,r){return t=Buffer.isBuffer(t)?n.hash256(t):n.hash256(Buffer.from(i.stringify(t))),"string"==typeof e&&(e=Buffer.from(e,"hex")),"string"==typeof r&&(r=Buffer.from(r,"hex")),s.verify(t,e,r)}}},function(t,e,r){"use strict";
147
147
  /*!
148
148
  * invitem.js - inv item object for vallnet
149
149
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -156,7 +156,7 @@ let i=[];[r(567),r(568),r(569),r(570),r(571),r(572),r(573),r(574),r(575),r(576),
156
156
  * private.js - hd private keys for vallnet
157
157
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
158
158
  * https://github.com/bookmansoft/gamegold
159
- */const i=r(0),s=r(1),n=r(6),a=r(95),o=r(71),c=r(28),u=r(15),h=r(4),l=r(2),p=r(70),d=r(3),f=r(142),m=r(200),g=r(312);class y{constructor(t){if(!(this instanceof y))return new y(t);this.disableCache=!1,this.network=u.primary,this.depth=0,this.parentFingerPrint=0,this.childIndex=0,this.chainCode=d.ZERO_HASH,this.privateKey=d.ZERO_HASH,this.publicKey=d.ZERO_KEY,this.fingerPrint=-1,this._xprivkey=null,this._hdPublicKey=null,t&&this.fromOptions(t)}static getHmac(t,e){e=e||d.DefaultChainCode;let r=y.fromKey(n.sha256(Buffer.concat([Buffer.from(t),e])),e),i={id:"primary"};return i.cid=t,i.pubkey=r.publicKey.toString("hex"),i.time=s.now()/3600|0,e=n.hash256(Buffer.from(s.stringify(i))),t=c.sign(e,r.privateKey).toString("hex"),{token:i.pubkey,random:t}}fromOptions(t){return i(t,"No options for HD private key."),i(s.isU8(t.depth)),i(s.isU32(t.parentFingerPrint)),i(s.isU32(t.childIndex)),i(Buffer.isBuffer(t.chainCode)),i(Buffer.isBuffer(t.privateKey)),t.network&&(this.network=u.get(t.network)),this.depth=t.depth,this.parentFingerPrint=t.parentFingerPrint,this.childIndex=t.childIndex,this.chainCode=t.chainCode,this.privateKey=t.privateKey,this.publicKey=c.publicKeyCreate(t.privateKey,!0),this}static fromOptions(t){return(new y).fromOptions(t)}toPublic(){let t=this._hdPublicKey;return t||((t=new g).network=this.network,t.depth=this.depth,t.parentFingerPrint=this.parentFingerPrint,t.childIndex=this.childIndex,t.chainCode=this.chainCode,t.publicKey=this.publicKey,this._hdPublicKey=t),t}xprivkey(){return this._xprivkey||(this._xprivkey=this.toBase58()),this._xprivkey}xpubkey(){return this.toPublic().xpubkey()}destroy(t){this.depth=0,this.childIndex=0,this.parentFingerPrint=0,a(this.chainCode),a(this.privateKey),a(this.publicKey),this.fingerPrint=-1,this._hdPublicKey&&(t&&this._hdPublicKey.destroy(),this._hdPublicKey=null),this._xprivkey=null}derive(t,e){if(i("number"==typeof t),t>>>0!==t)throw new Error("Index out of range.");if(255<=this.depth)throw new Error("Depth too high.");if((e&&(t=(t|f.HARDENED)>>>0),e=this.getID(t),!this.disableCache)&&(a=f.cache.get(e)))return a;const r=h.pool(37);t&f.HARDENED?(r.writeU8(0),r.writeBytes(this.privateKey)):r.writeBytes(this.publicKey),r.writeU32BE(t),a=r.render();const s=n.hmac("sha512",a,this.chainCode);var a=s.slice(0,32),o=s.slice(32,64);let u;try{u=c.privateKeyTweakAdd(this.privateKey,a)}catch(e){return this.derive(t+1)}if(-1===this.fingerPrint){const t=n.hash160(this.publicKey);this.fingerPrint=t.readUInt32BE(0,!0)}const l=new y;return l.disableCache=this.disableCache,l.network=this.network,l.depth=this.depth+1,l.parentFingerPrint=this.fingerPrint,l.childIndex=t,l.chainCode=o,l.privateKey=u,l.publicKey=c.publicKeyCreate(u,!0),this.disableCache||f.cache.set(e,l),l}getID(t){return this.network.keyPrefix.xprivkey58+this.publicKey.toString("hex")+t}deriveAccount(t,e){return i(s.isU32(t),"Purpose must be a number."),i(s.isU32(e),"Account index must be a number."),i(this.isMaster(),"Cannot derive account index."),this.derive(t,!0).derive(this.network.keyPrefix.coinType,!0).derive(e,!0)}isMaster(){return f.isMaster(this)}isAccount(t){return f.isAccount(this,t)}static isBase58(t,e){if("string"!=typeof t)return!1;if(t.length<4)return!1;t=t.substring(0,4);try{return u.fromPrivate58(t,e),!0}catch(t){return!1}}static isRaw(t,e){if(!Buffer.isBuffer(t))return!1;if(t.length<4)return!1;t=t.readUInt32BE(0,!0);try{return u.fromPrivate(t,e),!0}catch(t){return!1}}static isValidPath(t){try{return f.parsePath(t,!0),!0}catch(t){return!1}}derivePath(t){let e=this;for(const r of f.parsePath(t,!0))e=e.derive(r);return e}equals(t){return i(y.isHDPrivateKey(t)),this.network===t.network&&this.depth===t.depth&&this.parentFingerPrint===t.parentFingerPrint&&this.childIndex===t.childIndex&&this.chainCode.equals(t.chainCode)&&this.privateKey.equals(t.privateKey)}compare(t){i(y.isHDPrivateKey(t));let e=this.depth-t.depth;return 0!==e||0!=(e=this.parentFingerPrint-t.parentFingerPrint)||0!=(e=this.childIndex-t.childIndex)||0!==(e=this.chainCode.compare(t.chainCode))||0!==(e=this.privateKey.compare(t.privateKey))?e:0}fromSeed(t,e){if(i(Buffer.isBuffer(t)),8*t.length<f.MIN_ENTROPY||8*t.length>f.MAX_ENTROPY)throw new Error("Entropy not in range.");const r=n.hmac("sha512",t,d.SEED_SALT);t=r.slice(0,32);var s=r.slice(32,64);if(c.privateKeyVerify(t))return this.network=u.get(e),this.depth=0,this.parentFingerPrint=0,this.childIndex=0,this.chainCode=s,this.privateKey=t,this.publicKey=c.publicKeyCreate(t,!0),this;throw new Error("Master private key is invalid.")}static fromSeed(t,e){return(new y).fromSeed(t,e)}fromMnemonic(t,e){return i(t instanceof m),this.fromSeed(t.toSeed(),e)}static fromMnemonic(t,e){return(new y).fromMnemonic(t,e)}fromPhrase(t,e){return t=m.fromPhrase(t),this.fromMnemonic(t,e),this}static fromPhrase(t,e){return(new y).fromPhrase(t,e)}static getAes(t,e){var r=Buffer.from(t);let i=Buffer.alloc(32);for(let t=0;t<Math.max(32,r.length);t++){var s=t%32;i[s]=r[s]^d.RANDOM_HASH[s]}return y.fromKey(d.RANDOM_HASH,i,e).getAes(t)}fromKey(t,e,r){return i(Buffer.isBuffer(t)&&32===t.length),i(Buffer.isBuffer(e)&&32===e.length),this.network=u.get(r),this.depth=0,this.parentFingerPrint=0,this.childIndex=0,this.chainCode=e,this.privateKey=t,this.publicKey=c.publicKeyCreate(t,!0),this}getAes(t){t=y.getHmac(t,this.chainCode).token;let e=n.hash256(Buffer.from(t));return{aeskey:e.toString("base64").slice(0,32),aesiv:(e=n.hash256(e)).toString("base64").slice(0,16)}}static fromKey(t,e,r){return(new y).fromKey(t,e,r)}static eccEncrypt(t,e){var r=y.generate();let i=c.ecdh(e,r.privateKey);var{aeskey:e,aesiv:n}=y.getAes(i.toString());return{pub:r.publicKey,msg:s.encrypt(e,n,Buffer.from(t).toString("hex"))}}static eccDecrypt(t,e){let r=c.ecdh(t.pub,e);var{aeskey:e,aesiv:i}=y.getAes(r.toString());return Buffer.from(s.decrypt(e,i,t.msg),"hex").toString()}static generate(t){var e=c.generatePrivateKey(),r=o.randomBytes(32);return y.fromKey(e,r,t)}fromBase58(t,e){return i("string"==typeof t),this._xprivkey=t,this.fromRaw(p.decode(t),e)}fromReader(t,e){var r=t.readU32BE();return this.network=u.fromPrivate(r,e),this.depth=t.readU8(),this.parentFingerPrint=t.readU32BE(),this.childIndex=t.readU32BE(),this.chainCode=t.readBytes(32),i(0===t.readU8()),this.privateKey=t.readBytes(32),this.publicKey=c.publicKeyCreate(this.privateKey,!0),t.verifyChecksum(),this}fromRaw(t,e){return this.fromReader(new l(t),e)}toBase58(t){return p.encode(this.toRaw(t))}getSize(){return 82}toWriter(t,e){return e=e||this.network,e=u.get(e),t.writeU32BE(e.keyPrefix.xprivkey),t.writeU8(this.depth),t.writeU32BE(this.parentFingerPrint),t.writeU32BE(this.childIndex),t.writeBytes(this.chainCode),t.writeU8(0),t.writeBytes(this.privateKey),t.writeChecksum(),t}toRaw(t){return this.toWriter(new h(82),t).render()}static fromBase58(t,e){return(new y).fromBase58(t,e)}static fromReader(t,e){return(new y).fromReader(t,e)}static fromRaw(t,e){return(new y).fromRaw(t,e)}toJSON(){return{xprivkey:this.xprivkey(),pubkey:this.publicKey.toString("hex")}}fromJSON(t,e){return i(t.xprivkey,"Could not handle key JSON."),this.fromBase58(t.xprivkey,e),this}static fromJSON(t,e){return(new y).fromJSON(t,e)}static isHDPrivateKey(t){return t instanceof y}}t.exports=y},function(t,e,r){"use strict";
159
+ */const i=r(0),s=r(1),n=r(6),a=r(95),o=r(71),c=r(29),u=r(15),h=r(4),l=r(2),p=r(70),d=r(3),f=r(142),m=r(200),g=r(312);class y{constructor(t){if(!(this instanceof y))return new y(t);this.disableCache=!1,this.network=u.primary,this.depth=0,this.parentFingerPrint=0,this.childIndex=0,this.chainCode=d.ZERO_HASH,this.privateKey=d.ZERO_HASH,this.publicKey=d.ZERO_KEY,this.fingerPrint=-1,this._xprivkey=null,this._hdPublicKey=null,t&&this.fromOptions(t)}static getHmac(t,e){e=e||d.DefaultChainCode;let r=y.fromKey(n.sha256(Buffer.concat([Buffer.from(t),e])),e),i={id:"primary"};return i.cid=t,i.pubkey=r.publicKey.toString("hex"),i.time=s.now()/3600|0,e=n.hash256(Buffer.from(s.stringify(i))),t=c.sign(e,r.privateKey).toString("hex"),{token:i.pubkey,random:t}}fromOptions(t){return i(t,"No options for HD private key."),i(s.isU8(t.depth)),i(s.isU32(t.parentFingerPrint)),i(s.isU32(t.childIndex)),i(Buffer.isBuffer(t.chainCode)),i(Buffer.isBuffer(t.privateKey)),t.network&&(this.network=u.get(t.network)),this.depth=t.depth,this.parentFingerPrint=t.parentFingerPrint,this.childIndex=t.childIndex,this.chainCode=t.chainCode,this.privateKey=t.privateKey,this.publicKey=c.publicKeyCreate(t.privateKey,!0),this}static fromOptions(t){return(new y).fromOptions(t)}toPublic(){let t=this._hdPublicKey;return t||((t=new g).network=this.network,t.depth=this.depth,t.parentFingerPrint=this.parentFingerPrint,t.childIndex=this.childIndex,t.chainCode=this.chainCode,t.publicKey=this.publicKey,this._hdPublicKey=t),t}xprivkey(){return this._xprivkey||(this._xprivkey=this.toBase58()),this._xprivkey}xpubkey(){return this.toPublic().xpubkey()}destroy(t){this.depth=0,this.childIndex=0,this.parentFingerPrint=0,a(this.chainCode),a(this.privateKey),a(this.publicKey),this.fingerPrint=-1,this._hdPublicKey&&(t&&this._hdPublicKey.destroy(),this._hdPublicKey=null),this._xprivkey=null}derive(t,e){if(i("number"==typeof t),t>>>0!==t)throw new Error("Index out of range.");if(255<=this.depth)throw new Error("Depth too high.");if((e&&(t=(t|f.HARDENED)>>>0),e=this.getID(t),!this.disableCache)&&(a=f.cache.get(e)))return a;const r=h.pool(37);t&f.HARDENED?(r.writeU8(0),r.writeBytes(this.privateKey)):r.writeBytes(this.publicKey),r.writeU32BE(t),a=r.render();const s=n.hmac("sha512",a,this.chainCode);var a=s.slice(0,32),o=s.slice(32,64);let u;try{u=c.privateKeyTweakAdd(this.privateKey,a)}catch(e){return this.derive(t+1)}if(-1===this.fingerPrint){const t=n.hash160(this.publicKey);this.fingerPrint=t.readUInt32BE(0,!0)}const l=new y;return l.disableCache=this.disableCache,l.network=this.network,l.depth=this.depth+1,l.parentFingerPrint=this.fingerPrint,l.childIndex=t,l.chainCode=o,l.privateKey=u,l.publicKey=c.publicKeyCreate(u,!0),this.disableCache||f.cache.set(e,l),l}getID(t){return this.network.keyPrefix.xprivkey58+this.publicKey.toString("hex")+t}deriveAccount(t,e){return i(s.isU32(t),"Purpose must be a number."),i(s.isU32(e),"Account index must be a number."),i(this.isMaster(),"Cannot derive account index."),this.derive(t,!0).derive(this.network.keyPrefix.coinType,!0).derive(e,!0)}isMaster(){return f.isMaster(this)}isAccount(t){return f.isAccount(this,t)}static isBase58(t,e){if("string"!=typeof t)return!1;if(t.length<4)return!1;t=t.substring(0,4);try{return u.fromPrivate58(t,e),!0}catch(t){return!1}}static isRaw(t,e){if(!Buffer.isBuffer(t))return!1;if(t.length<4)return!1;t=t.readUInt32BE(0,!0);try{return u.fromPrivate(t,e),!0}catch(t){return!1}}static isValidPath(t){try{return f.parsePath(t,!0),!0}catch(t){return!1}}derivePath(t){let e=this;for(const r of f.parsePath(t,!0))e=e.derive(r);return e}equals(t){return i(y.isHDPrivateKey(t)),this.network===t.network&&this.depth===t.depth&&this.parentFingerPrint===t.parentFingerPrint&&this.childIndex===t.childIndex&&this.chainCode.equals(t.chainCode)&&this.privateKey.equals(t.privateKey)}compare(t){i(y.isHDPrivateKey(t));let e=this.depth-t.depth;return 0!==e||0!=(e=this.parentFingerPrint-t.parentFingerPrint)||0!=(e=this.childIndex-t.childIndex)||0!==(e=this.chainCode.compare(t.chainCode))||0!==(e=this.privateKey.compare(t.privateKey))?e:0}fromSeed(t,e){if(i(Buffer.isBuffer(t)),8*t.length<f.MIN_ENTROPY||8*t.length>f.MAX_ENTROPY)throw new Error("Entropy not in range.");const r=n.hmac("sha512",t,d.SEED_SALT);t=r.slice(0,32);var s=r.slice(32,64);if(c.privateKeyVerify(t))return this.network=u.get(e),this.depth=0,this.parentFingerPrint=0,this.childIndex=0,this.chainCode=s,this.privateKey=t,this.publicKey=c.publicKeyCreate(t,!0),this;throw new Error("Master private key is invalid.")}static fromSeed(t,e){return(new y).fromSeed(t,e)}fromMnemonic(t,e){return i(t instanceof m),this.fromSeed(t.toSeed(),e)}static fromMnemonic(t,e){return(new y).fromMnemonic(t,e)}fromPhrase(t,e){return t=m.fromPhrase(t),this.fromMnemonic(t,e),this}static fromPhrase(t,e){return(new y).fromPhrase(t,e)}static getAes(t,e){var r=Buffer.from(t);let i=Buffer.alloc(32);for(let t=0;t<Math.max(32,r.length);t++){var s=t%32;i[s]=r[s]^d.RANDOM_HASH[s]}return y.fromKey(d.RANDOM_HASH,i,e).getAes(t)}fromKey(t,e,r){return i(Buffer.isBuffer(t)&&32===t.length),i(Buffer.isBuffer(e)&&32===e.length),this.network=u.get(r),this.depth=0,this.parentFingerPrint=0,this.childIndex=0,this.chainCode=e,this.privateKey=t,this.publicKey=c.publicKeyCreate(t,!0),this}getAes(t){t=y.getHmac(t,this.chainCode).token;let e=n.hash256(Buffer.from(t));return{aeskey:e.toString("base64").slice(0,32),aesiv:(e=n.hash256(e)).toString("base64").slice(0,16)}}static fromKey(t,e,r){return(new y).fromKey(t,e,r)}static eccEncrypt(t,e){var r=y.generate();let i=c.ecdh(e,r.privateKey);var{aeskey:e,aesiv:n}=y.getAes(i.toString());return{pub:r.publicKey,msg:s.encrypt(e,n,Buffer.from(t).toString("hex"))}}static eccDecrypt(t,e){let r=c.ecdh(t.pub,e);var{aeskey:e,aesiv:i}=y.getAes(r.toString());return Buffer.from(s.decrypt(e,i,t.msg),"hex").toString()}static generate(t){var e=c.generatePrivateKey(),r=o.randomBytes(32);return y.fromKey(e,r,t)}fromBase58(t,e){return i("string"==typeof t),this._xprivkey=t,this.fromRaw(p.decode(t),e)}fromReader(t,e){var r=t.readU32BE();return this.network=u.fromPrivate(r,e),this.depth=t.readU8(),this.parentFingerPrint=t.readU32BE(),this.childIndex=t.readU32BE(),this.chainCode=t.readBytes(32),i(0===t.readU8()),this.privateKey=t.readBytes(32),this.publicKey=c.publicKeyCreate(this.privateKey,!0),t.verifyChecksum(),this}fromRaw(t,e){return this.fromReader(new l(t),e)}toBase58(t){return p.encode(this.toRaw(t))}getSize(){return 82}toWriter(t,e){return e=e||this.network,e=u.get(e),t.writeU32BE(e.keyPrefix.xprivkey),t.writeU8(this.depth),t.writeU32BE(this.parentFingerPrint),t.writeU32BE(this.childIndex),t.writeBytes(this.chainCode),t.writeU8(0),t.writeBytes(this.privateKey),t.writeChecksum(),t}toRaw(t){return this.toWriter(new h(82),t).render()}static fromBase58(t,e){return(new y).fromBase58(t,e)}static fromReader(t,e){return(new y).fromReader(t,e)}static fromRaw(t,e){return(new y).fromRaw(t,e)}toJSON(){return{xprivkey:this.xprivkey(),pubkey:this.publicKey.toString("hex")}}fromJSON(t,e){return i(t.xprivkey,"Could not handle key JSON."),this.fromBase58(t.xprivkey,e),this}static fromJSON(t,e){return(new y).fromJSON(t,e)}static isHDPrivateKey(t){return t instanceof y}}t.exports=y},function(t,e,r){"use strict";
160
160
  /*!
161
161
  * base58.js - base58 for vallnet
162
162
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -199,12 +199,12 @@ let i=[];[r(567),r(568),r(569),r(570),r(571),r(572),r(573),r(574),r(575),r(576),
199
199
  * pkg.js - package constants
200
200
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
201
201
  * https://github.com/bookmansoft/gamegold
202
- */e.protocol="vallnet",e.version="v4.0.7",e.url="https://github.com/bookmansoft/gamegold"},function(t,e,r){"use strict";
202
+ */e.protocol="vallnet",e.version="v4.0.8",e.url="https://github.com/bookmansoft/gamegold"},function(t,e,r){"use strict";
203
203
  /*!
204
204
  * common.js - p2p constants for vallnet
205
205
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
206
206
  * https://github.com/bookmansoft/gamegold
207
- */r=r(83),e.PROTOCOL_VERSION=70015,e.MIN_VERSION=70001,e.HEADERS_VERSION=31800,e.PONG_VERSION=6e4,e.BLOOM_VERSION=70011,e.COMPACT_VERSION=70014,e.COMPACT_WITNESS_VERSION=70015,e.services={NETWORK:1,GETUTXO:2,BLOOM:4,WITNESS:8},e.LOCAL_SERVICES=0|e.services.NETWORK|e.services.WITNESS,e.REQUIRED_SERVICES=0|e.services.NETWORK,e.USER_AGENT=`/${r.protocol}:${r.version}/`,e.MAX_MESSAGE=5e7,e.BAN_TIME=86400,e.BAN_SCORE=100},function(t,e,r){const i=r(143),{ContractType:s,ContractEnvType:n}=r(5),a=r(1);var o=r(29);const c=r(4),u=r(2),h=r(3);r(20);const{SR:l,SRR:p}=r(94),d={Offer:1,Purchase:2,Send:3,Bonus:4,Ads:5,Bid:6,Auction:7};class f extends o{constructor(t){super(),this.cpNameMap=new Map,this.cpIndexMap=new Map,this.env=t}async loadHistory(){var t;for(t of await this.env.getCps())this.set(t.cid,t),this.cpNameMap.set(t.name,t),this.cpIndexMap.set(i(t.cid),t)}async addItem(t){var e=new m(t);(t=(this.set(e.cid,e),this.getItem(t.cid)))&&this.removeNameIndex(t.name),this.cpNameMap.set(e.name,e),this.cpIndexMap.set(i(e.cid),e),await this.env.setCp(e)}async delItem(t){await this.env.delCp(t.cid),this.cpIndexMap.delete(i(t.cid)),this.removeNameIndex(t.name),this.delete(t.cid)}getItem(t){return this.has(t)?this.get(t):null}getItemByName(t){return this.cpNameMap.get(t)}getRecord(t){return(t=this.get(t))||null}removeNameIndex(t){this.cpNameMap.delete(t)}async canExecute(t){switch(t.oper){case s.cpRegister:if(this.cpIndexMap.has(i(t.cid))||this.has(t.cid)||this.cpNameMap.has(t.name))break;return!0;case s.cpChange:var e=this.getItem(t.cid),r=this.cpNameMap.get(t.name);if(e)return!r||r.cid===t.cid}return!1}getCPList(t,e){let r=[];if(0<t.length)r=this.where([["cid","include",t]]).paginate(50,1).records(),e.pageCount=this.pageNum;else{e.pageSize=e.pageSize||10;let t=e.cls?this.where([["cls",e.cls]]):this;r=t.paginate(e.pageSize,e.page).records(),e.pageCount=t.pageNum}return e.page=Math.min(e.page,e.pageCount),r}getCPListByName(t,e){let r=[];return r=(0<t.length?this.where([["name","include",t]]).paginate(50,1):this.paginate(10,page)).records(),e.pageCount=this.pageNum,e.page=Math.min(e.page,e.pageCount),r}async stockOffer(t){if(!await this.env.getStockRecordById(t.itemNo)){let e=this.getItem(t.cid);if(!e)throw new Error("Invalid CP Info.");let r=e.clone();r.stock.sum=t.sum,r.stock.price=t.price,r.stock.height=t.height,r.stock.hHeight||(r.stock.hHeight=t.height),await this.addItem(r),await this.env.setStockRecord(t)}}async stockBid(t){await this.env.getStockRecordById(t.itemNo)||await this.env.setStockRecord(t)}async stockAuction(t){if(!await this.env.getStockRecordById(t.itemNo)){let e=this.getItem(t.cid);if(e){let t=e.clone();t.status=1,await this.addItem(t)}await this.env.setStockRecord(t)}}async stockPurchase(t){var e=await this.env.getStockRecordById(t.itemNo);if(!e){let r=this.getItem(t.cid);if(r){t.price=r.stock.price;let i=r.clone();e=i.stock.hSum+t.sum,i.stock.hPrice=i.stock.hSum/e*i.stock.hPrice+t.sum/e*t.price|0,i.stock.hSum=e,i.stock.sum-=t.sum,i.status=1,await this.addItem(i)}await this.env.setStockRecord(t)}}async stockSend(t){if(!await this.env.getStockRecordById(t.itemNo)){let e=this.getItem(t.cid);if(e){let t=e.clone();t.status=1,await this.addItem(t)}await this.env.setStockRecord(t)}}async stockBonus(t){if(!await this.env.getStockRecordById(t.itemNo)){let e=this.getItem(t.cid);if(e){let r=e.clone();r.stock.hBonus+=t.price,await this.addItem(r)}await this.env.setStockRecord(t)}}async stockAds(t){if(!await this.env.getStockRecordById(t.itemNo)){let e=this.getItem(t.cid);if(e){let r=e.clone();r.stock.hAds+=t.price,await this.addItem(r)}await this.env.setStockRecord(t)}}async stockCancelBonus(t){if(await this.env.getStockRecordById(t.itemNo)||this.env.mode!=n.Block&&this.env.mode!=n.Wallet){let e=this.getItem(t.cid);if(e){let r=e.clone();r.stock.hBonus=Math.max(0,r.stock.hBonus-t.price),await this.addItem(r)}await this.env.unsetStockRecord(t)}}async stockCancelAds(t){if(await this.env.getStockRecordById(t.itemNo)||this.env.mode!=n.Block&&this.env.mode!=n.Wallet){let e=this.getItem(t.cid);if(e){let r=e.clone();r.stock.hAds=Math.max(0,r.stock.hAds-t.price),await this.addItem(r)}await this.env.unsetStockRecord(t)}}async stockCancelOffer(t){if(await this.env.getStockRecordById(t.itemNo)||this.env.mode!=n.Block&&this.env.mode!=n.Wallet){let e=this.getItem(t.cid);if(e){let r=e.clone();r.stock.sum=0,r.stock.price=0,r.stock.height=0,r.stock.hHeight==t.height&&(r.stock.hHeight=0),await this.addItem(r)}await this.env.unsetStockRecord(t)}}async stockCancelBid(t){(await this.env.getStockRecordById(t.itemNo)||this.env.mode!=n.Block&&this.env.mode!=n.Wallet)&&await this.env.unsetStockRecord(t)}async stockCancelAuction(t){if(await this.env.getStockRecordById(t.itemNo)||this.env.mode!=n.Block&&this.env.mode!=n.Wallet){let e=this.getItem(t.cid);if(e){let t=e.clone();t.status=1,await this.addItem(t)}await this.env.unsetStockRecord(t)}}async stockCancelPurchase(t){if(await this.env.getStockRecordById(t.itemNo)||this.env.mode!=n.Block&&this.env.mode!=n.Wallet){let r=this.getItem(t.cid);if(r){let i=r.clone();var e=i.stock.hSum-t.sum;i.stock.hPrice=i.stock.hSum/e*i.stock.hPrice-t.sum/e*t.price|0,i.stock.hSum=e,i.stock.sum+=t.sum,i.status=1,await this.addItem(i)}await this.env.unsetStockRecord(t)}}async stockCancelSend(t){if(await this.env.getStockRecordById(t.itemNo)||this.env.mode!=n.Block&&this.env.mode!=n.Wallet){let e=this.getItem(t.cid);if(e){let t=e.clone();t.status=1,await this.addItem(t)}await this.env.unsetStockRecord(t)}}}class m{constructor(t){this.cid=(t=t||{}).cid,this.name=t.name,this.ip=t.ip||"",this.cls=t.cls||"",this.grate=t.grate||0,this.current={hash:"",index:0,address:""},t.current&&(this.current.hash=t.current.hash,this.current.index=t.current.index,this.current.address=t.current.address),this.pubAddress=t.pubAddress||"",this.pubKey=t.pubKey||"",this.signMethod=t.signMethod||"secp256k1",this.register=t.register||"",this.stock=t.stock||{hHeight:0,hSum:0,hPrice:0,hBonus:0,hAds:0,sum:0,price:0,height:0},this.height=t.height,this.status=t.status||0}getSize(){var t=0;return(t+=h.sizeVarString(this.cid,"utf8"))+h.sizeVarString(this.name,"utf8")+h.sizeVarString(this.ip,"utf8")+h.sizeVarString(this.cls,"utf8")+4+h.sizeVarString(this.current.hash,"utf8")+4+h.sizeVarString(this.current.address,"utf8")+h.sizeVarString(this.pubAddress,"utf8")+h.sizeVarString(this.pubKey,"utf8")+h.sizeVarString(this.signMethod,"utf8")+h.sizeVarString(this.register,"hex")+4+4+4+8+8+4+4+4+4+4}toWriter(t){return t.writeVarString(this.cid,"utf8"),t.writeVarString(this.name,"utf8"),t.writeVarString(this.ip,"utf8"),t.writeVarString(this.cls,"utf8"),t.writeU32(this.grate),this.current||(this.current={hash:"",index:0,address:""}),t.writeVarString(this.current.hash,"utf8"),t.writeU32(this.current.index),t.writeVarString(this.current.address,"utf8"),t.writeVarString(this.pubAddress,"utf8"),t.writeVarString(this.pubKey,"utf8"),t.writeVarString(this.signMethod,"utf8"),t.writeVarString(this.register,"hex"),t.writeU32(this.stock.hHeight),t.writeU32(this.stock.hSum),t.writeU32(this.stock.hPrice),t.writeU64(this.stock.hBonus),t.writeU64(this.stock.hAds),t.writeU32(this.stock.sum),t.writeU32(this.stock.price),t.writeU32(this.stock.height),t.writeI32(this.height),t.writeI32(this.status),t}toRaw(){var t=this.getSize();return this.toWriter(new c(t)).render()}fromReader(t){return this.cid=t.readVarString("utf8"),this.name=t.readVarString("utf8"),this.ip=t.readVarString("utf8"),this.cls=t.readVarString("utf8"),this.grate=t.readU32(),this.current={},this.current.hash=t.readVarString("utf8"),this.current.index=t.readU32(),this.current.address=t.readVarString("utf8"),this.pubAddress=t.readVarString("utf8"),this.pubKey=t.readVarString("utf8"),this.signMethod=t.readVarString("utf8"),this.register=t.readVarString("hex"),this.stock={},this.stock.hHeight=t.readU32(),this.stock.hSum=t.readU32(),this.stock.hPrice=t.readU32(),this.stock.hBonus=t.readU64(),this.stock.hAds=t.readU64(),this.stock.sum=t.readU32(),this.stock.price=t.readU32(),this.stock.height=t.readU32(),this.height=t.readI32(),this.status=t.readI32(),this}fromRaw(t){return this.fromReader(new u(t))}clone(){return m.fromRaw(this.toRaw())}static fromReader(t){return(new m).fromReader(t)}static fromRaw(t){return(new m).fromRaw(t)}}class g{constructor(){this.height=0,this.txid="",this.type=0,this.cid="",this.sum=0,this.addr="",this.to="",this.price=0,this.seq=0,this.sn=a.hashInt(i())}get itemNo(){var t=0<=this.height?this.height:0;return l(this.type,this.cid,t,this.txid,this.seq,this.sn)}static itemNo(t,e,r,i,s,n){return l(t,e,r=0<=r?r:0,i,s,n)}static keyInfo(t){"string"==typeof t&&(t=Buffer.from(t,"hex"));var[t,e,r,i,s,n]=p(t);return{type:t,cid:e,height:r,txid:i,seq:s,sn:n}}getSize(){var t=0;return(t+=4)+h.sizeVarString(this.txid,"utf8")+4+h.sizeVarString(this.cid,"utf8")+4+h.sizeVarString(this.addr,"utf8")+h.sizeVarString(this.to,"utf8")+4+4+4}static fromObj(t){let e=new g;return e.height=t.h,e.txid=t.txid,e.type=t.body.data.type,e.cid=t.body.data.cid,e.sum=t.body.data.sum,e.addr=t.body.data.addr,e.to=t.body.data.to||"",e.price=t.body.data.price||0,e.seq=t.body.data.seq||0,e.sn=a.hashInt(t.sn),e}toWriter(t){return t.writeU32(this.height),t.writeVarString(this.txid,"utf8"),t.writeU32(this.type),t.writeVarString(this.cid,"utf8"),t.writeU32(this.sum),t.writeVarString(this.addr,"utf8"),t.writeVarString(this.to,"utf8"),t.writeU32(this.price),t.writeU32(this.seq),t.writeU32(this.sn),t}toRaw(){var t=this.getSize();return this.toWriter(new c(t)).render()}fromReader(t){return this.height=t.readU32(),this.txid=t.readVarString("utf8"),this.type=t.readU32(),this.cid=t.readVarString("utf8"),this.sum=t.readU32(),this.addr=t.readVarString("utf8"),this.to=t.readVarString("utf8"),this.price=t.readU32(),this.seq=t.readU32(),this.sn=t.readU32(),this}fromRaw(t){return this.fromReader(new u(t))}static get RecordType(){return d}clone(){return g.fromRaw(this.toRaw())}static fromReader(t){return(new g).fromReader(t)}static fromRaw(t){return(new g).fromRaw(t)}}class y{constructor(t){if(this.grate=(t=t||{}).grate||0,this.addrOfMaster=t.addrOfMaster||"",this.hSum=t.hSum||0,this.lords={},t.lords)for(var e of Object.keys(t.lords))this.lords[e]=t.lords[e];if(this.slist=[],t.slist)for(var r of t.slist)this.slist.push({sum:r.sum,addr:r.addr})}getSize(){let t=0;for(var e of(t=(t=(t+=4)+h.sizeVarString(this.addrOfMaster,"utf8"))+4+4,Object.keys(this.lords)))t=t+h.sizeVarString(e,"utf8")+4;for(var r of(t+=4,this.slist))t=(t+=4)+h.sizeVarString(r.addr,"utf8");return t}toWriter(t){for(var e of(t.writeU32(this.grate),t.writeVarString(this.addrOfMaster,"utf8"),t.writeU32(this.hSum),this.lords||(this.lords={}),t.writeU32(Object.keys(this.lords).length),Object.keys(this.lords)))t.writeVarString(e,"utf8"),t.writeU32(this.lords[e]);for(var r of(this.slist||(this.slist=[]),t.writeU32(this.slist.length),this.slist))t.writeU32(r.sum),t.writeVarString(r.addr,"utf8");return t}toRaw(){var t=this.getSize();return this.toWriter(new c(t)).render()}fromReader(t){this.grate=t.readU32(),this.addrOfMaster=t.readVarString("utf8"),this.hSum=t.readU32(),this.lords={};let e=t.readU32();for(let s=0;s<e;s++){var r=t.readVarString("utf8"),i=t.readU32();this.lords[r]=i}this.slist=[],e=t.readU32();for(let r=0;r<e;r++){var s=t.readU32(),n=t.readVarString("utf8");this.slist.push({addr:n,sum:s})}return this}fromRaw(t){return this.fromReader(new u(t))}clone(){return y.fromRaw(this.toRaw())}static fromReader(t){return(new y).fromReader(t)}static fromRaw(t){return(new y).fromRaw(t)}}f.cpSnap=y,f.stockItem=g,f.cpItem=m,t.exports=f},function(t,e,r){function i(t){return Object.prototype.toString.call(t)}e.isArray=function(t){return Array.isArray?Array.isArray(t):"[object Array]"===i(t)},e.isBoolean=function(t){return"boolean"==typeof t},e.isNull=function(t){return null===t},e.isNullOrUndefined=function(t){return null==t},e.isNumber=function(t){return"number"==typeof t},e.isString=function(t){return"string"==typeof t},e.isSymbol=function(t){return"symbol"==typeof t},e.isUndefined=function(t){return void 0===t},e.isRegExp=function(t){return"[object RegExp]"===i(t)},e.isObject=function(t){return"object"==typeof t&&null!==t},e.isDate=function(t){return"[object Date]"===i(t)},e.isError=function(t){return"[object Error]"===i(t)||t instanceof Error},e.isFunction=function(t){return"function"==typeof t},e.isPrimitive=function(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t},e.isBuffer=r(128).Buffer.isBuffer},function(t,e,r){"use strict";var i=r(132),s=Object.keys||function(t){var e,r=[];for(e in t)r.push(e);return r},n=((t=(t.exports=h,Object.create(r(86)))).inherits=r(49),r(257)),a=r(260);t.inherits(h,n);for(var o=s(a.prototype),c=0;c<o.length;c++){var u=o[c];h.prototype[u]||(h.prototype[u]=a.prototype[u])}function h(t){if(!(this instanceof h))return new h(t);n.call(this,t),a.call(this,t),t&&!1===t.readable&&(this.readable=!1),t&&!1===t.writable&&(this.writable=!1),this.allowHalfOpen=!0,t&&!1===t.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",l)}function l(){this.allowHalfOpen||this._writableState.ended||i.nextTick(p,this)}function p(t){t.end()}Object.defineProperty(h.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(h.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function(t){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=t,this._writableState.destroyed=t)}}),h.prototype._destroy=function(t,e){this.push(null),this.end(),i.nextTick(e,t)}},function(t,e){t.exports=require("fs")},function(t,e,r){"use strict";
207
+ */r=r(83),e.PROTOCOL_VERSION=70015,e.MIN_VERSION=70001,e.HEADERS_VERSION=31800,e.PONG_VERSION=6e4,e.BLOOM_VERSION=70011,e.COMPACT_VERSION=70014,e.COMPACT_WITNESS_VERSION=70015,e.services={NETWORK:1,GETUTXO:2,BLOOM:4,WITNESS:8},e.LOCAL_SERVICES=0|e.services.NETWORK|e.services.WITNESS,e.REQUIRED_SERVICES=0|e.services.NETWORK,e.USER_AGENT=`/${r.protocol}:${r.version}/`,e.MAX_MESSAGE=5e7,e.BAN_TIME=86400,e.BAN_SCORE=100},function(t,e,r){const i=r(143),{ContractType:s,ContractEnvType:n}=r(5),a=r(1);var o=r(28);const c=r(4),u=r(2),h=r(3);r(20);const{SR:l,SRR:p}=r(94),d={Offer:1,Purchase:2,Send:3,Bonus:4,Ads:5,Bid:6,Auction:7};class f extends o{constructor(t){super(),this.cpNameMap=new Map,this.cpIndexMap=new Map,this.env=t}async loadHistory(){var t;for(t of await this.env.getCps())this.set(t.cid,t),this.cpNameMap.set(t.name,t),this.cpIndexMap.set(i(t.cid),t)}async addItem(t){var e=new m(t);(t=(this.set(e.cid,e),this.getItem(t.cid)))&&this.removeNameIndex(t.name),this.cpNameMap.set(e.name,e),this.cpIndexMap.set(i(e.cid),e),await this.env.setCp(e)}async delItem(t){await this.env.delCp(t.cid),this.cpIndexMap.delete(i(t.cid)),this.removeNameIndex(t.name),this.delete(t.cid)}getItem(t){return this.has(t)?this.get(t):null}getItemByName(t){return this.cpNameMap.get(t)}getRecord(t){return(t=this.get(t))||null}removeNameIndex(t){this.cpNameMap.delete(t)}async canExecute(t){switch(t.oper){case s.cpRegister:if(this.cpIndexMap.has(i(t.cid))||this.has(t.cid)||this.cpNameMap.has(t.name))break;return!0;case s.cpChange:var e=this.getItem(t.cid),r=this.cpNameMap.get(t.name);if(e)return!r||r.cid===t.cid}return!1}getCPList(t,e){let r=[];if(0<t.length)r=this.where([["cid","include",t]]).paginate(50,1).records(),e.pageCount=this.pageNum;else{e.pageSize=e.pageSize||10;let t=e.cls?this.where([["cls",e.cls]]):this;r=t.paginate(e.pageSize,e.page).records(),e.pageCount=t.pageNum}return e.page=Math.min(e.page,e.pageCount),r}getCPListByName(t,e){let r=[];return r=(0<t.length?this.where([["name","include",t]]).paginate(50,1):this.paginate(10,page)).records(),e.pageCount=this.pageNum,e.page=Math.min(e.page,e.pageCount),r}async stockOffer(t){if(!await this.env.getStockRecordById(t.itemNo)){let e=this.getItem(t.cid);if(!e)throw new Error("Invalid CP Info.");let r=e.clone();r.stock.sum=t.sum,r.stock.price=t.price,r.stock.height=t.height,r.stock.hHeight||(r.stock.hHeight=t.height),await this.addItem(r),await this.env.setStockRecord(t)}}async stockBid(t){await this.env.getStockRecordById(t.itemNo)||await this.env.setStockRecord(t)}async stockAuction(t){if(!await this.env.getStockRecordById(t.itemNo)){let e=this.getItem(t.cid);if(e){let t=e.clone();t.status=1,await this.addItem(t)}await this.env.setStockRecord(t)}}async stockPurchase(t){var e=await this.env.getStockRecordById(t.itemNo);if(!e){let r=this.getItem(t.cid);if(r){t.price=r.stock.price;let i=r.clone();e=i.stock.hSum+t.sum,i.stock.hPrice=i.stock.hSum/e*i.stock.hPrice+t.sum/e*t.price|0,i.stock.hSum=e,i.stock.sum-=t.sum,i.status=1,await this.addItem(i)}await this.env.setStockRecord(t)}}async stockSend(t){if(!await this.env.getStockRecordById(t.itemNo)){let e=this.getItem(t.cid);if(e){let t=e.clone();t.status=1,await this.addItem(t)}await this.env.setStockRecord(t)}}async stockBonus(t){if(!await this.env.getStockRecordById(t.itemNo)){let e=this.getItem(t.cid);if(e){let r=e.clone();r.stock.hBonus+=t.price,await this.addItem(r)}await this.env.setStockRecord(t)}}async stockAds(t){if(!await this.env.getStockRecordById(t.itemNo)){let e=this.getItem(t.cid);if(e){let r=e.clone();r.stock.hAds+=t.price,await this.addItem(r)}await this.env.setStockRecord(t)}}async stockCancelBonus(t){if(await this.env.getStockRecordById(t.itemNo)||this.env.mode!=n.Block&&this.env.mode!=n.Wallet){let e=this.getItem(t.cid);if(e){let r=e.clone();r.stock.hBonus=Math.max(0,r.stock.hBonus-t.price),await this.addItem(r)}await this.env.unsetStockRecord(t)}}async stockCancelAds(t){if(await this.env.getStockRecordById(t.itemNo)||this.env.mode!=n.Block&&this.env.mode!=n.Wallet){let e=this.getItem(t.cid);if(e){let r=e.clone();r.stock.hAds=Math.max(0,r.stock.hAds-t.price),await this.addItem(r)}await this.env.unsetStockRecord(t)}}async stockCancelOffer(t){if(await this.env.getStockRecordById(t.itemNo)||this.env.mode!=n.Block&&this.env.mode!=n.Wallet){let e=this.getItem(t.cid);if(e){let r=e.clone();r.stock.sum=0,r.stock.price=0,r.stock.height=0,r.stock.hHeight==t.height&&(r.stock.hHeight=0),await this.addItem(r)}await this.env.unsetStockRecord(t)}}async stockCancelBid(t){(await this.env.getStockRecordById(t.itemNo)||this.env.mode!=n.Block&&this.env.mode!=n.Wallet)&&await this.env.unsetStockRecord(t)}async stockCancelAuction(t){if(await this.env.getStockRecordById(t.itemNo)||this.env.mode!=n.Block&&this.env.mode!=n.Wallet){let e=this.getItem(t.cid);if(e){let t=e.clone();t.status=1,await this.addItem(t)}await this.env.unsetStockRecord(t)}}async stockCancelPurchase(t){if(await this.env.getStockRecordById(t.itemNo)||this.env.mode!=n.Block&&this.env.mode!=n.Wallet){let r=this.getItem(t.cid);if(r){let i=r.clone();var e=i.stock.hSum-t.sum;i.stock.hPrice=i.stock.hSum/e*i.stock.hPrice-t.sum/e*t.price|0,i.stock.hSum=e,i.stock.sum+=t.sum,i.status=1,await this.addItem(i)}await this.env.unsetStockRecord(t)}}async stockCancelSend(t){if(await this.env.getStockRecordById(t.itemNo)||this.env.mode!=n.Block&&this.env.mode!=n.Wallet){let e=this.getItem(t.cid);if(e){let t=e.clone();t.status=1,await this.addItem(t)}await this.env.unsetStockRecord(t)}}}class m{constructor(t){this.cid=(t=t||{}).cid,this.name=t.name,this.ip=t.ip||"",this.cls=t.cls||"",this.grate=t.grate||0,this.current={hash:"",index:0,address:""},t.current&&(this.current.hash=t.current.hash,this.current.index=t.current.index,this.current.address=t.current.address),this.pubAddress=t.pubAddress||"",this.pubKey=t.pubKey||"",this.signMethod=t.signMethod||"secp256k1",this.register=t.register||"",this.stock=t.stock||{hHeight:0,hSum:0,hPrice:0,hBonus:0,hAds:0,sum:0,price:0,height:0},this.height=t.height,this.status=t.status||0}getSize(){var t=0;return(t+=h.sizeVarString(this.cid,"utf8"))+h.sizeVarString(this.name,"utf8")+h.sizeVarString(this.ip,"utf8")+h.sizeVarString(this.cls,"utf8")+4+h.sizeVarString(this.current.hash,"utf8")+4+h.sizeVarString(this.current.address,"utf8")+h.sizeVarString(this.pubAddress,"utf8")+h.sizeVarString(this.pubKey,"utf8")+h.sizeVarString(this.signMethod,"utf8")+h.sizeVarString(this.register,"hex")+4+4+4+8+8+4+4+4+4+4}toWriter(t){return t.writeVarString(this.cid,"utf8"),t.writeVarString(this.name,"utf8"),t.writeVarString(this.ip,"utf8"),t.writeVarString(this.cls,"utf8"),t.writeU32(this.grate),this.current||(this.current={hash:"",index:0,address:""}),t.writeVarString(this.current.hash,"utf8"),t.writeU32(this.current.index),t.writeVarString(this.current.address,"utf8"),t.writeVarString(this.pubAddress,"utf8"),t.writeVarString(this.pubKey,"utf8"),t.writeVarString(this.signMethod,"utf8"),t.writeVarString(this.register,"hex"),t.writeU32(this.stock.hHeight),t.writeU32(this.stock.hSum),t.writeU32(this.stock.hPrice),t.writeU64(this.stock.hBonus),t.writeU64(this.stock.hAds),t.writeU32(this.stock.sum),t.writeU32(this.stock.price),t.writeU32(this.stock.height),t.writeI32(this.height),t.writeI32(this.status),t}toRaw(){var t=this.getSize();return this.toWriter(new c(t)).render()}fromReader(t){return this.cid=t.readVarString("utf8"),this.name=t.readVarString("utf8"),this.ip=t.readVarString("utf8"),this.cls=t.readVarString("utf8"),this.grate=t.readU32(),this.current={},this.current.hash=t.readVarString("utf8"),this.current.index=t.readU32(),this.current.address=t.readVarString("utf8"),this.pubAddress=t.readVarString("utf8"),this.pubKey=t.readVarString("utf8"),this.signMethod=t.readVarString("utf8"),this.register=t.readVarString("hex"),this.stock={},this.stock.hHeight=t.readU32(),this.stock.hSum=t.readU32(),this.stock.hPrice=t.readU32(),this.stock.hBonus=t.readU64(),this.stock.hAds=t.readU64(),this.stock.sum=t.readU32(),this.stock.price=t.readU32(),this.stock.height=t.readU32(),this.height=t.readI32(),this.status=t.readI32(),this}fromRaw(t){return this.fromReader(new u(t))}clone(){return m.fromRaw(this.toRaw())}static fromReader(t){return(new m).fromReader(t)}static fromRaw(t){return(new m).fromRaw(t)}}class g{constructor(){this.height=0,this.txid="",this.type=0,this.cid="",this.sum=0,this.addr="",this.to="",this.price=0,this.seq=0,this.sn=a.hashInt(i())}get itemNo(){var t=0<=this.height?this.height:0;return l(this.type,this.cid,t,this.txid,this.seq,this.sn)}static itemNo(t,e,r,i,s,n){return l(t,e,r=0<=r?r:0,i,s,n)}static keyInfo(t){"string"==typeof t&&(t=Buffer.from(t,"hex"));var[t,e,r,i,s,n]=p(t);return{type:t,cid:e,height:r,txid:i,seq:s,sn:n}}getSize(){var t=0;return(t+=4)+h.sizeVarString(this.txid,"utf8")+4+h.sizeVarString(this.cid,"utf8")+4+h.sizeVarString(this.addr,"utf8")+h.sizeVarString(this.to,"utf8")+4+4+4}static fromObj(t){let e=new g;return e.height=t.h,e.txid=t.txid,e.type=t.body.data.type,e.cid=t.body.data.cid,e.sum=t.body.data.sum,e.addr=t.body.data.addr,e.to=t.body.data.to||"",e.price=t.body.data.price||0,e.seq=t.body.data.seq||0,e.sn=a.hashInt(t.sn),e}toWriter(t){return t.writeU32(this.height),t.writeVarString(this.txid,"utf8"),t.writeU32(this.type),t.writeVarString(this.cid,"utf8"),t.writeU32(this.sum),t.writeVarString(this.addr,"utf8"),t.writeVarString(this.to,"utf8"),t.writeU32(this.price),t.writeU32(this.seq),t.writeU32(this.sn),t}toRaw(){var t=this.getSize();return this.toWriter(new c(t)).render()}fromReader(t){return this.height=t.readU32(),this.txid=t.readVarString("utf8"),this.type=t.readU32(),this.cid=t.readVarString("utf8"),this.sum=t.readU32(),this.addr=t.readVarString("utf8"),this.to=t.readVarString("utf8"),this.price=t.readU32(),this.seq=t.readU32(),this.sn=t.readU32(),this}fromRaw(t){return this.fromReader(new u(t))}static get RecordType(){return d}clone(){return g.fromRaw(this.toRaw())}static fromReader(t){return(new g).fromReader(t)}static fromRaw(t){return(new g).fromRaw(t)}}class y{constructor(t){if(this.grate=(t=t||{}).grate||0,this.addrOfMaster=t.addrOfMaster||"",this.hSum=t.hSum||0,this.lords={},t.lords)for(var e of Object.keys(t.lords))this.lords[e]=t.lords[e];if(this.slist=[],t.slist)for(var r of t.slist)this.slist.push({sum:r.sum,addr:r.addr})}getSize(){let t=0;for(var e of(t=(t=(t+=4)+h.sizeVarString(this.addrOfMaster,"utf8"))+4+4,Object.keys(this.lords)))t=t+h.sizeVarString(e,"utf8")+4;for(var r of(t+=4,this.slist))t=(t+=4)+h.sizeVarString(r.addr,"utf8");return t}toWriter(t){for(var e of(t.writeU32(this.grate),t.writeVarString(this.addrOfMaster,"utf8"),t.writeU32(this.hSum),this.lords||(this.lords={}),t.writeU32(Object.keys(this.lords).length),Object.keys(this.lords)))t.writeVarString(e,"utf8"),t.writeU32(this.lords[e]);for(var r of(this.slist||(this.slist=[]),t.writeU32(this.slist.length),this.slist))t.writeU32(r.sum),t.writeVarString(r.addr,"utf8");return t}toRaw(){var t=this.getSize();return this.toWriter(new c(t)).render()}fromReader(t){this.grate=t.readU32(),this.addrOfMaster=t.readVarString("utf8"),this.hSum=t.readU32(),this.lords={};let e=t.readU32();for(let s=0;s<e;s++){var r=t.readVarString("utf8"),i=t.readU32();this.lords[r]=i}this.slist=[],e=t.readU32();for(let r=0;r<e;r++){var s=t.readU32(),n=t.readVarString("utf8");this.slist.push({addr:n,sum:s})}return this}fromRaw(t){return this.fromReader(new u(t))}clone(){return y.fromRaw(this.toRaw())}static fromReader(t){return(new y).fromReader(t)}static fromRaw(t){return(new y).fromRaw(t)}}f.cpSnap=y,f.stockItem=g,f.cpItem=m,t.exports=f},function(t,e,r){function i(t){return Object.prototype.toString.call(t)}e.isArray=function(t){return Array.isArray?Array.isArray(t):"[object Array]"===i(t)},e.isBoolean=function(t){return"boolean"==typeof t},e.isNull=function(t){return null===t},e.isNullOrUndefined=function(t){return null==t},e.isNumber=function(t){return"number"==typeof t},e.isString=function(t){return"string"==typeof t},e.isSymbol=function(t){return"symbol"==typeof t},e.isUndefined=function(t){return void 0===t},e.isRegExp=function(t){return"[object RegExp]"===i(t)},e.isObject=function(t){return"object"==typeof t&&null!==t},e.isDate=function(t){return"[object Date]"===i(t)},e.isError=function(t){return"[object Error]"===i(t)||t instanceof Error},e.isFunction=function(t){return"function"==typeof t},e.isPrimitive=function(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t},e.isBuffer=r(128).Buffer.isBuffer},function(t,e,r){"use strict";var i=r(132),s=Object.keys||function(t){var e,r=[];for(e in t)r.push(e);return r},n=((t=(t.exports=h,Object.create(r(86)))).inherits=r(49),r(257)),a=r(260);t.inherits(h,n);for(var o=s(a.prototype),c=0;c<o.length;c++){var u=o[c];h.prototype[u]||(h.prototype[u]=a.prototype[u])}function h(t){if(!(this instanceof h))return new h(t);n.call(this,t),a.call(this,t),t&&!1===t.readable&&(this.readable=!1),t&&!1===t.writable&&(this.writable=!1),this.allowHalfOpen=!0,t&&!1===t.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",l)}function l(){this.allowHalfOpen||this._writableState.ended||i.nextTick(p,this)}function p(t){t.end()}Object.defineProperty(h.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(h.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function(t){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=t,this._writableState.destroyed=t)}}),h.prototype._destroy=function(t,e){this.push(null),this.end(),i.nextTick(e,t)}},function(t,e){t.exports=require("fs")},function(t,e,r){"use strict";
208
208
  /*!
209
209
  * headers.js - headers object for vallnet
210
210
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -289,7 +289,7 @@ const i=r(21).opcodes;function s(t){let e=null;var r=s.list[t.type];return new(r
289
289
  /*!
290
290
  * wallet.js - wallet object for vallnet
291
291
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
292
- */const i=r(0);var s=r(16);const n=r(319),a=r(15),o=r(1),c=r(3),u=r(35),h=r(201),l=r(120).sortWithSeq,p=r(6),d=r(95),f=r(2),m=r(4),g=r(70),y=r(345);r(226);const v=r(111),b=r(73),w=r(12),x=r(60),k=r(17),S=r(227),E=r(124),_=r(26),A=r(161),R=r(346),I=r(65),j=r(28),C=r(27),P=r(7),O=r(315),T=r(32),F=E.Mnemonic,{opcodes:B,hashType:N}=r(21),D=r(169),L=r(77),H=r(78),z=r(143),M=r(46),U=r(19),q=r(43),V=r(53),{NotifyMsg:K,OrderData:W,ContractStatus:G,ContractType:$}=r(5),Y=r(38).VerifyError,X=r(85).stockItem;r(323).AuditItem;const J=r(157).ErItem,Z=r(158).ErAbolishItem,Q=r(241).EnchancementItem,tt=r(159).X509Cert,et=r(160).X509Abolish,rt=r(29),it=r(69),st=r(59),nt=r(83);class at extends s{constructor(t,e){super(),i(t,"DB required."),this.db=t,this.network=t.network,this.logger=t.logger,this.readLock=new h,this.writeLock=new u,this.sendLock=new u,this.indexCache=new I(1e4),this.accountCache=new I(1e4),this.pathCache=new I(1e5),this.current=null,this.wid=0,this.id=null,this.initialized=!1,this.watchOnly=!1,this.accountDepth=0,this.token=c.ZERO_HASH,this.tokenDepth=0,this.master=new R,this.txdb=new y(this),this.account=null,e&&this.fromOptions(e)}fromOptions(t){let e,r,s=t.master;return s?("string"==typeof s&&(s=E.PrivateKey.fromBase58(s,this.network)),i(E.isPrivate(s),"Must create wallet with hd private key.")):(r=new F(t.mnemonic),s=E.fromMnemonic(r,this.network)),i(s.network===this.network,"Network mismatch for master key."),this.master.fromKey(s,r),null!=t.wid&&(i(o.isU32(t.wid)),this.wid=t.wid),t.id&&(i(b.isName(t.id),"Bad wallet ID."),e=t.id),null!=t.initialized&&(i("boolean"==typeof t.initialized),this.initialized=t.initialized),null!=t.watchOnly&&(i("boolean"==typeof t.watchOnly),this.watchOnly=t.watchOnly),null!=t.accountDepth&&(i(o.isU32(t.accountDepth)),this.accountDepth=t.accountDepth),t.token&&(i(Buffer.isBuffer(t.token)),i(32===t.token.length),this.token=t.token),e=e||this.getID(),this.id=e,this}static fromOptions(t,e){return new at(t).fromOptions(e)}async init(t){var e=t.passphrase;i(!this.initialized),this.initialized=!0,e&&await this.master.encrypt(e),t=await this._createAccount(t,e);i(t),this.account=t,this.logger.info("Wallet initialized (%s).",this.id),await this.txdb.open()}async open(){i(this.initialized);var t=await this.getAccount(0);if(!t)throw new Error("Default account not found.");this.account=t,this.logger.info("Wallet opened (%s).",this.id),await this.txdb.open()}async ensureNotifyKey(){this.notifyKey||(await this.ensureAccount({name:"alliance",witness:!0}),this.notifyKey=await this.createReceive("alliance",1,this.master),this.notifyAddress=this.notifyKey.getAddress("string"))}async createAllianceInfo(t,e,r){let i={alliancename:t,nodeid:e};return t?(i.alliancePrivateKey=p.hash256(Buffer.concat([Buffer.from(t),this.master.key.privateKey])),r?(i.prv=Buffer.alloc(0),i.pub=Buffer.from(r,"hex"),i.awardAddress=w.fromWitnessPubkeyhash(p.hash160(i.pub),this.network.type).toString(this.network.type),i.mnemonic=new F):(r=p.hash256(Buffer.concat([Buffer.from(t+"-"+e),this.master.key.privateKey])),i.mnemonic=new F({entropy:r,language:this.master.mnemonic.language,passphrase:this.master.mnemonic.passphrase}),i.prv=p.hash256(Buffer.from(i.mnemonic.toSeed().toString("hex"))),i.pub=j.publicKeyCreate(i.prv,!0),t=R.fromKey(E.fromMnemonic(i.mnemonic),this.network.type).key.deriveAccount(44,0).derive(9).derive(1),i.awardAddress=w.fromWitnessPubkeyhash(p.hash160(t.publicKey),this.network.type).toString(this.network.type))):(e=await this.createReceive("default",1,this.master),i.prv=e.privateKey,i.pub=e.publicKey,i.awardAddress=w.fromWitnessPubkeyhash(p.hash160(i.pub),this.network.type).toString(this.network.type),i.mnemonic=new F),i.address=w.fromWitnessPubkeyhash(p.hash160(i.pub),this.network.type).toString(),i}async destroy(){const t=await this.writeLock.lock(),e=await this.sendLock.lock();try{this.db.unregister(this),await this.master.destroy(),this.readLock.destroy(),this.writeLock.destroy(),this.sendLock.destroy()}finally{e(),t()}}async addSharedKey(t,e){const r=await this.writeLock.lock();try{return await this._addSharedKey(t,e)}finally{r()}}async _addSharedKey(t,e){e||(e=t,t=null);const r=await this.getAccount(t=null==t?0:t);if(!r)throw new Error("Account not found.");let i;this.start();try{i=await r.addSharedKey(e)}catch(t){throw this.drop(),t}return await this.commit(),i}async removeSharedKey(t,e){const r=await this.writeLock.lock();try{return await this._removeSharedKey(t,e)}finally{r()}}async _removeSharedKey(t,e){e||(e=t,t=null);const r=await this.getAccount(t=null==t?0:t);if(!r)throw new Error("Account not found.");let i;this.start();try{i=await r.removeSharedKey(e)}catch(t){throw this.drop(),t}return await this.commit(),i}async setPassphrase(t,e){t&&await this.decrypt(t),e&&await this.encrypt(e)}async encrypt(t){const e=await this.writeLock.lock();try{return await this._encrypt(t)}finally{e()}}async _encrypt(t){t=await this.master.encrypt(t,!0),this.start();try{await this.db.encryptKeys(this,t)}catch(e){throw d(t),this.drop(),e}d(t),this.save(),await this.commit()}async decrypt(t){const e=await this.writeLock.lock();try{return await this._decrypt(t)}finally{e()}}async _decrypt(t){t=await this.master.decrypt(t,!0),this.start();try{await this.db.decryptKeys(this,t)}catch(e){throw d(t),this.drop(),e}d(t),this.save(),await this.commit()}async rename(t){const e=await this.writeLock.lock();try{return await this.db.rename(this,t)}finally{e()}}async writeBalanceLog(t){const e=await this.writeLock.lock();try{return await this.db.writeBalanceLog(this,t)}finally{e()}}async renameAccount(t,e){const r=await this.writeLock.lock();try{return await this._renameAccount(t,e)}finally{r()}}async _renameAccount(t,e){if(!b.isName(e))throw new Error("Bad account name.");var r=await this.getAccount(t);if(!r)throw new Error("Account not found.");if(0===r.accountIndex)throw new Error("Cannot rename default account.");if(await this.hasAccount(e))throw new Error("Account name not available.");t=r.name,this.start(),this.db.renameAccount(r,e),await this.commit(),this.indexCache.remove(t),t=this.pathCache.values();for(const i of t)i.account===r.accountIndex&&(i.name=e)}async lock(){const t=await this.writeLock.lock(),e=await this.sendLock.lock();try{await this.master.lock()}finally{e(),t()}}unlock(t,e){return this.master.unlock(t,e)}getID(){i(this.master.key,"Cannot derive id.");var t=this.master.key.derive(44);const e=new m(37);e.writeBytes(t.publicKey),e.writeU32(this.network.magic),t=p.hash160(e.render());const r=new m(27);return r.writeU8(3),r.writeU8(190),r.writeU8(4),r.writeBytes(t),r.writeChecksum(),g.encode(r.render())}async createAccount(t,e){const r=await this.writeLock.lock();try{return await this._createAccount(t,e)}finally{r()}}async _createAccount(t,e){let r,s,n=t.name,a=(n=n||this.accountDepth.toString(10),0);if(0!=this.accountDepth&&(a=o.hashInt(n)),await this.hasAccountIndex(a))throw new Error("Account Index Conflict.");if(await this.hasAccount(n))throw new Error("Account already exists.");if(await this.unlock(e),this.watchOnly&&t.accountKey){if("string"==typeof(r=t.accountKey)&&(r=E.PublicKey.fromBase58(r,this.network)),!E.isPublic(r))throw new Error("Must add HD public keys to watch only wallet.");i(r.network===this.network,"Network mismatch for watch only key.")}else i(this.master.key),r=(r=this.master.key.deriveAccount(44,a)).toPublic();e={wid:this.wid,id:this.id,name:0===this.accountDepth?"default":n,witness:t.witness,watchOnly:this.watchOnly,accountKey:r,accountIndex:a,type:t.type,m:t.m,n:t.n,keys:t.keys},this.start();try{(s=A.fromOptions(this.db,e)).wallet=this,await s.init()}catch(t){throw this.drop(),t}return this.logger.info("Created account %s/%s/%d.",s.id,s.name,s.accountIndex),this.accountDepth++,this.save(),await this.commit(),s}async ensureAccount(t,e){var r=t.name;return(r=await this.getAccount(r))||this.createAccount(t,e)}getAccounts(){return this.db.getAccounts(this.wid)}getAddressHashes(t){return null!=t?this.getAccountHashes(t):this.db.getWalletHashes(this.wid)}async getAccountHashes(t){return t=await this.ensureIndex(t,!0),this.db.getAccountHashes(this.wid,t)}async getAccount(t){if(this.account&&(null==t||"default"===t||"number"==typeof t&&0===t||"string"==typeof t&&0===t.length))return this.account;if(-1===(t=await this.getAccountIndex(t)))return null;const e=await this.readLock.lock(t);try{return await this._getAccount(t)}finally{e()}}async _getAccount(t){var e=this.accountCache.get(t);if(e)return e;const r=await this.db.getAccount(this.wid,t);return r?(r.wallet=this,r.wid=this.wid,r.id=this.id,r.watchOnly=this.watchOnly,await r.open(),this.accountCache.set(t,r),r):null}async getAccountIndex(t){var e;return null==t?-1:"number"==typeof t?t:null!=(e=this.indexCache.get(t))?e:-1===(e=await this.db.getAccountIndex(this.wid,t))?-1:(this.indexCache.set(t,e),e)}async getAccountName(t){var e;return"string"==typeof t?t:(e=this.accountCache.get(t))?e.name:this.db.getAccountName(this.wid,t)}async hasAccount(t){return-1!==(t=await this.getAccountIndex(t))&&(!!this.accountCache.has(t)||this.db.hasAccount(this.wid,t))}async hasAccountIndex(t){return!!this.accountCache.has(t)||this.db.hasAccount(this.wid,t)}createReceive(t,e=0,r=null){return this.createKey(t,0,e,r)}createChange(t){return this.createKey(t,1)}createNested(t){return this.createKey(t,2)}async createKey(t,e,r=0,i=null){const s=await this.writeLock.lock();try{return await this._createKey(t,e,r,i)}finally{s()}}async _createKey(t,e,r=0,i=null){null==e&&(e=t,t=null);const s=await this.getAccount(t=t||0);if(!s)throw new Error("Account not found.");let n;this.start();try{n=await s.createKey(e,r,i)}catch(t){throw this.drop(),t}return await this.commit(),n}async deriveKey(t,e,r,i=null){let s=null;const n=await this.writeLock.lock();try{this.start(),s=await this._deriveKey(t,e,r,i),await this.commit()}catch(t){throw this.drop(),t}finally{n()}return s}async _deriveKey(t,e,r=0,i=null){null==e&&(e=t,t=null),t=t||0,t=parseInt(t);const s=await this.getAccount(t);if(s)return t=await s.deriveKey(e,r,i),await s.saveKey(t),t;throw new Error("Account not found.")}save(){return this.db.save(this)}async saveAccount(t){const e=await this.writeLock.lock();try{this.start(),t._save(),await this.commit(),0==t.accountIndex&&(this.account=t)}finally{e()}}start(){return this.db.start(this)}drop(){return this.db.drop(this)}clear(){return this.db.clear(this)}commit(){return this.db.commit(this)}async hasAddress(t){return t=w.getHash(t,"hex"),null!=await this.getPath(t)}async getPath(t){const e=await this.readPath(t);return e?(e.name=await this.getAccountName(e.account),i(e.name),this.pathCache.set(e.hash,e),e):null}async readPath(t){t=w.getHash(t,"hex");var e=this.pathCache.get(t);if(e)return e;const r=await this.db.getPath(this.wid,t);return r?(r.id=this.id,r):null}async hasPath(t){return t=w.getHash(t,"hex"),!!this.pathCache.has(t)||this.db.hasPath(this.wid,t)}async getPaths(t){if(null!=t)return this.getAccountPaths(t);const e=[];for(const t of await this.db.getWalletPaths(this.wid))t.id=this.id,t.name=await this.getAccountName(t.account),i(t.name),this.pathCache.set(t.hash,t),e.push(t);return e}async getAccountPaths(t){var e=await this.ensureIndex(t,!0),r=await this.getAccountHashes(e),s=await this.getAccountName(t);i(s);const n=[];for(const t of r){const r=await this.readPath(t);i(r),i(r.account===e),r.name=s,this.pathCache.set(r.hash,r),n.push(r)}return n}async importKey(t,e,r){const i=await this.writeLock.lock();try{return await this._importKey(t,e,r)}finally{i()}}async _importKey(t,e,r){if(t&&"object"==typeof t&&(r=e,e=t,t=null),null==t&&(t=0),i(e.network===this.network,"Network mismatch for key."),this.watchOnly){if(e.privateKey)throw new Error("Cannot import privkey into watch-only wallet.")}else if(!e.privateKey)throw new Error("Cannot import pubkey into non watch-only wallet.");var s=e.getHash("hex");if(await this.getPath(s))throw new Error("Key already exists.");const n=await this.getAccount(t);if(!n)throw new Error("Account not found.");if(n.type!==A.types.PUBKEYHASH)throw new Error("Cannot import into non-pkh account.");await this.unlock(r);const a=S.fromRing(n,e).toPath();this.master.encrypted&&(a.data=this.master.encipher(a.data,a.hash),i(a.data),a.encrypted=!0),this.start();try{await n.savePath(a)}catch(t){throw this.drop(),t}await this.commit()}async importAddress(t,e){const r=await this.writeLock.lock();try{return await this._importAddress(t,e)}finally{r()}}async _importAddress(t,e){if(e||(e=t,t=null),null==t&&(t=0),e.network!==this.network)throw new Error("Network mismatch for address.");if(!this.watchOnly)throw new Error("Cannot import address into non watch-only wallet.");if(await this.getPath(e))throw new Error("Address already exists.");const r=await this.getAccount(t);if(!r)throw new Error("Account not found.");if(r.type!==A.types.PUBKEYHASH)throw new Error("Cannot import into non-pkh account.");t=v.fromAddress(r,e),this.start();try{await r.savePath(t)}catch(t){throw this.drop(),t}await this.commit()}async fund(t,e){const r=await this.writeLock.lock();try{return await this._fund(t,e)}finally{r()}}async _fund(t,e){if(e=e||{},!this.initialized)throw new Error("Wallet is not initialized.");if(this.watchOnly)throw new Error("Cannot fund from watch-only wallet.");let r;if(null!=e.account){if(!(r=await this.getAccount(e.account)))throw new Error("Account not found.")}else r=this.account;if(!r.initialized)throw new Error("Account is not initialized.");let s,n=e.rate;return null==n&&(n=await this.db.estimateFee(e.blocks)),s=e.smart?await this.getSmartCoins(r.name):(s=await this.getCoins(r.name),this.txdb.filterConserved(s)),await t.fund(s,{allowPreInput:e.allowPreInput,noChange:e.noChange,selection:e.selection,round:e.round,depth:e.depth,hardFee:e.hardFee,subtractFee:e.subtractFee,subtractIndex:e.subtractIndex,changeAddress:r.change.getAddress(),height:this.db.curHeight,rate:n,maxFee:e.maxFee,estimate:t=>this.estimateSize(t),network:this.network}),!e.allowInfiniteFee&&e.noChange&&i(t.getFee()<=O.MAX_FEE,"TX exceeds MAX_FEE."),s}async getAccountByAddress(t){return t=w.getHash(t,"hex"),(t=await this.getPath(t))?this.getAccount(t.account):null}async estimateSize(t){var e=P.WITNESS_SCALE_FACTOR,r=w.fromScript(t);if(!r)return-1;var i=await this.getAccountByAddress(r);if(!i)return-1;let s=0;if(t.isScripthash()&&i.witness)switch(i.type){case A.types.PUBKEYHASH:s=4*(s+23);break;case A.types.MULTISIG:s=4*(s+35)}switch(i.type){case A.types.PUBKEYHASH:s=s+74+34;break;case A.types.MULTISIG:s=(s=(s=(s=(s+=1)+74*i.m)+3+1)+34*i.n)+1+1}return i.witness?s=((s+=1)+e-1)/e|0:s+=c.sizeVarint(s),s}async createTX(t){var e=t.outputs;const r=new x;i(Array.isArray(e),"Outputs must be an array."),i(0<e.length,"No outputs available."),t.comment&&("object"==typeof t.comment&&(t.comment=JSON.stringify(t.comment)),r.outputs.push(_.fromScript(k.createScript(Buffer.from(t.comment),k.types.NULLDATA),0)));for(const t of e){const e=new _(t),i=e.getAddress();if(e.isDust())throw new Error("Output is dust.");if(0<e.value){if(!i)throw new Error("Cannot send to unknown address.");if(i.isNull())throw new Error("Cannot send to null address.")}r.outputs.push(e)}let s=null;if(t.inputs)for(const e of t.inputs){var n=await this.getTX(e.hash);if(n){let i=V.fromTX(n.tx,e.index,-1,0);i&&(s=i.getAddress(),t.allowPreInput=!0,r.addCoin(i))}}else await this.fund(r,t);if(s){const t=new _;t.value=r.getFee()-O.MIN_FEE,t.script.fromAddress(s),r.outputs.push(t),r.changeIndex=r.outputs.length-1}if(!1!==t.sort&&r.sortMembers(),null!=t.locktime&&r.setLocktime(t.locktime),i(r.isSane(),"TX failed sanity check."),i(r.verifyInputs(this.db.curHeight+1),"TX failed context check."),0===await this.template(r))throw new Error("Templating failed.");return r}async send(t,e){const r=await this.sendLock.lock();try{return await this._send(t,e)}finally{r()}}async _send(t,e){return e&&(t.account=e),e=await this.createTX(t,!0),await this.sign(e),this.sendMTX(e,{sendafter:t.sendafter})}async sendMTX(t,e={}){if(!t.isSigned())throw new Error("TX could not be fully signed.");const r=t.toTX();if(r.getSigopsCost(t.view)>C.MAX_TX_SIGOPS_COST)throw new Error("TX exceeds policy sigops.");if(r.getWeight()>C.MAX_TX_WEIGHT)throw new Error("TX exceeds policy weight.");return e.sendafter||(this.logger.debug("Sending wallet tx (%s): %s",this.id,r.txid()),await this.db.addTX(r),await this.db.send(r)),r}async resend(){var t=await this.getPending();0<t.length&&this.logger.info("Rebroadcasting %d transactions.",t.length);const e=[];for(const r of t)e.push(r.tx);for(const t of await l(e,this.db))await this.db.send(t);return e}async deriveInputs(t){var e;i(t.mutable);const r=[];for(const i of await this.getInputPaths(t)){const t=await this.getAccount(i.account);t&&(e=t.derivePath(i,this.master))&&r.push(e)}return r}async getKey(t){if(t=w.getHash(t,"hex",this.network.type),!(t=await this.getPath(t)))return null;const e=await this.getAccount(t.account);return e?e.derivePath(t,this.master):null}async exportToFile(t){if(!st.unsupported){var e=await this.db.getTip(),r=o.date();let n=1,a="",c=[o.fmt("# Wallet Dump created by %s %s",nt.protocol,nt.version),o.fmt("# * Created on %s",r),o.fmt("# * Best block at time of backup was %d (%s).",e.height,o.revHex(e.hash)),o.fmt("# * File: %s",t.file),""];var i;e=o.fmt("W %s wid= %s",this.toRaw().toString("base64"),this.wid),e=(c.push(e),await this.getAccounts());for(const t of e){const e=await this.getAccount(t);var s=o.fmt("C %s name= %s index= %d",e.toRaw().toString("base64"),e.name,e.accountIndex);c.push(s)}for(const e of await this.getAddressHashes()){const s=await this.getPrivateKey(e);s&&(i=s.getAddress("string"),i=o.fmt("A %s %s label= account= %s branch= %s index= %s addr= %s",s.toSecret(),r,s.account,s.branch,s.index,i),c.push(i),1e5<c.length&&(a=c.join("\n"),await st.writeFile(`${t.file}-${n++}.txt`,a,"utf8"),c=[]))}c.push(""),c.push("# End of dump"),c.push(""),a=c.join("\n"),await st.writeFile(`${t.file}-${n++}.txt`,a,"utf8")}}async getPrivateKey(t,e){if(t=w.getHash(t,"hex"),!(t=await this.getPath(t)))return null;const r=await this.getAccount(t.account);return r?(await this.unlock(e),(e=r.derivePath(t,this.master)).privateKey?e:null):null}async getInputPaths(t){if(i(t.mutable),!t.hasCoins())throw new Error("Not all coins available.");const e=[];for(const i of t.getInputHashes("hex")){var r=await this.getPath(i);r&&e.push(r)}return e}async getOutputPaths(t){const e=[];for(const i of t.getOutputHashes("hex")){var r=await this.getPath(i);r&&e.push(r)}return e}async setLookahead(t,e){const r=await this.writeLock.lock();try{return this._setLookahead(t,e)}finally{r()}}async _setLookahead(t,e){null==e&&(e=t,t=null);const r=await this.getAccount(t=null==t?0:t);if(!r)throw new Error("Account not found.");this.start();try{await r.setLookahead(e)}catch(t){throw this.drop(),t}await this.commit()}async syncOutputDepth(t){const e=new Map;for(const i of t.outputs){var r=i.path;r&&-1!==r.index&&(e.has(r.account)||e.set(r.account,[]),e.get(r.account).push(r))}const s=[];for(var[n,a]of e){let t=-1,e=-1,r=-1;for(const i of a)switch(i.branch){case 0:i.index>t&&(t=i.index);break;case 1:i.index>e&&(e=i.index);break;case 2:i.index>r&&(r=i.index)}t+=2,e+=2,r+=2;const o=await this.getAccount(n);i(o),(a=await o.syncDepth(t,e,r))&&s.push(a)}return s}async getRedeem(t){"string"==typeof t&&(t=Buffer.from(t,"hex"));const e=await this.getKey(t.toString("hex"));return e?e.getRedeem(t):null}async template(t){var e=await this.deriveInputs(t);return t.sign(e)}async getOrderList(t,e){let r=[],i=new rt,s=((await this.getHistory(e||"default")).reduce((t,e)=>{let{tx:i,hash:s,height:n}=e;if(i.outputs[0].getReturnType(B.OP_RETURN))try{var a=JSON.parse(i.outputs[0].script.code[1].toString());if(a&&a.oper==$.payOrder){let e=W.fromJson(a);e.hash=s,e.height=n,t.set(""+e.cid+e.sn,e),r.push(e.cid)}}catch(e){}return t},i),i.query(t));return await this.db.flushCP(r),s.list.map(t=>{t.cp=this.db.cpList.getItem(t.cid)}),s}async propCreate(t,e){const r=new x;for(var s of t){var n=await this.ensureCp(s.cid,!0);n&&s.cid!=this.network.genesisId&&(s.gold=(0|s.gold)>>>0,s.gold<P.MINPROPVALUE||(s.pid||(s.pid=z()),r.propCreate(n.current.address,s),s.index=r.outputs.length-1))}if(0<r.outputs.length){e?await this.fund(r,{account:e}):await this.fund(r),await this.sign(r);let s=r.commit();for(var a of(await this.db.addTX(s[0]),await this.db.send(s[0]),i(s[0].verify(s[1],k.flags.STANDARD_VERIFY_FLAGS)),t))a.hash=s[0].hash("hex"),a.txid=s[0].txid();return s}return[]}async stockAddress(t,e){return await this.ensureAccount({name:e,witness:!0}),(await this.createReceive(e,o.hashInt(t),this.master)).getAddress()}async stockOffer(t,e,r,s){i(!!t),i(!!e),i(!!r),e=(0|e)>>>0,r=(0|r)>>>0;var n=await this.ensureCp(t);let a=await this.getKey(n.current.address);if(i(!!a),s&&s!==a.name)throw new L(H.errors.TYPE_ERROR,"illegal account");t=a.signData({cid:t,type:X.RecordType.Offer,sum:e,price:r});const o=new x;o.outputs.push(_.fromScript(t.data.addr,.05*e*r));let c=new K($.stock,z(),this.db.curHeight,t);e=_.fromScript(k.createScript(c.toRaw(),k.types.NULLDATA),0),o.outputs.push(e),s?await this.fund(o,{account:s}):await this.fund(o),o.outputs.shift(),await this.sign(o);let u=o.commit();return i(u[0].verify(u[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.verifyClsTx(u[0]),await this.db.send(u[0]),c.hash=u[0].hash("hex"),c.height=-1,c.cp=n,c}async stockPurchase(t,e,r){if(i(!!t),i(!!e),(e=(0|e)>>>0)<P.STOCK_TRADE_SINGLE||e>P.STOCK_MAX_TRADE_SINGLE)throw new L(H.errors.TYPE_ERROR,"Invalid Stock Amount.");var s=await this.ensureCp(t);t={type:X.RecordType.Purchase,cid:t,uid:r,seq:0,to:s.current.address,sum:e},await this.addStockAccountSeq(t),t=await this.tokenCreate(t,r);const n=new x;let a=new K($.stock,z(),this.db.curHeight,t);t=_.fromScript(k.createScript(a.toRaw(),k.types.NULLDATA),0),n.outputs.push(t),n.outputs.push(_.fromScript(s.current.address,e*s.stock.price)),r?await this.fund(n,{account:r}):await this.fund(n),await this.sign(n);let o=n.commit();return i(o[0].verify(o[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.verifyClsTx(o[0]),await this.db.send(o[0]),a.hash=o[0].hash("hex"),a.height=-1,a.cp=s,a}async stockPurchaseTo(t,e,r,s){if(i(!!t),i(!!e),(e=(0|e)>>>0)<P.STOCK_TRADE_SINGLE||e>P.STOCK_MAX_TRADE_SINGLE)throw new L(H.errors.TYPE_ERROR,"Invalid Stock Amount.");var n=await this.ensureCp(t);t={type:X.RecordType.Purchase,cid:t,uid:r,seq:0,to:n.current.address,sum:e},await this.addStockAccountSeq(t),t=await this.tokenCreate(t,r);const a=new x;let o=new K($.stock,z(),this.db.curHeight,t);r=_.fromScript(k.createScript(o.toRaw(),k.types.NULLDATA),0),a.outputs.push(r),a.outputs.push(_.fromScript(n.current.address,e*n.stock.price)),s?await this.fund(a,{account:s}):await this.fund(a),await this.sign(a);let c=a.commit();return i(c[0].verify(c[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.verifyClsTx(c[0]),await this.db.send(c[0]),o.hash=c[0].hash("hex"),o.height=-1,o.cp=n,o}async stockSend(t,e,r,s,n){i(!!t),i(!!e),e=(0|e)>>>0;var a=await this.ensureCp(t,!0);if(!a)return null;t={type:X.RecordType.Send,cid:t,uid:s,seq:0,sum:e,to:r},await this.addStockAccountSeq(t),e=await this.tokenCreate(t,s,n);const o=new x;let c=new K($.stock,z(),this.db.curHeight,e);r=_.fromScript(k.createScript(c.toRaw(),k.types.NULLDATA),0),o.outputs.push(r),s?await this.fund(o,{account:s}):await this.fund(o),await this.sign(o);let u=o.commit();return i(u[0].verify(u[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.verifyClsTx(u[0]),await this.db.send(u[0]),c.hash=u[0].hash("hex"),c.height=-1,c.cp=a,c}async stockBid(t,e,r,s,n){i(!!t),i(!!e),i(!!r),e=(0|e)>>>0,r=(0|r)>>>0;var a=await this.ensureCp(t,!0);if(!a)return null;t={type:X.RecordType.Bid,cid:t,uid:s,seq:0,sum:e,price:r},await this.addStockAccountSeq(t),t=await this.tokenCreate(t,s,n);const o=new x;o.outputs.push(_.fromScript(t.data.addr,.05*e*r));let c=new K($.stock,z(),this.db.curHeight,t);n=_.fromScript(k.createScript(c.toRaw(),k.types.NULLDATA),0),o.outputs.push(n),s?await this.fund(o,{account:s}):await this.fund(o),o.outputs.shift(),await this.sign(o);let u=o.commit();return i(u[0].verify(u[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.verifyClsTx(u[0]),await this.db.send(u[0]),c.hash=u[0].hash("hex"),c.height=-1,c.cp=a,c}async stockAuction(t,e,r,s,n,a){i(!!t),i(!!e),i(!!r);var o=await this.ensureCp(t,!0);if(!o)return null;r=(0|r)>>>0,t={type:X.RecordType.Auction,cid:t,to:e,uid:n,seq:0,sum:r,price:s},await this.addStockAccountSeq(t),t=await this.tokenCreate(t,n,a);const c=new x;let u=new K($.stock,z(),this.db.curHeight,t);a=_.fromScript(k.createScript(u.toRaw(),k.types.NULLDATA),0),c.outputs.push(a),c.outputs.push(_.fromScript(e,r*s)),n?await this.fund(c,{account:n}):await this.fund(c),await this.sign(c);let h=c.commit();return i(h[0].verify(h[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.verifyClsTx(h[0]),await this.db.send(h[0]),u.hash=h[0].hash("hex"),u.height=-1,u.cp=o,u}async sendSecret(t,e,r){let i=this.db.$contacts.get(t);if(!i||!i.sender){var s=(await this.createReceive(r)).getAddress("string");if(t==s)throw new L(H.errors.TYPE_ERROR,"Forbid Sending to Self Address.");i=await this.db.ensureContact({contact:t,messenger:s,wallet:this,account:r})}if(i)return i.send(e);throw new L(H.errors.TYPE_ERROR,"Invalid Address.")}async commNotify(t){i(!!t),i(!!t.dst),i(!!t.content);const e=new x;var r=t.src||this.getReceive().toString();let s=new K($.notify,z(),this.db.curHeight,{src:r,content:t.content});r=_.fromScript(k.createScript(s.toRaw(),k.types.NULLDATA),0),e.outputs.push(r),r={address:t.dst,locktime:P.BLOCK_DAY,locktype:"csb",value:.1*P.COIN},e.outputs.push(new _(r)),t.account?await this.fund(e,{account:t.account,noChange:!0,allowInfiniteFee:!0}):await this.fund(e,{noChange:!0,allowInfiniteFee:!0}),await this.sign(e);let n=e.commit();return i(n[0].verify(n[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(n[0]),this.logger.debug("Sending tx on wallet(%s): %s",this.id,n[0].txid()),await this.db.send(n[0]),s.hash=n[0].hash("hex"),s.height=-1,s}async payOrder(t,e,r,s,n){i(!!t),i(!!e),i(!!r),i(!!s);var a=(await this.tokenCreate({cid:t,uid:e},n)).data.addr,c=(r=o.sprintf("%0-36s",r),await this.getOrderList([["cid",t],["sn",r]],n));if(0<c.list.length)return c.list[0];if((s=(0|s)>>>0)<P.MINPROPVALUE)return null;if(!(c=await this.ensureCp(t,!0)))return null;let u=new W(t,e,r,s,a,"");const h=new x;for(t=_.fromScript(k.createScript(Buffer.from(JSON.stringify(u)),k.types.NULLDATA),0),h.outputs.push(t),h.outputs.push(_.fromScript(c.current.address,s)),n?await this.fund(h,{account:n}):await this.fund(h);2<h.outputs.length;)h.outputs.pop();await this.sign(h,null,N.ZERO|N.ANYONECANPAY);let l=h.commit();return i(l[0].verify(l[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(l[0]),await this.db.send(l[0]),u.hash=l[0].hash("hex"),u.height=-1,u.cp=c,u}async cpRegister(t,e,r,s){if(i(!!e&&"object"==typeof e),!await this.db.client.execute("canExecute",[{confirm:!1,cid:e.cid,name:e.name,oper:$.cpRegister}]))throw new L(H.errors.TYPE_ERROR,"Invalid CP Register Info.");const n=new x;if(!t){let e=await this.createReceive(r);t=e.getAddress()}let a=await this.getKey(t);if(!a)throw new L(H.errors.TYPE_ERROR,"Invalid CP Register Address, Not along to this wallet.");e.pubAddress=t.toString(),e.pubKey=a.getPublicKey("hex"),e.signMethod="secp256k1",e.register=this.master.key.publicKey.toString("hex"),n.cpRegister(t,P.registerFee,e);for(let r=0;r<10;r++){var c=""+e.cid+this.network.stockFix+o.sprintf("%02d",r);c={oper:$.propCreate,pid:c,oid:e.cid,cid:e.cid,gold:P.MINPROPVALUE};n.propCreate(t,c)}var u=async()=>{r?await this.fund(n,{account:r}):await this.fund(n),await this.sign(n);let s=n.commit();return i(s[0].verify(s[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(s[0]),await this.db.send(s[0]),e.txid=s[0].txid(),e.addr=t.toString(),s};if(!s)return u();u()}async cpX509(t,e){var r=await this.ensureCp(t);let i=await this.getKey(r.pubAddress);if(!i)throw new L(H.errors.TYPE_ERROR,"Invalid cid, Not along to this wallet.");if(u=this.db.x509CertList.get(tt.getKey(t,1)))return[u,{}];const s=new Date,a=new Date(s.getTime()+315576e6),o=new n.asn1.DERUTCTime({date:s}),c=new n.asn1.DERUTCTime({date:a});var u=i.privateKey.toString("Hex"),h=j.publicKeyConvert(i.publicKey,!1).toString("Hex");u=new n.crypto.ECDSA({curve:"secp256k1",prv:u,pub:h}),h="/C=CN/O=ggserver/OU="+t+"/CN="+r.name,h=n.asn1.x509.X509Util.newCertPEM({serial:{int:1},sigalg:{name:"SHA256withECDSA"},issuer:{str:h},notbefore:{str:o.getString()},notafter:{str:c.getString()},subject:{str:h},sbjpubkey:u,ext:[{basicConstraints:{cA:!1,critical:!0}},{keyUsage:{bin:"11111"}}],cakey:u});let l=new tt({oper:"x509Issue",witness:t,certSq:1,activeTime:a.getTime(),cert:h});return l.sign(i),u=l.toOptions(!0),t={outputs:[{address:r.pubAddress,value:1e4}],comment:u},[u,await this.send(t,e)]}async x509Issue(t,e){var r=await this.ensureCp(t.cid);let i=await this.getKey(r.pubAddress);if(!i)throw new L(H.errors.TYPE_ERROR,"Invalid cid, Not along to this wallet.");var s=o.hashInt(t.csrData),a=this.db.x509CertList.get(tt.getKey(t.cid,s));if(a)return[a,{}];if(!(a=n.asn1.csr.CSRUtil.getInfo(t.csrData))||!a.pubkey||!a.pubkey.obj)throw new L(H.errors.TYPE_ERROR,"Invalid csr request Data!");var c=a.pubkey.obj;if("object"!=typeof c||!(c instanceof n.crypto.ECDSA)||"secp256k1"!=c.curveName)throw new L(H.errors.TYPE_ERROR,"Invalid csr request Alg, Use secp256k1 ECC !");var u=new Date,h=new Date(t.activeTime);const l=new n.asn1.DERUTCTime({date:u}),p=new n.asn1.DERUTCTime({date:h});u=i.privateKey.toString("Hex"),h=j.publicKeyConvert(i.publicKey,!1).toString("Hex"),u=new n.crypto.ECDSA({curve:"secp256k1",prv:u,pub:h}),h="/C=CN/O=ggserver/OU="+t.cid+"/CN="+r.name,r=n.asn1.x509.X509Util.newCertPEM({serial:{int:s},sigalg:{name:"SHA256withECDSA"},issuer:{str:h},notbefore:{str:l.getString()},notafter:{str:p.getString()},subject:{str:a.subject.name},sbjpubkey:c,ext:[{basicConstraints:{cA:!1,critical:!0}},{keyUsage:{bin:"11"}}],cakey:u});let d=new tt({oper:"x509Issue",witness:t.cid,certSq:s,activeTime:t.activeTime,cert:r});return d.sign(i),h=d.toOptions(!0),a={outputs:[{address:t.addr.toString(),value:1e4}],comment:h},[h,await this.send(a,e)]}async x509Abolish(t,e){var r=await this.ensureCp(t.cid),i=await this.getKey(r.pubAddress);if(!i)throw new L(H.errors.TYPE_ERROR,"Invalid cid, Not along to this wallet.");if(!this.db.x509CertList.get(tt.getKey(t.cid,t.seqno)))throw new L(H.errors.TYPE_ERROR,"Invalid Cert SeqNo, Not find Cert");let s=new et({oper:"x509Abolish",witness:t.cid,certSq:t.seqno,activeTime:t.activeTime});return s.sign(i),t=s.toOptions(!0),i={outputs:[{address:r.pubAddress,value:1e4}],comment:t},[t,await this.send(i,e)]}getSCAddress(t){return t=it.fromMnemonic(F.fromOptions(P.SmartContractMnemonic),this.network).deriveAccount(44,t).derive(9).derive(1),w.fromWitnessPubkeyhash(p.hash160(t.publicKey),this.network)}async cpChange(t,e){var r=await this.ensureCp(t.cid);if(r.cid==this.network.genesisId||"ATHENA"==r.name)throw new L(H.errors.TYPE_ERROR,"Invalid cp name.");let s=await this.getTX(r.current.hash);if(!s)throw new L(H.errors.TYPE_ERROR,"Do not have permission to change this info.");if(s=s.tx,!await this.belongToAccount(e,s.outputs[0].getAddress()))throw new L(H.errors.TYPE_ERROR,"Invalid account info.");if(t.newName){if(!await this.db.client.execute("canExecute",[{confirm:!1,cid:r.cid,name:t.newName,oper:$.cpChange}]))throw new L(H.errors.TYPE_ERROR,"Invalid CP Change Info.")}else t.newName=r.name;t.addr||(t.addr=w.fromString(r.current.address));const n=x.cpChange(s,t);e?await this.fund(n,{allowPreInput:!0,account:e}):await this.fund(n,{allowPreInput:!0}),await this.sign(n);let a=n.commit();return await this.db.send(a[0]),i(a[0].verify(a[1],k.flags.STANDARD_VERIFY_FLAGS)),t.txid=a[0].txid(),a}async propExchangeList(t,e,r=!1){let s=new x,n=[];for(var[a,o,c]of t){let t=null;var u;if(t=await this.getTX(a.hash)){if(t=t.tx,u=a.index,t&&t.outputs&&!(t.outputs.length<=u))if(r||await this.belongToAccount(e,t.outputs[u].getAddress())){let e=t.outputs[u].getReturnData();e&&(s.propExchange(t,u,o),e.index=s.outputs.length-1,e.addr=o.toString(),n.push(e))}else this.logger.error("not owned prop:",a.hash,a.index)}else this.logger.error("tx not find:",a.hash,c)}e?await this.fund(s,{allowPreInput:!0,account:e}):await this.fund(s,{allowPreInput:!0}),await this.sign(s);let h=s.commit();return await this.db.addTX(h[0]),await this.db.send(h[0]),i(h[0].verify(h[1],k.flags.STANDARD_VERIFY_FLAGS)),h.push(n),h}async propDonate(t,e){var r=t.index;let i=await this.getTX(t.hash);if(!i||!i.tx||!i.tx.outputs||i.tx.outputs.length<=r)throw new L(H.errors.TYPE_ERROR,"Invalid tx info.");if(!await this.belongToAccount(e,i.tx.outputs[r].getAddress()))throw new L(H.errors.TYPE_ERROR,"Props that do not belong to you.");if(!(t=i.tx.outputs[r].getReturnData()))throw new L(H.errors.TYPE_ERROR,"Invalid tx info.");if(t.cid&&t.cid==this.network.genesisId)throw new Y(i.tx,"invalid","Special props that can not to donate",100);const s=new x;s.addInputFromTx(i.tx,r),s.addOutput(k.createScript(Buffer.from(JSON.stringify({value:i.tx.outputs[r].value,cid:t.cid,pid:t.pid,oid:t.oid,gaddr:this.getAddress().toString(this.network)})),k.types.NULLDATA),0),await this.sign(s,null,N.NONE|N.ANYONECANPAY);let n=s.commit();return n.push(t),n}async propReceive(t,e){let r=x.fromTX(t,1);t=r.inputs[0].prevout;let i=r.outputs[0].getReturnData(),s=(r.view.addOutput({hash:r.inputs[0].prevout.hash,index:r.inputs[0].prevout.index},new _({value:i.value})),r.outputs.pop(),this.getAddress().toString(this.network));e&&(n={cid:i.cid,uid:e},s=(n=await this.tokenCreate(n,e)).data.addr),r.outputs.push(_.fromScript(s,i.value,{oper:$.propExchange,pid:i.pid,cid:i.cid,oid:i.oid,prev:{hash:t.hash,index:t.index}})),e?await this.fund(r,{allowPreInput:!0,account:e}):await this.fund(r,{allowPreInput:!0}),await this.sign(r,null,N.ALL,[0]);var n=r.commit();return await this.db.send(n[0]),i.simAddr=s,[n[0],null,i]}async belongToAccount(t,e){return!(!e||!(e=await this.getAccountByAddress(e))||t&&e.name!==t)}async propExchange(t,e,r){let s=null,n=0;var a;if(Array.isArray(t)?(s=t[0],n=t[1]):(a=await this.getTX(t.hash))&&(s=a.tx,n=t.index),!s||!s.outputs||s.outputs.length<=n)return this.logger.error("Invalid tx info."),null;if(!await this.belongToAccount(r,s.outputs[n].getAddress()))return this.logger.error("Invalid user."),null;let o=s.outputs[n].getReturnData();if(!o)return this.logger.error("Invalid tx info."),null;const c=(new x).propExchange(s,n,e);o.index=c.outputs.length-1,r?await this.fund(c,{allowPreInput:!0,account:r}):await this.fund(c,{allowPreInput:!0}),await this.sign(c);let u=c.commit();return await this.db.addTX(u[0]),await this.db.send(u[0]),i(u[0].verify(u[1],k.flags.STANDARD_VERIFY_FLAGS)),u.push(o),u}async propFound(t,e){if(t=await this.getTX(t),i(t),!(t=t.tx))throw new L(H.errors.TYPE_ERROR,"Invalid hex string.");let r=0,s=(3<=t.outputs.length&&(r=2),t.outputs[r]);var n=s.getReturnData();if(!n||n.oper!==$.propExchange&&n.oper!==$.propCreate)throw new L(H.errors.TYPE_ERROR,"Invalid tx type.");if(n.cid==this.network.genesisId)throw new Y(block,"invalid","prop found supertoken",100);const a=new x;a.addInputFromTx(t,r),t=_.fromScript(s.getAddress(),s.value),a.outputs.push(t),e?await this.fund(a,{allowPreInput:!0,subtractFee:!0,account:e}):await this.fund(a,{allowPreInput:!0,subtractFee:!0}),await this.sign(a);let o=a.commit();return await this.db.send(o[0]),i(o[0].verify(o[1],k.flags.STANDARD_VERIFY_FLAGS)),o.push(n),o}async propSale(t,e,r,s){let n=await this.getTX(t);if(!n)throw new L(H.errors.TYPE_ERROR,"Invalid tx info.");if(n.getDepth(this.db.curHeight)<=0)throw new L(H.errors.TYPE_ERROR,"No enough confirmations.");if(!(n=n.tx))throw new L(H.errors.TYPE_ERROR,"Invalid tx info.");n.outputs[0].getReturnType(k.opcodes.OP_RETURN)&&(e=2);var a=n.outputs[e].getReturnData([k.opcodes.OP_PROPEXCHANGE,k.opcodes.OP_PROPCREATE]);if(!a)throw new L(H.errors.TYPE_ERROR,"Invalid tx type.");if(!await this.belongToAccount(s,n.outputs[e].getAddress()))throw new L(H.errors.TYPE_ERROR,"Invalid tx info.");if(!(s=await this.getCoin(t,e))||-1===s.height||-2===s.height)throw new L(H.errors.WALLET_INSUFFICIENT_FUNDS,"Invalid coin.");if(await this.txdb.isSpent(t,e))throw new L(H.errors.WALLET_INSUFFICIENT_FUNDS,"Invalid coin.");if(r<=n.outputs[e].value)throw new L(H.errors.TYPE_ERROR,"Invalid fixed price.");if(a.cid==this.network.genesisId)throw new Y(n,"invalid","prop not for sale",100);const o=new x;s=o.addInputFromTx(n,e),t={oper:$.propSale,pid:a.pid,prev:{hash:s.prevout.hash,index:s.prevout.index},fixed:r,period:this.db.curHeight+P.BLOCK_DAY},e=_.fromScript(k.createScript(Buffer.from(JSON.stringify(t)),k.types.NULLDATA),0),o.outputs.push(e),await this.sign(o,null,N.SINGLE|N.ANYONECANPAY);let c=o.commit();return i(c[0].verify(c[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.send(c[0]),c}async propBuy(t,e,r){if(!(t=this.db.propList.get(t))||!t.bid||!t.bid.raw)throw new L(H.errors.INVALID_PARAMS,"Invalid Tx Hash.");const i=U.fromRaw(Buffer.from(t.bid.raw,"hex"));var s=(await this.createReceive(r)).getAddress(),n=t.gold,a=w.fromString(t.current.address,this.network).getHash();if(e<n)throw new Error("wrong price");if(1<i.outputs.length&&e<i.outputs[1].value)throw new Error("low bid price than before");let o=x.fromTX(i,1);if(!o.outputs[0].getReturnType(B.OP_RETURN))throw new Error("not a sale order");return await this.remove(i.hash("hex")),o.view.addOutput({hash:o.inputs[0].prevout.hash,index:o.inputs[0].prevout.index},new _({value:t.gold})),a=_.fromScript(k.createScript(a),e),o.outputs.push(a),e={oper:$.propExchange,pid:t.pid,cid:t.cid,oid:t.oid,prev:{hash:o.inputs[0].prevout.hash,index:o.inputs[0].prevout.index}},a=_.fromScript(s,n,e),o.outputs.push(a),r?await this.fund(o,{allowPreInput:!0,account:r}):await this.fund(o,{allowPreInput:!0}),await this.sign(o,null,N.ALL,[0]),s=o.commit(),t.owned||this.db.client.watchOutpoint((new M).fromOptions(i.inputs[0].prevout)),await this.db.send(s[0]),s}async getTXByAmount(t,e){let r=null;var i;for(i of await this.getCoins(e))if(!(i.height<=0)&&i.value==t){r=i;break}return r&&(e=await this.getTX(r.hash))?[e.tx,r.index,r.height]:[]}async contractCreate(t,e,r,s,n){if(this.db.transactionList.query(t,s)!=G.None)throw new L(H.errors.TYPE_ERROR,"Contract with the same address finded.");if(0!=parseInt(e%1e3,10))throw new L(H.errors.TYPE_ERROR,"Contract source should an integer multiple of 1000.");if(!await q.checkSum(this.network,t,s))throw new L(H.errors.TYPE_ERROR,"Create contract with an invalid Address or a Address with old transations.");let a=!1,[o,c,u]=await this.getTXByAmount(e,n);if(!o){a=!0;const t=new x;let r="";if(n){r=(await this.createReceive(n)).getAddress()}else r=this.getAddress();t.outputs.push(_.fromScript(r,e)),n?await this.fund(t,{allowPreInput:!0,account:n}):await this.fund(t,{allowPreInput:!0}),await this.sign(t);let s=t.commit();i(s[0].verify(s[1],k.flags.STANDARD_VERIFY_FLAGS)),o=s[0],c=0,u=-1}const h=new x;h.addInputFromTx(o,c,u);let l="";if(n){l=(await this.createReceive(n)).getAddress()}else l=this.getAddress();let p=await this.getKey(l);return t={oper:$.contractCreate,type:t,addr:s,src:e,dst:r,srcact:n,alice:p.getPublicKey("hex"),period:this.db.curHeight+P.TRANSACTION_PERIOD},s=_.fromScript(k.createScript(Buffer.from(JSON.stringify(t)),k.types.NULLDATA),0),h.outputs.push(s),await this.sign(h,null,N.SINGLE|N.ANYONECANPAY),e=h.commit(),a&&await this.db.send(o),await this.db.send(e[0]),e}async contractPromise(t,e){if(!(t=this.db.transactionList.get(t))||t.transStatus!=G.CreatedOnMem)throw new L(H.errors.INVALID_PARAMS,"Invalid Tx id.");const r=U.fromRaw(Buffer.from(t.raw,"hex"));if(!r)throw new L(H.errors.TYPE_ERROR,"Invalid Tx id.");if(!(t=q.parseContract(r))||t.oper!==$.contractCreate)throw new L(H.errors.TYPE_ERROR,"Invalid tx type.");let i=x.fromTX(r,1);if(!i.outputs[0].getReturnType(B.OP_RETURN))throw new Error("not a valid contract");i.view.addOutput({hash:i.inputs[0].prevout.hash,index:i.inputs[0].prevout.index},new _({value:t.src}));let s="";if(e){s=(await this.createReceive(e)).getAddress()}else s=this.getAddress();let n=await this.getKey(s),a={oper:$.contractPromise,prevhash:r.hash("hex"),type:t.type,addr:t.addr,dst:t.dst,srcact:t.srcact,dstact:e,bob:n.getPublicKey("hex"),period:t.period};e=new k([D.fromSymbol("promise"),D.fromData(Buffer.from(JSON.stringify(a))),D.fromSymbol("drop"),D.fromSymbol("greaterthan"),D.fromSymbol("drop"),D.fromSymbol("if"),D.fromData(p.hash160(Buffer.from(a.bob,"hex"))),D.fromSymbol("else"),D.fromData(p.hash160(Buffer.from(t.alice,"hex"))),D.fromSymbol("endif"),D.fromSymbol("checksig")]),i.outputs.push(_.fromScript(e,t.src)),await this.remove(a.prevhash),await this.sign(i,null,N.ALL,[0]);let o=i.commit();return await this.db.send(o[0]),a.current={hash:o[0].hash("hex"),index:0},a.raw=o[0].toRaw().toString("hex"),a.transStatus=G.Promised,this.db.transactionList.saveContract(a,!0),o}async contractExecute(t,e){if(!(t=this.db.transactionList.get(t))||t.transStatus!=G.Confirmed&&t.transStatus!=G.Expired)throw new L(H.errors.INVALID_PARAMS,"Invalid Tx id.");const r=U.fromRaw(Buffer.from(t.raw,"hex"));if(!r)throw new L(H.errors.TYPE_ERROR,"Invalid Tx id.");if(e=e||1,!(t=q.parseContract(r))||t.oper!==$.contractPromise)throw new L(H.errors.TYPE_ERROR,"Invalid tx type.");var s=r.outputs[1].getReturnData();if(!s||s.oper!==$.contractPromise)throw new L(H.errors.TYPE_ERROR,"Invalid tx type.");i.strictEqual(t.addr,s.addr),i.strictEqual(t.type,s.type),i.strictEqual(t.dst,s.dst),i.strictEqual(t.period,s.period),i.strictEqual(t.srcact,s.srcact),i.strictEqual(t.dstact,s.dstact);var n=this.db.transactionList.query(t.type,t.addr);if(n!=G.Confirmed&&n!=G.Expired)throw new L(H.errors.TYPE_ERROR,"Contract Promise not Check yet.");if(n==G.Expired&&1!=e||n==G.Confirmed&&2!=e)throw new L(H.errors.TYPE_ERROR,"Invalid Executor.");let a=t.srcact,o="";if(a=2==e?t.dstact:a){o=(await this.createReceive(a)).getAddress()}else o=this.getAddress();let c=new x;c.addInputFromTx(r,1);var u={oper:$.contractExecute,type:t.type,addr:t.addr,master:e};u=_.fromScript(k.createScript(Buffer.from(JSON.stringify(u)),k.types.NULLDATA),0),c.outputs.push(u),u=_.fromScript(o,r.outputs[1].value);c.outputs.push(u);let h=1==e?await T.fromPublic(Buffer.from(t.ori.alice,"hex")):await T.fromPublic(Buffer.from(s.bob,"hex"));u=await this.getKey(h.getAddress()),await c.signAsync(u,k.hashType.ALL,this.db.workers);let l=c.commit();return i(l[0].verify(l[1],k.flags.STANDARD_VERIFY_FLAGS,n)),await this.db.send(l[0]),l}async htlcDeal(t,e){var r=await this.getTX(t.hash);let i=null;if(e){const t=await this.getAccount(e);if(!t)throw new L(H.errors.TYPE_ERROR,"Invalid Account.");i=t.getReceive().toString()}else i=this.getReceive().toString();const s=new x;let n=(new k).pushOp(B.OP_1);return t.suggest&&n.pushData(Buffer.from(t.sa,"hex")),s.addInput({prevout:{hash:t.hash,index:t.index},script:n}),s.addOutput(i,r.tx.outputs[t.index].value-1e4),s.view.addOutput({hash:t.hash,index:t.index},new _(r.tx.outputs[t.index])),await this.sign(s,null,N.ALL),e=s.commit(),await this.db.send(e[0]),e}async htlcCancel(t,e){let r=null;var i=await this.getTX(t.hash);if(!(r=i?i.tx.outputs[t.index]:r))throw new L(H.errors.TYPE_ERROR,"Invalid Input.");let s=null;if(e){const t=await this.getAccount(e);if(!t)throw new L(H.errors.TYPE_ERROR,"Invalid Account.");s=t.getReceive().toString()}else s=this.getReceive().toString();const n=new x;let a=(new k).pushOp(B.OP_0);return t.suggest&&a.pushData(Buffer.from(t.sa,"hex")),n.addInput({prevout:{hash:t.hash,index:t.index},script:a}),t.suggest?n.setSequence(0,2*P.HTLC_CANCEL_PERIOD,!1):n.setSequence(0,P.HTLC_CANCEL_PERIOD,!1),n.addOutput(s,r.value-1e4),n.view.addOutput({hash:t.hash,index:t.index},new _(r)),i=await this.getKey(t.master),await n.signAsync(i,k.hashType.ALL,this.db.workers),e=n.commit(),await this.db.send(e[0]),e}async sendContracts(t,e,r){const i=new x;for(var s of t)i.outputs.push(r.create(s));return e?await this.fund(i,{account:e}):await this.fund(i),await this.sign(i),t=i.commit(),await this.db.addTX(t[0]),await this.db.send(t[0]),t}async addStockAccountSeq(t){i(t&&"object"==typeof t,"Token data should be a object"),i(t.cid,"Token data should has a cid property"),i(t.uid,"Token data should has a uid property");let e=await this.stockAddress(t.cid,t.uid);var r=this.db.accountList.getOrCreateStockAccount(t.cid,e.toString());return t.seq=r.seq+1,t}async tokenCreate(t,e="",r){i(t&&"object"==typeof t,"Token data should be a object"),i(t.cid,"Token data should has a cid property"),i(t.uid,"Token data should has a uid property"),t.time=!0,await this.ensureAccount({name:e,witness:!0});let s=null;if(r){if(!await this.belongToAccount(e,r))throw new L(H.errors.TYPE_ERROR,`stock.send address error: addr:${r} is not belongs to account:`+e);s=await this.getKey(r)}else s=await this.createReceive(e,o.hashInt(t.cid),this.master);return s.signData(t)}async sign(t,e,r=k.hashType.ALL,i){if(this.watchOnly)throw new Error("Cannot sign from a watch-only wallet.");return await this.unlock(e),e=await this.deriveInputs(t),t.signAsync(e,r,this.db.workers,i)}getCoinView(t){return this.txdb.getCoinView(t)}getSpentView(t){return this.txdb.getSpentView(t)}toDetails(t){return this.txdb.toDetails(t)}getDetails(t){return this.txdb.getDetails(t)}async getCoin(t,e){return this.txdb.getCoin(t,e)}async getCredit(t,e){return this.txdb.getCredit(t,e)}async getStatusOfSC(t){return this.txdb.getStatusOfSC(t)}async setStatusOfSC(t,e){const r=await this.writeLock.lock();try{this.txdb.start();try{await this.txdb._setStatusOfSC(t,e),await this.txdb.commit()}catch(t){throw this.txdb.drop(),t}}finally{r()}}getLockedCoins(){return this.txdb.lockedCoins.values}getTX(t){return this.txdb.getTX(t)}getBlocks(){return this.txdb.getBlocks()}getBlock(t){return this.txdb.getBlock(t)}async add(t,e,r){const i=await this.writeLock.lock();try{return await this._add(t,e,r)}finally{i()}}async _add(t,e,r){let i,s;this.txdb.start();try{(i=await this.txdb._add(t,e,r))&&(s=await this.syncOutputDepth(i)),await this.txdb.commit()}catch(t){throw this.txdb.drop(),t}return s&&0<s.length&&(this.db.emit("address",this.id,s),this.emit("address",s)),i}async resetBalance(){const t=await this.writeLock.lock();try{this.txdb.start();try{await this.txdb.resetBalance(),await this.txdb.commit()}catch(t){throw this.txdb.drop(),t}}finally{t()}}async unconfirm(t){const e=await this.writeLock.lock();try{return await this.txdb.unconfirm(t)}finally{e()}}async remove(t){const e=await this.writeLock.lock();try{return await this.txdb.remove(t)}finally{e()}}async zap(t,e){const r=await this.writeLock.lock();try{return await this._zap(t,e)}finally{r()}}async _zap(t,e){return t=await this.ensureIndex(t),this.txdb.zap(t,e)}async abandon(t){const e=await this.writeLock.lock();try{return await this._abandon(t)}finally{e()}}_abandon(t){return this.txdb.abandon(t)}conserveCoin(t){return this.txdb.conserveCoin(t)}unConserveCoin(t){return this.txdb.unConserveCoin(t)}isConserved(t){return this.txdb.isConserved(t)}getConserved(){return this.txdb.getConserved()}async getHistory(t){return t=await this.ensureIndex(t),this.txdb.getHistory(t)}async getCoins(t){return t=await this.ensureIndex(t),this.txdb.getCoins(t)}async getCredits(t){return t=await this.ensureIndex(t),this.txdb.getCredits(t)}async getSmartCoins(t){const e=[];for(const i of await this.getCredits(t)){var r=i.coin;i.spent||this.txdb.isConserved(r)||(-1!==r.height&&-2!==r.height||i.own)&&e.push(r)}return e}async getPending(t){return t=await this.ensureIndex(t),this.txdb.getPending(t)}async getBalance(t){return t=await this.ensureIndex(t),this.txdb.getBalance(t)}async queryBalanceLog(t,e=0){return(t=await this.ensureIndex(t))?this.db.queryBalanceLog(this.wid,t,e):[]}async getRange(t,e){return t&&"object"==typeof t&&(e=t,t=null),t=await this.ensureIndex(t),this.txdb.getRange(t,e)}async getLast(t,e){return t=await this.ensureIndex(t),this.txdb.getLast(t,e)}async ensureIndex(t,e){if(null==t){if(e)throw new Error("No account provided.");return null}if(-1===(e=await this.getAccountIndex(t)))throw new Error("Account not found.");return e}getAddress(t){return this.account.getAddress(t)}getReceive(t){return this.account.getReceive(t)}getChange(t){return this.account.getChange(t)}getNested(t){return this.account.getNested(t)}inspect(){return{wid:this.wid,id:this.id,network:this.network.type,initialized:this.initialized,accountDepth:this.accountDepth,token:this.token.toString("hex"),tokenDepth:this.tokenDepth,state:this.txdb.state?this.txdb.state.toJSON(!0):null,master:this.master,account:this.account}}toJSON(t){return{network:this.network.type,wid:this.wid,id:this.id,initialized:this.initialized,watchOnly:this.watchOnly,accountDepth:this.accountDepth,token:this.token.toString("hex"),tokenDepth:this.tokenDepth,height:this.db.curHeight,state:this.txdb.state.toJSON(!0),master:this.master.toJSON(t),account:this.account.toJSON(!0)}}getSize(){var t=0;return(t+=50)+c.sizeVarString(this.id,"ascii")+c.sizeVarlen(this.master.getSize())}toRaw(){var t=this.getSize();const e=new m(t);return e.writeU32(this.network.magic),e.writeU32(this.wid),e.writeVarString(this.id,"ascii"),e.writeU8(this.initialized?1:0),e.writeU8(this.watchOnly?1:0),e.writeU32(this.accountDepth),e.writeBytes(this.token),e.writeU32(this.tokenDepth),e.writeVarBytes(this.master.toRaw()),e.render()}fromRaw(t){const e=new f(t);return t=a.fromMagic(e.readU32()),this.wid=e.readU32(),this.id=e.readVarString("ascii"),this.initialized=1===e.readU8(),this.watchOnly=1===e.readU8(),this.accountDepth=e.readU32(),this.token=e.readBytes(32),this.tokenDepth=e.readU32(),this.master.fromRaw(e.readVarBytes()),i(t===this.db.network,"Wallet network mismatch."),this}static fromRaw(t,e){return new at(t).fromRaw(e)}static isWallet(t){return t instanceof at}async issueCreate(t,e,r){let i=new J(t),s=(i.source.subjectName||(i.source.subjectName=i.erid),T.fromPrivate(Buffer.from(t.key,"hex"),!0,this.network));s.witness=!0,i.sign(s,!0,this.network);var n=i.toOptions(!0);return r?this.send({outputs:[{address:t.address,value:1e4}],comment:n},e):await this.send({outputs:[{address:t.address,value:1e4}],comment:n},e),n}async caAbolish(t,e,r){let i=T.fromPrivate(Buffer.from(t.key,"hex"),!0,this.network),s=(i.witness=!0,await this.db.$parent.chain.db.erList.getEr(t.erid));if(!s)throw new L(H.errors.TYPE_ERROR,"ca.abolish: Invalid erid.");if(s.source.cid!=t.cid)throw new L(H.errors.TYPE_ERROR,"ca.abolish: Invalid cid.");if(s.source.uid!=t.uid)throw new L(H.errors.TYPE_ERROR,"ca.abolish: Invalid uid.");var n=s.signature;if(s.sign(i,!0,this.network),s.witness!=t.witness||s.signature!=n)throw new L(H.errors.TYPE_ERROR,"ca.abolish: You have no permission to abolish this witness.");let a=new Z(t);return a.sign(i),n=a.toOptions(!0),r?this.send({outputs:[{address:t.address,value:1e4}],comment:n},e):await this.send({outputs:[{address:t.address,value:1e4}],comment:n},e),n}async enchanceCp(t,e){let r=new Q(t);r.oper="enchanceCp";t=await this.ensureCp(r.to);var i=await this.ensureCp(r.from);if(!(i=await this.getKey(i.pubAddress)))throw new L(H.errors.TYPE_ERROR,"Invalid cid, Not along to this wallet.");return r.sign(i),i=r.toOptions(!0),[await this.send({outputs:[{address:t.pubAddress,value:1e4}],comment:i},e),i]}async ensureCp(t,e=!1){if(await this.db.flushCP([t]),(t=this.db.cpList.getItem(t))||e)return t;throw new L(H.errors.TYPE_ERROR,"Invalid cid, cannot find cp.")}}t.exports=at},function(t,e,r){"use strict";
292
+ */const i=r(0);var s=r(16);const n=r(319),a=r(15),o=r(1),c=r(3),u=r(35),h=r(201),l=r(120).sortWithSeq,p=r(6),d=r(95),f=r(2),m=r(4),g=r(70),y=r(345);r(226);const v=r(111),b=r(73),w=r(12),x=r(60),k=r(17),S=r(227),E=r(124),_=r(26),A=r(161),R=r(346),I=r(65),j=r(29),C=r(27),P=r(7),O=r(315),T=r(32),F=E.Mnemonic,{opcodes:B,hashType:N}=r(21),D=r(169),L=r(77),H=r(78),z=r(143),M=r(46),U=r(19),q=r(43),V=r(53),{NotifyMsg:K,OrderData:W,ContractStatus:G,ContractType:$}=r(5),Y=r(38).VerifyError,X=r(85).stockItem;r(323).AuditItem;const J=r(157).ErItem,Z=r(158).ErAbolishItem,Q=r(241).EnchancementItem,tt=r(159).X509Cert,et=r(160).X509Abolish,rt=r(28),it=r(69),st=r(59),nt=r(83);class at extends s{constructor(t,e){super(),i(t,"DB required."),this.db=t,this.network=t.network,this.logger=t.logger,this.readLock=new h,this.writeLock=new u,this.sendLock=new u,this.indexCache=new I(1e4),this.accountCache=new I(1e4),this.pathCache=new I(1e5),this.current=null,this.wid=0,this.id=null,this.initialized=!1,this.watchOnly=!1,this.accountDepth=0,this.token=c.ZERO_HASH,this.tokenDepth=0,this.master=new R,this.txdb=new y(this),this.account=null,e&&this.fromOptions(e)}fromOptions(t){let e,r,s=t.master;return s?("string"==typeof s&&(s=E.PrivateKey.fromBase58(s,this.network)),i(E.isPrivate(s),"Must create wallet with hd private key.")):(r=new F(t.mnemonic),s=E.fromMnemonic(r,this.network)),i(s.network===this.network,"Network mismatch for master key."),this.master.fromKey(s,r),null!=t.wid&&(i(o.isU32(t.wid)),this.wid=t.wid),t.id&&(i(b.isName(t.id),"Bad wallet ID."),e=t.id),null!=t.initialized&&(i("boolean"==typeof t.initialized),this.initialized=t.initialized),null!=t.watchOnly&&(i("boolean"==typeof t.watchOnly),this.watchOnly=t.watchOnly),null!=t.accountDepth&&(i(o.isU32(t.accountDepth)),this.accountDepth=t.accountDepth),t.token&&(i(Buffer.isBuffer(t.token)),i(32===t.token.length),this.token=t.token),e=e||this.getID(),this.id=e,this}static fromOptions(t,e){return new at(t).fromOptions(e)}async init(t){var e=t.passphrase;i(!this.initialized),this.initialized=!0,e&&await this.master.encrypt(e),t=await this._createAccount(t,e);i(t),this.account=t,this.logger.info("Wallet initialized (%s).",this.id),await this.txdb.open()}async open(){i(this.initialized);var t=await this.getAccount(0);if(!t)throw new Error("Default account not found.");this.account=t,this.logger.info("Wallet opened (%s).",this.id),await this.txdb.open()}async ensureNotifyKey(){this.notifyKey||(await this.ensureAccount({name:"alliance",witness:!0}),this.notifyKey=await this.createReceive("alliance",1,this.master),this.notifyAddress=this.notifyKey.getAddress("string"))}async createAllianceInfo(t,e,r){let i={alliancename:t,nodeid:e};return t?(i.alliancePrivateKey=p.hash256(Buffer.concat([Buffer.from(t),this.master.key.privateKey])),r?(i.prv=Buffer.alloc(0),i.pub=Buffer.from(r,"hex"),i.awardAddress=w.fromWitnessPubkeyhash(p.hash160(i.pub),this.network.type).toString(this.network.type),i.mnemonic=new F):(r=p.hash256(Buffer.concat([Buffer.from(t+"-"+e),this.master.key.privateKey])),i.mnemonic=new F({entropy:r,language:this.master.mnemonic.language,passphrase:this.master.mnemonic.passphrase}),i.prv=p.hash256(Buffer.from(i.mnemonic.toSeed().toString("hex"))),i.pub=j.publicKeyCreate(i.prv,!0),t=R.fromKey(E.fromMnemonic(i.mnemonic),this.network.type).key.deriveAccount(44,0).derive(9).derive(1),i.awardAddress=w.fromWitnessPubkeyhash(p.hash160(t.publicKey),this.network.type).toString(this.network.type))):(e=await this.createReceive("default",1,this.master),i.prv=e.privateKey,i.pub=e.publicKey,i.awardAddress=w.fromWitnessPubkeyhash(p.hash160(i.pub),this.network.type).toString(this.network.type),i.mnemonic=new F),i.address=w.fromWitnessPubkeyhash(p.hash160(i.pub),this.network.type).toString(),i}async destroy(){const t=await this.writeLock.lock(),e=await this.sendLock.lock();try{this.db.unregister(this),await this.master.destroy(),this.readLock.destroy(),this.writeLock.destroy(),this.sendLock.destroy()}finally{e(),t()}}async addSharedKey(t,e){const r=await this.writeLock.lock();try{return await this._addSharedKey(t,e)}finally{r()}}async _addSharedKey(t,e){e||(e=t,t=null);const r=await this.getAccount(t=null==t?0:t);if(!r)throw new Error("Account not found.");let i;this.start();try{i=await r.addSharedKey(e)}catch(t){throw this.drop(),t}return await this.commit(),i}async removeSharedKey(t,e){const r=await this.writeLock.lock();try{return await this._removeSharedKey(t,e)}finally{r()}}async _removeSharedKey(t,e){e||(e=t,t=null);const r=await this.getAccount(t=null==t?0:t);if(!r)throw new Error("Account not found.");let i;this.start();try{i=await r.removeSharedKey(e)}catch(t){throw this.drop(),t}return await this.commit(),i}async setPassphrase(t,e){t&&await this.decrypt(t),e&&await this.encrypt(e)}async encrypt(t){const e=await this.writeLock.lock();try{return await this._encrypt(t)}finally{e()}}async _encrypt(t){t=await this.master.encrypt(t,!0),this.start();try{await this.db.encryptKeys(this,t)}catch(e){throw d(t),this.drop(),e}d(t),this.save(),await this.commit()}async decrypt(t){const e=await this.writeLock.lock();try{return await this._decrypt(t)}finally{e()}}async _decrypt(t){t=await this.master.decrypt(t,!0),this.start();try{await this.db.decryptKeys(this,t)}catch(e){throw d(t),this.drop(),e}d(t),this.save(),await this.commit()}async rename(t){const e=await this.writeLock.lock();try{return await this.db.rename(this,t)}finally{e()}}async writeBalanceLog(t){const e=await this.writeLock.lock();try{return await this.db.writeBalanceLog(this,t)}finally{e()}}async renameAccount(t,e){const r=await this.writeLock.lock();try{return await this._renameAccount(t,e)}finally{r()}}async _renameAccount(t,e){if(!b.isName(e))throw new Error("Bad account name.");var r=await this.getAccount(t);if(!r)throw new Error("Account not found.");if(0===r.accountIndex)throw new Error("Cannot rename default account.");if(await this.hasAccount(e))throw new Error("Account name not available.");t=r.name,this.start(),this.db.renameAccount(r,e),await this.commit(),this.indexCache.remove(t),t=this.pathCache.values();for(const i of t)i.account===r.accountIndex&&(i.name=e)}async lock(){const t=await this.writeLock.lock(),e=await this.sendLock.lock();try{await this.master.lock()}finally{e(),t()}}unlock(t,e){return this.master.unlock(t,e)}getID(){i(this.master.key,"Cannot derive id.");var t=this.master.key.derive(44);const e=new m(37);e.writeBytes(t.publicKey),e.writeU32(this.network.magic),t=p.hash160(e.render());const r=new m(27);return r.writeU8(3),r.writeU8(190),r.writeU8(4),r.writeBytes(t),r.writeChecksum(),g.encode(r.render())}async createAccount(t,e){const r=await this.writeLock.lock();try{return await this._createAccount(t,e)}finally{r()}}async _createAccount(t,e){let r,s,n=t.name,a=(n=n||this.accountDepth.toString(10),0);if(0!=this.accountDepth&&(a=o.hashInt(n)),await this.hasAccountIndex(a))throw new Error("Account Index Conflict.");if(await this.hasAccount(n))throw new Error("Account already exists.");if(await this.unlock(e),this.watchOnly&&t.accountKey){if("string"==typeof(r=t.accountKey)&&(r=E.PublicKey.fromBase58(r,this.network)),!E.isPublic(r))throw new Error("Must add HD public keys to watch only wallet.");i(r.network===this.network,"Network mismatch for watch only key.")}else i(this.master.key),r=(r=this.master.key.deriveAccount(44,a)).toPublic();e={wid:this.wid,id:this.id,name:0===this.accountDepth?"default":n,witness:t.witness,watchOnly:this.watchOnly,accountKey:r,accountIndex:a,type:t.type,m:t.m,n:t.n,keys:t.keys},this.start();try{(s=A.fromOptions(this.db,e)).wallet=this,await s.init()}catch(t){throw this.drop(),t}return this.logger.info("Created account %s/%s/%d.",s.id,s.name,s.accountIndex),this.accountDepth++,this.save(),await this.commit(),s}async ensureAccount(t,e){var r=t.name;return(r=await this.getAccount(r))||this.createAccount(t,e)}getAccounts(){return this.db.getAccounts(this.wid)}getAddressHashes(t){return null!=t?this.getAccountHashes(t):this.db.getWalletHashes(this.wid)}async getAccountHashes(t){return t=await this.ensureIndex(t,!0),this.db.getAccountHashes(this.wid,t)}async getAccount(t){if(this.account&&(null==t||"default"===t||"number"==typeof t&&0===t||"string"==typeof t&&0===t.length))return this.account;if(-1===(t=await this.getAccountIndex(t)))return null;const e=await this.readLock.lock(t);try{return await this._getAccount(t)}finally{e()}}async _getAccount(t){var e=this.accountCache.get(t);if(e)return e;const r=await this.db.getAccount(this.wid,t);return r?(r.wallet=this,r.wid=this.wid,r.id=this.id,r.watchOnly=this.watchOnly,await r.open(),this.accountCache.set(t,r),r):null}async getAccountIndex(t){var e;return null==t?-1:"number"==typeof t?t:null!=(e=this.indexCache.get(t))?e:-1===(e=await this.db.getAccountIndex(this.wid,t))?-1:(this.indexCache.set(t,e),e)}async getAccountName(t){var e;return"string"==typeof t?t:(e=this.accountCache.get(t))?e.name:this.db.getAccountName(this.wid,t)}async hasAccount(t){return-1!==(t=await this.getAccountIndex(t))&&(!!this.accountCache.has(t)||this.db.hasAccount(this.wid,t))}async hasAccountIndex(t){return!!this.accountCache.has(t)||this.db.hasAccount(this.wid,t)}createReceive(t,e=0,r=null){return this.createKey(t,0,e,r)}createChange(t){return this.createKey(t,1)}createNested(t){return this.createKey(t,2)}async createKey(t,e,r=0,i=null){const s=await this.writeLock.lock();try{return await this._createKey(t,e,r,i)}finally{s()}}async _createKey(t,e,r=0,i=null){null==e&&(e=t,t=null);const s=await this.getAccount(t=t||0);if(!s)throw new Error("Account not found.");let n;this.start();try{n=await s.createKey(e,r,i)}catch(t){throw this.drop(),t}return await this.commit(),n}async deriveKey(t,e,r,i=null){let s=null;const n=await this.writeLock.lock();try{this.start(),s=await this._deriveKey(t,e,r,i),await this.commit()}catch(t){throw this.drop(),t}finally{n()}return s}async _deriveKey(t,e,r=0,i=null){null==e&&(e=t,t=null),t=t||0,t=parseInt(t);const s=await this.getAccount(t);if(s)return t=await s.deriveKey(e,r,i),await s.saveKey(t),t;throw new Error("Account not found.")}save(){return this.db.save(this)}async saveAccount(t){const e=await this.writeLock.lock();try{this.start(),t._save(),await this.commit(),0==t.accountIndex&&(this.account=t)}finally{e()}}start(){return this.db.start(this)}drop(){return this.db.drop(this)}clear(){return this.db.clear(this)}commit(){return this.db.commit(this)}async hasAddress(t){return t=w.getHash(t,"hex"),null!=await this.getPath(t)}async getPath(t){const e=await this.readPath(t);return e?(e.name=await this.getAccountName(e.account),i(e.name),this.pathCache.set(e.hash,e),e):null}async readPath(t){t=w.getHash(t,"hex");var e=this.pathCache.get(t);if(e)return e;const r=await this.db.getPath(this.wid,t);return r?(r.id=this.id,r):null}async hasPath(t){return t=w.getHash(t,"hex"),!!this.pathCache.has(t)||this.db.hasPath(this.wid,t)}async getPaths(t){if(null!=t)return this.getAccountPaths(t);const e=[];for(const t of await this.db.getWalletPaths(this.wid))t.id=this.id,t.name=await this.getAccountName(t.account),i(t.name),this.pathCache.set(t.hash,t),e.push(t);return e}async getAccountPaths(t){var e=await this.ensureIndex(t,!0),r=await this.getAccountHashes(e),s=await this.getAccountName(t);i(s);const n=[];for(const t of r){const r=await this.readPath(t);i(r),i(r.account===e),r.name=s,this.pathCache.set(r.hash,r),n.push(r)}return n}async importKey(t,e,r){const i=await this.writeLock.lock();try{return await this._importKey(t,e,r)}finally{i()}}async _importKey(t,e,r){if(t&&"object"==typeof t&&(r=e,e=t,t=null),null==t&&(t=0),i(e.network===this.network,"Network mismatch for key."),this.watchOnly){if(e.privateKey)throw new Error("Cannot import privkey into watch-only wallet.")}else if(!e.privateKey)throw new Error("Cannot import pubkey into non watch-only wallet.");var s=e.getHash("hex");if(await this.getPath(s))throw new Error("Key already exists.");const n=await this.getAccount(t);if(!n)throw new Error("Account not found.");if(n.type!==A.types.PUBKEYHASH)throw new Error("Cannot import into non-pkh account.");await this.unlock(r);const a=S.fromRing(n,e).toPath();this.master.encrypted&&(a.data=this.master.encipher(a.data,a.hash),i(a.data),a.encrypted=!0),this.start();try{await n.savePath(a)}catch(t){throw this.drop(),t}await this.commit()}async importAddress(t,e){const r=await this.writeLock.lock();try{return await this._importAddress(t,e)}finally{r()}}async _importAddress(t,e){if(e||(e=t,t=null),null==t&&(t=0),e.network!==this.network)throw new Error("Network mismatch for address.");if(!this.watchOnly)throw new Error("Cannot import address into non watch-only wallet.");if(await this.getPath(e))throw new Error("Address already exists.");const r=await this.getAccount(t);if(!r)throw new Error("Account not found.");if(r.type!==A.types.PUBKEYHASH)throw new Error("Cannot import into non-pkh account.");t=v.fromAddress(r,e),this.start();try{await r.savePath(t)}catch(t){throw this.drop(),t}await this.commit()}async fund(t,e){const r=await this.writeLock.lock();try{return await this._fund(t,e)}finally{r()}}async _fund(t,e){if(e=e||{},!this.initialized)throw new Error("Wallet is not initialized.");if(this.watchOnly)throw new Error("Cannot fund from watch-only wallet.");let r;if(null!=e.account){if(!(r=await this.getAccount(e.account)))throw new Error("Account not found.")}else r=this.account;if(!r.initialized)throw new Error("Account is not initialized.");let s,n=e.rate;return null==n&&(n=await this.db.estimateFee(e.blocks)),s=e.smart?await this.getSmartCoins(r.name):(s=await this.getCoins(r.name),this.txdb.filterConserved(s)),await t.fund(s,{allowPreInput:e.allowPreInput,noChange:e.noChange,selection:e.selection,round:e.round,depth:e.depth,hardFee:e.hardFee,subtractFee:e.subtractFee,subtractIndex:e.subtractIndex,changeAddress:r.change.getAddress(),height:this.db.curHeight,rate:n,maxFee:e.maxFee,estimate:t=>this.estimateSize(t),network:this.network}),!e.allowInfiniteFee&&e.noChange&&i(t.getFee()<=O.MAX_FEE,"TX exceeds MAX_FEE."),s}async getAccountByAddress(t){return t=w.getHash(t,"hex"),(t=await this.getPath(t))?this.getAccount(t.account):null}async estimateSize(t){var e=P.WITNESS_SCALE_FACTOR,r=w.fromScript(t);if(!r)return-1;var i=await this.getAccountByAddress(r);if(!i)return-1;let s=0;if(t.isScripthash()&&i.witness)switch(i.type){case A.types.PUBKEYHASH:s=4*(s+23);break;case A.types.MULTISIG:s=4*(s+35)}switch(i.type){case A.types.PUBKEYHASH:s=s+74+34;break;case A.types.MULTISIG:s=(s=(s=(s=(s+=1)+74*i.m)+3+1)+34*i.n)+1+1}return i.witness?s=((s+=1)+e-1)/e|0:s+=c.sizeVarint(s),s}async createTX(t){var e=t.outputs;const r=new x;i(Array.isArray(e),"Outputs must be an array."),i(0<e.length,"No outputs available."),t.comment&&("object"==typeof t.comment&&(t.comment=JSON.stringify(t.comment)),r.outputs.push(_.fromScript(k.createScript(Buffer.from(t.comment),k.types.NULLDATA),0)));for(const t of e){const e=new _(t),i=e.getAddress();if(e.isDust())throw new Error("Output is dust.");if(0<e.value){if(!i)throw new Error("Cannot send to unknown address.");if(i.isNull())throw new Error("Cannot send to null address.")}r.outputs.push(e)}let s=null;if(t.inputs)for(const e of t.inputs){var n=await this.getTX(e.hash);if(n){let i=V.fromTX(n.tx,e.index,-1,0);i&&(s=i.getAddress(),t.allowPreInput=!0,r.addCoin(i))}}else await this.fund(r,t);if(s){const t=new _;t.value=r.getFee()-O.MIN_FEE,t.script.fromAddress(s),r.outputs.push(t),r.changeIndex=r.outputs.length-1}if(!1!==t.sort&&r.sortMembers(),null!=t.locktime&&r.setLocktime(t.locktime),i(r.isSane(),"TX failed sanity check."),i(r.verifyInputs(this.db.curHeight+1),"TX failed context check."),0===await this.template(r))throw new Error("Templating failed.");return r}async send(t,e){const r=await this.sendLock.lock();try{return await this._send(t,e)}finally{r()}}async _send(t,e){return e&&(t.account=e),e=await this.createTX(t,!0),await this.sign(e),this.sendMTX(e,{sendafter:t.sendafter})}async sendMTX(t,e={}){if(!t.isSigned())throw new Error("TX could not be fully signed.");const r=t.toTX();if(r.getSigopsCost(t.view)>C.MAX_TX_SIGOPS_COST)throw new Error("TX exceeds policy sigops.");if(r.getWeight()>C.MAX_TX_WEIGHT)throw new Error("TX exceeds policy weight.");return e.sendafter||(this.logger.debug("Sending wallet tx (%s): %s",this.id,r.txid()),await this.db.addTX(r),await this.db.send(r)),r}async resend(){var t=await this.getPending();0<t.length&&this.logger.info("Rebroadcasting %d transactions.",t.length);const e=[];for(const r of t)e.push(r.tx);for(const t of await l(e,this.db))await this.db.send(t);return e}async deriveInputs(t){var e;i(t.mutable);const r=[];for(const i of await this.getInputPaths(t)){const t=await this.getAccount(i.account);t&&(e=t.derivePath(i,this.master))&&r.push(e)}return r}async getKey(t){if(t=w.getHash(t,"hex",this.network.type),!(t=await this.getPath(t)))return null;const e=await this.getAccount(t.account);return e?e.derivePath(t,this.master):null}async exportToFile(t){if(!st.unsupported){var e=await this.db.getTip(),r=o.date();let n=1,a="",c=[o.fmt("# Wallet Dump created by %s %s",nt.protocol,nt.version),o.fmt("# * Created on %s",r),o.fmt("# * Best block at time of backup was %d (%s).",e.height,o.revHex(e.hash)),o.fmt("# * File: %s",t.file),""];var i;e=o.fmt("W %s wid= %s",this.toRaw().toString("base64"),this.wid),e=(c.push(e),await this.getAccounts());for(const t of e){const e=await this.getAccount(t);var s=o.fmt("C %s name= %s index= %d",e.toRaw().toString("base64"),e.name,e.accountIndex);c.push(s)}for(const e of await this.getAddressHashes()){const s=await this.getPrivateKey(e);s&&(i=s.getAddress("string"),i=o.fmt("A %s %s label= account= %s branch= %s index= %s addr= %s",s.toSecret(),r,s.account,s.branch,s.index,i),c.push(i),1e5<c.length&&(a=c.join("\n"),await st.writeFile(`${t.file}-${n++}.txt`,a,"utf8"),c=[]))}c.push(""),c.push("# End of dump"),c.push(""),a=c.join("\n"),await st.writeFile(`${t.file}-${n++}.txt`,a,"utf8")}}async getPrivateKey(t,e){if(t=w.getHash(t,"hex"),!(t=await this.getPath(t)))return null;const r=await this.getAccount(t.account);return r?(await this.unlock(e),(e=r.derivePath(t,this.master)).privateKey?e:null):null}async getInputPaths(t){if(i(t.mutable),!t.hasCoins())throw new Error("Not all coins available.");const e=[];for(const i of t.getInputHashes("hex")){var r=await this.getPath(i);r&&e.push(r)}return e}async getOutputPaths(t){const e=[];for(const i of t.getOutputHashes("hex")){var r=await this.getPath(i);r&&e.push(r)}return e}async setLookahead(t,e){const r=await this.writeLock.lock();try{return this._setLookahead(t,e)}finally{r()}}async _setLookahead(t,e){null==e&&(e=t,t=null);const r=await this.getAccount(t=null==t?0:t);if(!r)throw new Error("Account not found.");this.start();try{await r.setLookahead(e)}catch(t){throw this.drop(),t}await this.commit()}async syncOutputDepth(t){const e=new Map;for(const i of t.outputs){var r=i.path;r&&-1!==r.index&&(e.has(r.account)||e.set(r.account,[]),e.get(r.account).push(r))}const s=[];for(var[n,a]of e){let t=-1,e=-1,r=-1;for(const i of a)switch(i.branch){case 0:i.index>t&&(t=i.index);break;case 1:i.index>e&&(e=i.index);break;case 2:i.index>r&&(r=i.index)}t+=2,e+=2,r+=2;const o=await this.getAccount(n);i(o),(a=await o.syncDepth(t,e,r))&&s.push(a)}return s}async getRedeem(t){"string"==typeof t&&(t=Buffer.from(t,"hex"));const e=await this.getKey(t.toString("hex"));return e?e.getRedeem(t):null}async template(t){var e=await this.deriveInputs(t);return t.sign(e)}async getOrderList(t,e){let r=[],i=new rt,s=((await this.getHistory(e||"default")).reduce((t,e)=>{let{tx:i,hash:s,height:n}=e;if(i.outputs[0].getReturnType(B.OP_RETURN))try{var a=JSON.parse(i.outputs[0].script.code[1].toString());if(a&&a.oper==$.payOrder){let e=W.fromJson(a);e.hash=s,e.height=n,t.set(""+e.cid+e.sn,e),r.push(e.cid)}}catch(e){}return t},i),i.query(t));return await this.db.flushCP(r),s.list.map(t=>{t.cp=this.db.cpList.getItem(t.cid)}),s}async propCreate(t,e){const r=new x;for(var s of t){var n=await this.ensureCp(s.cid,!0);n&&s.cid!=this.network.genesisId&&(s.gold=(0|s.gold)>>>0,s.gold<P.MINPROPVALUE||(s.pid||(s.pid=z()),r.propCreate(n.current.address,s),s.index=r.outputs.length-1))}if(0<r.outputs.length){e?await this.fund(r,{account:e}):await this.fund(r),await this.sign(r);let s=r.commit();for(var a of(await this.db.addTX(s[0]),await this.db.send(s[0]),i(s[0].verify(s[1],k.flags.STANDARD_VERIFY_FLAGS)),t))a.hash=s[0].hash("hex"),a.txid=s[0].txid();return s}return[]}async stockAddress(t,e){return await this.ensureAccount({name:e,witness:!0}),(await this.createReceive(e,o.hashInt(t),this.master)).getAddress()}async stockOffer(t,e,r,s){i(!!t),i(!!e),i(!!r),e=(0|e)>>>0,r=(0|r)>>>0;var n=await this.ensureCp(t);let a=await this.getKey(n.current.address);if(i(!!a),s&&s!==a.name)throw new L(H.errors.TYPE_ERROR,"illegal account");t=a.signData({cid:t,type:X.RecordType.Offer,sum:e,price:r});const o=new x;o.outputs.push(_.fromScript(t.data.addr,.05*e*r));let c=new K($.stock,z(),this.db.curHeight,t);e=_.fromScript(k.createScript(c.toRaw(),k.types.NULLDATA),0),o.outputs.push(e),s?await this.fund(o,{account:s}):await this.fund(o),o.outputs.shift(),await this.sign(o);let u=o.commit();return i(u[0].verify(u[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.verifyClsTx(u[0]),await this.db.send(u[0]),c.hash=u[0].hash("hex"),c.height=-1,c.cp=n,c}async stockPurchase(t,e,r){if(i(!!t),i(!!e),(e=(0|e)>>>0)<P.STOCK_TRADE_SINGLE||e>P.STOCK_MAX_TRADE_SINGLE)throw new L(H.errors.TYPE_ERROR,"Invalid Stock Amount.");var s=await this.ensureCp(t);t={type:X.RecordType.Purchase,cid:t,uid:r,seq:0,to:s.current.address,sum:e},await this.addStockAccountSeq(t),t=await this.tokenCreate(t,r);const n=new x;let a=new K($.stock,z(),this.db.curHeight,t);t=_.fromScript(k.createScript(a.toRaw(),k.types.NULLDATA),0),n.outputs.push(t),n.outputs.push(_.fromScript(s.current.address,e*s.stock.price)),r?await this.fund(n,{account:r}):await this.fund(n),await this.sign(n);let o=n.commit();return i(o[0].verify(o[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.verifyClsTx(o[0]),await this.db.send(o[0]),a.hash=o[0].hash("hex"),a.height=-1,a.cp=s,a}async stockPurchaseTo(t,e,r,s){if(i(!!t),i(!!e),(e=(0|e)>>>0)<P.STOCK_TRADE_SINGLE||e>P.STOCK_MAX_TRADE_SINGLE)throw new L(H.errors.TYPE_ERROR,"Invalid Stock Amount.");var n=await this.ensureCp(t);t={type:X.RecordType.Purchase,cid:t,uid:r,seq:0,to:n.current.address,sum:e},await this.addStockAccountSeq(t),t=await this.tokenCreate(t,r);const a=new x;let o=new K($.stock,z(),this.db.curHeight,t);r=_.fromScript(k.createScript(o.toRaw(),k.types.NULLDATA),0),a.outputs.push(r),a.outputs.push(_.fromScript(n.current.address,e*n.stock.price)),s?await this.fund(a,{account:s}):await this.fund(a),await this.sign(a);let c=a.commit();return i(c[0].verify(c[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.verifyClsTx(c[0]),await this.db.send(c[0]),o.hash=c[0].hash("hex"),o.height=-1,o.cp=n,o}async stockSend(t,e,r,s,n){i(!!t),i(!!e),e=(0|e)>>>0;var a=await this.ensureCp(t,!0);if(!a)return null;t={type:X.RecordType.Send,cid:t,uid:s,seq:0,sum:e,to:r},await this.addStockAccountSeq(t),e=await this.tokenCreate(t,s,n);const o=new x;let c=new K($.stock,z(),this.db.curHeight,e);r=_.fromScript(k.createScript(c.toRaw(),k.types.NULLDATA),0),o.outputs.push(r),s?await this.fund(o,{account:s}):await this.fund(o),await this.sign(o);let u=o.commit();return i(u[0].verify(u[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.verifyClsTx(u[0]),await this.db.send(u[0]),c.hash=u[0].hash("hex"),c.height=-1,c.cp=a,c}async stockBid(t,e,r,s,n){i(!!t),i(!!e),i(!!r),e=(0|e)>>>0,r=(0|r)>>>0;var a=await this.ensureCp(t,!0);if(!a)return null;t={type:X.RecordType.Bid,cid:t,uid:s,seq:0,sum:e,price:r},await this.addStockAccountSeq(t),t=await this.tokenCreate(t,s,n);const o=new x;o.outputs.push(_.fromScript(t.data.addr,.05*e*r));let c=new K($.stock,z(),this.db.curHeight,t);n=_.fromScript(k.createScript(c.toRaw(),k.types.NULLDATA),0),o.outputs.push(n),s?await this.fund(o,{account:s}):await this.fund(o),o.outputs.shift(),await this.sign(o);let u=o.commit();return i(u[0].verify(u[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.verifyClsTx(u[0]),await this.db.send(u[0]),c.hash=u[0].hash("hex"),c.height=-1,c.cp=a,c}async stockAuction(t,e,r,s,n,a){i(!!t),i(!!e),i(!!r);var o=await this.ensureCp(t,!0);if(!o)return null;r=(0|r)>>>0,t={type:X.RecordType.Auction,cid:t,to:e,uid:n,seq:0,sum:r,price:s},await this.addStockAccountSeq(t),t=await this.tokenCreate(t,n,a);const c=new x;let u=new K($.stock,z(),this.db.curHeight,t);a=_.fromScript(k.createScript(u.toRaw(),k.types.NULLDATA),0),c.outputs.push(a),c.outputs.push(_.fromScript(e,r*s)),n?await this.fund(c,{account:n}):await this.fund(c),await this.sign(c);let h=c.commit();return i(h[0].verify(h[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.verifyClsTx(h[0]),await this.db.send(h[0]),u.hash=h[0].hash("hex"),u.height=-1,u.cp=o,u}async sendSecret(t,e,r){let i=this.db.$contacts.get(t);if(!i||!i.sender){var s=(await this.createReceive(r)).getAddress("string");if(t==s)throw new L(H.errors.TYPE_ERROR,"Forbid Sending to Self Address.");i=await this.db.ensureContact({contact:t,messenger:s,wallet:this,account:r})}if(i)return i.send(e);throw new L(H.errors.TYPE_ERROR,"Invalid Address.")}async commNotify(t){i(!!t),i(!!t.dst),i(!!t.content);const e=new x;var r=t.src||this.getReceive().toString();let s=new K($.notify,z(),this.db.curHeight,{src:r,content:t.content});r=_.fromScript(k.createScript(s.toRaw(),k.types.NULLDATA),0),e.outputs.push(r),r={address:t.dst,locktime:P.BLOCK_DAY,locktype:"csb",value:.1*P.COIN},e.outputs.push(new _(r)),t.account?await this.fund(e,{account:t.account,noChange:!0,allowInfiniteFee:!0}):await this.fund(e,{noChange:!0,allowInfiniteFee:!0}),await this.sign(e);let n=e.commit();return i(n[0].verify(n[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(n[0]),this.logger.debug("Sending tx on wallet(%s): %s",this.id,n[0].txid()),await this.db.send(n[0]),s.hash=n[0].hash("hex"),s.height=-1,s}async payOrder(t,e,r,s,n){i(!!t),i(!!e),i(!!r),i(!!s);var a=(await this.tokenCreate({cid:t,uid:e},n)).data.addr,c=(r=o.sprintf("%0-36s",r),await this.getOrderList([["cid",t],["sn",r]],n));if(0<c.list.length)return c.list[0];if((s=(0|s)>>>0)<P.MINPROPVALUE)return null;if(!(c=await this.ensureCp(t,!0)))return null;let u=new W(t,e,r,s,a,"");const h=new x;for(t=_.fromScript(k.createScript(Buffer.from(JSON.stringify(u)),k.types.NULLDATA),0),h.outputs.push(t),h.outputs.push(_.fromScript(c.current.address,s)),n?await this.fund(h,{account:n}):await this.fund(h);2<h.outputs.length;)h.outputs.pop();await this.sign(h,null,N.ZERO|N.ANYONECANPAY);let l=h.commit();return i(l[0].verify(l[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(l[0]),await this.db.send(l[0]),u.hash=l[0].hash("hex"),u.height=-1,u.cp=c,u}async cpRegister(t,e,r,s){if(i(!!e&&"object"==typeof e),!await this.db.client.execute("canExecute",[{confirm:!1,cid:e.cid,name:e.name,oper:$.cpRegister}]))throw new L(H.errors.TYPE_ERROR,"Invalid CP Register Info.");const n=new x;if(!t){let e=await this.createReceive(r);t=e.getAddress()}let a=await this.getKey(t);if(!a)throw new L(H.errors.TYPE_ERROR,"Invalid CP Register Address, Not along to this wallet.");e.pubAddress=t.toString(),e.pubKey=a.getPublicKey("hex"),e.signMethod="secp256k1",e.register=this.master.key.publicKey.toString("hex"),n.cpRegister(t,P.registerFee,e);for(let r=0;r<10;r++){var c=""+e.cid+this.network.stockFix+o.sprintf("%02d",r);c={oper:$.propCreate,pid:c,oid:e.cid,cid:e.cid,gold:P.MINPROPVALUE};n.propCreate(t,c)}var u=async()=>{r?await this.fund(n,{account:r}):await this.fund(n),await this.sign(n);let s=n.commit();return i(s[0].verify(s[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(s[0]),await this.db.send(s[0]),e.txid=s[0].txid(),e.addr=t.toString(),s};if(!s)return u();u()}async cpX509(t,e){var r=await this.ensureCp(t);let i=await this.getKey(r.pubAddress);if(!i)throw new L(H.errors.TYPE_ERROR,"Invalid cid, Not along to this wallet.");if(u=this.db.x509CertList.get(tt.getKey(t,1)))return[u,{}];const s=new Date,a=new Date(s.getTime()+315576e6),o=new n.asn1.DERUTCTime({date:s}),c=new n.asn1.DERUTCTime({date:a});var u=i.privateKey.toString("Hex"),h=j.publicKeyConvert(i.publicKey,!1).toString("Hex");u=new n.crypto.ECDSA({curve:"secp256k1",prv:u,pub:h}),h="/C=CN/O=ggserver/OU="+t+"/CN="+r.name,h=n.asn1.x509.X509Util.newCertPEM({serial:{int:1},sigalg:{name:"SHA256withECDSA"},issuer:{str:h},notbefore:{str:o.getString()},notafter:{str:c.getString()},subject:{str:h},sbjpubkey:u,ext:[{basicConstraints:{cA:!1,critical:!0}},{keyUsage:{bin:"11111"}}],cakey:u});let l=new tt({oper:"x509Issue",witness:t,certSq:1,activeTime:a.getTime(),cert:h});return l.sign(i),u=l.toOptions(!0),t={outputs:[{address:r.pubAddress,value:1e4}],comment:u},[u,await this.send(t,e)]}async x509Issue(t,e){var r=await this.ensureCp(t.cid);let i=await this.getKey(r.pubAddress);if(!i)throw new L(H.errors.TYPE_ERROR,"Invalid cid, Not along to this wallet.");var s=o.hashInt(t.csrData),a=this.db.x509CertList.get(tt.getKey(t.cid,s));if(a)return[a,{}];if(!(a=n.asn1.csr.CSRUtil.getInfo(t.csrData))||!a.pubkey||!a.pubkey.obj)throw new L(H.errors.TYPE_ERROR,"Invalid csr request Data!");var c=a.pubkey.obj;if("object"!=typeof c||!(c instanceof n.crypto.ECDSA)||"secp256k1"!=c.curveName)throw new L(H.errors.TYPE_ERROR,"Invalid csr request Alg, Use secp256k1 ECC !");var u=new Date,h=new Date(t.activeTime);const l=new n.asn1.DERUTCTime({date:u}),p=new n.asn1.DERUTCTime({date:h});u=i.privateKey.toString("Hex"),h=j.publicKeyConvert(i.publicKey,!1).toString("Hex"),u=new n.crypto.ECDSA({curve:"secp256k1",prv:u,pub:h}),h="/C=CN/O=ggserver/OU="+t.cid+"/CN="+r.name,r=n.asn1.x509.X509Util.newCertPEM({serial:{int:s},sigalg:{name:"SHA256withECDSA"},issuer:{str:h},notbefore:{str:l.getString()},notafter:{str:p.getString()},subject:{str:a.subject.name},sbjpubkey:c,ext:[{basicConstraints:{cA:!1,critical:!0}},{keyUsage:{bin:"11"}}],cakey:u});let d=new tt({oper:"x509Issue",witness:t.cid,certSq:s,activeTime:t.activeTime,cert:r});return d.sign(i),h=d.toOptions(!0),a={outputs:[{address:t.addr.toString(),value:1e4}],comment:h},[h,await this.send(a,e)]}async x509Abolish(t,e){var r=await this.ensureCp(t.cid),i=await this.getKey(r.pubAddress);if(!i)throw new L(H.errors.TYPE_ERROR,"Invalid cid, Not along to this wallet.");if(!this.db.x509CertList.get(tt.getKey(t.cid,t.seqno)))throw new L(H.errors.TYPE_ERROR,"Invalid Cert SeqNo, Not find Cert");let s=new et({oper:"x509Abolish",witness:t.cid,certSq:t.seqno,activeTime:t.activeTime});return s.sign(i),t=s.toOptions(!0),i={outputs:[{address:r.pubAddress,value:1e4}],comment:t},[t,await this.send(i,e)]}getSCAddress(t){return t=it.fromMnemonic(F.fromOptions(P.SmartContractMnemonic),this.network).deriveAccount(44,t).derive(9).derive(1),w.fromWitnessPubkeyhash(p.hash160(t.publicKey),this.network)}async cpChange(t,e){var r=await this.ensureCp(t.cid);if(r.cid==this.network.genesisId||"ATHENA"==r.name)throw new L(H.errors.TYPE_ERROR,"Invalid cp name.");let s=await this.getTX(r.current.hash);if(!s)throw new L(H.errors.TYPE_ERROR,"Do not have permission to change this info.");if(s=s.tx,!await this.belongToAccount(e,s.outputs[0].getAddress()))throw new L(H.errors.TYPE_ERROR,"Invalid account info.");if(t.newName){if(!await this.db.client.execute("canExecute",[{confirm:!1,cid:r.cid,name:t.newName,oper:$.cpChange}]))throw new L(H.errors.TYPE_ERROR,"Invalid CP Change Info.")}else t.newName=r.name;t.addr||(t.addr=w.fromString(r.current.address));const n=x.cpChange(s,t);e?await this.fund(n,{allowPreInput:!0,account:e}):await this.fund(n,{allowPreInput:!0}),await this.sign(n);let a=n.commit();return await this.db.send(a[0]),i(a[0].verify(a[1],k.flags.STANDARD_VERIFY_FLAGS)),t.txid=a[0].txid(),a}async propExchangeList(t,e,r=!1){let s=new x,n=[];for(var[a,o,c]of t){let t=null;var u;if(t=await this.getTX(a.hash)){if(t=t.tx,u=a.index,t&&t.outputs&&!(t.outputs.length<=u))if(r||await this.belongToAccount(e,t.outputs[u].getAddress())){let e=t.outputs[u].getReturnData();e&&(s.propExchange(t,u,o),e.index=s.outputs.length-1,e.addr=o.toString(),n.push(e))}else this.logger.error("not owned prop:",a.hash,a.index)}else this.logger.error("tx not find:",a.hash,c)}e?await this.fund(s,{allowPreInput:!0,account:e}):await this.fund(s,{allowPreInput:!0}),await this.sign(s);let h=s.commit();return await this.db.addTX(h[0]),await this.db.send(h[0]),i(h[0].verify(h[1],k.flags.STANDARD_VERIFY_FLAGS)),h.push(n),h}async propDonate(t,e){var r=t.index;let i=await this.getTX(t.hash);if(!i||!i.tx||!i.tx.outputs||i.tx.outputs.length<=r)throw new L(H.errors.TYPE_ERROR,"Invalid tx info.");if(!await this.belongToAccount(e,i.tx.outputs[r].getAddress()))throw new L(H.errors.TYPE_ERROR,"Props that do not belong to you.");if(!(t=i.tx.outputs[r].getReturnData()))throw new L(H.errors.TYPE_ERROR,"Invalid tx info.");if(t.cid&&t.cid==this.network.genesisId)throw new Y(i.tx,"invalid","Special props that can not to donate",100);const s=new x;s.addInputFromTx(i.tx,r),s.addOutput(k.createScript(Buffer.from(JSON.stringify({value:i.tx.outputs[r].value,cid:t.cid,pid:t.pid,oid:t.oid,gaddr:this.getAddress().toString(this.network)})),k.types.NULLDATA),0),await this.sign(s,null,N.NONE|N.ANYONECANPAY);let n=s.commit();return n.push(t),n}async propReceive(t,e){let r=x.fromTX(t,1);t=r.inputs[0].prevout;let i=r.outputs[0].getReturnData(),s=(r.view.addOutput({hash:r.inputs[0].prevout.hash,index:r.inputs[0].prevout.index},new _({value:i.value})),r.outputs.pop(),this.getAddress().toString(this.network));e&&(n={cid:i.cid,uid:e},s=(n=await this.tokenCreate(n,e)).data.addr),r.outputs.push(_.fromScript(s,i.value,{oper:$.propExchange,pid:i.pid,cid:i.cid,oid:i.oid,prev:{hash:t.hash,index:t.index}})),e?await this.fund(r,{allowPreInput:!0,account:e}):await this.fund(r,{allowPreInput:!0}),await this.sign(r,null,N.ALL,[0]);var n=r.commit();return await this.db.send(n[0]),i.simAddr=s,[n[0],null,i]}async belongToAccount(t,e){return!(!e||!(e=await this.getAccountByAddress(e))||t&&e.name!==t)}async propExchange(t,e,r){let s=null,n=0;var a;if(Array.isArray(t)?(s=t[0],n=t[1]):(a=await this.getTX(t.hash))&&(s=a.tx,n=t.index),!s||!s.outputs||s.outputs.length<=n)return this.logger.error("Invalid tx info."),null;if(!await this.belongToAccount(r,s.outputs[n].getAddress()))return this.logger.error("Invalid user."),null;let o=s.outputs[n].getReturnData();if(!o)return this.logger.error("Invalid tx info."),null;const c=(new x).propExchange(s,n,e);o.index=c.outputs.length-1,r?await this.fund(c,{allowPreInput:!0,account:r}):await this.fund(c,{allowPreInput:!0}),await this.sign(c);let u=c.commit();return await this.db.addTX(u[0]),await this.db.send(u[0]),i(u[0].verify(u[1],k.flags.STANDARD_VERIFY_FLAGS)),u.push(o),u}async propFound(t,e){if(t=await this.getTX(t),i(t),!(t=t.tx))throw new L(H.errors.TYPE_ERROR,"Invalid hex string.");let r=0,s=(3<=t.outputs.length&&(r=2),t.outputs[r]);var n=s.getReturnData();if(!n||n.oper!==$.propExchange&&n.oper!==$.propCreate)throw new L(H.errors.TYPE_ERROR,"Invalid tx type.");if(n.cid==this.network.genesisId)throw new Y(block,"invalid","prop found supertoken",100);const a=new x;a.addInputFromTx(t,r),t=_.fromScript(s.getAddress(),s.value),a.outputs.push(t),e?await this.fund(a,{allowPreInput:!0,subtractFee:!0,account:e}):await this.fund(a,{allowPreInput:!0,subtractFee:!0}),await this.sign(a);let o=a.commit();return await this.db.send(o[0]),i(o[0].verify(o[1],k.flags.STANDARD_VERIFY_FLAGS)),o.push(n),o}async propSale(t,e,r,s){let n=await this.getTX(t);if(!n)throw new L(H.errors.TYPE_ERROR,"Invalid tx info.");if(n.getDepth(this.db.curHeight)<=0)throw new L(H.errors.TYPE_ERROR,"No enough confirmations.");if(!(n=n.tx))throw new L(H.errors.TYPE_ERROR,"Invalid tx info.");n.outputs[0].getReturnType(k.opcodes.OP_RETURN)&&(e=2);var a=n.outputs[e].getReturnData([k.opcodes.OP_PROPEXCHANGE,k.opcodes.OP_PROPCREATE]);if(!a)throw new L(H.errors.TYPE_ERROR,"Invalid tx type.");if(!await this.belongToAccount(s,n.outputs[e].getAddress()))throw new L(H.errors.TYPE_ERROR,"Invalid tx info.");if(!(s=await this.getCoin(t,e))||-1===s.height||-2===s.height)throw new L(H.errors.WALLET_INSUFFICIENT_FUNDS,"Invalid coin.");if(await this.txdb.isSpent(t,e))throw new L(H.errors.WALLET_INSUFFICIENT_FUNDS,"Invalid coin.");if(r<=n.outputs[e].value)throw new L(H.errors.TYPE_ERROR,"Invalid fixed price.");if(a.cid==this.network.genesisId)throw new Y(n,"invalid","prop not for sale",100);const o=new x;s=o.addInputFromTx(n,e),t={oper:$.propSale,pid:a.pid,prev:{hash:s.prevout.hash,index:s.prevout.index},fixed:r,period:this.db.curHeight+P.BLOCK_DAY},e=_.fromScript(k.createScript(Buffer.from(JSON.stringify(t)),k.types.NULLDATA),0),o.outputs.push(e),await this.sign(o,null,N.SINGLE|N.ANYONECANPAY);let c=o.commit();return i(c[0].verify(c[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.send(c[0]),c}async propBuy(t,e,r){if(!(t=this.db.propList.get(t))||!t.bid||!t.bid.raw)throw new L(H.errors.INVALID_PARAMS,"Invalid Tx Hash.");const i=U.fromRaw(Buffer.from(t.bid.raw,"hex"));var s=(await this.createReceive(r)).getAddress(),n=t.gold,a=w.fromString(t.current.address,this.network).getHash();if(e<n)throw new Error("wrong price");if(1<i.outputs.length&&e<i.outputs[1].value)throw new Error("low bid price than before");let o=x.fromTX(i,1);if(!o.outputs[0].getReturnType(B.OP_RETURN))throw new Error("not a sale order");return await this.remove(i.hash("hex")),o.view.addOutput({hash:o.inputs[0].prevout.hash,index:o.inputs[0].prevout.index},new _({value:t.gold})),a=_.fromScript(k.createScript(a),e),o.outputs.push(a),e={oper:$.propExchange,pid:t.pid,cid:t.cid,oid:t.oid,prev:{hash:o.inputs[0].prevout.hash,index:o.inputs[0].prevout.index}},a=_.fromScript(s,n,e),o.outputs.push(a),r?await this.fund(o,{allowPreInput:!0,account:r}):await this.fund(o,{allowPreInput:!0}),await this.sign(o,null,N.ALL,[0]),s=o.commit(),t.owned||this.db.client.watchOutpoint((new M).fromOptions(i.inputs[0].prevout)),await this.db.send(s[0]),s}async getTXByAmount(t,e){let r=null;var i;for(i of await this.getCoins(e))if(!(i.height<=0)&&i.value==t){r=i;break}return r&&(e=await this.getTX(r.hash))?[e.tx,r.index,r.height]:[]}async contractCreate(t,e,r,s,n){if(this.db.transactionList.query(t,s)!=G.None)throw new L(H.errors.TYPE_ERROR,"Contract with the same address finded.");if(0!=parseInt(e%1e3,10))throw new L(H.errors.TYPE_ERROR,"Contract source should an integer multiple of 1000.");if(!await q.checkSum(this.network,t,s))throw new L(H.errors.TYPE_ERROR,"Create contract with an invalid Address or a Address with old transations.");let a=!1,[o,c,u]=await this.getTXByAmount(e,n);if(!o){a=!0;const t=new x;let r="";if(n){r=(await this.createReceive(n)).getAddress()}else r=this.getAddress();t.outputs.push(_.fromScript(r,e)),n?await this.fund(t,{allowPreInput:!0,account:n}):await this.fund(t,{allowPreInput:!0}),await this.sign(t);let s=t.commit();i(s[0].verify(s[1],k.flags.STANDARD_VERIFY_FLAGS)),o=s[0],c=0,u=-1}const h=new x;h.addInputFromTx(o,c,u);let l="";if(n){l=(await this.createReceive(n)).getAddress()}else l=this.getAddress();let p=await this.getKey(l);return t={oper:$.contractCreate,type:t,addr:s,src:e,dst:r,srcact:n,alice:p.getPublicKey("hex"),period:this.db.curHeight+P.TRANSACTION_PERIOD},s=_.fromScript(k.createScript(Buffer.from(JSON.stringify(t)),k.types.NULLDATA),0),h.outputs.push(s),await this.sign(h,null,N.SINGLE|N.ANYONECANPAY),e=h.commit(),a&&await this.db.send(o),await this.db.send(e[0]),e}async contractPromise(t,e){if(!(t=this.db.transactionList.get(t))||t.transStatus!=G.CreatedOnMem)throw new L(H.errors.INVALID_PARAMS,"Invalid Tx id.");const r=U.fromRaw(Buffer.from(t.raw,"hex"));if(!r)throw new L(H.errors.TYPE_ERROR,"Invalid Tx id.");if(!(t=q.parseContract(r))||t.oper!==$.contractCreate)throw new L(H.errors.TYPE_ERROR,"Invalid tx type.");let i=x.fromTX(r,1);if(!i.outputs[0].getReturnType(B.OP_RETURN))throw new Error("not a valid contract");i.view.addOutput({hash:i.inputs[0].prevout.hash,index:i.inputs[0].prevout.index},new _({value:t.src}));let s="";if(e){s=(await this.createReceive(e)).getAddress()}else s=this.getAddress();let n=await this.getKey(s),a={oper:$.contractPromise,prevhash:r.hash("hex"),type:t.type,addr:t.addr,dst:t.dst,srcact:t.srcact,dstact:e,bob:n.getPublicKey("hex"),period:t.period};e=new k([D.fromSymbol("promise"),D.fromData(Buffer.from(JSON.stringify(a))),D.fromSymbol("drop"),D.fromSymbol("greaterthan"),D.fromSymbol("drop"),D.fromSymbol("if"),D.fromData(p.hash160(Buffer.from(a.bob,"hex"))),D.fromSymbol("else"),D.fromData(p.hash160(Buffer.from(t.alice,"hex"))),D.fromSymbol("endif"),D.fromSymbol("checksig")]),i.outputs.push(_.fromScript(e,t.src)),await this.remove(a.prevhash),await this.sign(i,null,N.ALL,[0]);let o=i.commit();return await this.db.send(o[0]),a.current={hash:o[0].hash("hex"),index:0},a.raw=o[0].toRaw().toString("hex"),a.transStatus=G.Promised,this.db.transactionList.saveContract(a,!0),o}async contractExecute(t,e){if(!(t=this.db.transactionList.get(t))||t.transStatus!=G.Confirmed&&t.transStatus!=G.Expired)throw new L(H.errors.INVALID_PARAMS,"Invalid Tx id.");const r=U.fromRaw(Buffer.from(t.raw,"hex"));if(!r)throw new L(H.errors.TYPE_ERROR,"Invalid Tx id.");if(e=e||1,!(t=q.parseContract(r))||t.oper!==$.contractPromise)throw new L(H.errors.TYPE_ERROR,"Invalid tx type.");var s=r.outputs[1].getReturnData();if(!s||s.oper!==$.contractPromise)throw new L(H.errors.TYPE_ERROR,"Invalid tx type.");i.strictEqual(t.addr,s.addr),i.strictEqual(t.type,s.type),i.strictEqual(t.dst,s.dst),i.strictEqual(t.period,s.period),i.strictEqual(t.srcact,s.srcact),i.strictEqual(t.dstact,s.dstact);var n=this.db.transactionList.query(t.type,t.addr);if(n!=G.Confirmed&&n!=G.Expired)throw new L(H.errors.TYPE_ERROR,"Contract Promise not Check yet.");if(n==G.Expired&&1!=e||n==G.Confirmed&&2!=e)throw new L(H.errors.TYPE_ERROR,"Invalid Executor.");let a=t.srcact,o="";if(a=2==e?t.dstact:a){o=(await this.createReceive(a)).getAddress()}else o=this.getAddress();let c=new x;c.addInputFromTx(r,1);var u={oper:$.contractExecute,type:t.type,addr:t.addr,master:e};u=_.fromScript(k.createScript(Buffer.from(JSON.stringify(u)),k.types.NULLDATA),0),c.outputs.push(u),u=_.fromScript(o,r.outputs[1].value);c.outputs.push(u);let h=1==e?await T.fromPublic(Buffer.from(t.ori.alice,"hex")):await T.fromPublic(Buffer.from(s.bob,"hex"));u=await this.getKey(h.getAddress()),await c.signAsync(u,k.hashType.ALL,this.db.workers);let l=c.commit();return i(l[0].verify(l[1],k.flags.STANDARD_VERIFY_FLAGS,n)),await this.db.send(l[0]),l}async htlcDeal(t,e){var r=await this.getTX(t.hash);let i=null;if(e){const t=await this.getAccount(e);if(!t)throw new L(H.errors.TYPE_ERROR,"Invalid Account.");i=t.getReceive().toString()}else i=this.getReceive().toString();const s=new x;let n=(new k).pushOp(B.OP_1);return t.suggest&&n.pushData(Buffer.from(t.sa,"hex")),s.addInput({prevout:{hash:t.hash,index:t.index},script:n}),s.addOutput(i,r.tx.outputs[t.index].value-1e4),s.view.addOutput({hash:t.hash,index:t.index},new _(r.tx.outputs[t.index])),await this.sign(s,null,N.ALL),e=s.commit(),await this.db.send(e[0]),e}async htlcCancel(t,e){let r=null;var i=await this.getTX(t.hash);if(!(r=i?i.tx.outputs[t.index]:r))throw new L(H.errors.TYPE_ERROR,"Invalid Input.");let s=null;if(e){const t=await this.getAccount(e);if(!t)throw new L(H.errors.TYPE_ERROR,"Invalid Account.");s=t.getReceive().toString()}else s=this.getReceive().toString();const n=new x;let a=(new k).pushOp(B.OP_0);return t.suggest&&a.pushData(Buffer.from(t.sa,"hex")),n.addInput({prevout:{hash:t.hash,index:t.index},script:a}),t.suggest?n.setSequence(0,2*P.HTLC_CANCEL_PERIOD,!1):n.setSequence(0,P.HTLC_CANCEL_PERIOD,!1),n.addOutput(s,r.value-1e4),n.view.addOutput({hash:t.hash,index:t.index},new _(r)),i=await this.getKey(t.master),await n.signAsync(i,k.hashType.ALL,this.db.workers),e=n.commit(),await this.db.send(e[0]),e}async sendContracts(t,e,r){const i=new x;for(var s of t)i.outputs.push(r.create(s));return e?await this.fund(i,{account:e}):await this.fund(i),await this.sign(i),t=i.commit(),await this.db.addTX(t[0]),await this.db.send(t[0]),t}async addStockAccountSeq(t){i(t&&"object"==typeof t,"Token data should be a object"),i(t.cid,"Token data should has a cid property"),i(t.uid,"Token data should has a uid property");let e=await this.stockAddress(t.cid,t.uid);var r=this.db.accountList.getOrCreateStockAccount(t.cid,e.toString());return t.seq=r.seq+1,t}async tokenCreate(t,e="",r){i(t&&"object"==typeof t,"Token data should be a object"),i(t.cid,"Token data should has a cid property"),i(t.uid,"Token data should has a uid property"),t.time=!0,await this.ensureAccount({name:e,witness:!0});let s=null;if(r){if(!await this.belongToAccount(e,r))throw new L(H.errors.TYPE_ERROR,`stock.send address error: addr:${r} is not belongs to account:`+e);s=await this.getKey(r)}else s=await this.createReceive(e,o.hashInt(t.cid),this.master);return s.signData(t)}async sign(t,e,r=k.hashType.ALL,i){if(this.watchOnly)throw new Error("Cannot sign from a watch-only wallet.");return await this.unlock(e),e=await this.deriveInputs(t),t.signAsync(e,r,this.db.workers,i)}getCoinView(t){return this.txdb.getCoinView(t)}getSpentView(t){return this.txdb.getSpentView(t)}toDetails(t){return this.txdb.toDetails(t)}getDetails(t){return this.txdb.getDetails(t)}async getCoin(t,e){return this.txdb.getCoin(t,e)}async getCredit(t,e){return this.txdb.getCredit(t,e)}async getStatusOfSC(t){return this.txdb.getStatusOfSC(t)}async setStatusOfSC(t,e){const r=await this.writeLock.lock();try{this.txdb.start();try{await this.txdb._setStatusOfSC(t,e),await this.txdb.commit()}catch(t){throw this.txdb.drop(),t}}finally{r()}}getLockedCoins(){return this.txdb.lockedCoins.values}getTX(t){return this.txdb.getTX(t)}getBlocks(){return this.txdb.getBlocks()}getBlock(t){return this.txdb.getBlock(t)}async add(t,e,r){const i=await this.writeLock.lock();try{return await this._add(t,e,r)}finally{i()}}async _add(t,e,r){let i,s;this.txdb.start();try{(i=await this.txdb._add(t,e,r))&&(s=await this.syncOutputDepth(i)),await this.txdb.commit()}catch(t){throw this.txdb.drop(),t}return s&&0<s.length&&(this.db.emit("address",this.id,s),this.emit("address",s)),i}async resetBalance(){const t=await this.writeLock.lock();try{this.txdb.start();try{await this.txdb.resetBalance(),await this.txdb.commit()}catch(t){throw this.txdb.drop(),t}}finally{t()}}async unconfirm(t){const e=await this.writeLock.lock();try{return await this.txdb.unconfirm(t)}finally{e()}}async remove(t){const e=await this.writeLock.lock();try{return await this.txdb.remove(t)}finally{e()}}async zap(t,e){const r=await this.writeLock.lock();try{return await this._zap(t,e)}finally{r()}}async _zap(t,e){return t=await this.ensureIndex(t),this.txdb.zap(t,e)}async abandon(t){const e=await this.writeLock.lock();try{return await this._abandon(t)}finally{e()}}_abandon(t){return this.txdb.abandon(t)}conserveCoin(t){return this.txdb.conserveCoin(t)}unConserveCoin(t){return this.txdb.unConserveCoin(t)}isConserved(t){return this.txdb.isConserved(t)}getConserved(){return this.txdb.getConserved()}async getHistory(t){return t=await this.ensureIndex(t),this.txdb.getHistory(t)}async getCoins(t){return t=await this.ensureIndex(t),this.txdb.getCoins(t)}async getCredits(t){return t=await this.ensureIndex(t),this.txdb.getCredits(t)}async getSmartCoins(t){const e=[];for(const i of await this.getCredits(t)){var r=i.coin;i.spent||this.txdb.isConserved(r)||(-1!==r.height&&-2!==r.height||i.own)&&e.push(r)}return e}async getPending(t){return t=await this.ensureIndex(t),this.txdb.getPending(t)}async getBalance(t){return t=await this.ensureIndex(t),this.txdb.getBalance(t)}async queryBalanceLog(t,e=0){return(t=await this.ensureIndex(t))?this.db.queryBalanceLog(this.wid,t,e):[]}async getRange(t,e){return t&&"object"==typeof t&&(e=t,t=null),t=await this.ensureIndex(t),this.txdb.getRange(t,e)}async getLast(t,e){return t=await this.ensureIndex(t),this.txdb.getLast(t,e)}async ensureIndex(t,e){if(null==t){if(e)throw new Error("No account provided.");return null}if(-1===(e=await this.getAccountIndex(t)))throw new Error("Account not found.");return e}getAddress(t){return this.account.getAddress(t)}getReceive(t){return this.account.getReceive(t)}getChange(t){return this.account.getChange(t)}getNested(t){return this.account.getNested(t)}inspect(){return{wid:this.wid,id:this.id,network:this.network.type,initialized:this.initialized,accountDepth:this.accountDepth,token:this.token.toString("hex"),tokenDepth:this.tokenDepth,state:this.txdb.state?this.txdb.state.toJSON(!0):null,master:this.master,account:this.account}}toJSON(t){return{network:this.network.type,wid:this.wid,id:this.id,initialized:this.initialized,watchOnly:this.watchOnly,accountDepth:this.accountDepth,token:this.token.toString("hex"),tokenDepth:this.tokenDepth,height:this.db.curHeight,state:this.txdb.state.toJSON(!0),master:this.master.toJSON(t),account:this.account.toJSON(!0)}}getSize(){var t=0;return(t+=50)+c.sizeVarString(this.id,"ascii")+c.sizeVarlen(this.master.getSize())}toRaw(){var t=this.getSize();const e=new m(t);return e.writeU32(this.network.magic),e.writeU32(this.wid),e.writeVarString(this.id,"ascii"),e.writeU8(this.initialized?1:0),e.writeU8(this.watchOnly?1:0),e.writeU32(this.accountDepth),e.writeBytes(this.token),e.writeU32(this.tokenDepth),e.writeVarBytes(this.master.toRaw()),e.render()}fromRaw(t){const e=new f(t);return t=a.fromMagic(e.readU32()),this.wid=e.readU32(),this.id=e.readVarString("ascii"),this.initialized=1===e.readU8(),this.watchOnly=1===e.readU8(),this.accountDepth=e.readU32(),this.token=e.readBytes(32),this.tokenDepth=e.readU32(),this.master.fromRaw(e.readVarBytes()),i(t===this.db.network,"Wallet network mismatch."),this}static fromRaw(t,e){return new at(t).fromRaw(e)}static isWallet(t){return t instanceof at}async issueCreate(t,e,r){let i=new J(t),s=(i.source.subjectName||(i.source.subjectName=i.erid),T.fromPrivate(Buffer.from(t.key,"hex"),!0,this.network));s.witness=!0,i.sign(s,!0,this.network);var n=i.toOptions(!0);return r?this.send({outputs:[{address:t.address,value:1e4}],comment:n},e):await this.send({outputs:[{address:t.address,value:1e4}],comment:n},e),n}async caAbolish(t,e,r){let i=T.fromPrivate(Buffer.from(t.key,"hex"),!0,this.network),s=(i.witness=!0,await this.db.$parent.chain.db.erList.getEr(t.erid));if(!s)throw new L(H.errors.TYPE_ERROR,"ca.abolish: Invalid erid.");if(s.source.cid!=t.cid)throw new L(H.errors.TYPE_ERROR,"ca.abolish: Invalid cid.");if(s.source.uid!=t.uid)throw new L(H.errors.TYPE_ERROR,"ca.abolish: Invalid uid.");var n=s.signature;if(s.sign(i,!0,this.network),s.witness!=t.witness||s.signature!=n)throw new L(H.errors.TYPE_ERROR,"ca.abolish: You have no permission to abolish this witness.");let a=new Z(t);return a.sign(i),n=a.toOptions(!0),r?this.send({outputs:[{address:t.address,value:1e4}],comment:n},e):await this.send({outputs:[{address:t.address,value:1e4}],comment:n},e),n}async enchanceCp(t,e){let r=new Q(t);r.oper="enchanceCp";t=await this.ensureCp(r.to);var i=await this.ensureCp(r.from);if(!(i=await this.getKey(i.pubAddress)))throw new L(H.errors.TYPE_ERROR,"Invalid cid, Not along to this wallet.");return r.sign(i),i=r.toOptions(!0),[await this.send({outputs:[{address:t.pubAddress,value:1e4}],comment:i},e),i]}async ensureCp(t,e=!1){if(await this.db.flushCP([t]),(t=this.db.cpList.getItem(t))||e)return t;throw new L(H.errors.TYPE_ERROR,"Invalid cid, cannot find cp.")}}t.exports=at},function(t,e,r){"use strict";
293
293
  /*!
294
294
  * BlockMeta.js - walletdb records
295
295
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -321,7 +321,7 @@ const i=r(21).opcodes;function s(t){let e=null;var r=s.list[t.type];return new(r
321
321
  * merkleblock.js - merkleblock object for vallnet
322
322
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
323
323
  * https://github.com/bookmansoft/gamegold
324
- */const i=r(0),s=r(1),n=r(2),a=r(4),o=r(3),c=r(6),u=r(7);var h=r(117);const l=r(89),p=Buffer.from([0]);class d extends h{constructor(t){super(),this.txs=[],this.hashes=[],this.flags=p,this.totalTX=0,this._tree=null,t&&this.fromOptions(t)}fromOptions(t){if(this.parseOptions(t),i(t,"MerkleBlock data is required."),i(Array.isArray(t.hashes)),i(Buffer.isBuffer(t.flags)),i(s.isU32(t.totalTX)),t.hashes)for(var e of t.hashes)"string"==typeof e&&(e=Buffer.from(e,"hex")),i(Buffer.isBuffer(e)),this.hashes.push(e);return t.flags&&(i(Buffer.isBuffer(t.flags)),this.flags=t.flags),null!=t.totalTX&&(i(s.isU32(t.totalTX)),this.totalTX=t.totalTX),this}static fromOptions(t){return(new d).fromOptions(t)}refresh(t){if(this._refresh(),this._tree=null,t)for(const t of this.txs)t.refresh()}hasTX(t){return-1!==this.indexOf(t)}indexOf(t){return null==(t=this.getTree().map.get(t))?-1:t}verifyBody(){var[t]=this.checkBody();return t}checkBody(){return this.getTree().root!==this.merkleRoot?[!1,"bad-txnmrklroot",100]:[!0,"valid",0]}getTree(){if(!this._tree)try{this._tree=this.extractTree()}catch(t){this._tree=new f}return this._tree}extractTree(){const t=[],e=[],r=new Map,i=this.hashes,s=this.flags,n=this.totalTX;let a=0,h=0,l=!1,p=0;const d=t=>n+(1<<t)-1>>>t,m=(n,u)=>{if(a>=8*s.length)return l=!0,o.ZERO_HASH;var p=s[a/8|0]>>>a%8&1;if(a++,0===n||!p){if(h>=i.length)return l=!0,o.ZERO_HASH;const s=i[h++];return 0===n&&p&&(p=s.toString("hex"),t.push(s),e.push(u),r.set(p,u)),s}let f;return p=m(n-1,2*u),2*u+1<d(n-1)?(f=m(n-1,2*u+1)).equals(p)&&(l=!0):f=p,c.root256(p,f)};if(0===n)throw new Error("Zero transactions.");if(n>(u.MAX_BLOCK_SIZE-81)/60)throw new Error("Too many transactions.");if(i.length>n)throw new Error("Too many hashes.");if(8*s.length<i.length)throw new Error("Flags too small.");for(;1<d(p);)p++;var g=m(p,0);if(l)throw new Error("Mutated merkle tree.");if(((a+7)/8|0)!==s.length)throw new Error("Too many flag bits.");if(h!==i.length)throw new Error("Incorrect number of hashes.");return new f(g,t,e,r)}getCoinbaseHeight(){return-1}inspect(){return this.format()}format(t,e){return{hash:this.rhash(),height:null!=e?e:-1,date:s.date(this.time),version:s.hex32(this.version),prevBlock:s.revHex(this.prevBlock),merkleRoot:s.revHex(this.merkleRoot),time:this.time,bits:this.bits,nonce:this.nonce,totalTX:this.totalTX,hashes:this.hashes.map(t=>t.toString("hex")),flags:this.flags,map:this.getTree().map,txs:this.txs.length}}getSize(){return 84+o.sizeVarint(this.hashes.length)+32*this.hashes.length+o.sizeVarint(this.flags.length)+this.flags.length}toWriter(t){this.writeHead(t),t.writeU32(this.totalTX),t.writeVarint(this.hashes.length);for(const e of this.hashes)t.writeHash(e);return t.writeVarBytes(this.flags),t}toRaw(){var t=this.getSize();return this.toWriter(new a(t)).render()}fromReader(t){this.readHead(t),this.totalTX=t.readU32();var e=t.readVarint();for(let r=0;r<e;r++)this.hashes.push(t.readHash());return this.flags=t.readVarBytes(),this}fromRaw(t){return this.fromReader(new n(t))}static fromReader(t){return(new d).fromReader(t)}static fromRaw(t,e){return"string"==typeof t&&(t=Buffer.from(t,e)),(new d).fromRaw(t)}toJSON(){return this.getJSON()}getJSON(t,e,r){return{hash:this.rhash(),height:r,version:this.version,prevBlock:s.revHex(this.prevBlock),merkleRoot:s.revHex(this.merkleRoot),time:this.time,bits:this.bits,nonce:this.nonce,totalTX:this.totalTX,hashes:this.hashes.map(t=>s.revHex(t.toString("hex"))),flags:this.flags.toString("hex")}}fromJSON(t){for(var e of(i(t,"MerkleBlock data is required."),i(Array.isArray(t.hashes)),i("string"==typeof t.flags),i(s.isU32(t.totalTX)),this.parseJSON(t),t.hashes))e=s.revHex(e),this.hashes.push(Buffer.from(e,"hex"));return this.flags=Buffer.from(t.flags,"hex"),this.totalTX=t.totalTX,this}static fromJSON(t){return(new d).fromJSON(t)}static fromBlock(t,e){const r=[];for(const i of t.txs)r.push(i.isWatched(e)?1:0);return d.fromMatches(t,r)}static fromHashes(t,e){const r=new Set;for(var i of e)Buffer.isBuffer(i)&&(i=i.toString("hex")),r.add(i);const s=[];for(const e of t.txs){var n=e.hash("hex");s.push(r.has(n)?1:0)}return d.fromMatches(t,s)}static fromMatches(t,e){const r=[],i=[],s=[],n=[],a=t.txs.length;let o=0;const u=t=>a+(1<<t)-1>>>t,h=(t,e,r)=>{if(0===t)return r[e];var i=h(t-1,2*e,r);let s;return s=2*e+1<u(t-1)?h(t-1,2*e+1,r):i,c.root256(i,s)},l=(t,e,r,i)=>{let o=0;for(let r=e<<t;r<e+1<<t&&r<a;r++)o|=i[r];s.push(o),0!==t&&o?(l(t-1,2*e,r,i),2*e+1<u(t-1)&&l(t-1,2*e+1,r,i)):n.push(h(t,e,r))};for(let s=0;s<t.txs.length;s++){const n=t.txs[s];e[s]&&r.push(n),i.push(n.hash())}for(;1<u(o);)o++;l(o,0,i,e);const p=Buffer.allocUnsafe((s.length+7)/8|0);p.fill(0);for(let t=0;t<s.length;t++)p[t/8|0]|=s[t]<<t%8;const f=new d;return f._hash=t._hash,f._hhash=t._hhash,f.version=t.version,f.prevBlock=t.prevBlock,f.merkleRoot=t.merkleRoot,f.time=t.time,f.bits=t.bits,f.nonce=t.nonce,f.totalTX=a,f.hashes=n,f.flags=p,f.txs=r,f}static isMerkleBlock(t){return t instanceof d}toHeaders(){return l.fromBlock(this)}}function f(t,e,r,i){this.root=t?t.toString("hex"):o.NULL_HASH,this.matches=e||[],this.indexes=r||[],this.map=i||new Map}t.exports=d},function(t,e,r){const i=r(5).PropStatus;r=r(29);class s extends r{constructor(t){super(),this.db=t||{getVp:async t=>this.get(t),setVp:t=>{this.set(t.pid,t)},delVp:t=>{this.delete(t)},loadVpList:()=>{}}}async loadHistory(){}setAccount(t,e,r){var i;t&&t.wid&&t.account&&(i=t.wid+"."+t.account,this.account.get(i)&&this.account.get(i).delete(t.pid)),t.wid=e,t.account=r,e&&r&&(i=t.wid+"."+t.account,this.account.get(i)||this.account.set(i,new Map),this.account.get(i).set(t.pid,t))}delAccount(t){var e;t&&t.wid&&t.account&&(e=t.wid+"."+t.account,this.account.get(e)&&this.account.get(e).delete(t.pid))}async getVp(t){return this.db.getVp(t)}async getVpByAddress(t){return this.db.getVpByAddress(t)}async getVpByOid(t){return this.db.getVpByOid(t)}async setVp(t,e){t=new n(t),await this.db.setVp(t,e)}async delVp(t){this.delete(t.pid),await this.db.delVp(t)}}class n{constructor(t){this.fromOptions(t=t||{})}fromOptions(t){this.pid=t.pid,this.cid=t.cid||"",this.oid=t.oid||"",this.gold=t.gold,this.current=null,t.current&&(this.current={},this.current.hash=t.current.hash,this.current.index=t.current.index,this.current.address=t.current.address),this.height=t.height,this.pst=t.pst||i.Ready,this.wid=t.wid||0,this.account=t.account||"",this.bid=null,t.bid&&(this.bid={},this.bid.raw=t.bid.raw||"",this.bid.fixed=t.bid.fixed||0,this.bid.period=t.bid.period||0,this.bid.hash=t.bid.hash||"",this.bid.value=t.bid.value||0,this.bid.address=t.bid.address||"")}toRaw(){let t={};return t.pid=this.pid,t.cid=this.cid||"",t.oid=this.oid||"",t.gold=this.gold,this.current&&(t.current={},t.current.hash=this.current.hash,t.current.index=this.current.index,t.current.address=this.current.address),t.height=this.height,t.pst=this.pst||i.Ready,t.wid=this.wid||0,t.account=this.account||"",this.bid&&(t.bid={},t.bid.raw=this.bid.raw||"",t.bid.fixed=this.bid.fixed||0,t.bid.period=this.bid.period||0,t.bid.hash=this.bid.hash||"",t.bid.value=this.bid.value||0,t.bid.address=this.bid.address||""),Buffer.from(JSON.stringify(t),"utf-8")}fromRaw(t){return t=JSON.parse(t.toString("utf8")),this.fromOptions(t),this}static fromRaw(t){return(new n).fromRaw(t)}}s.vpItem=n,t.exports=s},function(t,e,r){var i=r(10),s=r(179),n=(r=r(9),{sha1:!0,sha256:!0,sha512:!0}),a={rsa:!0,dsa:!0,ecdsa:!0};function o(t,e){Error.captureStackTrace&&Error.captureStackTrace(this,e||o),this.message=t,this.name=e.name}function c(t){o.call(this,t,c)}r.inherits(o,Error),r.inherits(c,o),t.exports={HASH_ALGOS:n,PK_ALGOS:a,HttpSignatureError:o,InvalidAlgorithmError:c,validateAlgorithm:function(t){if(2!==(t=t.toLowerCase().split("-")).length)throw new c(t[0].toUpperCase()+" is not a valid algorithm");if("hmac"!==t[0]&&!a[t[0]])throw new c(t[0].toUpperCase()+" type keys are not supported");if(n[t[1]])return t;throw new c(t[1].toUpperCase()+" is not a supported hash algorithm")},sshKeyToPEM:function(t){return i.string(t,"ssh_key"),s.parseKey(t,"ssh").toString("pem")},fingerprint:function(t){return i.string(t,"ssh_key"),s.parseKey(t,"ssh").fingerprint("md5").toString("hex")},pemToRsaSSHKey:function(t,e){return i.equal("string",typeof t,"typeof pem"),(t=s.parseKey(t,"pem")).comment=e,t.toString("ssh")}}},function(t,e,r){var i=r(104).BigInteger,s=i.prototype.Barrett;function n(t,e){this.x=e,this.q=t}function a(t,e,r,s){this.curve=t,this.x=e,this.y=r,this.z=null==s?i.ONE:s,this.zinv=null}function o(t,e,r){this.q=t,this.a=this.fromBigInteger(e),this.b=this.fromBigInteger(r),this.infinity=new a(this,null,null),this.reducer=new s(this.q)}n.prototype.equals=function(t){return t==this||this.q.equals(t.q)&&this.x.equals(t.x)},n.prototype.toBigInteger=function(){return this.x},n.prototype.negate=function(){return new n(this.q,this.x.negate().mod(this.q))},n.prototype.add=function(t){return new n(this.q,this.x.add(t.toBigInteger()).mod(this.q))},n.prototype.subtract=function(t){return new n(this.q,this.x.subtract(t.toBigInteger()).mod(this.q))},n.prototype.multiply=function(t){return new n(this.q,this.x.multiply(t.toBigInteger()).mod(this.q))},n.prototype.square=function(){return new n(this.q,this.x.square().mod(this.q))},n.prototype.divide=function(t){return new n(this.q,this.x.multiply(t.toBigInteger().modInverse(this.q)).mod(this.q))},a.prototype.getX=function(){null==this.zinv&&(this.zinv=this.z.modInverse(this.curve.q));var t=this.x.toBigInteger().multiply(this.zinv);return this.curve.reduce(t),this.curve.fromBigInteger(t)},a.prototype.getY=function(){null==this.zinv&&(this.zinv=this.z.modInverse(this.curve.q));var t=this.y.toBigInteger().multiply(this.zinv);return this.curve.reduce(t),this.curve.fromBigInteger(t)},a.prototype.equals=function(t){return t==this||(this.isInfinity()?t.isInfinity():t.isInfinity()?this.isInfinity():!!t.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(t.z)).mod(this.curve.q).equals(i.ZERO)&&t.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(t.z)).mod(this.curve.q).equals(i.ZERO))},a.prototype.isInfinity=function(){return null==this.x&&null==this.y||this.z.equals(i.ZERO)&&!this.y.toBigInteger().equals(i.ZERO)},a.prototype.negate=function(){return new a(this.curve,this.x,this.y.negate(),this.z)},a.prototype.add=function(t){var e,r,s,n,o,c,u;return this.isInfinity()?t:t.isInfinity()?this:(e=t.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(t.z)).mod(this.curve.q),o=t.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(t.z)).mod(this.curve.q),i.ZERO.equals(o)?i.ZERO.equals(e)?this.twice():this.curve.getInfinity():(u=new i("3"),c=this.x.toBigInteger(),r=this.y.toBigInteger(),t.x.toBigInteger(),t.y.toBigInteger(),s=(n=o.square()).multiply(o),c=c.multiply(n),o=(n=e.square().multiply(this.z)).subtract(c.shiftLeft(1)).multiply(t.z).subtract(s).multiply(o).mod(this.curve.q),c=c.multiply(u).multiply(e).subtract(r.multiply(s)).subtract(n.multiply(e)).multiply(t.z).add(e.multiply(s)).mod(this.curve.q),u=s.multiply(this.z).multiply(t.z).mod(this.curve.q),new a(this.curve,this.curve.fromBigInteger(o),this.curve.fromBigInteger(c),u)))},a.prototype.twice=function(){var t,e,r,s,n,o;return this.isInfinity()?this:0==this.y.toBigInteger().signum()?this.curve.getInfinity():(n=new i("3"),o=this.x.toBigInteger(),e=(t=(e=this.y.toBigInteger()).multiply(this.z)).multiply(e).mod(this.curve.q),s=this.curve.a.toBigInteger(),r=o.square().multiply(n),s=(r=(r=i.ZERO.equals(s)?r:r.add(this.z.square().multiply(s))).mod(this.curve.q)).square().subtract(o.shiftLeft(3).multiply(e)).shiftLeft(1).multiply(t).mod(this.curve.q),n=r.multiply(n).multiply(o).subtract(e.shiftLeft(1)).shiftLeft(2).multiply(e).subtract(r.square().multiply(r)).mod(this.curve.q),o=t.square().multiply(t).shiftLeft(3).mod(this.curve.q),new a(this.curve,this.curve.fromBigInteger(s),this.curve.fromBigInteger(n),o))},a.prototype.multiply=function(t){if(this.isInfinity())return this;if(0==t.signum())return this.curve.getInfinity();for(var e=t,r=e.multiply(new i("3")),s=this.negate(),n=this,a=r.bitLength()-2;0<a;--a){n=n.twice();var o=r.testBit(a);o!=e.testBit(a)&&(n=n.add(o?this:s))}return n},a.prototype.multiplyTwo=function(t,e,r){for(var i=t.bitLength()>r.bitLength()?t.bitLength()-1:r.bitLength()-1,s=this.curve.getInfinity(),n=this.add(e);0<=i;)s=s.twice(),t.testBit(i)?s=r.testBit(i)?s.add(n):s.add(this):r.testBit(i)&&(s=s.add(e)),--i;return s},o.prototype.getQ=function(){return this.q},o.prototype.getA=function(){return this.a},o.prototype.getB=function(){return this.b},o.prototype.equals=function(t){return t==this||this.q.equals(t.q)&&this.a.equals(t.a)&&this.b.equals(t.b)},o.prototype.getInfinity=function(){return this.infinity},o.prototype.fromBigInteger=function(t){return new n(this.q,t)},o.prototype.reduce=function(t){this.reducer.reduce(t)},o.prototype.encodePointHex=function(t){if(t.isInfinity())return"00";var e=t.getX().toBigInteger().toString(16),r=t.getY().toBigInteger().toString(16),i=this.getQ().toString(16).length;for(i%2!=0&&i++;e.length<i;)e="0"+e;for(;r.length<i;)r="0"+r;return"04"+e+r},o.prototype.decodePointHex=function(t){switch(parseInt(t.substr(0,2),16)){case 0:return this.infinity;case 2:c=!1;case 3:null==c&&(c=!0);var e=t.length-2,r=t.substr(2,e),s=this.fromBigInteger(new i(r,16)),n=s.multiply(s.square().add(this.getA())).add(this.getB()).sqrt();if(null==n)throw"Invalid point compression";var o=n.toBigInteger();return o.testBit(0)!=c&&(n=this.fromBigInteger(this.getQ().subtract(o))),new a(this,s,n);case 4:case 6:case 7:e=(t.length-2)/2,r=t.substr(2,e);var c=t.substr(e+2,e);return new a(this,this.fromBigInteger(new i(r,16)),this.fromBigInteger(new i(c,16)));default:return null}},o.prototype.encodeCompressedPointHex=function(t){if(t.isInfinity())return"00";var e=t.getX().toBigInteger().toString(16),r=this.getQ().toString(16).length;for(r%2!=0&&r++;e.length<r;)e="0"+e;return(t.getY().toBigInteger().isEven()?"02":"03")+e},n.prototype.getR=function(){var t;return null==this.r&&(this.r=null,128<(t=this.q.bitLength())&&-1==this.q.shiftRight(t-64).intValue()&&(this.r=i.ONE.shiftLeft(t).subtract(this.q))),this.r},n.prototype.modMult=function(t,e){return this.modReduce(t.multiply(e))},n.prototype.modReduce=function(t){if(null!=this.getR()){for(var e=q.bitLength();t.bitLength()>e+1;){var r=t.shiftRight(e),s=t.subtract(r.shiftLeft(e));t=(r=this.getR().equals(i.ONE)?r:r.multiply(this.getR())).add(s)}for(;0<=t.compareTo(q);)t=t.subtract(q)}else t=t.mod(q);return t},n.prototype.sqrt=function(){if(!this.q.testBit(0))throw"unsupported";var t;if(this.q.testBit(1))return(t=new n(this.q,this.x.modPow(this.q.shiftRight(2).add(i.ONE),this.q))).square().equals(this)?t:null;var e=this.q.subtract(i.ONE),r=e.shiftRight(1);if(this.x.modPow(r,this.q).equals(i.ONE)){var s,a=e.shiftRight(2).shiftLeft(1).add(i.ONE),o=this.x,c=modDouble(modDouble(o));do{for(;0<=(s=new i(this.q.bitLength(),new SecureRandom)).compareTo(this.q)||!s.multiply(s).subtract(c).modPow(r,this.q).equals(e););var u=(h=this.lucasSequence(s,o,a))[0],h=h[1];if(this.modMult(h,h).equals(c))return h=(h=h.testBit(0)?h.add(q):h).shiftRight(1),new n(q,h)}while(u.equals(i.ONE)||u.equals(e))}return null},n.prototype.lucasSequence=function(t,e,r){for(var s=r.bitLength(),n=r.getLowestSetBit(),a=i.ONE,o=i.TWO,c=t,u=i.ONE,h=i.ONE,l=s-1;n+1<=l;--l)u=this.modMult(u,h),r.testBit(l)?(h=this.modMult(u,e),a=this.modMult(a,c),o=this.modReduce(c.multiply(o).subtract(t.multiply(u))),c=this.modReduce(c.multiply(c).subtract(h.shiftLeft(1)))):(h=u,a=this.modReduce(a.multiply(o).subtract(u)),c=this.modReduce(c.multiply(o).subtract(t.multiply(u))),o=this.modReduce(o.multiply(o).subtract(u.shiftLeft(1))));for(u=this.modMult(u,h),h=this.modMult(u,e),a=this.modReduce(a.multiply(o).subtract(u)),o=this.modReduce(c.multiply(o).subtract(t.multiply(u))),u=this.modMult(u,h),l=1;l<=n;++l)a=this.modMult(a,o),o=this.modReduce(o.multiply(o).subtract(u.shiftLeft(1))),u=this.modMult(u,u);return[a,o]},t.exports={ECCurveFp:o,ECPointFp:a,ECFieldElementFp:n}},function(t,e,r){t.exports={read:function(t,e){return u.read(t,e)},readSSHPrivate:function(t,e,c){var u=(e=new l({buffer:e})).readCString(),f=(s.strictEqual(u,d,"bad magic string"),e.readString()),m=e.readString();u=e.readBuffer();if(1!==e.readInt())throw new Error("OpenSSH-format key file contains multiple keys: this is unsupported.");var g=e.readBuffer();if("public"===t)return s.ok(e.atEnd(),"excess bytes left after key"),h.read(g);var y=e.readBuffer(),v=(s.ok(e.atEnd(),"excess bytes left after key"),new l({buffer:u}));switch(m){case"none":if("none"!==f)throw new Error('OpenSSH-format key uses KDF "none" but specifies a cipher other than "none"');break;case"bcrypt":var b=v.readBuffer(),w=v.readInt(),x=a.opensshCipherInfo(f);if(void 0===i&&(i=r(284)),"string"==typeof c.passphrase&&(c.passphrase=n.from(c.passphrase,"utf-8")),!n.isBuffer(c.passphrase))throw new p.KeyEncryptedError(c.filename,"OpenSSH");var k=new Uint8Array(c.passphrase),S=(b=new Uint8Array(b),new Uint8Array(x.keySize+x.blockSize));if(0!==i.pbkdf(k,k.length,b,b.length,S,S.length,w))throw new Error("bcrypt_pbkdf function returned failure, parameters invalid");k=(S=n.from(S)).slice(0,x.keySize),b=S.slice(x.keySize,x.keySize+x.blockSize);var E=o.createDecipheriv(x.opensslName,k,b);E.setAutoPadding(!1);var _,A=[];for(E.once("error",(function(t){if(-1!==t.toString().indexOf("bad decrypt"))throw new Error("Incorrect passphrase supplied, could not decrypt key");throw t})),E.write(y),E.end();null!==(_=E.read());)A.push(_);y=n.concat(A);break;default:throw new Error('OpenSSH-format key uses unknown KDF "'+m+'"')}if((t=(e=new l({buffer:y})).readInt())!==(g=e.readInt()))throw new Error("Incorrect passphrase supplied, could not decrypt key");return u={},t=h.readInternal(u,"private",e.remainder()),e.skip(u.consumed),g=e.readString(),t.comment=g,t},write:function(t,e){var u;u=c.isPrivateKey(t)?t.toPublic():t;var h,p,f="none",m="none",g=n.alloc(0),y={blockSize:8};if(void 0!==e&&void 0!==(h="string"==typeof(h=e.passphrase)?n.from(h,"utf-8"):h)&&(s.buffer(h,"options.passphrase"),s.optionalString(e.cipher,"options.cipher"),void 0===(f=e.cipher)&&(f="aes128-ctr"),y=a.opensshCipherInfo(f),m="bcrypt"),c.isPrivateKey(t)){p=new l({});e=o.randomBytes(4).readUInt32BE(0);for(var v=(p.writeInt(e),p.writeInt(e),p.write(t.toBuffer("rfc4253")),p.writeString(t.comment||""),1);p._offset%y.blockSize!=0;)p.writeChar(v++);p=p.toBuffer()}switch(m){case"none":break;case"bcrypt":var b=o.randomBytes(16),w=((w=new l({})).writeBuffer(b),w.writeInt(16),g=w.toBuffer(),void 0===i&&(i=r(284)),new Uint8Array(h)),x=(b=new Uint8Array(b),new Uint8Array(y.keySize+y.blockSize));if(0!==i.pbkdf(w,w.length,b,b.length,x,x.length,16))throw new Error("bcrypt_pbkdf function returned failure, parameters invalid");w=(x=n.from(x)).slice(0,y.keySize),b=x.slice(y.keySize,y.keySize+y.blockSize);var k=o.createCipheriv(y.opensslName,w,b);k.setAutoPadding(!1);var S,E=[];for(k.once("error",(function(t){throw t})),k.write(p),k.end();null!==(S=k.read());)E.push(S);p=n.concat(E);break;default:throw new Error("Unsupported kdf "+m)}var _=new l({});_.writeCString(d),_.writeString(f),_.writeString(m),_.writeBuffer(g),_.writeInt(1),_.writeBuffer(u.toBuffer("rfc4253")),p&&_.writeBuffer(p),_=_.toBuffer(),e=c.isPrivateKey(t)?"OPENSSH PRIVATE KEY":"OPENSSH PUBLIC KEY";var A=_.toString("base64"),R=(f=A.length+A.length/70+18+16+2*e.length+10,_=n.alloc(f),0);R+=_.write("-----BEGIN "+e+"-----\n",R);for(var I=0;I<A.length;){var j=I+70;j>A.length&&(j=A.length),R+=_.write(A.slice(I,j),R),_[R++]=10,I=j}return R+=_.write("-----END "+e+"-----\n",R),_.slice(0,R)}};var i,s=r(10),n=(r(57),r(14).Buffer),a=(r(31),r(25)),o=r(8),c=(r(23),r(24)),u=r(67),h=r(68),l=r(91),p=r(51),d="openssh-key-v1"},function(t,e,r){var i=r(58);const s=r(83),n=r(17),a=r(26),o=r(7),c=r(0),{Transform:u,ContractType:h,HtlcStatus:l,ContractEnvType:p}=r(5),d=new u("\n /*携带合约信息*/\n HTLCSUGGEST var_contract DROP\n /*校验秘密,持有秘密者才可执行*/\n HASH160 var_ab EQUALVERIFY \n IF\n /*Bob确认时执行: 校验Bob签名*/\n DUP HASH160 var_ba EQUALVERIFY CHECKSIG\n ELSE\n /*Alice取消时执行: 校验延时和Alice签名*/\n var_period CHECKSEQUENCEVERIFY DROP\n DUP HASH160 var_aa EQUALVERIFY CHECKSIG\n ENDIF\n");t.exports=class extends i{async confirm(){let{env:t,output:e,hash:r,i:i,data:n,height:a}=this.options;var o=e.getHashs("hex");o={type:"suggest",src:s.protocol+"."+t.network.type,dst:n.dst,shash:r,sidx:i,sheight:a,pst:l.Sent,amount:e.value,rate:n.rate,ab:e.script.code[4].data.toString("hex"),aa:o[1],ba:o[0]};await t.setSuggest(o),t.mode==p.Block&&t.node.transmit("htlcsuggest.receive",o)}async unconfirm(){let{env:t,data:e}=this.options;var r={shash:e.hash,sidx:e.index};await t.delHtlc(r)}async spent(t){let e=this.options.env,r=e.htlcList.get(""+t.prevout.hash+t.prevout.index);r&&(81==t.script.code[2].value?(r.pst=l.Finished,await e.setSuggest(r),e.mode==p.Block&&e.node.transmit("htlcsuggest.deal",r)):(r.pst=l.Cancel,await e.setSuggest(r),e.mode==p.Block&&e.node.transmit("htlcsuggest.cancel",r)))}async verify(){let{output:t,data:e}=this.options;var r={oper:h.htlcSuggest,rate:e.rate,dst:e.dst};let i=t.getHashs("hex"),s=t.script.code[4].data.toString("hex");r={contract:"0x"+Buffer.from(JSON.stringify(r)).toString("hex"),ab:"0x"+s.toString("hex"),aa:"0x"+i[1].toString("hex"),ba:"0x"+i[0].toString("hex"),period:2*o.HTLC_CANCEL_PERIOD};let a=n.fromString(d.replace(r));return c(a.toString()===t.script.toString()),!0}static create(t){var e={oper:h.htlcSuggest,rate:t.rate,dst:t.dst};e={contract:"0x"+Buffer.from(JSON.stringify(e)).toString("hex"),ab:"0x"+t.ab.toString("hex"),aa:"0x"+t.aa.toString("hex"),ba:"0x"+t.ba.toString("hex"),period:2*o.HTLC_CANCEL_PERIOD},e=n.fromString(d.replace(e));return a.fromScript(e,t.amount)}}},function(t,e,r){var i=r(58);const s=r(83),n=r(17),a=r(26),o=r(7),{Transform:c,ContractType:u,HtlcStatus:h,ContractEnvType:l}=r(5),p=new c("\n /*携带合约信息*/\n HTLCASSENT var_contract DROP\n IF\n /*Alice确认时执行: 校验签名*/\n DUP HASH160 var_ab EQUALVERIFY CHECKSIG\n ELSE\n /*Bob取消时执行: 校验延时和签名*/\n var_period CHECKSEQUENCEVERIFY DROP\n DUP HASH160 var_bb EQUALVERIFY CHECKSIG\n ENDIF\n");t.exports=class extends i{async confirm(){let{env:t,i:e,output:r,hash:i,height:n,data:a}=this.options;var o=r.getHashs("hex");o={src:a.src,dst:s.protocol+"."+t.network.type,shash:a.hash,sidx:a.index,ahash:i,aidx:e,aheight:n,pst:h.Assent,amount:a.value,rate:a.rate,ab:o[0],bb:o[1]};await t.setAssent(o),t.mode==l.Block&&t.node.transmit("htlcassent.receive",o)}async unconfirm(){let{env:t,data:e}=this.options;var r={shash:e.hash,sidx:e.index};await t.delHtlc(r)}async spent(t){let e=this.options.env;var r=e.htlcList.query([["ahash",t.prevout.hash],["aidx",t.prevout.index]]);if(r&&1===r.list.length&&r.list[0].pst===h.Assent){let i=r.list[0];81==t.script.code[2].value?(i.secret=t.script.code[1].data.toString("hex"),i.pst=h.Deal,await e.setAssent(i),e.mode==l.Block&&e.node.transmit("htlcassent.deal",i)):(i.pst=h.Cancel,await e.setAssent(i),e.mode==l.Block&&e.node.transmit("htlcassent.cancel",i))}}async verify(){let{env:t,output:e,data:r}=this.options;if(r.dst!=s.protocol+"."+t.network.type)return!1;var i={oper:u.htlcAssent,hash:r.hash,index:r.index};let a=e.getHashs("hex"),c=n.fromString(p.replace({contract:"0x"+Buffer.from(JSON.stringify(i)).toString("hex"),ab:"0x"+a[0].toString("hex"),bb:"0x"+a[1].toString("hex"),period:o.HTLC_CANCEL_PERIOD}));return assert(c.toString()===e.script.toString()),!0}static create(t){var e={oper:u.htlcAssent,hash:t.hash,index:t.index};e=n.fromString(p.replace({contract:"0x"+Buffer.from(JSON.stringify(e)).toString("hex"),ab:"0x"+t.ab.toString("hex"),bb:"0x"+t.bb.toString("hex"),period:o.HTLC_CANCEL_PERIOD}));return a.fromScript(e,t.amount)}}},function(t,e,r){var i=r(58);const s=r(17),n=r(26),a=r(0),{Transform:o,ContractType:c,ContractEnvType:u}=r(5),h=r(12),l=r(63).verifyData,p=new o("\n /*携带合约信息*/\n COMMENT var_contract DROP\n /*Bob确认时执行: 校验Bob签名*/\n DUP HASH160 var_bob EQUALVERIFY CHECKSIG\n");t.exports=class extends i{async insert(){let{env:t,output:e,hash:r,i:i,data:s}=this.options;var n=h.fromWitnessPubkeyhash(e.getHash(),t.network).toString();n={shash:r,sidx:i,alice:s.payload.addr,bob:n,body:s.payload.body};t.mode==u.Wallet&&await t.setComment(n)}async erase(){let{env:t,hash:e,i:r}=this.options;var i={shash:e,sidx:r};t.mode==u.Wallet&&await t.delComment(i)}async verify(){let{output:t,data:e}=this.options,r=t.getHash(),i=s.fromString(p.replace({contract:"0x"+Buffer.from(JSON.stringify(e)).toString("hex"),bob:"0x"+r.toString("hex")}));a(i.toString()===t.script.toString());var n=e.payload.sig;return delete(e=e.payload).sig,a.strictEqual(!0,l({data:e,sig:n})),!0}static create(t){var e={oper:c.comment,payload:t};e={contract:"0x"+Buffer.from(JSON.stringify(e)).toString("hex"),bob:"0x"+h.fromString(t.bob).hash.toString("hex")},e=s.fromString(p.replace(e));return n.fromScript(e,t.amount)}}},function(t,e,r){"use strict";
324
+ */const i=r(0),s=r(1),n=r(2),a=r(4),o=r(3),c=r(6),u=r(7);var h=r(117);const l=r(89),p=Buffer.from([0]);class d extends h{constructor(t){super(),this.txs=[],this.hashes=[],this.flags=p,this.totalTX=0,this._tree=null,t&&this.fromOptions(t)}fromOptions(t){if(this.parseOptions(t),i(t,"MerkleBlock data is required."),i(Array.isArray(t.hashes)),i(Buffer.isBuffer(t.flags)),i(s.isU32(t.totalTX)),t.hashes)for(var e of t.hashes)"string"==typeof e&&(e=Buffer.from(e,"hex")),i(Buffer.isBuffer(e)),this.hashes.push(e);return t.flags&&(i(Buffer.isBuffer(t.flags)),this.flags=t.flags),null!=t.totalTX&&(i(s.isU32(t.totalTX)),this.totalTX=t.totalTX),this}static fromOptions(t){return(new d).fromOptions(t)}refresh(t){if(this._refresh(),this._tree=null,t)for(const t of this.txs)t.refresh()}hasTX(t){return-1!==this.indexOf(t)}indexOf(t){return null==(t=this.getTree().map.get(t))?-1:t}verifyBody(){var[t]=this.checkBody();return t}checkBody(){return this.getTree().root!==this.merkleRoot?[!1,"bad-txnmrklroot",100]:[!0,"valid",0]}getTree(){if(!this._tree)try{this._tree=this.extractTree()}catch(t){this._tree=new f}return this._tree}extractTree(){const t=[],e=[],r=new Map,i=this.hashes,s=this.flags,n=this.totalTX;let a=0,h=0,l=!1,p=0;const d=t=>n+(1<<t)-1>>>t,m=(n,u)=>{if(a>=8*s.length)return l=!0,o.ZERO_HASH;var p=s[a/8|0]>>>a%8&1;if(a++,0===n||!p){if(h>=i.length)return l=!0,o.ZERO_HASH;const s=i[h++];return 0===n&&p&&(p=s.toString("hex"),t.push(s),e.push(u),r.set(p,u)),s}let f;return p=m(n-1,2*u),2*u+1<d(n-1)?(f=m(n-1,2*u+1)).equals(p)&&(l=!0):f=p,c.root256(p,f)};if(0===n)throw new Error("Zero transactions.");if(n>(u.MAX_BLOCK_SIZE-81)/60)throw new Error("Too many transactions.");if(i.length>n)throw new Error("Too many hashes.");if(8*s.length<i.length)throw new Error("Flags too small.");for(;1<d(p);)p++;var g=m(p,0);if(l)throw new Error("Mutated merkle tree.");if(((a+7)/8|0)!==s.length)throw new Error("Too many flag bits.");if(h!==i.length)throw new Error("Incorrect number of hashes.");return new f(g,t,e,r)}getCoinbaseHeight(){return-1}inspect(){return this.format()}format(t,e){return{hash:this.rhash(),height:null!=e?e:-1,date:s.date(this.time),version:s.hex32(this.version),prevBlock:s.revHex(this.prevBlock),merkleRoot:s.revHex(this.merkleRoot),time:this.time,bits:this.bits,nonce:this.nonce,totalTX:this.totalTX,hashes:this.hashes.map(t=>t.toString("hex")),flags:this.flags,map:this.getTree().map,txs:this.txs.length}}getSize(){return 84+o.sizeVarint(this.hashes.length)+32*this.hashes.length+o.sizeVarint(this.flags.length)+this.flags.length}toWriter(t){this.writeHead(t),t.writeU32(this.totalTX),t.writeVarint(this.hashes.length);for(const e of this.hashes)t.writeHash(e);return t.writeVarBytes(this.flags),t}toRaw(){var t=this.getSize();return this.toWriter(new a(t)).render()}fromReader(t){this.readHead(t),this.totalTX=t.readU32();var e=t.readVarint();for(let r=0;r<e;r++)this.hashes.push(t.readHash());return this.flags=t.readVarBytes(),this}fromRaw(t){return this.fromReader(new n(t))}static fromReader(t){return(new d).fromReader(t)}static fromRaw(t,e){return"string"==typeof t&&(t=Buffer.from(t,e)),(new d).fromRaw(t)}toJSON(){return this.getJSON()}getJSON(t,e,r){return{hash:this.rhash(),height:r,version:this.version,prevBlock:s.revHex(this.prevBlock),merkleRoot:s.revHex(this.merkleRoot),time:this.time,bits:this.bits,nonce:this.nonce,totalTX:this.totalTX,hashes:this.hashes.map(t=>s.revHex(t.toString("hex"))),flags:this.flags.toString("hex")}}fromJSON(t){for(var e of(i(t,"MerkleBlock data is required."),i(Array.isArray(t.hashes)),i("string"==typeof t.flags),i(s.isU32(t.totalTX)),this.parseJSON(t),t.hashes))e=s.revHex(e),this.hashes.push(Buffer.from(e,"hex"));return this.flags=Buffer.from(t.flags,"hex"),this.totalTX=t.totalTX,this}static fromJSON(t){return(new d).fromJSON(t)}static fromBlock(t,e){const r=[];for(const i of t.txs)r.push(i.isWatched(e)?1:0);return d.fromMatches(t,r)}static fromHashes(t,e){const r=new Set;for(var i of e)Buffer.isBuffer(i)&&(i=i.toString("hex")),r.add(i);const s=[];for(const e of t.txs){var n=e.hash("hex");s.push(r.has(n)?1:0)}return d.fromMatches(t,s)}static fromMatches(t,e){const r=[],i=[],s=[],n=[],a=t.txs.length;let o=0;const u=t=>a+(1<<t)-1>>>t,h=(t,e,r)=>{if(0===t)return r[e];var i=h(t-1,2*e,r);let s;return s=2*e+1<u(t-1)?h(t-1,2*e+1,r):i,c.root256(i,s)},l=(t,e,r,i)=>{let o=0;for(let r=e<<t;r<e+1<<t&&r<a;r++)o|=i[r];s.push(o),0!==t&&o?(l(t-1,2*e,r,i),2*e+1<u(t-1)&&l(t-1,2*e+1,r,i)):n.push(h(t,e,r))};for(let s=0;s<t.txs.length;s++){const n=t.txs[s];e[s]&&r.push(n),i.push(n.hash())}for(;1<u(o);)o++;l(o,0,i,e);const p=Buffer.allocUnsafe((s.length+7)/8|0);p.fill(0);for(let t=0;t<s.length;t++)p[t/8|0]|=s[t]<<t%8;const f=new d;return f._hash=t._hash,f._hhash=t._hhash,f.version=t.version,f.prevBlock=t.prevBlock,f.merkleRoot=t.merkleRoot,f.time=t.time,f.bits=t.bits,f.nonce=t.nonce,f.totalTX=a,f.hashes=n,f.flags=p,f.txs=r,f}static isMerkleBlock(t){return t instanceof d}toHeaders(){return l.fromBlock(this)}}function f(t,e,r,i){this.root=t?t.toString("hex"):o.NULL_HASH,this.matches=e||[],this.indexes=r||[],this.map=i||new Map}t.exports=d},function(t,e,r){const i=r(5).PropStatus;r=r(28);class s extends r{constructor(t){super(),this.db=t||{getVp:async t=>this.get(t),setVp:t=>{this.set(t.pid,t)},delVp:t=>{this.delete(t)},loadVpList:()=>{}}}async loadHistory(){}setAccount(t,e,r){var i;t&&t.wid&&t.account&&(i=t.wid+"."+t.account,this.account.get(i)&&this.account.get(i).delete(t.pid)),t.wid=e,t.account=r,e&&r&&(i=t.wid+"."+t.account,this.account.get(i)||this.account.set(i,new Map),this.account.get(i).set(t.pid,t))}delAccount(t){var e;t&&t.wid&&t.account&&(e=t.wid+"."+t.account,this.account.get(e)&&this.account.get(e).delete(t.pid))}async getVp(t){return this.db.getVp(t)}async getVpByAddress(t){return this.db.getVpByAddress(t)}async getVpByOid(t){return this.db.getVpByOid(t)}async setVp(t,e){t=new n(t),await this.db.setVp(t,e)}async delVp(t){this.delete(t.pid),await this.db.delVp(t)}}class n{constructor(t){this.fromOptions(t=t||{})}fromOptions(t){this.pid=t.pid,this.cid=t.cid||"",this.oid=t.oid||"",this.gold=t.gold,this.current=null,t.current&&(this.current={},this.current.hash=t.current.hash,this.current.index=t.current.index,this.current.address=t.current.address),this.height=t.height,this.pst=t.pst||i.Ready,this.wid=t.wid||0,this.account=t.account||"",this.bid=null,t.bid&&(this.bid={},this.bid.raw=t.bid.raw||"",this.bid.fixed=t.bid.fixed||0,this.bid.period=t.bid.period||0,this.bid.hash=t.bid.hash||"",this.bid.value=t.bid.value||0,this.bid.address=t.bid.address||"")}toRaw(){let t={};return t.pid=this.pid,t.cid=this.cid||"",t.oid=this.oid||"",t.gold=this.gold,this.current&&(t.current={},t.current.hash=this.current.hash,t.current.index=this.current.index,t.current.address=this.current.address),t.height=this.height,t.pst=this.pst||i.Ready,t.wid=this.wid||0,t.account=this.account||"",this.bid&&(t.bid={},t.bid.raw=this.bid.raw||"",t.bid.fixed=this.bid.fixed||0,t.bid.period=this.bid.period||0,t.bid.hash=this.bid.hash||"",t.bid.value=this.bid.value||0,t.bid.address=this.bid.address||""),Buffer.from(JSON.stringify(t),"utf-8")}fromRaw(t){return t=JSON.parse(t.toString("utf8")),this.fromOptions(t),this}static fromRaw(t){return(new n).fromRaw(t)}}s.vpItem=n,t.exports=s},function(t,e,r){var i=r(10),s=r(179),n=(r=r(9),{sha1:!0,sha256:!0,sha512:!0}),a={rsa:!0,dsa:!0,ecdsa:!0};function o(t,e){Error.captureStackTrace&&Error.captureStackTrace(this,e||o),this.message=t,this.name=e.name}function c(t){o.call(this,t,c)}r.inherits(o,Error),r.inherits(c,o),t.exports={HASH_ALGOS:n,PK_ALGOS:a,HttpSignatureError:o,InvalidAlgorithmError:c,validateAlgorithm:function(t){if(2!==(t=t.toLowerCase().split("-")).length)throw new c(t[0].toUpperCase()+" is not a valid algorithm");if("hmac"!==t[0]&&!a[t[0]])throw new c(t[0].toUpperCase()+" type keys are not supported");if(n[t[1]])return t;throw new c(t[1].toUpperCase()+" is not a supported hash algorithm")},sshKeyToPEM:function(t){return i.string(t,"ssh_key"),s.parseKey(t,"ssh").toString("pem")},fingerprint:function(t){return i.string(t,"ssh_key"),s.parseKey(t,"ssh").fingerprint("md5").toString("hex")},pemToRsaSSHKey:function(t,e){return i.equal("string",typeof t,"typeof pem"),(t=s.parseKey(t,"pem")).comment=e,t.toString("ssh")}}},function(t,e,r){var i=r(104).BigInteger,s=i.prototype.Barrett;function n(t,e){this.x=e,this.q=t}function a(t,e,r,s){this.curve=t,this.x=e,this.y=r,this.z=null==s?i.ONE:s,this.zinv=null}function o(t,e,r){this.q=t,this.a=this.fromBigInteger(e),this.b=this.fromBigInteger(r),this.infinity=new a(this,null,null),this.reducer=new s(this.q)}n.prototype.equals=function(t){return t==this||this.q.equals(t.q)&&this.x.equals(t.x)},n.prototype.toBigInteger=function(){return this.x},n.prototype.negate=function(){return new n(this.q,this.x.negate().mod(this.q))},n.prototype.add=function(t){return new n(this.q,this.x.add(t.toBigInteger()).mod(this.q))},n.prototype.subtract=function(t){return new n(this.q,this.x.subtract(t.toBigInteger()).mod(this.q))},n.prototype.multiply=function(t){return new n(this.q,this.x.multiply(t.toBigInteger()).mod(this.q))},n.prototype.square=function(){return new n(this.q,this.x.square().mod(this.q))},n.prototype.divide=function(t){return new n(this.q,this.x.multiply(t.toBigInteger().modInverse(this.q)).mod(this.q))},a.prototype.getX=function(){null==this.zinv&&(this.zinv=this.z.modInverse(this.curve.q));var t=this.x.toBigInteger().multiply(this.zinv);return this.curve.reduce(t),this.curve.fromBigInteger(t)},a.prototype.getY=function(){null==this.zinv&&(this.zinv=this.z.modInverse(this.curve.q));var t=this.y.toBigInteger().multiply(this.zinv);return this.curve.reduce(t),this.curve.fromBigInteger(t)},a.prototype.equals=function(t){return t==this||(this.isInfinity()?t.isInfinity():t.isInfinity()?this.isInfinity():!!t.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(t.z)).mod(this.curve.q).equals(i.ZERO)&&t.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(t.z)).mod(this.curve.q).equals(i.ZERO))},a.prototype.isInfinity=function(){return null==this.x&&null==this.y||this.z.equals(i.ZERO)&&!this.y.toBigInteger().equals(i.ZERO)},a.prototype.negate=function(){return new a(this.curve,this.x,this.y.negate(),this.z)},a.prototype.add=function(t){var e,r,s,n,o,c,u;return this.isInfinity()?t:t.isInfinity()?this:(e=t.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(t.z)).mod(this.curve.q),o=t.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(t.z)).mod(this.curve.q),i.ZERO.equals(o)?i.ZERO.equals(e)?this.twice():this.curve.getInfinity():(u=new i("3"),c=this.x.toBigInteger(),r=this.y.toBigInteger(),t.x.toBigInteger(),t.y.toBigInteger(),s=(n=o.square()).multiply(o),c=c.multiply(n),o=(n=e.square().multiply(this.z)).subtract(c.shiftLeft(1)).multiply(t.z).subtract(s).multiply(o).mod(this.curve.q),c=c.multiply(u).multiply(e).subtract(r.multiply(s)).subtract(n.multiply(e)).multiply(t.z).add(e.multiply(s)).mod(this.curve.q),u=s.multiply(this.z).multiply(t.z).mod(this.curve.q),new a(this.curve,this.curve.fromBigInteger(o),this.curve.fromBigInteger(c),u)))},a.prototype.twice=function(){var t,e,r,s,n,o;return this.isInfinity()?this:0==this.y.toBigInteger().signum()?this.curve.getInfinity():(n=new i("3"),o=this.x.toBigInteger(),e=(t=(e=this.y.toBigInteger()).multiply(this.z)).multiply(e).mod(this.curve.q),s=this.curve.a.toBigInteger(),r=o.square().multiply(n),s=(r=(r=i.ZERO.equals(s)?r:r.add(this.z.square().multiply(s))).mod(this.curve.q)).square().subtract(o.shiftLeft(3).multiply(e)).shiftLeft(1).multiply(t).mod(this.curve.q),n=r.multiply(n).multiply(o).subtract(e.shiftLeft(1)).shiftLeft(2).multiply(e).subtract(r.square().multiply(r)).mod(this.curve.q),o=t.square().multiply(t).shiftLeft(3).mod(this.curve.q),new a(this.curve,this.curve.fromBigInteger(s),this.curve.fromBigInteger(n),o))},a.prototype.multiply=function(t){if(this.isInfinity())return this;if(0==t.signum())return this.curve.getInfinity();for(var e=t,r=e.multiply(new i("3")),s=this.negate(),n=this,a=r.bitLength()-2;0<a;--a){n=n.twice();var o=r.testBit(a);o!=e.testBit(a)&&(n=n.add(o?this:s))}return n},a.prototype.multiplyTwo=function(t,e,r){for(var i=t.bitLength()>r.bitLength()?t.bitLength()-1:r.bitLength()-1,s=this.curve.getInfinity(),n=this.add(e);0<=i;)s=s.twice(),t.testBit(i)?s=r.testBit(i)?s.add(n):s.add(this):r.testBit(i)&&(s=s.add(e)),--i;return s},o.prototype.getQ=function(){return this.q},o.prototype.getA=function(){return this.a},o.prototype.getB=function(){return this.b},o.prototype.equals=function(t){return t==this||this.q.equals(t.q)&&this.a.equals(t.a)&&this.b.equals(t.b)},o.prototype.getInfinity=function(){return this.infinity},o.prototype.fromBigInteger=function(t){return new n(this.q,t)},o.prototype.reduce=function(t){this.reducer.reduce(t)},o.prototype.encodePointHex=function(t){if(t.isInfinity())return"00";var e=t.getX().toBigInteger().toString(16),r=t.getY().toBigInteger().toString(16),i=this.getQ().toString(16).length;for(i%2!=0&&i++;e.length<i;)e="0"+e;for(;r.length<i;)r="0"+r;return"04"+e+r},o.prototype.decodePointHex=function(t){switch(parseInt(t.substr(0,2),16)){case 0:return this.infinity;case 2:c=!1;case 3:null==c&&(c=!0);var e=t.length-2,r=t.substr(2,e),s=this.fromBigInteger(new i(r,16)),n=s.multiply(s.square().add(this.getA())).add(this.getB()).sqrt();if(null==n)throw"Invalid point compression";var o=n.toBigInteger();return o.testBit(0)!=c&&(n=this.fromBigInteger(this.getQ().subtract(o))),new a(this,s,n);case 4:case 6:case 7:e=(t.length-2)/2,r=t.substr(2,e);var c=t.substr(e+2,e);return new a(this,this.fromBigInteger(new i(r,16)),this.fromBigInteger(new i(c,16)));default:return null}},o.prototype.encodeCompressedPointHex=function(t){if(t.isInfinity())return"00";var e=t.getX().toBigInteger().toString(16),r=this.getQ().toString(16).length;for(r%2!=0&&r++;e.length<r;)e="0"+e;return(t.getY().toBigInteger().isEven()?"02":"03")+e},n.prototype.getR=function(){var t;return null==this.r&&(this.r=null,128<(t=this.q.bitLength())&&-1==this.q.shiftRight(t-64).intValue()&&(this.r=i.ONE.shiftLeft(t).subtract(this.q))),this.r},n.prototype.modMult=function(t,e){return this.modReduce(t.multiply(e))},n.prototype.modReduce=function(t){if(null!=this.getR()){for(var e=q.bitLength();t.bitLength()>e+1;){var r=t.shiftRight(e),s=t.subtract(r.shiftLeft(e));t=(r=this.getR().equals(i.ONE)?r:r.multiply(this.getR())).add(s)}for(;0<=t.compareTo(q);)t=t.subtract(q)}else t=t.mod(q);return t},n.prototype.sqrt=function(){if(!this.q.testBit(0))throw"unsupported";var t;if(this.q.testBit(1))return(t=new n(this.q,this.x.modPow(this.q.shiftRight(2).add(i.ONE),this.q))).square().equals(this)?t:null;var e=this.q.subtract(i.ONE),r=e.shiftRight(1);if(this.x.modPow(r,this.q).equals(i.ONE)){var s,a=e.shiftRight(2).shiftLeft(1).add(i.ONE),o=this.x,c=modDouble(modDouble(o));do{for(;0<=(s=new i(this.q.bitLength(),new SecureRandom)).compareTo(this.q)||!s.multiply(s).subtract(c).modPow(r,this.q).equals(e););var u=(h=this.lucasSequence(s,o,a))[0],h=h[1];if(this.modMult(h,h).equals(c))return h=(h=h.testBit(0)?h.add(q):h).shiftRight(1),new n(q,h)}while(u.equals(i.ONE)||u.equals(e))}return null},n.prototype.lucasSequence=function(t,e,r){for(var s=r.bitLength(),n=r.getLowestSetBit(),a=i.ONE,o=i.TWO,c=t,u=i.ONE,h=i.ONE,l=s-1;n+1<=l;--l)u=this.modMult(u,h),r.testBit(l)?(h=this.modMult(u,e),a=this.modMult(a,c),o=this.modReduce(c.multiply(o).subtract(t.multiply(u))),c=this.modReduce(c.multiply(c).subtract(h.shiftLeft(1)))):(h=u,a=this.modReduce(a.multiply(o).subtract(u)),c=this.modReduce(c.multiply(o).subtract(t.multiply(u))),o=this.modReduce(o.multiply(o).subtract(u.shiftLeft(1))));for(u=this.modMult(u,h),h=this.modMult(u,e),a=this.modReduce(a.multiply(o).subtract(u)),o=this.modReduce(c.multiply(o).subtract(t.multiply(u))),u=this.modMult(u,h),l=1;l<=n;++l)a=this.modMult(a,o),o=this.modReduce(o.multiply(o).subtract(u.shiftLeft(1))),u=this.modMult(u,u);return[a,o]},t.exports={ECCurveFp:o,ECPointFp:a,ECFieldElementFp:n}},function(t,e,r){t.exports={read:function(t,e){return u.read(t,e)},readSSHPrivate:function(t,e,c){var u=(e=new l({buffer:e})).readCString(),f=(s.strictEqual(u,d,"bad magic string"),e.readString()),m=e.readString();u=e.readBuffer();if(1!==e.readInt())throw new Error("OpenSSH-format key file contains multiple keys: this is unsupported.");var g=e.readBuffer();if("public"===t)return s.ok(e.atEnd(),"excess bytes left after key"),h.read(g);var y=e.readBuffer(),v=(s.ok(e.atEnd(),"excess bytes left after key"),new l({buffer:u}));switch(m){case"none":if("none"!==f)throw new Error('OpenSSH-format key uses KDF "none" but specifies a cipher other than "none"');break;case"bcrypt":var b=v.readBuffer(),w=v.readInt(),x=a.opensshCipherInfo(f);if(void 0===i&&(i=r(284)),"string"==typeof c.passphrase&&(c.passphrase=n.from(c.passphrase,"utf-8")),!n.isBuffer(c.passphrase))throw new p.KeyEncryptedError(c.filename,"OpenSSH");var k=new Uint8Array(c.passphrase),S=(b=new Uint8Array(b),new Uint8Array(x.keySize+x.blockSize));if(0!==i.pbkdf(k,k.length,b,b.length,S,S.length,w))throw new Error("bcrypt_pbkdf function returned failure, parameters invalid");k=(S=n.from(S)).slice(0,x.keySize),b=S.slice(x.keySize,x.keySize+x.blockSize);var E=o.createDecipheriv(x.opensslName,k,b);E.setAutoPadding(!1);var _,A=[];for(E.once("error",(function(t){if(-1!==t.toString().indexOf("bad decrypt"))throw new Error("Incorrect passphrase supplied, could not decrypt key");throw t})),E.write(y),E.end();null!==(_=E.read());)A.push(_);y=n.concat(A);break;default:throw new Error('OpenSSH-format key uses unknown KDF "'+m+'"')}if((t=(e=new l({buffer:y})).readInt())!==(g=e.readInt()))throw new Error("Incorrect passphrase supplied, could not decrypt key");return u={},t=h.readInternal(u,"private",e.remainder()),e.skip(u.consumed),g=e.readString(),t.comment=g,t},write:function(t,e){var u;u=c.isPrivateKey(t)?t.toPublic():t;var h,p,f="none",m="none",g=n.alloc(0),y={blockSize:8};if(void 0!==e&&void 0!==(h="string"==typeof(h=e.passphrase)?n.from(h,"utf-8"):h)&&(s.buffer(h,"options.passphrase"),s.optionalString(e.cipher,"options.cipher"),void 0===(f=e.cipher)&&(f="aes128-ctr"),y=a.opensshCipherInfo(f),m="bcrypt"),c.isPrivateKey(t)){p=new l({});e=o.randomBytes(4).readUInt32BE(0);for(var v=(p.writeInt(e),p.writeInt(e),p.write(t.toBuffer("rfc4253")),p.writeString(t.comment||""),1);p._offset%y.blockSize!=0;)p.writeChar(v++);p=p.toBuffer()}switch(m){case"none":break;case"bcrypt":var b=o.randomBytes(16),w=((w=new l({})).writeBuffer(b),w.writeInt(16),g=w.toBuffer(),void 0===i&&(i=r(284)),new Uint8Array(h)),x=(b=new Uint8Array(b),new Uint8Array(y.keySize+y.blockSize));if(0!==i.pbkdf(w,w.length,b,b.length,x,x.length,16))throw new Error("bcrypt_pbkdf function returned failure, parameters invalid");w=(x=n.from(x)).slice(0,y.keySize),b=x.slice(y.keySize,y.keySize+y.blockSize);var k=o.createCipheriv(y.opensslName,w,b);k.setAutoPadding(!1);var S,E=[];for(k.once("error",(function(t){throw t})),k.write(p),k.end();null!==(S=k.read());)E.push(S);p=n.concat(E);break;default:throw new Error("Unsupported kdf "+m)}var _=new l({});_.writeCString(d),_.writeString(f),_.writeString(m),_.writeBuffer(g),_.writeInt(1),_.writeBuffer(u.toBuffer("rfc4253")),p&&_.writeBuffer(p),_=_.toBuffer(),e=c.isPrivateKey(t)?"OPENSSH PRIVATE KEY":"OPENSSH PUBLIC KEY";var A=_.toString("base64"),R=(f=A.length+A.length/70+18+16+2*e.length+10,_=n.alloc(f),0);R+=_.write("-----BEGIN "+e+"-----\n",R);for(var I=0;I<A.length;){var j=I+70;j>A.length&&(j=A.length),R+=_.write(A.slice(I,j),R),_[R++]=10,I=j}return R+=_.write("-----END "+e+"-----\n",R),_.slice(0,R)}};var i,s=r(10),n=(r(57),r(14).Buffer),a=(r(31),r(25)),o=r(8),c=(r(23),r(24)),u=r(67),h=r(68),l=r(91),p=r(51),d="openssh-key-v1"},function(t,e,r){var i=r(58);const s=r(83),n=r(17),a=r(26),o=r(7),c=r(0),{Transform:u,ContractType:h,HtlcStatus:l,ContractEnvType:p}=r(5),d=new u("\n /*携带合约信息*/\n HTLCSUGGEST var_contract DROP\n /*校验秘密,持有秘密者才可执行*/\n HASH160 var_ab EQUALVERIFY \n IF\n /*Bob确认时执行: 校验Bob签名*/\n DUP HASH160 var_ba EQUALVERIFY CHECKSIG\n ELSE\n /*Alice取消时执行: 校验延时和Alice签名*/\n var_period CHECKSEQUENCEVERIFY DROP\n DUP HASH160 var_aa EQUALVERIFY CHECKSIG\n ENDIF\n");t.exports=class extends i{async confirm(){let{env:t,output:e,hash:r,i:i,data:n,height:a}=this.options;var o=e.getHashs("hex");o={type:"suggest",src:s.protocol+"."+t.network.type,dst:n.dst,shash:r,sidx:i,sheight:a,pst:l.Sent,amount:e.value,rate:n.rate,ab:e.script.code[4].data.toString("hex"),aa:o[1],ba:o[0]};await t.setSuggest(o),t.mode==p.Block&&t.node.transmit("htlcsuggest.receive",o)}async unconfirm(){let{env:t,data:e}=this.options;var r={shash:e.hash,sidx:e.index};await t.delHtlc(r)}async spent(t){let e=this.options.env,r=e.htlcList.get(""+t.prevout.hash+t.prevout.index);r&&(81==t.script.code[2].value?(r.pst=l.Finished,await e.setSuggest(r),e.mode==p.Block&&e.node.transmit("htlcsuggest.deal",r)):(r.pst=l.Cancel,await e.setSuggest(r),e.mode==p.Block&&e.node.transmit("htlcsuggest.cancel",r)))}async verify(){let{output:t,data:e}=this.options;var r={oper:h.htlcSuggest,rate:e.rate,dst:e.dst};let i=t.getHashs("hex"),s=t.script.code[4].data.toString("hex");r={contract:"0x"+Buffer.from(JSON.stringify(r)).toString("hex"),ab:"0x"+s.toString("hex"),aa:"0x"+i[1].toString("hex"),ba:"0x"+i[0].toString("hex"),period:2*o.HTLC_CANCEL_PERIOD};let a=n.fromString(d.replace(r));return c(a.toString()===t.script.toString()),!0}static create(t){var e={oper:h.htlcSuggest,rate:t.rate,dst:t.dst};e={contract:"0x"+Buffer.from(JSON.stringify(e)).toString("hex"),ab:"0x"+t.ab.toString("hex"),aa:"0x"+t.aa.toString("hex"),ba:"0x"+t.ba.toString("hex"),period:2*o.HTLC_CANCEL_PERIOD},e=n.fromString(d.replace(e));return a.fromScript(e,t.amount)}}},function(t,e,r){var i=r(58);const s=r(83),n=r(17),a=r(26),o=r(7),{Transform:c,ContractType:u,HtlcStatus:h,ContractEnvType:l}=r(5),p=new c("\n /*携带合约信息*/\n HTLCASSENT var_contract DROP\n IF\n /*Alice确认时执行: 校验签名*/\n DUP HASH160 var_ab EQUALVERIFY CHECKSIG\n ELSE\n /*Bob取消时执行: 校验延时和签名*/\n var_period CHECKSEQUENCEVERIFY DROP\n DUP HASH160 var_bb EQUALVERIFY CHECKSIG\n ENDIF\n");t.exports=class extends i{async confirm(){let{env:t,i:e,output:r,hash:i,height:n,data:a}=this.options;var o=r.getHashs("hex");o={src:a.src,dst:s.protocol+"."+t.network.type,shash:a.hash,sidx:a.index,ahash:i,aidx:e,aheight:n,pst:h.Assent,amount:a.value,rate:a.rate,ab:o[0],bb:o[1]};await t.setAssent(o),t.mode==l.Block&&t.node.transmit("htlcassent.receive",o)}async unconfirm(){let{env:t,data:e}=this.options;var r={shash:e.hash,sidx:e.index};await t.delHtlc(r)}async spent(t){let e=this.options.env;var r=e.htlcList.query([["ahash",t.prevout.hash],["aidx",t.prevout.index]]);if(r&&1===r.list.length&&r.list[0].pst===h.Assent){let i=r.list[0];81==t.script.code[2].value?(i.secret=t.script.code[1].data.toString("hex"),i.pst=h.Deal,await e.setAssent(i),e.mode==l.Block&&e.node.transmit("htlcassent.deal",i)):(i.pst=h.Cancel,await e.setAssent(i),e.mode==l.Block&&e.node.transmit("htlcassent.cancel",i))}}async verify(){let{env:t,output:e,data:r}=this.options;if(r.dst!=s.protocol+"."+t.network.type)return!1;var i={oper:u.htlcAssent,hash:r.hash,index:r.index};let a=e.getHashs("hex"),c=n.fromString(p.replace({contract:"0x"+Buffer.from(JSON.stringify(i)).toString("hex"),ab:"0x"+a[0].toString("hex"),bb:"0x"+a[1].toString("hex"),period:o.HTLC_CANCEL_PERIOD}));return assert(c.toString()===e.script.toString()),!0}static create(t){var e={oper:u.htlcAssent,hash:t.hash,index:t.index};e=n.fromString(p.replace({contract:"0x"+Buffer.from(JSON.stringify(e)).toString("hex"),ab:"0x"+t.ab.toString("hex"),bb:"0x"+t.bb.toString("hex"),period:o.HTLC_CANCEL_PERIOD}));return a.fromScript(e,t.amount)}}},function(t,e,r){var i=r(58);const s=r(17),n=r(26),a=r(0),{Transform:o,ContractType:c,ContractEnvType:u}=r(5),h=r(12),l=r(63).verifyData,p=new o("\n /*携带合约信息*/\n COMMENT var_contract DROP\n /*Bob确认时执行: 校验Bob签名*/\n DUP HASH160 var_bob EQUALVERIFY CHECKSIG\n");t.exports=class extends i{async insert(){let{env:t,output:e,hash:r,i:i,data:s}=this.options;var n=h.fromWitnessPubkeyhash(e.getHash(),t.network).toString();n={shash:r,sidx:i,alice:s.payload.addr,bob:n,body:s.payload.body};t.mode==u.Wallet&&await t.setComment(n)}async erase(){let{env:t,hash:e,i:r}=this.options;var i={shash:e,sidx:r};t.mode==u.Wallet&&await t.delComment(i)}async verify(){let{output:t,data:e}=this.options,r=t.getHash(),i=s.fromString(p.replace({contract:"0x"+Buffer.from(JSON.stringify(e)).toString("hex"),bob:"0x"+r.toString("hex")}));a(i.toString()===t.script.toString());var n=e.payload.sig;return delete(e=e.payload).sig,a.strictEqual(!0,l({data:e,sig:n})),!0}static create(t){var e={oper:c.comment,payload:t};e={contract:"0x"+Buffer.from(JSON.stringify(e)).toString("hex"),bob:"0x"+h.fromString(t.bob).hash.toString("hex")},e=s.fromString(p.replace(e));return n.fromScript(e,t.amount)}}},function(t,e,r){"use strict";
325
325
  /*!
326
326
  * netaddress.js - network address object for vallnet
327
327
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -376,7 +376,7 @@ const i=r(21).opcodes;function s(t){let e=null;var r=s.list[t.type];return new(r
376
376
  * mempoolentry.js - mempool entry object for vallnet
377
377
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
378
378
  * https://github.com/bookmansoft/gamegold
379
- */const i=r(27),s=r(1),n=r(17),a=r(2),o=r(4),c=r(19);r(61),t.exports=class t{constructor(t){this.tx=null,this.height=-1,this.size=0,this.sigops=0,this.priority=0,this.fee=0,this.deltaFee=0,this.time=0,this.value=0,this.coinbase=!1,this.dependencies=!1,this.descFee=0,this.descSize=0,t&&this.fromOptions(t)}fromOptions(t){return this.tx=t.tx,this.height=t.height,this.size=t.size,this.sigops=t.sigops,this.priority=t.priority,this.fee=t.fee,this.deltaFee=t.deltaFee,this.time=t.time,this.value=t.value,this.coinbase=t.coinbase,this.dependencies=t.dependencies,this.descFee=t.descFee,this.descSize=t.descSize,this}static fromOptions(e){return(new t).fromOptions(e)}fromTX(t,e,r){var i=n.flags.STANDARD_VERIFY_FLAGS,a=t.getChainValue(e),o=(i=t.getSigopsCost(e,i),t.getSigopsSize(i)),c=t.getPriority(e,r,o),u=t.getFee(e);let h=!1;var l,p=t.isCoinbase();for({prevout:l}of t.inputs)if(-1===e.getHeight(l)){h=!0;break}return this.tx=t,this.height=r,this.size=o,this.sigops=i,this.priority=c,this.fee=u,this.deltaFee=u,this.time=s.now(),this.value=a,this.coinbase=p,this.dependencies=h,this.descFee=u,this.descSize=o,this}static fromTX(e,r,i){return(new t).fromTX(e,r,i)}hash(t){return this.tx.hash(t)}txid(){return this.tx.txid()}getPriority(t){return t=(t-this.height)*this.value/this.size,Math.max(0,this.priority+Math.floor(t))}getFee(){return this.fee}getDeltaFee(){return this.deltaFee}getRate(){return i.getRate(this.size,this.fee)}getDeltaRate(){return i.getRate(this.size,this.deltaFee)}getDescRate(){return i.getRate(this.descSize,this.descFee)}memUsage(){var t=this.tx;let e=0;e=(e=(e=(e=(e=e+176+48)+48+208)+80+88)+80+80)+48+32;for(const r of t.inputs){e=(e=(e=(e=e+120+104)+88+40)+80+32)+40*r.script.code.length;for(const t of r.script.code)t.data&&(e+=80);e=(e=e+96+32)+80*r.witness.items.length}e+=32;for(const r of t.outputs){e=(e=(e=e+104+40)+80+32)+40*r.script.code.length;for(const t of r.script.code)t.data&&(e+=80)}return e}isFree(t){return this.getPriority(t)>i.FREE_THRESHOLD}getSize(){return this.tx.getSize()+42}toRaw(){const t=new o(this.getSize());return t.writeBytes(this.tx.toRaw()),t.writeU32(this.height),t.writeU32(this.size),t.writeU32(this.sigops),t.writeDouble(this.priority),t.writeU64(this.fee),t.writeU32(this.time),t.writeU64(this.value),t.writeU8(this.coinbase?1:0),t.writeU8(this.dependencies?1:0),t.render()}fromRaw(t){const e=new a(t);return this.tx=c.fromReader(e),this.height=e.readU32(),this.size=e.readU32(),this.sigops=e.readU32(),this.priority=e.readDouble(),this.fee=e.readU64(),this.time=e.readU32(),this.value=e.readU64(),this.coinbase=1===e.readU8(),this.dependencies=1===e.readU8(),this.deltaFee=this.fee,this.descFee=this.fee,this.descSize=this.size,this}static fromRaw(e){return(new t).fromRaw(e)}}},function(t,e,r){var i=r(29);const s=r(4),n=r(2),a=r(3);r(20);const o=r(1);class c extends i{constructor(t){super(),this.env=t}async loadHistory(){var t;for(t of await this.env.getScs())this.set(t.id,t)}async addItem(t){this.set(t.id,t),await this.env.setSc(t)}async delItem(t){await this.env.delSc(t.id),this.delete(t.id)}getItem(t){return this.has(t)?this.get(t):null}}class u{constructor(t){this.options=t||{},this.history=[]}do(){var t=JSON.stringify(this.options);this.history.push(o.parseJson(t)),144<this.history.length&&this.history.shift()}undo(){var t;1<this.history.length&&(this.history.pop(),t=JSON.stringify(this.history[0]),this.options=o.parseJson(t))}get id(){return this.options.addr}getSize(){return 0+a.sizeVarString(JSON.stringify(this.history),"utf8")}toWriter(t){return t.writeVarString(JSON.stringify(this.history),"utf8"),t}toRaw(){var t=this.getSize();return this.toWriter(new s(t)).render()}fromReader(t){return t=t.readVarString("utf8"),this.history=o.parseJson(t),t=JSON.stringify(this.history[0]),this.options=o.parseJson(t),this}fromRaw(t){return this.fromReader(new n(t))}clone(){return u.fromRaw(this.toRaw())}static fromReader(t){return(new u).fromReader(t)}static fromRaw(t){return(new u).fromRaw(t)}}c.scItem=u,t.exports=c},function(t,e,r){
379
+ */const i=r(27),s=r(1),n=r(17),a=r(2),o=r(4),c=r(19);r(61),t.exports=class t{constructor(t){this.tx=null,this.height=-1,this.size=0,this.sigops=0,this.priority=0,this.fee=0,this.deltaFee=0,this.time=0,this.value=0,this.coinbase=!1,this.dependencies=!1,this.descFee=0,this.descSize=0,t&&this.fromOptions(t)}fromOptions(t){return this.tx=t.tx,this.height=t.height,this.size=t.size,this.sigops=t.sigops,this.priority=t.priority,this.fee=t.fee,this.deltaFee=t.deltaFee,this.time=t.time,this.value=t.value,this.coinbase=t.coinbase,this.dependencies=t.dependencies,this.descFee=t.descFee,this.descSize=t.descSize,this}static fromOptions(e){return(new t).fromOptions(e)}fromTX(t,e,r){var i=n.flags.STANDARD_VERIFY_FLAGS,a=t.getChainValue(e),o=(i=t.getSigopsCost(e,i),t.getSigopsSize(i)),c=t.getPriority(e,r,o),u=t.getFee(e);let h=!1;var l,p=t.isCoinbase();for({prevout:l}of t.inputs)if(-1===e.getHeight(l)){h=!0;break}return this.tx=t,this.height=r,this.size=o,this.sigops=i,this.priority=c,this.fee=u,this.deltaFee=u,this.time=s.now(),this.value=a,this.coinbase=p,this.dependencies=h,this.descFee=u,this.descSize=o,this}static fromTX(e,r,i){return(new t).fromTX(e,r,i)}hash(t){return this.tx.hash(t)}txid(){return this.tx.txid()}getPriority(t){return t=(t-this.height)*this.value/this.size,Math.max(0,this.priority+Math.floor(t))}getFee(){return this.fee}getDeltaFee(){return this.deltaFee}getRate(){return i.getRate(this.size,this.fee)}getDeltaRate(){return i.getRate(this.size,this.deltaFee)}getDescRate(){return i.getRate(this.descSize,this.descFee)}memUsage(){var t=this.tx;let e=0;e=(e=(e=(e=(e=e+176+48)+48+208)+80+88)+80+80)+48+32;for(const r of t.inputs){e=(e=(e=(e=e+120+104)+88+40)+80+32)+40*r.script.code.length;for(const t of r.script.code)t.data&&(e+=80);e=(e=e+96+32)+80*r.witness.items.length}e+=32;for(const r of t.outputs){e=(e=(e=e+104+40)+80+32)+40*r.script.code.length;for(const t of r.script.code)t.data&&(e+=80)}return e}isFree(t){return this.getPriority(t)>i.FREE_THRESHOLD}getSize(){return this.tx.getSize()+42}toRaw(){const t=new o(this.getSize());return t.writeBytes(this.tx.toRaw()),t.writeU32(this.height),t.writeU32(this.size),t.writeU32(this.sigops),t.writeDouble(this.priority),t.writeU64(this.fee),t.writeU32(this.time),t.writeU64(this.value),t.writeU8(this.coinbase?1:0),t.writeU8(this.dependencies?1:0),t.render()}fromRaw(t){const e=new a(t);return this.tx=c.fromReader(e),this.height=e.readU32(),this.size=e.readU32(),this.sigops=e.readU32(),this.priority=e.readDouble(),this.fee=e.readU64(),this.time=e.readU32(),this.value=e.readU64(),this.coinbase=1===e.readU8(),this.dependencies=1===e.readU8(),this.deltaFee=this.fee,this.descFee=this.fee,this.descSize=this.size,this}static fromRaw(e){return(new t).fromRaw(e)}}},function(t,e,r){var i=r(28);const s=r(4),n=r(2),a=r(3);r(20);const o=r(1);class c extends i{constructor(t){super(),this.env=t}async loadHistory(){var t;for(t of await this.env.getScs())this.set(t.id,t)}async addItem(t){this.set(t.id,t),await this.env.setSc(t)}async delItem(t){await this.env.delSc(t.id),this.delete(t.id)}getItem(t){return this.has(t)?this.get(t):null}}class u{constructor(t){this.options=t||{},this.history=[]}do(){var t=JSON.stringify(this.options);this.history.push(o.parseJson(t)),144<this.history.length&&this.history.shift()}undo(){var t;1<this.history.length&&(this.history.pop(),t=JSON.stringify(this.history[0]),this.options=o.parseJson(t))}get id(){return this.options.addr}getSize(){return 0+a.sizeVarString(JSON.stringify(this.history),"utf8")}toWriter(t){return t.writeVarString(JSON.stringify(this.history),"utf8"),t}toRaw(){var t=this.getSize();return this.toWriter(new s(t)).render()}fromReader(t){return t=t.readVarString("utf8"),this.history=o.parseJson(t),t=JSON.stringify(this.history[0]),this.options=o.parseJson(t),this}fromRaw(t){return this.fromReader(new n(t))}clone(){return u.fromRaw(this.toRaw())}static fromReader(t){return(new u).fromReader(t)}static fromRaw(t){return(new u).fromRaw(t)}}c.scItem=u,t.exports=c},function(t,e,r){
380
380
  /*!
381
381
  * selector.js
382
382
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -386,7 +386,7 @@ function i(t){let e=null;var r=i.list[t.contract.options.type];return r?new(e=r.
386
386
  * jobs.js - worker jobs for vallnet
387
387
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
388
388
  * https://github.com/bookmansoft/gamegold
389
- */const i=r(28),s=r(238).derive,n=r(316),a=r(121);r(60),r(22);var{}=r(5);const o=e;o.execute=function(t){try{return o.handle(t)}catch(t){return new a.ErrorResultPacket(t)}},o.handle=function(t){return t.jobsHandle(o)},o.check=function(t,e,r,i){try{t.check(e,r,i)}catch(t){if("ScriptError"===t.type)return new a.CheckResultPacket(t);throw t}return new a.CheckResultPacket},o.checkInput=function(t,e,r,i,s){try{t.checkInput(e,r,i,s)}catch(t){if("ScriptError"===t.type)return new a.CheckInputResultPacket(t);throw t}return new a.CheckInputResultPacket},o.sign=function(t,e,r,i){return e=t.sign(e,!0,r,i),a.SignResultPacket.fromTX(t,e)},o.signInput=function(t,e,r,i,s){return r=t.signInput(t,e,r,i,s),a.SignInputResultPacket.fromTX(t,e,r)},o.ecVerify=function(t,e,r){return t=i.verify(t,e,r),new a.ECVerifyResultPacket(t)},o.ecSign=function(t,e){return t=i.sign(t,e),new a.ECSignResultPacket(t)},o.mine=function(t,e,r,i){return t=n(t,e,r,i),new a.MineResultPacket(t)},o.scrypt=function(t,e,r,i,n,o){return t=s(t,e,r,i,n,o),new a.ScryptResultPacket(t)}},function(t,e,r){var i=r(29);const s=r(4),n=r(3),a=r(6),o=r(65);class c extends i{constructor(t){super(),this.db=t||{getEr:()=>{},setEr:()=>{},delEr:()=>{}},this.cache=new o(1e4)}async loadHistory(){}async getEr(t){return this.cache.get(t)||this.db.getEr(t)}async setEr(t,e){t=new u(t),await this.db.setEr(t,e),this.cache.set(t.erid,t)}async delEr(t,e){await this.db.delEr(t),this.cache.remove(t.erid)}async query(t){let e=!1,r=null,i=[];for(var s of t)if(s&&Array.isArray(s)){if("erid"==s[0])return{list:[await this.getEr(s[1])],page:0,count:1};"merge"==s[0]?e=s[1]:"pubkey"==s[0]?r=s[1]:i.push(s)}return r?this.db.byPubkey(r,i,e):{list:[],page:0,count:1}}}class u{constructor(t){this.fromOptions(t=t||{})}fromOptions(t){this.oper=t.oper||"erIssue",this.erid=t.erid,this.witness=t.witness||"",this.validHeight=t.validHeight,this.startHeight=t.startHeight||0,this.signature=t.signature||"",this.source=null,t.source&&(this.source={},this.source.subjectName=t.source.subjectName,this.source.pubkey=t.source.pubkey,this.source.subjectHash=t.source.subjectHash,this.source.cluster=t.source.cluster,this.source.cid=t.source.cid,this.source.uid=t.source.uid),this.wid=t.wid||0,this.account=t.account||""}toRaw(){return Buffer.from(JSON.stringify(this.toOptions(!0)),"utf-8")}toOptions(t=!1){let e={};return e.oper=this.oper||"erIssue",e.erid=this.erid,e.witness=this.witness||"",e.validHeight=this.validHeight,t&&(e.startHeight=this.startHeight,e.signature=this.signature||""),this.source&&(e.source={},e.source.subjectName=this.source.subjectName,e.source.pubkey=this.source.pubkey,e.source.subjectHash=this.source.subjectHash,e.source.cluster=this.source.cluster||"",e.source.cid=this.source.cid||"",e.source.uid=this.source.uid||0),e}getSignObjSize(t){let e=0;return e=(e=(e=(e+=n.sizeVarString(t.oper,"utf8"))+n.sizeVarString(t.erid,"utf8"))+n.sizeVarString(t.witness,"ascii"))+4+4,t.source?(e=(e=(e=(e+=n.sizeVarString(t.source.subjectName,"utf8"))+n.sizeVarString(t.source.pubkey,"utf8"))+n.sizeVarString(t.source.subjectHash,"utf8"))+n.sizeVarString(t.source.cluster,"utf8"))+n.sizeVarString(t.source.cid,"utf8")+4:e}toWriter(t,e){return e.writeVarString(t.oper,"utf8"),e.writeVarString(t.erid,"utf8"),e.writeVarString(t.witness,"ascii"),e.writeU32(t.validHeight),e.writeU32(t.startHeight),t.source&&(e.writeVarString(t.source.subjectName,"utf8"),e.writeVarString(t.source.pubkey,"utf8"),e.writeVarString(t.source.subjectHash,"utf8"),e.writeVarString(t.source.cluster,"utf8"),e.writeVarString(t.source.cid,"utf8"),e.writeU32(t.source.uid)),e}toHash(){var t=this.toOptions();return a.hash256(this.toWriter(t,new s(this.getSignObjSize(t))).render())}fromRaw(t){return t=JSON.parse(t.toString("utf8")),this.fromOptions(t),this}static fromRaw(t){return(new u).fromRaw(t)}sign(t){this.signature=t.sign(this.toHash()).toString("hex")}verifying(t){return t.verify(this.toHash(),Buffer.from(this.signature,"hex"))}}c.ErItem=u,t.exports=c},function(t,e,r){var i=r(29);const s=r(4),n=r(3),a=r(6);class o extends i{constructor(t){super(),this.db=t||{getErAbolish:()=>{},setErAbolish:()=>{},delErAbolish:()=>{},loadErAbolishList:()=>{}}}async loadHistory(){}async getErAb(t){return this.db.getErAbolish(t)}async setErAb(t,e){t=new c(t),await this.db.setErAbolish(t),this.set(t.erid,t)}async delErAb(t,e){await this.db.delErAbolish(t),this.delete(t.erid)}async query(t){let e=!1;for(var r of t)"cluster"==r[0]&&(e=r[1]);for(var i of t){if("erid"==i[0])return{list:[await this.getErAb(i[1])],page:0,count:1};if("pubkey"==i[0])return this.db.byPubkey(i[1],e)}return{list:[],page:0,count:1}}}class c{constructor(t){this.fromOptions(t=t||{})}fromOptions(t){this.oper=t.oper||"erAbolish",this.erid=t.erid,this.witness=t.witness||"",this.abolishHeight=t.abolishHeight,this.startHeight=t.startHeight||0,this.signature=t.signature||""}toOptions(t){let e={};return e.oper=this.oper||"erAbolish",e.erid=this.erid,e.witness=this.witness||"",e.abolishHeight=this.abolishHeight,t&&(e.startHeight=this.startHeight,e.signature=this.signature||""),e}getMsgSize(){var t=0;return(t+=n.sizeVarString(this.oper,"utf8"))+n.sizeVarString(this.erid,"utf8")+n.sizeVarString(this.witness,"ascii")+4+4}toWriter(t,e){return e.writeVarString(this.oper,"utf8"),e.writeVarString(this.erid,"utf8"),e.writeVarString(this.witness,"ascii"),e.writeU32(this.abolishHeight),e.writeU32(this.startHeight),e}toHash(){var t=this.toOptions();return a.hash256(this.toWriter(t,new s(this.getMsgSize(t))).render())}toRaw(){return Buffer.from(JSON.stringify(this.toOptions(!0)),"utf-8")}fromReader(t){return t=JSON.parse(t.toString("utf8")),this.fromOptions(t),this}fromRaw(t){return this.fromReader(t)}static fromRaw(t){return(new c).fromRaw(t)}sign(t){this.signature=t.sign(this.toHash()).toString("hex")}verifying(t){return t.verify(this.toHash(),Buffer.from(this.signature,"hex"))}}o.ErAbolishItem=c,t.exports=o},function(t,e,r){var i=r(29);const s=r(4),n=r(3),a=r(6),{SX:o,SXX:c}=r(94);class u extends i{constructor(t){super(),this.db=t||{setX509Cert:()=>{},delX509Cert:()=>{},loadX509CertList:()=>{}}}async loadHistory(){var t,e;for(t of(this.clear(),await this.db.loadX509CertList()))this.set(t.getCertNo(),t),t.wid&&t.account&&(e=t.wid+"."+t.account,this.account.get(e)||this.account.set(e,new Map),this.account.get(e).set(t.getCertNo(),t))}setAccount(t,e,r){var i;t&&t.wid&&t.account&&(i=t.wid+"."+t.account,this.account.get(i)&&this.account.get(i).delete(t.getCertNo())),erItem.wid=e,erItem.account=r,e&&r&&(i=erItem.wid+"."+erItem.account,this.account.get(i)||this.account.set(i,new Map),this.account.get(i).set(t.getCertNo(),erItem))}delAccount(t){var e;t&&t.wid&&t.account&&(e=t.wid+"."+t.account,this.account.get(e)&&this.account.get(e).delete(t.getCertNo()))}getX509(t,e){return t=o(t,e,!0).toString("hex"),this.get(t)}async setX509Cert(t,e){t=new h(t),await this.db.setX509Cert(t,e),this.set(t.getCertNo(),t)}async delX509Cert(t,e){await this.db.delX509Cert(t),this.delete(t.getCertNo())}}class h{constructor(t){this.fromOptions(t=t||{})}fromOptions(t){this.oper=t.oper||"x509Issue",this.witness=t.witness||"",this.certSq=t.certSq,this.activeTime=t.activeTime,this.cert=t.cert||"",this.signature=t.signature||"",this.wid=t.wid||0,this.account=t.account||""}toRaw(){return Buffer.from(JSON.stringify(this.toOptions(!0)),"utf-8")}toOptions(t=!1){let e={};return e.oper=this.oper||"x509Issue",e.witness=this.witness||"",e.certSq=this.certSq,e.activeTime=this.activeTime,e.cert=this.cert,t&&(e.signature=this.signature||"",e.wid=this.wid||0,e.account=this.account||""),e}get certNo(){return o(this.witness,this.certSq,!0)}getCertNo(){return o(this.witness,this.certSq,!0).toString("hex")}static getKey(t,e){return o(t,e,!0).toString("hex")}static keyInfo(t){"string"==typeof t&&(t=Buffer.from(t,"hex"));var[t,e,r]=c(t);return r?{witness:t,certSq:e}:null}getSignObjSize(t){var e=0;return(e+=n.sizeVarString(t.oper,"utf8"))+n.sizeVarString(t.witness,"utf8")+4+8+n.sizeVarString(t.cert,"utf8")}toWriter(t,e){return e.writeVarString(t.oper,"utf8"),e.writeVarString(t.witness,"utf8"),e.writeU32(t.certSq),e.writeU64(t.activeTime),e.writeVarString(t.cert,"utf8"),e}toHash(){var t=this.toOptions();return a.hash256(this.toWriter(t,new s(this.getSignObjSize(t))).render())}fromRaw(t){return t=JSON.parse(t.toString("utf8")),this.fromOptions(t),this}static fromRaw(t){return(new h).fromRaw(t)}sign(t){this.signature=t.sign(this.toHash()).toString("hex")}verifying(t){return t.verify(this.toHash(),Buffer.from(this.signature,"hex"))}}u.X509Cert=h,t.exports=u},function(t,e,r){var i=r(29);const s=r(4),n=r(3),a=r(6),{SX:o,SXX:c}=r(94);class u extends i{constructor(t){super(),this.db=t||{setX509Abolish:()=>{},delX509Abolish:()=>{},loadX509AbolishList:()=>{}}}async loadHistory(){var t,e;for(t of(this.clear(),await this.db.loadX509AbolishList()))this.set(t.getCertNo(),t),t.wid&&t.account&&(e=t.wid+"."+t.account,this.account.get(e)||this.account.set(e,new Map),this.account.get(e).set(t.getCertNo(),t))}setAccount(t,e,r){var i;t&&t.wid&&t.account&&(i=t.wid+"."+t.account,this.account.get(i)&&this.account.get(i).delete(t.getCertNo())),erItem.wid=e,erItem.account=r,e&&r&&(i=erItem.wid+"."+erItem.account,this.account.get(i)||this.account.set(i,new Map),this.account.get(i).set(t.getCertNo(),erItem))}delAccount(t){var e;t&&t.wid&&t.account&&(e=t.wid+"."+t.account,this.account.get(e)&&this.account.get(e).delete(t.getCertNo()))}getX509(t,e){return t=o(t,e,!1).toString("hex"),this.get(t)}async setX509Abolish(t,e){t=new h(t),await this.db.setX509Abolish(t,e),this.set(t.getCertNo(),t)}async delX509Abolish(t,e){await this.db.delX509Abolish(t),this.delete(t.getCertNo())}}class h{constructor(t){this.fromOptions(t=t||{})}fromOptions(t){this.oper=t.oper||"x509Abolish",this.witness=t.witness||"",this.certSq=t.certSq,this.activeTime=t.activeTime,this.signature=t.signature||"",this.wid=t.wid||0,this.account=t.account||""}toRaw(){return Buffer.from(JSON.stringify(this.toOptions(!0)),"utf-8")}toOptions(t=!1){let e={};return e.oper=this.oper||"x509Issue",e.witness=this.witness||"",e.certSq=this.certSq,e.activeTime=this.activeTime,t&&(e.signature=this.signature||"",e.wid=this.wid||0,e.account=this.account||""),e}get certNo(){return o(this.witness,this.certSq,!1)}getCertNo(){return o(this.witness,this.certSq,!1).toString("hex")}static getKey(t,e){return o(t,e,!1).toString("hex")}static keyInfo(t){"string"==typeof t&&(t=Buffer.from(t,"hex"));var[t,e,r]=c(t);return r?null:{witness:t,certSq:e}}getSignObjSize(t){var e=0;return(e+=n.sizeVarString(t.oper,"utf8"))+n.sizeVarString(t.witness,"utf8")+4+8}toWriter(t,e){return e.writeVarString(t.oper,"utf8"),e.writeVarString(t.witness,"utf8"),e.writeU32(t.certSq),e.writeU64(t.activeTime),e}toHash(){var t=this.toOptions();return a.hash256(this.toWriter(t,new s(this.getSignObjSize(t))).render())}fromRaw(t){return t=JSON.parse(t.toString("utf8")),this.fromOptions(t),this}static fromRaw(t){return(new h).fromRaw(t)}sign(t){this.signature=t.sign(this.toHash()).toString("hex")}verifying(t){return t.verify(this.toHash(),Buffer.from(this.signature,"hex"))}}u.X509Abolish=h,t.exports=u},function(t,e,r){"use strict";
389
+ */const i=r(29),s=r(238).derive,n=r(316),a=r(121);r(60),r(22);var{}=r(5);const o=e;o.execute=function(t){try{return o.handle(t)}catch(t){return new a.ErrorResultPacket(t)}},o.handle=function(t){return t.jobsHandle(o)},o.check=function(t,e,r,i){try{t.check(e,r,i)}catch(t){if("ScriptError"===t.type)return new a.CheckResultPacket(t);throw t}return new a.CheckResultPacket},o.checkInput=function(t,e,r,i,s){try{t.checkInput(e,r,i,s)}catch(t){if("ScriptError"===t.type)return new a.CheckInputResultPacket(t);throw t}return new a.CheckInputResultPacket},o.sign=function(t,e,r,i){return e=t.sign(e,!0,r,i),a.SignResultPacket.fromTX(t,e)},o.signInput=function(t,e,r,i,s){return r=t.signInput(t,e,r,i,s),a.SignInputResultPacket.fromTX(t,e,r)},o.ecVerify=function(t,e,r){return t=i.verify(t,e,r),new a.ECVerifyResultPacket(t)},o.ecSign=function(t,e){return t=i.sign(t,e),new a.ECSignResultPacket(t)},o.mine=function(t,e,r,i){return t=n(t,e,r,i),new a.MineResultPacket(t)},o.scrypt=function(t,e,r,i,n,o){return t=s(t,e,r,i,n,o),new a.ScryptResultPacket(t)}},function(t,e,r){var i=r(28);const s=r(4),n=r(3),a=r(6),o=r(65);class c extends i{constructor(t){super(),this.db=t||{getEr:()=>{},setEr:()=>{},delEr:()=>{}},this.cache=new o(1e4)}async loadHistory(){}async getEr(t){return this.cache.get(t)||this.db.getEr(t)}async setEr(t,e){t=new u(t),await this.db.setEr(t,e),this.cache.set(t.erid,t)}async delEr(t,e){await this.db.delEr(t),this.cache.remove(t.erid)}async query(t){let e=!1,r=null,i=[];for(var s of t)if(s&&Array.isArray(s)){if("erid"==s[0])return{list:[await this.getEr(s[1])],page:0,count:1};"merge"==s[0]?e=s[1]:"pubkey"==s[0]?r=s[1]:i.push(s)}return r?this.db.byPubkey(r,i,e):{list:[],page:0,count:1}}}class u{constructor(t){this.fromOptions(t=t||{})}fromOptions(t){this.oper=t.oper||"erIssue",this.erid=t.erid,this.witness=t.witness||"",this.validHeight=t.validHeight,this.startHeight=t.startHeight||0,this.signature=t.signature||"",this.source=null,t.source&&(this.source={},this.source.subjectName=t.source.subjectName,this.source.pubkey=t.source.pubkey,this.source.subjectHash=t.source.subjectHash,this.source.cluster=t.source.cluster,this.source.cid=t.source.cid,this.source.uid=t.source.uid),this.wid=t.wid||0,this.account=t.account||""}toRaw(){return Buffer.from(JSON.stringify(this.toOptions(!0)),"utf-8")}toOptions(t=!1){let e={};return e.oper=this.oper||"erIssue",e.erid=this.erid,e.witness=this.witness||"",e.validHeight=this.validHeight,t&&(e.startHeight=this.startHeight,e.signature=this.signature||""),this.source&&(e.source={},e.source.subjectName=this.source.subjectName,e.source.pubkey=this.source.pubkey,e.source.subjectHash=this.source.subjectHash,e.source.cluster=this.source.cluster||"",e.source.cid=this.source.cid||"",e.source.uid=this.source.uid||0),e}getSignObjSize(t){let e=0;return e=(e=(e=(e+=n.sizeVarString(t.oper,"utf8"))+n.sizeVarString(t.erid,"utf8"))+n.sizeVarString(t.witness,"ascii"))+4+4,t.source?(e=(e=(e=(e+=n.sizeVarString(t.source.subjectName,"utf8"))+n.sizeVarString(t.source.pubkey,"utf8"))+n.sizeVarString(t.source.subjectHash,"utf8"))+n.sizeVarString(t.source.cluster,"utf8"))+n.sizeVarString(t.source.cid,"utf8")+4:e}toWriter(t,e){return e.writeVarString(t.oper,"utf8"),e.writeVarString(t.erid,"utf8"),e.writeVarString(t.witness,"ascii"),e.writeU32(t.validHeight),e.writeU32(t.startHeight),t.source&&(e.writeVarString(t.source.subjectName,"utf8"),e.writeVarString(t.source.pubkey,"utf8"),e.writeVarString(t.source.subjectHash,"utf8"),e.writeVarString(t.source.cluster,"utf8"),e.writeVarString(t.source.cid,"utf8"),e.writeU32(t.source.uid)),e}toHash(){var t=this.toOptions();return a.hash256(this.toWriter(t,new s(this.getSignObjSize(t))).render())}fromRaw(t){return t=JSON.parse(t.toString("utf8")),this.fromOptions(t),this}static fromRaw(t){return(new u).fromRaw(t)}sign(t){this.signature=t.sign(this.toHash()).toString("hex")}verifying(t){return t.verify(this.toHash(),Buffer.from(this.signature,"hex"))}}c.ErItem=u,t.exports=c},function(t,e,r){var i=r(28);const s=r(4),n=r(3),a=r(6);class o extends i{constructor(t){super(),this.db=t||{getErAbolish:()=>{},setErAbolish:()=>{},delErAbolish:()=>{},loadErAbolishList:()=>{}}}async loadHistory(){}async getErAb(t){return this.db.getErAbolish(t)}async setErAb(t,e){t=new c(t),await this.db.setErAbolish(t),this.set(t.erid,t)}async delErAb(t,e){await this.db.delErAbolish(t),this.delete(t.erid)}async query(t){let e=!1;for(var r of t)"cluster"==r[0]&&(e=r[1]);for(var i of t){if("erid"==i[0])return{list:[await this.getErAb(i[1])],page:0,count:1};if("pubkey"==i[0])return this.db.byPubkey(i[1],e)}return{list:[],page:0,count:1}}}class c{constructor(t){this.fromOptions(t=t||{})}fromOptions(t){this.oper=t.oper||"erAbolish",this.erid=t.erid,this.witness=t.witness||"",this.abolishHeight=t.abolishHeight,this.startHeight=t.startHeight||0,this.signature=t.signature||""}toOptions(t){let e={};return e.oper=this.oper||"erAbolish",e.erid=this.erid,e.witness=this.witness||"",e.abolishHeight=this.abolishHeight,t&&(e.startHeight=this.startHeight,e.signature=this.signature||""),e}getMsgSize(){var t=0;return(t+=n.sizeVarString(this.oper,"utf8"))+n.sizeVarString(this.erid,"utf8")+n.sizeVarString(this.witness,"ascii")+4+4}toWriter(t,e){return e.writeVarString(this.oper,"utf8"),e.writeVarString(this.erid,"utf8"),e.writeVarString(this.witness,"ascii"),e.writeU32(this.abolishHeight),e.writeU32(this.startHeight),e}toHash(){var t=this.toOptions();return a.hash256(this.toWriter(t,new s(this.getMsgSize(t))).render())}toRaw(){return Buffer.from(JSON.stringify(this.toOptions(!0)),"utf-8")}fromReader(t){return t=JSON.parse(t.toString("utf8")),this.fromOptions(t),this}fromRaw(t){return this.fromReader(t)}static fromRaw(t){return(new c).fromRaw(t)}sign(t){this.signature=t.sign(this.toHash()).toString("hex")}verifying(t){return t.verify(this.toHash(),Buffer.from(this.signature,"hex"))}}o.ErAbolishItem=c,t.exports=o},function(t,e,r){var i=r(28);const s=r(4),n=r(3),a=r(6),{SX:o,SXX:c}=r(94);class u extends i{constructor(t){super(),this.db=t||{setX509Cert:()=>{},delX509Cert:()=>{},loadX509CertList:()=>{}}}async loadHistory(){var t,e;for(t of(this.clear(),await this.db.loadX509CertList()))this.set(t.getCertNo(),t),t.wid&&t.account&&(e=t.wid+"."+t.account,this.account.get(e)||this.account.set(e,new Map),this.account.get(e).set(t.getCertNo(),t))}setAccount(t,e,r){var i;t&&t.wid&&t.account&&(i=t.wid+"."+t.account,this.account.get(i)&&this.account.get(i).delete(t.getCertNo())),erItem.wid=e,erItem.account=r,e&&r&&(i=erItem.wid+"."+erItem.account,this.account.get(i)||this.account.set(i,new Map),this.account.get(i).set(t.getCertNo(),erItem))}delAccount(t){var e;t&&t.wid&&t.account&&(e=t.wid+"."+t.account,this.account.get(e)&&this.account.get(e).delete(t.getCertNo()))}getX509(t,e){return t=o(t,e,!0).toString("hex"),this.get(t)}async setX509Cert(t,e){t=new h(t),await this.db.setX509Cert(t,e),this.set(t.getCertNo(),t)}async delX509Cert(t,e){await this.db.delX509Cert(t),this.delete(t.getCertNo())}}class h{constructor(t){this.fromOptions(t=t||{})}fromOptions(t){this.oper=t.oper||"x509Issue",this.witness=t.witness||"",this.certSq=t.certSq,this.activeTime=t.activeTime,this.cert=t.cert||"",this.signature=t.signature||"",this.wid=t.wid||0,this.account=t.account||""}toRaw(){return Buffer.from(JSON.stringify(this.toOptions(!0)),"utf-8")}toOptions(t=!1){let e={};return e.oper=this.oper||"x509Issue",e.witness=this.witness||"",e.certSq=this.certSq,e.activeTime=this.activeTime,e.cert=this.cert,t&&(e.signature=this.signature||"",e.wid=this.wid||0,e.account=this.account||""),e}get certNo(){return o(this.witness,this.certSq,!0)}getCertNo(){return o(this.witness,this.certSq,!0).toString("hex")}static getKey(t,e){return o(t,e,!0).toString("hex")}static keyInfo(t){"string"==typeof t&&(t=Buffer.from(t,"hex"));var[t,e,r]=c(t);return r?{witness:t,certSq:e}:null}getSignObjSize(t){var e=0;return(e+=n.sizeVarString(t.oper,"utf8"))+n.sizeVarString(t.witness,"utf8")+4+8+n.sizeVarString(t.cert,"utf8")}toWriter(t,e){return e.writeVarString(t.oper,"utf8"),e.writeVarString(t.witness,"utf8"),e.writeU32(t.certSq),e.writeU64(t.activeTime),e.writeVarString(t.cert,"utf8"),e}toHash(){var t=this.toOptions();return a.hash256(this.toWriter(t,new s(this.getSignObjSize(t))).render())}fromRaw(t){return t=JSON.parse(t.toString("utf8")),this.fromOptions(t),this}static fromRaw(t){return(new h).fromRaw(t)}sign(t){this.signature=t.sign(this.toHash()).toString("hex")}verifying(t){return t.verify(this.toHash(),Buffer.from(this.signature,"hex"))}}u.X509Cert=h,t.exports=u},function(t,e,r){var i=r(28);const s=r(4),n=r(3),a=r(6),{SX:o,SXX:c}=r(94);class u extends i{constructor(t){super(),this.db=t||{setX509Abolish:()=>{},delX509Abolish:()=>{},loadX509AbolishList:()=>{}}}async loadHistory(){var t,e;for(t of(this.clear(),await this.db.loadX509AbolishList()))this.set(t.getCertNo(),t),t.wid&&t.account&&(e=t.wid+"."+t.account,this.account.get(e)||this.account.set(e,new Map),this.account.get(e).set(t.getCertNo(),t))}setAccount(t,e,r){var i;t&&t.wid&&t.account&&(i=t.wid+"."+t.account,this.account.get(i)&&this.account.get(i).delete(t.getCertNo())),erItem.wid=e,erItem.account=r,e&&r&&(i=erItem.wid+"."+erItem.account,this.account.get(i)||this.account.set(i,new Map),this.account.get(i).set(t.getCertNo(),erItem))}delAccount(t){var e;t&&t.wid&&t.account&&(e=t.wid+"."+t.account,this.account.get(e)&&this.account.get(e).delete(t.getCertNo()))}getX509(t,e){return t=o(t,e,!1).toString("hex"),this.get(t)}async setX509Abolish(t,e){t=new h(t),await this.db.setX509Abolish(t,e),this.set(t.getCertNo(),t)}async delX509Abolish(t,e){await this.db.delX509Abolish(t),this.delete(t.getCertNo())}}class h{constructor(t){this.fromOptions(t=t||{})}fromOptions(t){this.oper=t.oper||"x509Abolish",this.witness=t.witness||"",this.certSq=t.certSq,this.activeTime=t.activeTime,this.signature=t.signature||"",this.wid=t.wid||0,this.account=t.account||""}toRaw(){return Buffer.from(JSON.stringify(this.toOptions(!0)),"utf-8")}toOptions(t=!1){let e={};return e.oper=this.oper||"x509Issue",e.witness=this.witness||"",e.certSq=this.certSq,e.activeTime=this.activeTime,t&&(e.signature=this.signature||"",e.wid=this.wid||0,e.account=this.account||""),e}get certNo(){return o(this.witness,this.certSq,!1)}getCertNo(){return o(this.witness,this.certSq,!1).toString("hex")}static getKey(t,e){return o(t,e,!1).toString("hex")}static keyInfo(t){"string"==typeof t&&(t=Buffer.from(t,"hex"));var[t,e,r]=c(t);return r?null:{witness:t,certSq:e}}getSignObjSize(t){var e=0;return(e+=n.sizeVarString(t.oper,"utf8"))+n.sizeVarString(t.witness,"utf8")+4+8}toWriter(t,e){return e.writeVarString(t.oper,"utf8"),e.writeVarString(t.witness,"utf8"),e.writeU32(t.certSq),e.writeU64(t.activeTime),e}toHash(){var t=this.toOptions();return a.hash256(this.toWriter(t,new s(this.getSignObjSize(t))).render())}fromRaw(t){return t=JSON.parse(t.toString("utf8")),this.fromOptions(t),this}static fromRaw(t){return(new h).fromRaw(t)}sign(t){this.signature=t.sign(this.toHash()).toString("hex")}verifying(t){return t.verify(this.toHash(),Buffer.from(this.signature,"hex"))}}u.X509Abolish=h,t.exports=u},function(t,e,r){"use strict";
390
390
  /*!
391
391
  * account.js - account object for vallnet
392
392
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -426,7 +426,7 @@ function i(t){let e=null;var r=i.list[t.contract.options.type];return r?new(e=r.
426
426
  *
427
427
  * @note 为了让打包程序正常工作,没有使用自动化方案来引入类文件
428
428
  */
429
- const i=r(5).ContractType;t.exports=function(t){if(!t)return r(192);switch(t.oper){case i.cpRegister:return r(195);case i.cpChange:return r(197);case i.coinbase:return r(198);case i.contractPromise:return r(199);case i.scRegister:return r(202);case i.scUpdate:return r(203);case i.scState:return r(204);case i.scRun:return r(205);case i.scNotify:return r(211);case i.propFound:return r(212);case i.vote:return r(213);case i.propSale:return r(214);case i.payOrder:return r(215);case i.notify:return r(216);case i.contractCreate:return r(217);case i.contractExecute:return r(218);case i.stock:return r(219);case i.guideRegister:return r(220);case i.erIssue:return r(221);case i.erAbolish:return r(222);case i.enchanceCp:return r(223);case i.x509Issue:return r(224);case i.x509Abolish:return r(225);default:try{return r(612)("./"+t.oper)}catch(t){return r(11)}}}},function(t,e,r){var i=r(11);const s=r(21).nestingCodes,n=r(119);t.exports=class extends i{async insert(){let t=this.getOpt();for(let r=0;r<t.tx.outputs.length;r++){var e=""+t.hash+r;t.env.middleHashMem.has(e)||this.setOptIndex(t,r)&&(await n(t).insert(),t.env.middleHashMem.add(e))}}async erase(){let t=this.getOpt();for(let e=0;e<t.tx.outputs.length;e++)t.env.middleHashMem.delete(""+t.hash+e),this.setOptIndex(t,e)&&await n(t).erase()}async confirm(){let t=this.getOpt();for(let r=0;r<t.tx.outputs.length;r++){var e=""+t.hash+r;t.env.middleHashChain.has(e)||this.setOptIndex(t,r)&&(await n(t).confirm(),t.env.middleHashChain.add(e))}}async unconfirm(){let t=this.getOpt();for(let e=0;e<t.tx.outputs.length;e++)t.env.middleHashChain.delete(""+t.hash+e),this.setOptIndex(t,e)&&await n(t).unconfirm()}async verify(){var t=this.getOpt();for(let e=0;e<t.tx.outputs.length;e++)if(this.setOptIndex(t,e)&&!await n(t).verify())return!1;return!0}getOpt(){return{env:this.options.env,tx:this.options.tx,block:this.options.block,height:this.options.coinbaseHeight,hash:this.options.hash}}setOptIndex(t,e){return t.i=e,t.output=t.tx.outputs[e],t.type=t.output.getReturnType(),t.data=t.output.getReturnData(s),!!t.data}}},function(t,e,r){const i=r(5).PropStatus;var s=r(58);const n=r(7),a=r(150);t.exports=class extends s{async confirm(){let{env:t,i:e,output:r,data:s,hash:n,tx:a}=this.options;var o=await t.propList.getVp(s.pid);o&&(o.current.hash!=n||o.current.index!=e)||(s.current={hash:n,index:e,address:r.getAddress().toString()},s.height=0<t.curHeight?t.curHeight+1:0,s.pst=i.Ready,s.gold=r.value,await t.propList.setVp(s,a))}async unconfirm(){let{env:t,i:e,data:r,hash:i}=this.options;var s=await t.propList.getVp(r.pid);s&&s.current.hash==i&&s.current.index==e&&await t.propList.delVp(s)}async verify(){let{env:t,i:e,output:r,data:i,hash:s}=this.options;if(!a.unittest){var o=t.cpList.getItem(i.cid);if(!o||o.current.address!=r.getAddress().toString())return!1}return!(r.value<n.MINPROPVALUE||t.network.stockReg.test(i.pid)||t.network.tokenReg.test(i.pid)||(o=await t.propList.getVp(i.pid))&&(o.current.hash!=s||o.current.index!=e))}}},function(t,e,r){const i=r(0),s=r(21).opcodes,n=r(37).broadcast;r(134).vpItem;var a=r(58);const{ContractEnvType:o,PropStatus:c}=r(5);t.exports=class extends a{async confirm(){let{env:t,i:e,output:r,data:i,hash:a,tx:u,block:h}=this.options,l=await t.propList.getVp(i.pid);if(l&&l.current.hash==i.prev.hash&&l.current.index==i.prev.index){var p,d=l.current.address,f=r.getAddress().toString();if(t.setGuider(d,i.cid,f),l.current={hash:a,index:e,address:f},l.height=t.curHeight,l.pst=c.Ready,await t.propList.setVp(l,u),t.network.stockReg.test(l.pid)){let e=t.cpList.getItem(l.cid);e&&(e.status=1,await t.cpList.addItem(e))}t.mode==o.Wallet&&(p={pid:l.pid,address:l.current.address,wid:l.wid,account:l.account,time:h.time,height:l.height,cid:l.cid},t.emit("prop/receive",p),n("prop/receive",p)),t.mode==o.Block&&l.cid==t.network.genesisId&&(t.propList.getVpByAddress(d).count<=0&&t.voteMgr.delTokenAddress(d),t.voteMgr.addTokenAddress(f));let g=0,y=i;for(;r&&r.getReturnType(s.OP_PROPEXCHANGE)&&g++<2e3;){let e=y.prev;t.middleHashChain.add(e.hash+e.index.toString());var m=await t.finder(e.hash);if(!m)break;if(r=m.outputs[e.index],!(y=r.getReturnData())||!y.prev||t.middleHashChain.has(y.prev.hash+y.prev.index.toString()))break}}}async unconfirm(){let{env:t,data:e}=this.options;var r,i,n=await t.finder(e.prev.hash);if(n&&n.outputs[e.prev.index]){let a=n.outputs[e.prev.index];a.getReturnData([s.OP_PROPEXCHANGE,s.OP_PROPCREATE])&&(r=a.getAddress().toString(),i=ori.current.address,t.unsetGuider(r,e.cid,i),ori.current.hash=e.prev.hash,ori.current.index=e.prev.index,ori.current.address=r,await t.propList.setVp(ori,n),t.mode==o.Block&&ori.cid==t.network.genesisId&&(t.propList.getVpByAddress(i).count<=0&&t.voteMgr.delTokenAddress(i),t.voteMgr.addTokenAddress(r)))}}async verify(){let{env:t,tx:e,i:r,data:s}=this.options;i.strictEqual(s.prev.hash,e.inputs[r].prevout.hash),i.strictEqual(s.prev.index,e.inputs[r].prevout.index);var n=await t.propList.getVp(s.pid);return!!n&&(n.current.hash!=s.prev.hash&&t.logger.warning("not equals:",s.pid,n.current.hash,s.prev.hash),i(n.current.hash==s.prev.hash),i(n.current.index==s.prev.index),!0)}}},function(t,e,r){var i=r(11);const s=r(5).ContractEnvType,n=r(38).VerifyError,a=r(21).opcodes,o=r(196);t.exports=class extends i{async insert(){let t=this.options.env,e=this.options.tx;var r=e.hash("hex");let i=this.data;i.current={hash:r,index:0,address:e.outputs[0].getAddress().toString()},i.height=-1,await t.cpMemList.addItem(i)}async erase(){let t=this.options.env;var e=this.data;await t.cpMemList.delItem(e)}async confirm(){let t=this.options.env,e=this.options.tx;var r=e.hash("hex");let i=this.data;i.current={hash:r,index:0,address:e.outputs[0].getAddress().toString()},i.height=this.options.coinbaseHeight,i.status=1,await t.cpList.addItem(i);for(let i=1;i<=Math.min(10,e.outputs.length-1);i++){let s=e.outputs[i].getReturnData(a.OP_PROPCREATE);if(s){t.network.stockReg.test(s.pid)&&(s.current={hash:r,index:i,address:e.outputs[i].getAddress().toString()},s.gold=e.outputs[i].value,s.height=this.options.coinbaseHeight,await t.propList.setVp(s,e))}}}async unconfirm(){let t=this.options.env;var e=this.data;let r=this.options.tx;await t.cpList.delItem(e);for(let e=1;e<=Math.min(10,r.outputs.length-1);e++){var i=r.outputs[e].getReturnData(a.OP_PROPCREATE);if(i){t.network.stockReg.test(i.pid)&&await t.propList.delVp(i)}}}async verify(){let t=this.options.env;var e=this.options.tx;if(!this.data)throw new n(e,"invalid","null cpRegister data",100);var r=o.verifyDataFormat(this.data);if(r)throw new n(e,"invalid",r,100);if(r=this.mode!=s.Mempool,await t.rpcExecute({method:"canExecute",params:[{confirm:r,cid:this.data.cid,name:this.data.name,oper:this.data.oper}]}))return!0;throw new n(e,"invalid info on "+this.data.oper,"cp.create",0)}}},function(t,e,r){"use strict";
429
+ const i=r(5).ContractType;t.exports=function(t){if(!t)return r(192);switch(t.oper){case i.cpRegister:return r(195);case i.cpChange:return r(197);case i.coinbase:return r(198);case i.contractPromise:return r(199);case i.scRegister:return r(202);case i.scUpdate:return r(203);case i.scState:return r(204);case i.scRun:return r(205);case i.scNotify:return r(211);case i.propFound:return r(212);case i.vote:return r(213);case i.propSale:return r(214);case i.payOrder:return r(215);case i.notify:return r(216);case i.contractCreate:return r(217);case i.contractExecute:return r(218);case i.stock:return r(219);case i.guideRegister:return r(220);case i.erIssue:return r(221);case i.erAbolish:return r(222);case i.enchanceCp:return r(223);case i.x509Issue:return r(224);case i.x509Abolish:return r(225);default:try{return r(612)("./"+t.oper)}catch(t){return r(11)}}}},function(t,e,r){var i=r(11);const s=r(21).nestingCodes,n=r(119);t.exports=class extends i{async insert(){let t=this.getOpt();for(let r=0;r<t.tx.outputs.length;r++){var e=""+t.hash+r;t.env.middleHashMem.has(e)||this.setOptIndex(t,r)&&(await n(t).insert(),t.env.middleHashMem.add(e))}}async erase(){let t=this.getOpt();for(let e=0;e<t.tx.outputs.length;e++)t.env.middleHashMem.delete(""+t.hash+e),this.setOptIndex(t,e)&&await n(t).erase()}async confirm(){let t=this.getOpt();for(let r=0;r<t.tx.outputs.length;r++){var e=""+t.hash+r;t.env.middleHashChain.has(e)||this.setOptIndex(t,r)&&(await n(t).confirm(),t.env.middleHashChain.add(e))}}async unconfirm(){let t=this.getOpt();for(let e=0;e<t.tx.outputs.length;e++)t.env.middleHashChain.delete(""+t.hash+e),this.setOptIndex(t,e)&&await n(t).unconfirm()}async verify(){var t=this.getOpt();for(let e=0;e<t.tx.outputs.length;e++)if(this.setOptIndex(t,e)&&!await n(t).verify())return!1;return!0}getOpt(){return{env:this.options.env,tx:this.options.tx,block:this.options.block,height:this.options.coinbaseHeight,hash:this.options.hash}}setOptIndex(t,e){return t.i=e,t.output=t.tx.outputs[e],t.type=t.output.getReturnType(),t.data=t.output.getReturnData(s),!!t.data}}},function(t,e,r){const i=r(5).PropStatus;var s=r(58);const n=r(7),a=r(150);t.exports=class extends s{async confirm(){let{env:t,i:e,output:r,data:s,hash:n,tx:a}=this.options;var o=await t.propList.getVp(s.pid);o&&(o.current.hash!=n||o.current.index!=e)||(s.current={hash:n,index:e,address:r.getAddress().toString()},s.height=0<t.curHeight?t.curHeight+1:0,s.pst=i.Ready,s.gold=r.value,await t.propList.setVp(s,a))}async unconfirm(){let{env:t,i:e,data:r,hash:i}=this.options;var s=await t.propList.getVp(r.pid);s&&s.current.hash==i&&s.current.index==e&&await t.propList.delVp(s)}async verify(){let{env:t,i:e,output:r,data:i,hash:s}=this.options;if(!a.unittest){var o=t.cpList.getItem(i.cid);if(!o||o.current.address!=r.getAddress().toString())return!1}return!(r.value<n.MINPROPVALUE||t.network.stockReg.test(i.pid)||t.network.tokenReg.test(i.pid)||(o=await t.propList.getVp(i.pid))&&(o.current.hash!=s||o.current.index!=e))}}},function(t,e,r){const i=r(0),s=r(21).opcodes,n=r(37).broadcast;r(134).vpItem;var a=r(58);const{ContractEnvType:o,PropStatus:c}=r(5);t.exports=class extends a{async confirm(){let{env:t,i:e,output:r,data:i,hash:a,tx:u,block:h}=this.options,l=await t.propList.getVp(i.pid);if(l&&l.current.hash==i.prev.hash&&l.current.index==i.prev.index){var p,d=l.current.address,f=r.getAddress().toString();if(t.setGuider(d,i.cid,f),l.current={hash:a,index:e,address:f},l.height=t.curHeight,l.pst=c.Ready,await t.propList.setVp(l,u),t.network.stockReg.test(l.pid)){let e=t.cpList.getItem(l.cid);e&&(e.status=1,await t.cpList.addItem(e))}t.mode==o.Wallet&&(p={pid:l.pid,address:l.current.address,wid:l.wid,account:l.account,time:h.time,height:l.height,cid:l.cid},t.emit("prop/receive",p),n("prop/receive",p)),t.mode==o.Block&&l.cid==t.network.genesisId&&(t.propList.getVpByAddress(d).count<=0&&t.voteMgr.delTokenAddress(d),t.voteMgr.addTokenAddress(f));let g=0,y=i;for(;r&&r.getReturnType(s.OP_PROPEXCHANGE)&&g++<2e3;){let e=y.prev;t.middleHashChain.add(e.hash+e.index.toString());var m=await t.finder(e.hash);if(!m)break;if(r=m.outputs[e.index],!(y=r.getReturnData())||!y.prev||t.middleHashChain.has(y.prev.hash+y.prev.index.toString()))break}}}async unconfirm(){let{env:t,data:e}=this.options;var r,i,n=await t.finder(e.prev.hash);if(n&&n.outputs[e.prev.index]){let a=n.outputs[e.prev.index];if(a.getReturnData([s.OP_PROPEXCHANGE,s.OP_PROPCREATE])){let s=await t.propList.getVp(e.pid);s&&(r=a.getAddress().toString(),i=s.current.address,t.unsetGuider(r,e.cid,i),s.current.hash=e.prev.hash,s.current.index=e.prev.index,s.current.address=r,await t.propList.setVp(s,n),t.mode==o.Block&&s.cid==t.network.genesisId&&(t.propList.getVpByAddress(i).count<=0&&t.voteMgr.delTokenAddress(i),t.voteMgr.addTokenAddress(r)))}}}async verify(){let{env:t,tx:e,i:r,data:s}=this.options;i.strictEqual(s.prev.hash,e.inputs[r].prevout.hash),i.strictEqual(s.prev.index,e.inputs[r].prevout.index);var n=await t.propList.getVp(s.pid);return!!n&&(n.current.hash!=s.prev.hash&&t.logger.warning("not equals:",s.pid,n.current.hash,s.prev.hash),i(n.current.hash==s.prev.hash),i(n.current.index==s.prev.index),!0)}}},function(t,e,r){var i=r(11);const s=r(5).ContractEnvType,n=r(38).VerifyError,a=r(21).opcodes,o=r(196);t.exports=class extends i{async insert(){let t=this.options.env,e=this.options.tx;var r=e.hash("hex");let i=this.data;i.current={hash:r,index:0,address:e.outputs[0].getAddress().toString()},i.height=-1,await t.cpMemList.addItem(i)}async erase(){let t=this.options.env;var e=this.data;await t.cpMemList.delItem(e)}async confirm(){let t=this.options.env,e=this.options.tx;var r=e.hash("hex");let i=this.data;i.current={hash:r,index:0,address:e.outputs[0].getAddress().toString()},i.height=this.options.coinbaseHeight,i.status=1,await t.cpList.addItem(i),this.mode==s.Block&&await t.chain.node.mempool.cpMemList.delItem(i);for(let i=1;i<=Math.min(10,e.outputs.length-1);i++){let s=e.outputs[i].getReturnData(a.OP_PROPCREATE);if(s){t.network.stockReg.test(s.pid)&&(s.current={hash:r,index:i,address:e.outputs[i].getAddress().toString()},s.gold=e.outputs[i].value,s.height=this.options.coinbaseHeight,await t.propList.setVp(s,e))}}}async unconfirm(){let t=this.options.env;var e=this.data;let r=this.options.tx;await t.cpList.delItem(e);for(let e=1;e<=Math.min(10,r.outputs.length-1);e++){var i=r.outputs[e].getReturnData(a.OP_PROPCREATE);if(i){t.network.stockReg.test(i.pid)&&await t.propList.delVp(i)}}}async verify(){let t=this.options.env;var e=this.options.tx;if(!this.data)throw new n(e,"invalid","null cpRegister data",100);var r=o.verifyDataFormat(this.data);if(r)throw new n(e,"invalid",r,100);if(r=this.mode!=s.Mempool,await t.rpcExecute({method:"canExecute",params:[{confirm:r,cid:this.data.cid,name:this.data.name,oper:this.data.oper}]}))return!0;throw new n(e,"invalid info on "+this.data.oper,"cp.create",0)}}},function(t,e,r){"use strict";
430
430
  /*!
431
431
  * cpHelper.js
432
432
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -468,7 +468,7 @@ const i=r(5).ContractType;t.exports=function(t){if(!t)return r(192);switch(t.ope
468
468
  /*!
469
469
  * rollingfilter.js - rolling bloom filter for vallnet
470
470
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
471
- */const i=r(0),s=r(147),n=s.sum32,a=s.mul32,o=Buffer.alloc(0);function c(t,e){this.hi=t,this.lo=e}function u(t,e){return new c(t.readUInt32LE(e+4,!0),t.readUInt32LE(e,!0))}function h(t,e,r){t.writeUInt32LE(e.hi,r+4,!0),t.writeUInt32LE(e.lo,r,!0)}t.exports=class t{constructor(t,e){this.entries=0,this.generation=1,this.n=0,this.limit=0,this.size=0,this.items=0,this.tweak=0,this.filter=o,null!=t&&this.fromRate(t,e)}fromRate(t,e){i("number"==typeof t,"`items` must be a number."),i(0<t,"`items` must be greater than zero."),i(Number.isSafeInteger(t),"`items` must be an integer."),i("number"==typeof e,"`rate` must be a number."),i(0<=e&&e<=1,"`rate` must be between 0.0 and 1.0.");e=Math.log(e);var r=Math.max(1,Math.min(Math.round(e/Math.log(.5)),50)),s=(t+1)/2|0,n=(e=-1*r*(3*s)/Math.log(1-Math.exp(e/r)),t=(((e=Math.ceil(e))+63)/64|0)<<1,t>>>=0,t=Math.max(1,t),4294967296*Math.random()>>>0);const a=Buffer.allocUnsafe(8*t);return a.fill(0),this.n=r,this.limit=s,this.size=e,this.items=t,this.tweak=n,this.filter=a,this}static fromRate(e,r){return(new t).fromRate(e,r)}hash(t,e){return s(t,n(a(e,4221880213),this.tweak))}reset(){0!==this.entries&&(this.entries=0,this.generation=1,this.filter.fill(0))}add(t,e){if("string"==typeof t&&(t=Buffer.from(t,e)),this.entries===this.limit){this.entries=0,this.generation+=1,4===this.generation&&(this.generation=1);var r=4294967295*(1&this.generation),i=4294967295*(this.generation>>>1);for(let t=0;t<this.items;t+=2){var s=8*t,n=8*(t+1);const e=u(this.filter,s),c=u(this.filter,n);var a=e.hi^r|c.hi^i,o=e.lo^r|c.lo^i;e.hi&=a,e.lo&=o,c.hi&=a,c.lo&=o,e.hi=e.hi>>>0,e.lo=e.lo>>>0,c.hi=c.hi>>>0,c.lo=c.lo>>>0,h(this.filter,e,s),h(this.filter,c,n)}}this.entries+=1;for(let e=0;e<this.n;e++){var c=63&(p=this.hash(t,e)),l=8*(-2&(p=(p>>>6)%this.items)),p=8*(1|p),d=c%8;c=(c-d)/8;this.filter[l+c]&=~(1<<d),this.filter[l+c]|=(1&this.generation)<<d,this.filter[p+c]&=~(1<<d),this.filter[p+c]|=this.generation>>>1<<d}}test(t,e){if(0===this.entries)return!1;"string"==typeof t&&(t=Buffer.from(t,e));for(let e=0;e<this.n;e++){var r=63&(i=this.hash(t,e)),i=(i>>>6)%this.items,s=r%8;r=(r-s)/8;if(0==(this.filter[8*(-2&i)+r]>>>s&1|this.filter[8*(1|i)+r]>>>s&1))return!1}return!0}added(t,e){return"string"==typeof t&&(t=Buffer.from(t,e)),!this.test(t)&&(this.add(t),!0)}}},function(t,e,r){var i=r(29);const s=r(4),n=r(2),a=r(3);r(20);const{SN:o,SNN:c}=r(94),u=r(12);class h extends i{constructor(t){super(),this.env=t||{getStockAccountList:()=>{}}}async loadHistory(){var t;for(t of(this.clear(),await this.env.getStockAccountList()))this.setStockAccount(t)}getStockAccount(t,e){return this.get(l.getItemNo(t,e))}getOrCreateStockAccount(t,e){let r=this.get(l.getItemNo(t,e));return r||(r=new l(t,e,0,0,0),this.setStockAccount(r)),r}setStockAccount(t){"walletdb"===this.env.eid&&(async()=>{try{var e;for(e of await this.env.getWallets()){let s=await this.env.get(e);if(s){var r=await s.getAccountByAddress(t.addr);if(r){t.wid=r.wid,t.account=r.name;var i=t.wid+"."+t.account;this.account.get(i)||this.account.set(i,new Map),this.account.get(i).set(t.getItemNo(),t);break}}}}catch(t){console.error(t)}})(),this.set(t.getItemNo(),t)}}class l{constructor(t,e,r,i,s){this.cid=t||"",this.addr=e||"",this.sum=r||0,this.price=i||0,this.seq=s||0,this.stock={sum:0,price:0,period:0}}getSize(){var t=0;return(t+=a.sizeVarString(this.cid,"utf8"))+a.sizeVarString(this.addr,"utf8")+4+4+4+4+4+4}get itemNo(){return o(this.cid,u.fromString(this.addr).getHash())}getItemNo(){return o(this.cid,u.fromString(this.addr).getHash()).toString("hex")}static keyInfo(t){"string"==typeof t&&(t=Buffer.from(t,"hex"));var[t,e]=c(t);return{cid:t,addr:e}}static getItemNo(t,e){return o(t,u.fromString(e).getHash()).toString("hex")}static SN(t,e){return o(t,e).toString("hex")}toWriter(t){return t.writeVarString(this.cid,"utf8"),t.writeVarString(this.addr,"utf8"),t.writeU32(this.sum),t.writeU32(this.price),t.writeU32(this.seq),t.writeU32(this.stock.sum),t.writeU32(this.stock.price),t.writeU32(this.stock.period),t}toRaw(){var t=this.getSize();return this.toWriter(new s(t)).render()}fromReader(t){return this.cid=t.readVarString("utf8"),this.addr=t.readVarString("utf8"),this.sum=t.readU32(),this.price=t.readU32(),this.seq=t.readU32(),this.stock={},this.stock.sum=t.readU32(),this.stock.price=t.readU32(),this.stock.period=t.readU32(),this}fromRaw(t){return this.fromReader(new n(t))}clone(){return l.fromRaw(this.toRaw())}static fromReader(t){return(new l).fromReader(t)}static fromRaw(t){return(new l).fromRaw(t)}}h.stockAccount=l,t.exports=h},function(t,e,r){"use strict";
471
+ */const i=r(0),s=r(147),n=s.sum32,a=s.mul32,o=Buffer.alloc(0);function c(t,e){this.hi=t,this.lo=e}function u(t,e){return new c(t.readUInt32LE(e+4,!0),t.readUInt32LE(e,!0))}function h(t,e,r){t.writeUInt32LE(e.hi,r+4,!0),t.writeUInt32LE(e.lo,r,!0)}t.exports=class t{constructor(t,e){this.entries=0,this.generation=1,this.n=0,this.limit=0,this.size=0,this.items=0,this.tweak=0,this.filter=o,null!=t&&this.fromRate(t,e)}fromRate(t,e){i("number"==typeof t,"`items` must be a number."),i(0<t,"`items` must be greater than zero."),i(Number.isSafeInteger(t),"`items` must be an integer."),i("number"==typeof e,"`rate` must be a number."),i(0<=e&&e<=1,"`rate` must be between 0.0 and 1.0.");e=Math.log(e);var r=Math.max(1,Math.min(Math.round(e/Math.log(.5)),50)),s=(t+1)/2|0,n=(e=-1*r*(3*s)/Math.log(1-Math.exp(e/r)),t=(((e=Math.ceil(e))+63)/64|0)<<1,t>>>=0,t=Math.max(1,t),4294967296*Math.random()>>>0);const a=Buffer.allocUnsafe(8*t);return a.fill(0),this.n=r,this.limit=s,this.size=e,this.items=t,this.tweak=n,this.filter=a,this}static fromRate(e,r){return(new t).fromRate(e,r)}hash(t,e){return s(t,n(a(e,4221880213),this.tweak))}reset(){0!==this.entries&&(this.entries=0,this.generation=1,this.filter.fill(0))}add(t,e){if("string"==typeof t&&(t=Buffer.from(t,e)),this.entries===this.limit){this.entries=0,this.generation+=1,4===this.generation&&(this.generation=1);var r=4294967295*(1&this.generation),i=4294967295*(this.generation>>>1);for(let t=0;t<this.items;t+=2){var s=8*t,n=8*(t+1);const e=u(this.filter,s),c=u(this.filter,n);var a=e.hi^r|c.hi^i,o=e.lo^r|c.lo^i;e.hi&=a,e.lo&=o,c.hi&=a,c.lo&=o,e.hi=e.hi>>>0,e.lo=e.lo>>>0,c.hi=c.hi>>>0,c.lo=c.lo>>>0,h(this.filter,e,s),h(this.filter,c,n)}}this.entries+=1;for(let e=0;e<this.n;e++){var c=63&(p=this.hash(t,e)),l=8*(-2&(p=(p>>>6)%this.items)),p=8*(1|p),d=c%8;c=(c-d)/8;this.filter[l+c]&=~(1<<d),this.filter[l+c]|=(1&this.generation)<<d,this.filter[p+c]&=~(1<<d),this.filter[p+c]|=this.generation>>>1<<d}}test(t,e){if(0===this.entries)return!1;"string"==typeof t&&(t=Buffer.from(t,e));for(let e=0;e<this.n;e++){var r=63&(i=this.hash(t,e)),i=(i>>>6)%this.items,s=r%8;r=(r-s)/8;if(0==(this.filter[8*(-2&i)+r]>>>s&1|this.filter[8*(1|i)+r]>>>s&1))return!1}return!0}added(t,e){return"string"==typeof t&&(t=Buffer.from(t,e)),!this.test(t)&&(this.add(t),!0)}}},function(t,e,r){var i=r(28);const s=r(4),n=r(2),a=r(3);r(20);const{SN:o,SNN:c}=r(94),u=r(12);class h extends i{constructor(t){super(),this.env=t||{getStockAccountList:()=>{}}}async loadHistory(){var t;for(t of(this.clear(),await this.env.getStockAccountList()))this.setStockAccount(t)}getStockAccount(t,e){return this.get(l.getItemNo(t,e))}getOrCreateStockAccount(t,e){let r=this.get(l.getItemNo(t,e));return r||(r=new l(t,e,0,0,0),this.setStockAccount(r)),r}setStockAccount(t){"walletdb"===this.env.eid&&(async()=>{try{var e;for(e of await this.env.getWallets()){let s=await this.env.get(e);if(s){var r=await s.getAccountByAddress(t.addr);if(r){t.wid=r.wid,t.account=r.name;var i=t.wid+"."+t.account;this.account.get(i)||this.account.set(i,new Map),this.account.get(i).set(t.getItemNo(),t);break}}}}catch(t){console.error(t)}})(),this.set(t.getItemNo(),t)}}class l{constructor(t,e,r,i,s){this.cid=t||"",this.addr=e||"",this.sum=r||0,this.price=i||0,this.seq=s||0,this.stock={sum:0,price:0,period:0}}getSize(){var t=0;return(t+=a.sizeVarString(this.cid,"utf8"))+a.sizeVarString(this.addr,"utf8")+4+4+4+4+4+4}get itemNo(){return o(this.cid,u.fromString(this.addr).getHash())}getItemNo(){return o(this.cid,u.fromString(this.addr).getHash()).toString("hex")}static keyInfo(t){"string"==typeof t&&(t=Buffer.from(t,"hex"));var[t,e]=c(t);return{cid:t,addr:e}}static getItemNo(t,e){return o(t,u.fromString(e).getHash()).toString("hex")}static SN(t,e){return o(t,e).toString("hex")}toWriter(t){return t.writeVarString(this.cid,"utf8"),t.writeVarString(this.addr,"utf8"),t.writeU32(this.sum),t.writeU32(this.price),t.writeU32(this.seq),t.writeU32(this.stock.sum),t.writeU32(this.stock.price),t.writeU32(this.stock.period),t}toRaw(){var t=this.getSize();return this.toWriter(new s(t)).render()}fromReader(t){return this.cid=t.readVarString("utf8"),this.addr=t.readVarString("utf8"),this.sum=t.readU32(),this.price=t.readU32(),this.seq=t.readU32(),this.stock={},this.stock.sum=t.readU32(),this.stock.price=t.readU32(),this.stock.period=t.readU32(),this}fromRaw(t){return this.fromReader(new n(t))}clone(){return l.fromRaw(this.toRaw())}static fromReader(t){return(new l).fromReader(t)}static fromRaw(t){return(new l).fromRaw(t)}}h.stockAccount=l,t.exports=h},function(t,e,r){"use strict";
472
472
  /*!
473
473
  * workerpool.js - worker processes for vallnet
474
474
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -512,7 +512,7 @@ const i=r(5).ContractType;t.exports=function(t){if(!t)return r(192);switch(t.ope
512
512
  /*!
513
513
  * framer.js - workers framer
514
514
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
515
- */const i=r(4);function s(){if(!(this instanceof s))return new s}s.prototype.packet=function(t){var e=10+t.getSize();const r=new i(e),s=(r.writeU32(t.id),r.writeU8(t.cmd),r.seek(4),t.toWriter(r),r.writeU8(10),r.render());return s.writeUInt32LE(s.length-10,5,!0),s},t.exports=s},function(t,e,r){var i=r(29);const s=r(4),n=r(3),a=r(6);class o extends i{constructor(t,e){super(),this.db=t||{setEn:()=>{},delEn:()=>{},loadCpEnList:()=>{}},this.options=e,this.rank={}}async loadHistory(){this.clear();let t=[];for(var e of t="cp"===this.options.type?await this.db.loadCpEnList():t)this.rank[e.to]||(this.rank[e.to]=[]),-1==this.rank[e.to].indexOf(e.from)&&this.rank[e.to].push(e.from)}async setEn(t){t&&t.to&&t.from&&(t=new c(t),"cp"===this.options.type&&await this.db.setCpEn(t),this.rank[t.to]||(this.rank[t.to]=[]),-1==this.rank[t.to].indexOf(t.from)&&this.rank[t.to].push(t.from))}async delEn(t){var e;t&&t.to&&t.from&&("cp"===this.options.type&&await this.db.delCpEn(t),this.rank[t.to]&&-1!=(e=this.rank[t.to].indexOf(t.from))&&this.rank[t.to].splice(e,1))}}class c{constructor(t){this.fromOptions(t=t||{})}fromOptions(t){this.oper=t.oper,this.to=t.to,this.from=t.from,this.enchanceHeight=t.enchanceHeight,this.enchanceTx=t.enchanceTx,this.signature=t.signature}toOptions(t){let e={};return e.oper=this.oper,e.to=this.to,e.from=this.from,e.enchanceHeight=this.enchanceHeight,"string"==typeof this.enchanceTx&&(e.enchanceTx=this.enchanceTx),t&&(e.signature=this.signature),e}getSignObjSize(){let t=0;return t=(t=(t+=n.sizeVarString(this.oper,"utf8"))+n.sizeVarString(this.to,"utf8"))+n.sizeVarString(this.from,"utf8")+4,"string"==typeof this.enchanceTx&&(t+=n.sizeVarString(this.enchanceTx,"utf8")),t}toWriter(t,e){return e.writeVarString(this.oper,"utf8"),e.writeVarString(this.to,"utf8"),e.writeVarString(this.from,"utf8"),e.writeU32(this.enchanceHeight),"string"==typeof this.enchanceTx&&e.writeVarString(this.enchanceTx,"utf8"),e}toHash(){var t=this.toOptions();return a.hash256(this.toWriter(t,new s(this.getSignObjSize(t))).render())}toRaw(){return Buffer.from(JSON.stringify(this.toOptions(!0)),"utf-8")}fromRaw(t){return t=JSON.parse(t.toString("utf8")),this.fromOptions(t),this}static fromRaw(t){return(new c).fromRaw(t)}sign(t){this.signature=t.sign(this.toHash()).toString("hex")}verifying(t){return t.verify(this.toHash(),Buffer.from(this.signature,"hex"))}}o.EnchancementItem=c,t.exports=o},function(t,e,r){"use strict";
515
+ */const i=r(4);function s(){if(!(this instanceof s))return new s}s.prototype.packet=function(t){var e=10+t.getSize();const r=new i(e),s=(r.writeU32(t.id),r.writeU8(t.cmd),r.seek(4),t.toWriter(r),r.writeU8(10),r.render());return s.writeUInt32LE(s.length-10,5,!0),s},t.exports=s},function(t,e,r){var i=r(28);const s=r(4),n=r(3),a=r(6);class o extends i{constructor(t,e){super(),this.db=t||{setEn:()=>{},delEn:()=>{},loadCpEnList:()=>{}},this.options=e,this.rank={}}async loadHistory(){this.clear();let t=[];for(var e of t="cp"===this.options.type?await this.db.loadCpEnList():t)this.rank[e.to]||(this.rank[e.to]=[]),-1==this.rank[e.to].indexOf(e.from)&&this.rank[e.to].push(e.from)}async setEn(t){t&&t.to&&t.from&&(t=new c(t),"cp"===this.options.type&&await this.db.setCpEn(t),this.rank[t.to]||(this.rank[t.to]=[]),-1==this.rank[t.to].indexOf(t.from)&&this.rank[t.to].push(t.from))}async delEn(t){var e;t&&t.to&&t.from&&("cp"===this.options.type&&await this.db.delCpEn(t),this.rank[t.to]&&-1!=(e=this.rank[t.to].indexOf(t.from))&&this.rank[t.to].splice(e,1))}}class c{constructor(t){this.fromOptions(t=t||{})}fromOptions(t){this.oper=t.oper,this.to=t.to,this.from=t.from,this.enchanceHeight=t.enchanceHeight,this.enchanceTx=t.enchanceTx,this.signature=t.signature}toOptions(t){let e={};return e.oper=this.oper,e.to=this.to,e.from=this.from,e.enchanceHeight=this.enchanceHeight,"string"==typeof this.enchanceTx&&(e.enchanceTx=this.enchanceTx),t&&(e.signature=this.signature),e}getSignObjSize(){let t=0;return t=(t=(t+=n.sizeVarString(this.oper,"utf8"))+n.sizeVarString(this.to,"utf8"))+n.sizeVarString(this.from,"utf8")+4,"string"==typeof this.enchanceTx&&(t+=n.sizeVarString(this.enchanceTx,"utf8")),t}toWriter(t,e){return e.writeVarString(this.oper,"utf8"),e.writeVarString(this.to,"utf8"),e.writeVarString(this.from,"utf8"),e.writeU32(this.enchanceHeight),"string"==typeof this.enchanceTx&&e.writeVarString(this.enchanceTx,"utf8"),e}toHash(){var t=this.toOptions();return a.hash256(this.toWriter(t,new s(this.getSignObjSize(t))).render())}toRaw(){return Buffer.from(JSON.stringify(this.toOptions(!0)),"utf-8")}fromRaw(t){return t=JSON.parse(t.toString("utf8")),this.fromOptions(t),this}static fromRaw(t){return(new c).fromRaw(t)}sign(t){this.signature=t.sign(this.toHash()).toString("hex")}verifying(t){return t.verify(this.toHash(),Buffer.from(this.signature,"hex"))}}o.EnchancementItem=c,t.exports=o},function(t,e,r){"use strict";
516
516
  /*!
517
517
  * plugin.js - contract plugin for vallnet
518
518
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -737,7 +737,7 @@ const i=r(5).ContractType;t.exports=function(t){if(!t)return r(192);switch(t.ope
737
737
  * public.js - hd public keys for vallnet
738
738
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
739
739
  * https://github.com/bookmansoft/gamegold
740
- */const i=r(0),s=r(1),n=r(6),a=r(95),o=r(28),c=r(15),u=r(4),h=r(2),l=r(70),p=r(3),d=r(142);class f{constructor(t){this.network=c.primary,this.depth=0,this.parentFingerPrint=0,this.childIndex=0,this.chainCode=p.ZERO_HASH,this.publicKey=p.ZERO_KEY,this.fingerPrint=-1,this._xpubkey=null,t&&this.fromOptions(t)}fromOptions(t){return i(t,"No options for HDPublicKey"),i(s.isU8(t.depth)),i(s.isU32(t.parentFingerPrint)),i(s.isU32(t.childIndex)),i(Buffer.isBuffer(t.chainCode)),i(Buffer.isBuffer(t.publicKey)),t.network&&(this.network=c.get(t.network)),this.depth=t.depth,this.parentFingerPrint=t.parentFingerPrint,this.childIndex=t.childIndex,this.chainCode=t.chainCode,this.publicKey=t.publicKey,this}static fromOptions(t){return(new f).fromOptions(t)}toPublic(){return this}xprivkey(){return null}xpubkey(){return this._xpubkey||(this._xpubkey=this.toBase58()),this._xpubkey}destroy(){this.depth=0,this.childIndex=0,this.parentFingerPrint=0,a(this.chainCode),a(this.publicKey),this.fingerPrint=-1,this._xpubkey=null}derive(t,e){if(i("number"==typeof t),t>>>0!==t)throw new Error("Index out of range.");if(t&d.HARDENED||e)throw new Error("Cannot derive hardened.");if(255<=this.depth)throw new Error("Depth too high.");e=this.getID(t);if(a=d.cache.get(e))return a;const r=u.pool(37);r.writeBytes(this.publicKey),r.writeU32BE(t),a=r.render();const s=n.hmac("sha512",a,this.chainCode);var a=s.slice(0,32),c=s.slice(32,64);let h;try{h=o.publicKeyTweakAdd(this.publicKey,a,!0)}catch(e){return this.derive(t+1)}if(-1===this.fingerPrint){const t=n.hash160(this.publicKey);this.fingerPrint=t.readUInt32BE(0,!0)}const l=new f;return l.network=this.network,l.depth=this.depth+1,l.parentFingerPrint=this.fingerPrint,l.childIndex=t,l.chainCode=c,l.publicKey=h,d.cache.set(e,l),l}getID(t){return this.network.keyPrefix.xpubkey58+this.publicKey.toString("hex")+t}deriveAccount(t,e){return i(s.isU32(t)),i(s.isU32(e)),i(this.isAccount(e),"Cannot derive account index."),this}isMaster(){return d.isMaster(this)}isAccount(t){return d.isAccount(this,t)}static isValidPath(t){try{return d.parsePath(t,!1),!0}catch(t){return!1}}derivePath(t){let e=this;for(const r of d.parsePath(t,!1))e=e.derive(r);return e}equals(t){return i(f.isHDPublicKey(t)),this.network===t.network&&this.depth===t.depth&&this.parentFingerPrint===t.parentFingerPrint&&this.childIndex===t.childIndex&&this.chainCode.equals(t.chainCode)&&this.publicKey.equals(t.publicKey)}compare(t){i(f.isHDPublicKey(t));let e=this.depth-t.depth;return 0!==e||0!=(e=this.parentFingerPrint-t.parentFingerPrint)||0!=(e=this.childIndex-t.childIndex)||0!==(e=this.chainCode.compare(t.chainCode))||0!==(e=this.publicKey.compare(t.publicKey))?e:0}toJSON(){return{xpubkey:this.xpubkey()}}fromJSON(t,e){return i(t.xpubkey,"Could not handle HD key JSON."),this.fromBase58(t.xpubkey,e),this}static fromJSON(t,e){return(new f).fromJSON(t,e)}static isBase58(t,e){if("string"!=typeof t)return!1;if(t.length<4)return!1;t=t.substring(0,4);try{return c.fromPublic58(t,e),!0}catch(t){return!1}}static isRaw(t,e){if(!Buffer.isBuffer(t))return!1;if(t.length<4)return!1;t=t.readUInt32BE(0,!0);try{return c.fromPublic(t,e),!0}catch(t){return!1}}fromBase58(t,e){return i("string"==typeof t),this._xpubkey=t,this.fromRaw(l.decode(t),e)}fromReader(t,e){var r=t.readU32BE();return this.network=c.fromPublic(r,e),this.depth=t.readU8(),this.parentFingerPrint=t.readU32BE(),this.childIndex=t.readU32BE(),this.chainCode=t.readBytes(32),this.publicKey=t.readBytes(33),t.verifyChecksum(),this}fromRaw(t,e){return this.fromReader(new h(t),e)}toBase58(t){return l.encode(this.toRaw(t))}toWriter(t,e){return e=e||this.network,e=c.get(e),t.writeU32BE(e.keyPrefix.xpubkey),t.writeU8(this.depth),t.writeU32BE(this.parentFingerPrint),t.writeU32BE(this.childIndex),t.writeBytes(this.chainCode),t.writeBytes(this.publicKey),t.writeChecksum(),t}getSize(){return 82}toRaw(t){return this.toWriter(new u(82),t).render()}static fromBase58(t,e){return(new f).fromBase58(t,e)}static fromReader(t,e){return(new f).fromReader(t,e)}static fromRaw(t,e){return(new f).fromRaw(t,e)}static isHDPublicKey(t){return t instanceof f}}t.exports=f},function(t,e,r){"use strict";
740
+ */const i=r(0),s=r(1),n=r(6),a=r(95),o=r(29),c=r(15),u=r(4),h=r(2),l=r(70),p=r(3),d=r(142);class f{constructor(t){this.network=c.primary,this.depth=0,this.parentFingerPrint=0,this.childIndex=0,this.chainCode=p.ZERO_HASH,this.publicKey=p.ZERO_KEY,this.fingerPrint=-1,this._xpubkey=null,t&&this.fromOptions(t)}fromOptions(t){return i(t,"No options for HDPublicKey"),i(s.isU8(t.depth)),i(s.isU32(t.parentFingerPrint)),i(s.isU32(t.childIndex)),i(Buffer.isBuffer(t.chainCode)),i(Buffer.isBuffer(t.publicKey)),t.network&&(this.network=c.get(t.network)),this.depth=t.depth,this.parentFingerPrint=t.parentFingerPrint,this.childIndex=t.childIndex,this.chainCode=t.chainCode,this.publicKey=t.publicKey,this}static fromOptions(t){return(new f).fromOptions(t)}toPublic(){return this}xprivkey(){return null}xpubkey(){return this._xpubkey||(this._xpubkey=this.toBase58()),this._xpubkey}destroy(){this.depth=0,this.childIndex=0,this.parentFingerPrint=0,a(this.chainCode),a(this.publicKey),this.fingerPrint=-1,this._xpubkey=null}derive(t,e){if(i("number"==typeof t),t>>>0!==t)throw new Error("Index out of range.");if(t&d.HARDENED||e)throw new Error("Cannot derive hardened.");if(255<=this.depth)throw new Error("Depth too high.");e=this.getID(t);if(a=d.cache.get(e))return a;const r=u.pool(37);r.writeBytes(this.publicKey),r.writeU32BE(t),a=r.render();const s=n.hmac("sha512",a,this.chainCode);var a=s.slice(0,32),c=s.slice(32,64);let h;try{h=o.publicKeyTweakAdd(this.publicKey,a,!0)}catch(e){return this.derive(t+1)}if(-1===this.fingerPrint){const t=n.hash160(this.publicKey);this.fingerPrint=t.readUInt32BE(0,!0)}const l=new f;return l.network=this.network,l.depth=this.depth+1,l.parentFingerPrint=this.fingerPrint,l.childIndex=t,l.chainCode=c,l.publicKey=h,d.cache.set(e,l),l}getID(t){return this.network.keyPrefix.xpubkey58+this.publicKey.toString("hex")+t}deriveAccount(t,e){return i(s.isU32(t)),i(s.isU32(e)),i(this.isAccount(e),"Cannot derive account index."),this}isMaster(){return d.isMaster(this)}isAccount(t){return d.isAccount(this,t)}static isValidPath(t){try{return d.parsePath(t,!1),!0}catch(t){return!1}}derivePath(t){let e=this;for(const r of d.parsePath(t,!1))e=e.derive(r);return e}equals(t){return i(f.isHDPublicKey(t)),this.network===t.network&&this.depth===t.depth&&this.parentFingerPrint===t.parentFingerPrint&&this.childIndex===t.childIndex&&this.chainCode.equals(t.chainCode)&&this.publicKey.equals(t.publicKey)}compare(t){i(f.isHDPublicKey(t));let e=this.depth-t.depth;return 0!==e||0!=(e=this.parentFingerPrint-t.parentFingerPrint)||0!=(e=this.childIndex-t.childIndex)||0!==(e=this.chainCode.compare(t.chainCode))||0!==(e=this.publicKey.compare(t.publicKey))?e:0}toJSON(){return{xpubkey:this.xpubkey()}}fromJSON(t,e){return i(t.xpubkey,"Could not handle HD key JSON."),this.fromBase58(t.xpubkey,e),this}static fromJSON(t,e){return(new f).fromJSON(t,e)}static isBase58(t,e){if("string"!=typeof t)return!1;if(t.length<4)return!1;t=t.substring(0,4);try{return c.fromPublic58(t,e),!0}catch(t){return!1}}static isRaw(t,e){if(!Buffer.isBuffer(t))return!1;if(t.length<4)return!1;t=t.readUInt32BE(0,!0);try{return c.fromPublic(t,e),!0}catch(t){return!1}}fromBase58(t,e){return i("string"==typeof t),this._xpubkey=t,this.fromRaw(l.decode(t),e)}fromReader(t,e){var r=t.readU32BE();return this.network=c.fromPublic(r,e),this.depth=t.readU8(),this.parentFingerPrint=t.readU32BE(),this.childIndex=t.readU32BE(),this.chainCode=t.readBytes(32),this.publicKey=t.readBytes(33),t.verifyChecksum(),this}fromRaw(t,e){return this.fromReader(new h(t),e)}toBase58(t){return l.encode(this.toRaw(t))}toWriter(t,e){return e=e||this.network,e=c.get(e),t.writeU32BE(e.keyPrefix.xpubkey),t.writeU8(this.depth),t.writeU32BE(this.parentFingerPrint),t.writeU32BE(this.childIndex),t.writeBytes(this.chainCode),t.writeBytes(this.publicKey),t.writeChecksum(),t}getSize(){return 82}toRaw(t){return this.toWriter(new u(82),t).render()}static fromBase58(t,e){return(new f).fromBase58(t,e)}static fromReader(t,e){return(new f).fromReader(t,e)}static fromRaw(t,e){return(new f).fromRaw(t,e)}static isHDPublicKey(t){return t instanceof f}}t.exports=f},function(t,e,r){"use strict";
741
741
  /*!
742
742
  * siphash.js - siphash for vallnet
743
743
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -803,14 +803,14 @@ Me=new RegExp('(?:false|true|null|[\\{\\}\\[\\]]|(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.
803
803
  /*!
804
804
  * Balance.js - Balance object for vallnet
805
805
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
806
- */const i=r(34);t.exports=class{constructor(t,e,r){this.wid=t,this.id=e,this.account=r,this.unconfirmed=0,this.confirmed=0,this.locked=0}equal(t){return this.wid===t.wid&&this.confirmed===t.confirmed&&this.unconfirmed===t.unconfirmed&&this.locked===t.locked}toJSON(t){return{wid:t?void 0:this.wid,id:t?void 0:this.id,account:t?void 0:this.account,unconfirmed:this.unconfirmed,confirmed:this.confirmed,locked:this.locked}}toString(){return"<Balance unconfirmed="+i.btc(this.unconfirmed)+" confirmed="+i.btc(this.confirmed)+" locked="+i.btc(this.locked)+">"}inspect(){return this.toString()}}},function(t,e,r){var i=r(29);const s=r(3);class n extends i{constructor(t){super(),this.db=t||{getEr:()=>{},setEr:()=>{},delEr:()=>{}}}async loadHistory(){var t;for(t of(this.clear(),await this.db.loadAuditList()))this.set(t.erid,t)}async getAudit(t){return this.data.get(t)||this.db.getAudit(t)}async setAudit(t,e){t=new a(t),await this.db.setAudit(t,e),this.data.set(t.erid,t)}async delAudit(t){await this.db.delAudit(t),this.data.delete(t.erid)}async query(t){let e=[];for(var r of t)if(r&&Array.isArray(r)){if("erid"==r[0])return{list:[await this.getAudit(r[1])],page:0,count:1};e.push(r)}return super.query(e)}}class a{constructor(t){this.fromOptions(t=t||{})}fromOptions(t){this.erid=t.erid,this.address=t.address,this.oper=t.oper||"Audit",this.time=t.time,this.height=t.height,this.hash=t.hash,this.index=t.index}toRaw(){return Buffer.from(JSON.stringify(this.toOptions()),"utf-8")}toOptions(){let t={};return t.erid=this.erid,t.address=this.address,t.oper=this.oper||"Audit",t.time=this.time,t.height=this.height,t.hash=this.hash||"",t.index=this.index||0,t}getSignObjSize(t){var e=0;return(e+=s.sizeVarString(t.erid,"utf8"))+s.sizeVarString(t.address,"utf8")+s.sizeVarString(t.oper,"utf8")+4+4+s.sizeVarString(t.hash,"ascii")+4}toWriter(t,e){return e.writeVarString(t.erid,"utf8"),e.writeVarString(t.address,"utf8"),e.writeVarString(t.oper,"utf8"),e.writeU32(t.time),e.writeU32(t.height),e.writeVarString(t.hash,"ascii"),e.writeU32(t.index),e}fromRaw(t){return t=JSON.parse(t.toString("utf8")),this.fromOptions(t),this}static fromRaw(t){return(new a).fromRaw(t)}}n.AuditItem=a,t.exports=n},,,,,,,function(t,e){t.exports=class t{constructor(t){this.indicate=t||0}get value(){return this.indicate}set(t){return this.indicate=this.indicate|t,this}unSet(t){return this.indicate=this.indicate&~t,this}check(t){return!!this.indicate&&(this.indicate&t)==t}static inst(e){return new t(e)}}},function(t,e,r){"use strict";
806
+ */const i=r(34);t.exports=class{constructor(t,e,r){this.wid=t,this.id=e,this.account=r,this.unconfirmed=0,this.confirmed=0,this.locked=0}equal(t){return this.wid===t.wid&&this.confirmed===t.confirmed&&this.unconfirmed===t.unconfirmed&&this.locked===t.locked}toJSON(t){return{wid:t?void 0:this.wid,id:t?void 0:this.id,account:t?void 0:this.account,unconfirmed:this.unconfirmed,confirmed:this.confirmed,locked:this.locked}}toString(){return"<Balance unconfirmed="+i.btc(this.unconfirmed)+" confirmed="+i.btc(this.confirmed)+" locked="+i.btc(this.locked)+">"}inspect(){return this.toString()}}},function(t,e,r){var i=r(28);const s=r(3);class n extends i{constructor(t){super(),this.db=t||{getEr:()=>{},setEr:()=>{},delEr:()=>{}}}async loadHistory(){var t;for(t of(this.clear(),await this.db.loadAuditList()))this.set(t.erid,t)}async getAudit(t){return this.data.get(t)||this.db.getAudit(t)}async setAudit(t,e){t=new a(t),await this.db.setAudit(t,e),this.data.set(t.erid,t)}async delAudit(t){await this.db.delAudit(t),this.data.delete(t.erid)}async query(t){let e=[];for(var r of t)if(r&&Array.isArray(r)){if("erid"==r[0])return{list:[await this.getAudit(r[1])],page:0,count:1};e.push(r)}return super.query(e)}}class a{constructor(t){this.fromOptions(t=t||{})}fromOptions(t){this.erid=t.erid,this.address=t.address,this.oper=t.oper||"Audit",this.time=t.time,this.height=t.height,this.hash=t.hash,this.index=t.index}toRaw(){return Buffer.from(JSON.stringify(this.toOptions()),"utf-8")}toOptions(){let t={};return t.erid=this.erid,t.address=this.address,t.oper=this.oper||"Audit",t.time=this.time,t.height=this.height,t.hash=this.hash||"",t.index=this.index||0,t}getSignObjSize(t){var e=0;return(e+=s.sizeVarString(t.erid,"utf8"))+s.sizeVarString(t.address,"utf8")+s.sizeVarString(t.oper,"utf8")+4+4+s.sizeVarString(t.hash,"ascii")+4}toWriter(t,e){return e.writeVarString(t.erid,"utf8"),e.writeVarString(t.address,"utf8"),e.writeVarString(t.oper,"utf8"),e.writeU32(t.time),e.writeU32(t.height),e.writeVarString(t.hash,"ascii"),e.writeU32(t.index),e}fromRaw(t){return t=JSON.parse(t.toString("utf8")),this.fromOptions(t),this}static fromRaw(t){return(new a).fromRaw(t)}}n.AuditItem=a,t.exports=n},,,,,,,function(t,e){t.exports=class t{constructor(t){this.indicate=t||0}get value(){return this.indicate}set(t){return this.indicate=this.indicate|t,this}unSet(t){return this.indicate=this.indicate&~t,this}check(t){return!!this.indicate&&(this.indicate&t)==t}static inst(e){return new t(e)}}},function(t,e,r){"use strict";
807
807
  /*!
808
808
  * coins.js - coins object
809
809
  */const i=r(0),s=r(148);t.exports=class t{constructor(){this.outputs=new Map}clone(){let e=new t;for(var[r,i]of this.outputs)e.outputs.set(r,s.fromRaw(i.toRaw()));return e}add(t,e){return i(t>>>0===t),i(e),this.outputs.set(t,e),e}addOutput(t,e){return this.add(t,s.fromOutput(e))}addCoin(t){return this.add(t.index,s.fromCoin(t))}has(t){return this.outputs.has(t)}isUnspent(t){return!(!(t=this.outputs.get(t))||t.spent)}get(t){return this.outputs.get(t)||null}getOutput(t){return(t=this.outputs.get(t))?t.output:null}getCoin(t){const e=this.outputs.get(t.index);return e?e.toCoin(t):null}spend(t){const e=this.get(t);return!e||e.spent?null:(e.spent=!0,e)}remove(t){var e=this.get(t);return e?(this.outputs.delete(t),e):null}isEmpty(){return 0===this.outputs.size}fromTX(t,e,r){i("number"==typeof e),i("number"==typeof r);for(let i=0;i<t.outputs.length;i++){var n;t.outputs[i].script.isUnspendable()||(n=s.fromTX(t,i,e,r),this.outputs.set(i,n))}return this}static fromTX(e,r,i){return(new t).fromTX(e,r,i)}}},function(t,e,r){"use strict";
810
810
  /*!
811
811
  * compress.js - coin compressor for vallnet
812
812
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
813
- */const i=r(0),s=r(28),n=r(3),a=r(7),o=r(17),c=Buffer.alloc(0);function u(t){if(0!==t.length)switch(t[0]){case 2:case 3:return 33===t.length;case 4:return 65!==t.length?void 0:s.publicKeyVerify(t);default:return}}e.pack=function(t,e){return e.writeVarint(t.value),function(t,e){if(r=t.getPubkeyhash(!0))e.writeU8(0),e.writeBytes(r);else if(r=t.getScripthash())e.writeU8(1),e.writeBytes(r);else{var r;if((r=t.getPubkey(!0))&&u(r))return r=function(t){let e;switch(t[0]){case 2:case 3:e=t;break;case 4:(e=s.publicKeyConvert(t,!0))[0]=4|1&t[64];break;default:throw new Error("Bad point format.")}return i(33===e.length),e}(r),void e.writeBytes(r);e.writeVarint(t.raw.length+6),e.writeBytes(t.raw)}}(t.script,e),e},e.unpack=function(t,e){return t.value=e.readVarint(),function(t,e){switch(e.readU8()){case 0:var r=e.readBytes(20,!0);t.createScript(r);break;case 1:r=e.readBytes(20,!0),t.createScript(r,o.types.SCRIPTHASH);break;case 2:case 3:case 4:case 5:--e.offset,r=function(t){var e=t[0];switch(i(33===t.length),e){case 2:case 3:return t;case 4:t[0]=2;break;case 5:t[0]=3;break;default:throw new Error("Bad point format.")}var r=s.publicKeyConvert(t,!1);return t[0]=e,r}(e.readBytes(33,!0)),t.createScript(r,o.types.PUBKEY);break;default:--e.offset,(r=e.readVarint()-6)>a.MAX_SCRIPT_SIZE?(t.createScript(c,o.types.NULLDATA),e.seek(r)):(r=e.readBytes(r),t.fromRaw(r))}}(t.script,e),t},e.size=function(t){var e=0;return(e+=n.sizeVarint(t.value))+((e=t.script).isPubkeyhash(!0)||e.isScripthash()?21:(t=e.getPubkey(!0))&&u(t)?33:(t=0,(t+=n.sizeVarint(e.raw.length+6))+e.raw.length))}},function(t,e,r){"use strict";
813
+ */const i=r(0),s=r(29),n=r(3),a=r(7),o=r(17),c=Buffer.alloc(0);function u(t){if(0!==t.length)switch(t[0]){case 2:case 3:return 33===t.length;case 4:return 65!==t.length?void 0:s.publicKeyVerify(t);default:return}}e.pack=function(t,e){return e.writeVarint(t.value),function(t,e){if(r=t.getPubkeyhash(!0))e.writeU8(0),e.writeBytes(r);else if(r=t.getScripthash())e.writeU8(1),e.writeBytes(r);else{var r;if((r=t.getPubkey(!0))&&u(r))return r=function(t){let e;switch(t[0]){case 2:case 3:e=t;break;case 4:(e=s.publicKeyConvert(t,!0))[0]=4|1&t[64];break;default:throw new Error("Bad point format.")}return i(33===e.length),e}(r),void e.writeBytes(r);e.writeVarint(t.raw.length+6),e.writeBytes(t.raw)}}(t.script,e),e},e.unpack=function(t,e){return t.value=e.readVarint(),function(t,e){switch(e.readU8()){case 0:var r=e.readBytes(20,!0);t.createScript(r);break;case 1:r=e.readBytes(20,!0),t.createScript(r,o.types.SCRIPTHASH);break;case 2:case 3:case 4:case 5:--e.offset,r=function(t){var e=t[0];switch(i(33===t.length),e){case 2:case 3:return t;case 4:t[0]=2;break;case 5:t[0]=3;break;default:throw new Error("Bad point format.")}var r=s.publicKeyConvert(t,!1);return t[0]=e,r}(e.readBytes(33,!0)),t.createScript(r,o.types.PUBKEY);break;default:--e.offset,(r=e.readVarint()-6)>a.MAX_SCRIPT_SIZE?(t.createScript(c,o.types.NULLDATA),e.seek(r)):(r=e.readBytes(r),t.fromRaw(r))}}(t.script,e),t},e.size=function(t){var e=0;return(e+=n.sizeVarint(t.value))+((e=t.script).isPubkeyhash(!0)||e.isScripthash()?21:(t=e.getPubkey(!0))&&u(t)?33:(t=0,(t+=n.sizeVarint(e.raw.length+6))+e.raw.length))}},function(t,e,r){"use strict";
814
814
  /*!
815
815
  * asn1.js - asn1 parsing for vallnet
816
816
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -856,11 +856,11 @@ Me=new RegExp('(?:false|true|null|[\\{\\}\\[\\]]|(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.
856
856
  /*!
857
857
  * accountdb.js - storage for account management
858
858
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
859
- */const i=r(8),s=r(0),n=r(73),a=r(122),o=r(161),c=r(618),u=r(96),h=u.walletdb,l=r(6),p=r(162),d=r(127),f=r(171),m=r(7),g=r(38).VerifyError,y=r(46),v=r(12);r(19);const b=r(60),w=r(200),x=r(69),k=r(43),{getVerifyMsg:S,BlockFinalType:E,ContractEnvType:_}=r(5),A=r(163),R=r(620),I=r(29);var j=r(72);const C=r(1),P=r(120).sortWithSeq,O=r(35),T=r(201),F=r(65),B=r(102),N=r(3),D=N.U32,L=r(347),H=r(348),z=r(349),M=z.vpItem,U=r(621),q=U.vpItem,V=r(85),K=r(622),W=V.cpItem,G=V.stockItem,$=r(158),Y=$.ErAbolishItem,X=r(159),J=X.X509Cert,Z=r(160),Q=Z.X509Abolish,tt=r(37).broadcast,et=r(134),rt=et.vpItem,it=r(236),st=it.stockAccount,nt=r(157),at=nt.ErItem,ot=r(323),ct=ot.AuditItem,ut=r(320),ht=r(111),lt=r(623),pt=r(321),dt=r(123),ft=r(624),mt=r(226),gt=r(32),yt=r(36),vt=r(59),bt=r(78).errors,wt=r(77);class xt extends j{constructor(t){super(),this.readyLoad=!1,this.options=new c(t),this.network=this.options.network,this.logger=this.options.logger.context("wallet"),this.workers=this.options.workers,this.keys={hmacSalt:N.DefaultChainCode},t.keys&&t.keys.hmacSalt&&(s(Buffer.isBuffer(t.keys.hmacSalt)),this.keys.hmacSalt=t.keys.hmacSalt),this.client=this.options.client,this.client&&(this.client.wdb=this),this.jsonp=this.options.jsonp,this.jsonp&&(this.jsonp.wdb=this),this.spv=this.options.spv,this.feeRate=this.options.feeRate,this.db=f(this.options),this.rpc=new L(this),this.primary=null,this.state=new lt,this.wallets=new Map,this.depth=0,this.rescanning=!1,this.bound=!1,this.newRecord=!0,this.readLock=new T,this.writeLock=new O,this.txLock=new O,this.scanLock=new O,this.widCache=new F(1e4),this.pathMapCache=new F(1e5),this.filter=new B,this.middleHashMem=new Set,this.middleHashChain=new Set,this.autoTaskMgr=new A(this),this.transactionList=new H(this),this.htlcList=new z(this),this.commentList=new U(this),this.NotifyList=new I,this.propList=new et(this),this.accountList=new it(this),this.$contacts=new I,this.cpList=new V(this),this.cpMemList=new V(this),this.accountCoinList=new K(this),this.auditList=new ot(this),this.erList=new nt(this),this.erAbList=new $(this),this.x509CertList=new X(this),this.x509AbolishList=new Z(this),this.hmacConnection=[],this._init()}async logAudit(t){t.height=this.curHeight,t.time=C.now(),t.erid=l.sha256(C.stringify(t)).toString("hex"),t=new ct(t),await this.auditList.setAudit(t)}async getAccountByAddress(t,e){if(t){let i=null;if(i=e?await this.getWalletsByTX(e):await this.getWallets())for(const e of i){const i=await this.get(e);if(i){var r=await i.getPath(t);if(r)return[i.wid,r.name,i.id]}}}return[0,"",""]}_init(){let t=1e6,e=-1;this.spv&&(t=2e4,e=B.flags.ALL),this.filter=B.fromRate(t,.001,e)}async getCpSnap(){return{}}get mode(){return _.Wallet}async getTXFromAll(t){return this.getTXFromDb(t)}async checkNewRecord(){var t={createIfMissing:this.db.options.createIfMissing,errorIfExists:this.db.options.errorIfExists};this.db.options.createIfMissing=!1,this.db.options.errorIfExists=!0;try{await this.db.open();var e=await this.db.checkVersion(h,6);this.newRecord="new"==e}catch(t){if(-1!=t.message.indexOf("does not exist (create_if_missing is false)"))this.newRecord=!0;else{if(-1==t.message.indexOf("exists (error_if_exists is true)"))throw t;this.newRecord=!1}}try{await this.db.close()}catch(t){}this.db.options.createIfMissing=t.createIfMissing,this.db.options.errorIfExists=t.errorIfExists}async isNewRecord(){return await this.checkNewRecord(),this.newRecord}setmnemonic(t){if(this.options.mnemonic=this.options.mnemonic||{},t.bits)this.options.mnemonic={bits:t.bits};else if(t.entropy)this.options.mnemonic={entropy:Buffer.from(t.entropy,"hex")};else if(t.phrase){var e=this.testmnemonic(t.phrase);if(0!=e.code)throw e.msg;this.options.mnemonic={phrase:t.phrase}}t.passphrase&&(this.options.mnemonic.passphrase=t.passphrase),t.language&&(this.options.mnemonic.language=t.language)}testmnemonic(t){try{return new w(t),{code:0}}catch(t){return{code:-1,msg:t.message}}}async getContracts(t){let e=await this.db.values({gte:u.txdb.tx(N.NULL_HASH),lte:u.txdb.tx(N.HIGH_HASH),parse:t=>C.parseJson(t.toString())});return t?e.filter(e=>e.srcact==t||e.dstact==t):e}isFull(){return this.spv||this.synced||!1}async _open(t){}async handleNotify(t,e=!1){if(!e){let r=t.body.content;if("string"==typeof r)try{r=JSON.parse(t.body.content)}catch(e){return}if("object"==typeof r&&"secret"===r.type){let e={contact:t.body.src,messenger:t.body.dst};r.init&&(e.init=Buffer.from(r.init,"hex")),r.packet&&(e.packet=Buffer.from(r.packet)),await this.handleSecret(e)}}}async handleSecret(t){if(t.contact&&t.messenger&&t.contact!=t.messenger){try{v.fromString(t.contact,this.network.type),v.fromString(t.messenger,this.network.type)}catch(t){return}let e=await this.ensureContact(t);e&&await e.ensureMessenger(t).answer(t)}}async scanContact(t,e=-1){var r=async t=>{var e;t.witness&&"witnesspubkeyhash"==t.getType()&&(e=t.witness.getPubkeyhashInput()[1],t=v.fromWitness(t.witness).toString(),e&&t&&await this.ensureContact({contact:t,publicKey:e}))};if(0<=e&&e<t.inputs.length)await r(t.inputs[e]);else for(var i of t.inputs)await r(i)}async ensureContact(t){if(!t.contact||t.contact==t.messenger)return null;try{v.fromString(t.contact,this.network.type),t.messenger&&v.fromString(t.messenger,this.network.type)}catch(t){return null}t.network=this.network.type,this.$contacts.get(t.contact)||this.$contacts.set(t.contact,new R(t));let e=this.$contacts.get(t.contact);if(t.messenger){let i=e.ensureMessenger(t);if(!i.wallet){var[t,r]=await this.getAccountByAddress(i.address);if(!(t=await this.get(t)))return;i.wallet=t,i.account=r}}return e}getCps(){return this.db.values({gte:u.txdb.cp(N.ZERO_CID,"hex"),lte:u.txdb.cp(N.MAX_CID,"hex"),parse:t=>W.fromRaw(t)})}async _close(){await this.disconnect(),this.http&&this.options.listen&&await this.http.close();for(const t of this.wallets.values())await t.destroy();await this.db.close(),this.options.listen&&await this.logger.close()}async destroy(){await this.db.destroy(),this.widCache.reset(),this.pathMapCache.reset()}async load(t){if(this.readyLoad){const e=await this.txLock.lock();try{await this.init(t),await this.watch(),await this.sync()}finally{e()}setTimeout(()=>{this.resend()},5e3)}}bind(){!this.client||this.bound||(this.bound=!0,this.client.hook("htlcassent.cancel",t=>{this.setAssent(t),this.emit("htlcassent.cancel",t)}),this.client.hook("htlcassent.deal",t=>{this.setAssent(t),this.emit("htlcassent.deal",t)}),this.client.hook("htlcassent.receive",t=>{this.setAssent(t),this.emit("htlcassent.receive",t)}),this.client.hook("htlcsuggest.cancel",t=>{this.setSuggest(t),this.emit("htlcsuggest.cancel",t)}),this.client.hook("htlcsuggest.deal",t=>{this.setSuggest(t),this.emit("htlcsuggest.deal",t)}),this.client.hook("htlcsuggest.receive",t=>{this.setSuggest(t),this.emit("htlcsuggest.receive",t)}),this.on("mssendpubk/receive",async t=>{let e=await this.get(t.addr);if(!e){e=await this.ensure({id:t.addr,type:"multisig",m:t.m,n:t.n,witness:!0});var[r,i]=await this.getAccountByAddress(t.addr);let s=await this.get(r);s&&await s.send({subtractFee:!1,sort:!1,outputs:[{address:t.contract,value:1e4}],comment:JSON.stringify({oper:"scrun",params:{oper:"pubk",addr:t.addr,puba:e.account.accountKey}})},i)}if(e.account.keys.length<e.account.n-1){var s;for(s of t.data.split(","))try{await e.addSharedKey(s)}catch(s){}if(e.account.keys.length==e.account.n-1){var[r,i]=await this.getAccountByAddress(t.addr);let s=await this.get(r);s&&await s.send({subtractFee:!1,sort:!1,outputs:[{address:t.contract,value:1e4}],comment:JSON.stringify({oper:"scrun",params:{oper:"puba",addr:t.addr,puba:e.account.receive.getAddress().toString()}})},i)}}}),this.on("mssendtx/receive",async t=>{let e=await this.get(t.addr);if(e&&e.account.type==o.types.MULTISIG){const r=b.fromRaw(t.data,"hex");r.view=await e.getCoinView(r),r.isSigned()||(t.txid=r.txid(),await this.saveMSTrans(t))}}),this.client.hook("onConnect",async()=>{await this.load()}),this.client.hook("error",t=>{this.emit("error",t)}),this.client.hook("block.connect",async(t,e)=>{try{await this.addBlock(t,e)}catch(t){this.emit("error",t)}}),this.client.hook("block.disconnect",async(t,e)=>{try{await this.removeBlock(t,e)}catch(t){this.emit("error",t)}}),this.client.hook("chain.full",()=>{this.synced=!0}),this.client.hook("block.rescan",async(t,e)=>{try{await this.rescanBlock(t,e)}catch(t){this.emit("error",t)}}),this.client.hook("tx",async(t,e,r)=>{try{await this.addTX(t,null,r)}catch(t){this.emit("error",t)}}),this.client.hook("entry.remove",async(t,e)=>{try{if(e){var r=t.tx.hash("hex"),i=await this.getWalletsByTX(t.tx);if(i)for(const e of i){const i=await this.get(e);s(i),await i.remove(r),(await k.FactoryOfContract({tx:t.tx,env:this})).erase()}}}catch(e){this.emit("error",e)}}),this.client.hook("chain.reset",async t=>{try{await this.resetChain(t)}catch(t){this.emit("error",t)}}),this.jsonp&&this.jsonp.hook("error",t=>{this.emit("error",t)}))}async disconnect(){this.client&&await this.client._close(),this.jsonp&&await this.jsonp._close()}async flushCP(t,e=!1){this.client&&(t=t||[],e||(t=this.cpList.excludeCids(t),e=e||0<t.length),e&&await this.client.execute("cp.remoteQuery",[[["cid","include",t]]]))}async watch(){let t=this.db.iterator({gte:h.p(N.NULL_HASH),lte:h.p(N.HIGH_HASH)}),e=0,r=0;for(;;){var i=await t.next();if(!i)break;try{var s=h.pp(i.key);this.filter.add(s,"hex")}catch(e){throw await t.end(),e}e++}for(t=this.db.iterator({gte:h.o(N.NULL_HASH,0),lte:h.o(N.HIGH_HASH,4294967295)});;){var n=await t.next();if(!n)break;try{var[a,o]=h.oo(n.key);var c=new y(a,o).toRaw();this.filter.add(c)}catch(e){throw await t.end(),e}r++}this.logger.info("Filter: Added %d hashes to AccountDB filter.",e),this.logger.info("Filter: Added %d outpoints to AccountDB filter.",r),await this.setFilter()}async sync(){if(this.client){let e,r=this.curHeight;for(;0<=r;){var t=await this.getBlock(r);if(!t)break;if(e=await this.client.getEntry(t.hash))break;r--}e||(r=this.state.startHeight,(e=await this.client.getEntry(this.state.startHash))||(r=0)),await this.cpList.loadHistory(),await this.cpMemList.loadHistory(),await this.propList.loadHistory(),await this.htlcList.loadHistory(),await this.commentList.loadHistory(),await this.accountList.loadHistory(),await this.transactionList.loadHistory(),await this.loadContact(),await this.erList.loadHistory(),await this.auditList.loadHistory(),await this.erAbList.loadHistory(),await this.x509CertList.loadHistory(),await this.x509AbolishList.loadHistory(),await this.accountCoinList.loadHistory(),await this.scan(r,!1)}}async scan(t,e=!0){if(this.client&&(null==t&&(t=this.state.startHeight),s(t>>>0===t,"WDB: Must pass in a height."),!await this.rollback(t,e)||0===t)){this.logger.info("AccountDB is scanning %d blocks.",this.curHeight-t+1),e=await this.getTip();try{this.rescanning=!0,await this.client.rescan(e.hash)}finally{this.rescanning=!1}}}async rescan(t){const e=await this.txLock.lock();try{return await this.scan(t,!1)}finally{e()}}async send(t){if(this.client)return this.client.send(t);this.emit("send",t)}async getTX(t){for(const r of this.wallets.values()){var e=await r.getTX(t);if(e)return e.tx}return null}async getTXFromDb(t){for(const r of this.wallets.values()){var e=await r.getTX(t);if(e)return e.tx}return null}async getExtendTX(t){for(const r of this.wallets.values()){var e=await r.getTX(t);if(e)return e}return null}async removeTX(t){this.client?await this.client.removeTX(t):this.emit("remove",t)}async estimateFee(t){return 0<this.feeRate?this.feeRate:!this.client||(t=await this.client.estimateFee(t))<this.network.feeRate?this.network.feeRate:t>this.network.maxFeeRate?this.network.maxFeeRate:t}setFilter(){return this.client?this.client.setFilter(this.filter):(this.emit("filter.set",this.filter),Promise.resolve())}addFilter(t){return this.client?this.client.addFilter(t):(this.emit("filter.add",t),Promise.resolve())}resetFilter(){return this.client?this.client.resetFilter():(this.emit("filter.reset"),Promise.resolve())}backup(t){return this.db.backup(t)}async wipe(){this.logger.warning("Wiping AccountDB TXDB..."),this.logger.warning("I hope you know what you're doing.");const t=this.db.iterator({gte:Buffer.from([0]),lte:Buffer.from([255])}),e=this.db.batch();let r=0;for(;;){var i=await t.next();if(!i)break;try{switch(i.key[0]){case 98:case 99:case 101:case 116:case 111:case 104:case 82:e.del(i.key),r++}}catch(e){throw await t.end(),e}}this.logger.warning("Wiped %d txdb records.",r),await e.write()}async getDepth(){const t=this.db.iterator({gte:h.w(0),lte:h.w(4294967295),reverse:!0,limit:1});var e=await t.next();return e?(await t.end(),h.ww(e.key)+1):1}start(t){return s(!t.current,"WDB: Batch already started."),t.current=this.db.batch(),t.accountCache.start(),t.pathCache.start(),t.current}drop(t){const e=this.batch(t);t.current=null,t.accountCache.drop(),t.pathCache.drop(),e.clear()}clear(t){const e=this.batch(t);t.accountCache.clear(),t.pathCache.clear(),e.clear()}batch(t){return s(t.current,"WDB: Batch does not exist."),t.current}async commit(t){const e=this.batch(t);try{await e.write()}catch(t){throw this.drop(),t}t.current=null,t.accountCache.commit(),t.pathCache.commit()}testFilter(t){return this.filter.test(t,"hex")}addHash(t){return this.filter.add(t,"hex"),this.addFilter(t)}addOutpoint(t,e){const r=new y(t,e);this.filter.add(r.toRaw())}dump(){return this.db.dump()}register(t){s(!this.wallets.has(t.wid)),this.wallets.set(t.wid,t)}unregister(t){s(this.wallets.has(t.wid)),this.wallets.delete(t.wid)}async getWalletID(t){if(!t)return null;if("number"==typeof t)return t;var e=this.widCache.get(t);if(e)return e;const r=await this.db.get(h.l(t));return r?(e=r.readUInt32LE(0,!0),this.widCache.set(t,e),e):null}async get(t){if(!(t=await this.getWalletID(t)))return null;const e=await this.readLock.lock(t);try{return await this._get(t)}finally{e()}}async _get(t){var e=this.wallets.get(t);if(e)return e;if(!(e=await this.db.get(h.w(t))))return null;const r=a.fromRaw(this,e);return await r.open(),this.register(r),r}async loadBackup(t){if(vt.unsupported)throw new wt(bt.INTERNAL_ERROR,"FS not available.");let e=await this.get("primary");const r=await vt.readFile(t,"utf8");var i;for(i of r.split(/\n+/))if(0!==(i=i.trim()).length&&!/^\s*#/.test(i)){const t=i.split(/\s+/);if(t.length<4)throw new wt(bt.DESERIALIZATION_ERROR,"Malformed wallet Data File.");switch(t[0]){case"W":var n=Buffer.from(t[1],"base64");n=a.fromRaw(e.db,n);if(e.wid!=n.wid)throw new wt(bt.DESERIALIZATION_ERROR,"Malformed wallet Key");await this.replace(n),e=await this.get("primary"),this.logger.info("Import Wallet %s(%s)",e.id,e.wid);break;case"C":{n=Buffer.from(t[1],"base64");const r=o.fromRaw(e.db,n);r.wallet=e,r.wid=e.wid,r.id=e.id,r.initialized=!0,r.watchOnly=e.watchOnly,r.receive=r.deriveReceive(r.receiveDepth-1),r.change=r.deriveChange(r.changeDepth-1),r.witness&&(r.nested=r.deriveNested(r.nestedDepth-1));let i=e.master.key.deriveAccount(44,r.accountIndex);i.publicKey.toString("hex")!==r.accountKey.publicKey.toString("hex")&&s(i.publicKey.toString("hex")==r.accountKey.publicKey.toString("hex")),await e.saveAccount(r),this.logger.info("Import Account %s(%s)",r.name,r.accountIndex);break}case"A":{var c=parseInt(t[5]),u=parseInt(t[7]),h=parseInt(t[9]),l=t[11].trim();let r=await e.deriveKey(c,u,h),i=await e.deriveKey(c,u,h,e.master);r.getAddress("string")!==i.getAddress("string")&&s(r.getAddress("string")==i.getAddress("string")),r.getAddress("string")!==l&&s(r.getAddress("string")==l),this.logger.info("Import Address %s %s %s %s",c,u,h,r.getAddress("string"));break}}}return e.accountCache.reset(),e}save(t){var e=t.wid,r=t.id;const i=this.batch(t);this.widCache.set(r,e),i.put(h.w(e),t.toRaw()),i.put(h.l(r),D(e))}async rename(t,e){const r=await this.writeLock.lock();try{return await this._rename(t,e)}finally{r()}}async _rename(t,e){var r=t.id;if(!n.isName(e))throw new Error("WDB: Bad wallet ID.");if(await this.has(e))throw new Error("WDB: ID not available.");this.start(t).del(h.l(r)),t.id=e,this.save(t),await this.commit(t),this.widCache.remove(r);for(const r of t.pathCache.values())r.id=e}async replace(t){const e=await this.writeLock.lock();try{return await this._replace(t)}finally{e()}}async _replace(t){const e=this.start(t);e.del(h.l(t.id)),e.del(h.w(t.wid)),this.save(t),await this.commit(t),this.widCache.remove(t.id),this.wallets.delete(t.wid)}renameAccount(t,e){var r=t.wallet;this.batch(r).del(h.i(t.wid,t.name)),t.name=e,this.saveAccount(t)}async auth(t,e){if("string"==typeof e){if(!C.isHex256(e))throw new Error("WDB Authentication: Invalid Token.");e=Buffer.from(e,"hex")}t=x.getHmac(t.toString(),this.keys.hmacSalt);const r=i.createHmac("sha256",t.random);if(t=Buffer.from(r.update(t.token).digest("hex"),"hex"),!p(e,t))throw new Error("WDB Authentication: CRC Error.")}async create(t){const e=await this.writeLock.lock();t=t||{};try{return await this._create(t)}finally{e()}}async _create(t){if(await this.has(t.id))throw new Error("WDB: Wallet already exists.");"string"==typeof t.mnemonic&&(t.mnemonic={phrase:t.mnemonic}),t.mnemonic=t.mnemonic||{},!t.mnemonic.language&&this.options.mnemonic&&this.options.mnemonic.language&&(t.mnemonic.language=this.options.mnemonic.language);const e=a.fromOptions(this,t);return e.wid=this.depth++,await e.init(t),this.register(e),this.logger.info("Created wallet %s in AccountDB.",e.id),e}async has(t){return null!=await this.getWalletID(t)}async ensure(t){return await this.get(t.id)||this.create(t)}async getAccount(t,e){return(t=await this.db.get(h.a(t,e)))?o.fromRaw(this,t):null}getAccounts(t){return this.db.values({gte:h.n(t,0),lte:h.n(t,4294967295),parse:t=>t.toString("ascii")})}async getAccountIndex(t,e){const r=await this.db.get(h.i(t,e));return r?r.readUInt32LE(0,!0):-1}async getGuider(t){return t=v.fromString(t,this.network.type).getHash("hex"),(t=await this.db.get(h.g(t)))?v.fromRaw(t).toString():null}async setGuider(t,e,r){if(r=v.fromString(r,this.network.type).getHash("hex"),!await this.db.has(h.g(r))){t=v.fromString(t,this.network.type);const i=this.db.batch();i.put(h.g(r),t.toRaw()),i.put(h.gs(t.getHash("hex"),Buffer.from(e,"ascii").toString("hex"),r),null),await i.write()}}async unsetGuider(t,e,r){t=v.fromString(t,this.network.type).getHash("hex"),r=v.fromString(r,this.network.type).getHash("hex");const i=this.db.batch();i.del(h.g(r)),i.del(h.gs(t,Buffer.from(e,"ascii").toString("hex"),r)),await i.write()}async getAccountName(t,e){const r=await this.db.get(h.n(t,e));return r?r.toString("ascii"):null}saveAccount(t){var e=t.wid;const r=t.wallet;var i=t.accountIndex,s=t.name;const n=this.batch(r);n.put(h.a(e,i),t.toRaw()),n.put(h.i(e,s),D(i)),n.put(h.n(e,i),Buffer.from(s,"ascii")),r.accountCache.push(i,t)}hasAccount(t,e){return"number"==typeof t&&"number"==typeof e&&this.db.has(h.a(t,e))}async getPathMap(t){var e=this.pathMapCache.get(t);return e||((e=await this.db.get(h.p(t)))?(e=ft.fromRaw(t,e),this.pathMapCache.set(t,e),e):null)}saveKey(t,e){return this.savePath(t,e.toPath())}async savePath(t,e){var r=t.wid,i=e.hash;const s=this.batch(t);await this.addHash(i);let n=await this.getPathMap(i);(n=n||new ft(i)).add(r)&&(this.pathMapCache.set(i,n),t.pathCache.push(i,e),s.put(h.p(i),n.toRaw()),s.put(h.P(r,i),e.toRaw()),s.put(h.r(r,e.account,i),null))}async getPath(t,e){var r=await this.db.get(h.P(t,e));if(!r)return null;const i=ht.fromRaw(r);return i.wid=t,i.hash=e,i}hasPath(t,e){return this.db.has(h.P(t,e))}getHashes(){return this.db.keys({gte:h.p(N.NULL_HASH),lte:h.p(N.HIGH_HASH),parse:h.pp})}getOutpoints(){return this.db.keys({gte:h.o(N.NULL_HASH,0),lte:h.o(N.HIGH_HASH,4294967295),parse:t=>{var[t,e]=h.oo(t);return new y(t,e)}})}getWalletHashes(t){return this.db.keys({gte:h.P(t,N.NULL_HASH),lte:h.P(t,N.HIGH_HASH),parse:h.Pp})}getAccountHashes(t,e){return this.db.keys({gte:h.r(t,e,N.NULL_HASH),lte:h.r(t,e,N.HIGH_HASH),parse:h.rr})}async getWalletPaths(t){const e=[];for(const i of await this.db.range({gte:h.P(t,N.NULL_HASH),lte:h.P(t,N.HIGH_HASH)})){var r=h.Pp(i.key);const s=ht.fromRaw(i.value);s.hash=r,s.wid=t,e.push(s)}return e}async encryptKeys(t,e){var r,i=t.wid,n=await t.getPaths();const a=this.batch(t);for(r of n)if(r.data){s(!r.encrypted);var o=Buffer.from(r.hash,"hex").slice(0,16);(r=r.clone()).data=d.encipher(r.data,e,o),r.encrypted=!0,t.pathCache.push(r.hash,r),a.put(h.P(i,r.hash),r.toRaw())}}async decryptKeys(t,e){var r,i=t.wid,n=await t.getPaths();const a=this.batch(t);for(r of n)if(r.data){s(r.encrypted);var o=Buffer.from(r.hash,"hex").slice(0,16);(r=r.clone()).data=d.decipher(r.data,e,o),r.encrypted=!1,t.pathCache.push(r.hash,r),a.put(h.P(i,r.hash),r.toRaw())}}async resend(){let t={};var e;for(const e of await this.db.keys({gte:h.w(0),lte:h.w(4294967295)})){var r,i=h.ww(e);!i||(r=await this.resendPending(i))&&Array.isArray(r)&&(t[i]=r)}for(e of Object.keys(t)){let r=await this.get(parseInt(e));if(r)for(const i of t[e]){try{await this.send(i)}catch(t){this.logger.warning("wdb resend:",t.message);try{await r.abandon(i.hash("hex"))}catch(t){this.logger.warning("wdb abandon:",t.message)}}await yt.timeout(50)}}}async resendPending(t){const e=await this.get(t);var r=await this.db.keys({gte:u.txdb.prefix(t,u.txdb.p(N.NULL_HASH)),lte:u.txdb.prefix(t,u.txdb.p(N.HIGH_HASH))});if(0!==r.length){this.logger.info("Rebroadcasting %d transactions for %d.",r.length,t);const n=[];for(const a of r){var i=u.txdb.pp(a),s=u.txdb.prefix(t,u.txdb.t(i));if(s=await this.db.get(s)){const r=mt.fromRaw(s);if(!r.tx.isCoinbase())try{let t=await k.FactoryOfContract({tx:r.tx,env:this});"notify"!=t.oper&&(await t.isBlockFinal()==E.Expired?e&&(await this.removeTX(r.tx),await e.remove(i),await t.erase()):n.push(r.tx))}catch(t){this.logger.error("TX(%s) Smart Contract Error: %s",r.tx.txid(),t.message)}}}return await P(n,this)}}getWallets(){return this.db.keys({gte:h.l("\0"),lte:h.l("ÿ"),parse:h.ll})}async getWalletsByTX(t){const e=new Set;if(!t.isCoinbase())for(const i of t.inputs){const t=i.prevout;if(this.testFilter(t.toRaw())){var r=await this.getOutpointMap(t.hash,t.index);if(r)for(const t of r.wids)e.add(t)}}for(const r of t.getOutputHashes("hex"))if(this.testFilter(r)){var i=await this.getPathMap(r);if(i)for(const t of i.wids)e.add(t)}return 0===e.size?null:e}async getState(){var t=await this.db.get(h.R);return t?lt.fromRaw(t):null}async init(t){var e=this.options.startHeight;let r;if(this.client){if(null!=e){if(!(r=await this.client.getEntry(e)))throw new Error("WDB: Could not find start block.")}else r=await this.client.getTip();r=dt.fromEntry(r)}else r=dt.fromEntry(this.network.genesis);this.logger.info("Initializing AccountDB chain state (height %d).",r.height),(e=await this.getState())?this.state=e:await this.resetState(r,!1);let i=await this.ensure({id:"primary",witness:!0,mnemonic:this.options.mnemonic});await(i=t&&t.backup?await this.loadBackup(t.backup):i).createReceive(0,1,i.master,this.network.type),await i.ensureNotifyKey()}async resetState(t,e){const r=this.state.clone(),i=(r.startHeight=t.height,r.startHash=t.hash,r.height=t.height,r.marked=e,this.db.batch()),s=this.db.iterator({gte:h.h(t.height),lte:h.h(4294967295),values:!1});for(;;){var n=await s.next();if(!n)break;try{i.del(n.key)}catch(t){throw await s.end(),t}}i.put(h.h(t.height),t.toHash()),i.put(h.R,r.toRaw()),await i.write(),this.state=r}async syncState(t){const e=this.state.clone(),r=this.db.batch();if(t.height<e.height){let s=e.height;var i=s-t.height;for(let t=0;t<i;t++)r.del(h.h(s--))}else t.height>e.height&&s(t.height===e.height+1,`Bad chain sync tip ${t.height} while state `+e.height);e.height=t.height,r.put(h.h(t.height),t.toHash()),r.put(h.R,e.toRaw()),await r.write(),this.state=e,tt("block/tips",e)}get curHeight(){return this.state.height}get tidCreator(){return u.txdb.tx}get finder(){return this.getTXFromDb.bind(this)}rpcExecute(){return this.rpc.execute.apply(this.rpc,arguments)}async getBlockMap(t){var e=await this.db.get(h.b(t));return e?pt.fromRaw(t,e):null}writeBlockMap(t,e,r){this.batch(t).put(h.b(e),r.toRaw())}unwriteBlockMap(t,e){this.batch(t).del(h.b(e))}async getOutpointMap(t,e){var r=await this.db.get(h.o(t,e));return r?ut.fromRaw(t,e,r):null}writeOutpointMap(t,e,r,i){const s=this.batch(t);this.addOutpoint(e,r),s.put(h.o(e,r),i.toRaw())}unwriteOutpointMap(t,e,r){this.batch(t).del(h.o(e,r))}async writeBalanceLog(t,e){var r=h.log(t.wid,e.aidx,e.height,e.hash);e=Buffer.from(JSON.stringify(e));const i=await this.writeLock.lock();try{this.start(t).put(r,e),await this.commit(t)}finally{i()}}async queryBalanceLog(t,e,r=0){return this.db.values({gte:h.log(t,e,r,N.NULL_HASH),lte:h.log(t,e,this.curHeight,N.HIGH_HASH),parse:t=>JSON.parse(t.toString())})}async getBlock(t){const e=await this.db.get(h.h(t));if(!e)return null;const r=new dt;return r.hash=e.toString("hex"),r.height=t,r}async getTip(){var t=await this.getBlock(this.curHeight);if(t)return t;throw new Error("WDB: Tip not found!")}async rollback(t,e=!0){if(t>this.curHeight)throw new Error("WDB: Cannot rollback to the future.");if(t===this.curHeight)return this.logger.debug("Rolled back to same height (%d).",t),!0;this.logger.info("Rolling back %d AccountDB blocks to height %d.",this.curHeight-t,t);let r=await this.getBlock(t),i=!1;return r?(await this.revert(r.height),await this.syncState(r),e):(r=new dt,t>=this.state.startHeight?(r.height=this.state.startHeight,r.hash=this.state.startHash,i=this.state.marked,this.logger.warning("Rolling back AccountDB to start block (%d).",r.height)):(r.height=0,r.hash=this.network.genesis.hash,i=!1,this.logger.warning("Rolling back AccountDB to genesis block.")),await this.revert(r.height),await this.resetState(r,i),!1)}async revert(t){const e=this.db.iterator({gte:h.b(t+1),lte:h.b(4294967295),reverse:!0,values:!0});let r=0;for(;;){var i=await e.next();if(!i)break;try{var s=h.bb(i.key);var n=pt.fromRaw(s,i.value).toArray();r+=n.length;for(let t=n.length-1;0<=t;t--)await this._unconfirm(n[t])}catch(t){throw await e.end(),t}}this.logger.info("Rolled back %d AccountDB transactions.",r)}async addBlock(t,e){const r=await this.txLock.lock();try{return await this._addBlock(t,e)}finally{r()}}async _addBlock(t,e){var r=dt.fromEntry(t);let i=0;if(r.height<this.curHeight)this.logger.warning("AccountDB is connecting low blocks (%d).",r.height);else{if(r.height===this.curHeight)this.logger.warning("Already saw AccountDB block (%d).",r.height);else if(r.height!==this.curHeight+1)throw new Error(`WDB(addBlock): Bad disconnection (height mismatch, tip ${r.height} while state ${this.curHeight})`);if(await this.syncState(r),!(this.options.checkpoints&&r.height<=this.network.lastCheckpoint)){for(const t of e)await this._insert(t,r)&&i++;0<i&&this.logger.info("Connected AccountDB block %s (tx=%d).",C.revHex(r.hash),i)}}return i}async removeBlock(t,e){const r=await this.txLock.lock();try{return await this._removeBlock(t,e)}finally{r()}}async _removeBlock(t,e){if((t=dt.fromEntry(t)).height>this.curHeight)return this.logger.warning("AccountDB is disconnecting high blocks (%d).",t.height),0;if(t.height!==this.curHeight)throw new Error(`WDB(removeBlock): Bad disconnection (height mismatch, tip ${t.height} / ${C.revHex(t.hash)} while state ${this.curHeight})`);var r=await this.getBlock(t.height-1);if(!r)throw new Error(`WDB(removeBlock): Bad disconnection (no previous block of ${t.height} / ${C.revHex(t.hash)}).`);var i=await this.getBlockMap(t.height);if(i){for(let t=e.length-1;0<=t;t--){var s=e[t];await this._unconfirm(s,i)}this.logger.warning("Disconnected wallet block %s (tx=%d).",C.revHex(t.hash),i.txs.size)}return await this.syncState(r),i?i.txs.size:0}async rescanBlock(t,e){if(this.rescanning){const r=await this.scanLock.lock();try{await this._addBlock(t,e)}catch(t){throw this.emit("error",t),t}finally{r()}}else this.logger.warning("Unsolicited rescan block: %s.",t.height)}async addTX(t,e,r){const i=await this.txLock.lock();try{return await this._insert(t,e,r)}finally{i()}}listNotify(t){return this.NotifyList.deletes([["h","<",this.curHeight-12]]),this.NotifyList.query(t)}listContact(t,e,r){return this.$contacts.query(t,e,r)}async setCp(t){await this.batchPut(u.txdb.cp(t.cid),t.toRaw())}async delCp(t){await this.batchDel(u.txdb.cp(t))}async delVp(t){let e=this.db.batch();e.del(u.txdb.VP(t.pid)),await e.write()}async setVp(t,e){let r=this.db.batch();r.put(u.txdb.VP(t.pid),t.toRaw()),await r.write()}async getVp(t){return(t=await this.db.get(u.txdb.VP(t)))?rt.fromRaw(t):null}async getVpByAddress(t){return{list:[],count:0}}async getVpByOid(t){return{list:[],count:0}}async loadVpList(){return this.db.values({gte:u.txdb.VP(N.ZERO_CID,"hex"),lte:u.txdb.VP(N.MAX_CID,"hex"),parse:t=>rt.fromRaw(t)})}async saveContact(t){let e=this.db.batch();e.put(u.txdb.CT(t.getAddress()),t.toRaw()),await e.write()}async loadContact(t){var e;for(e of await this.db.values({gte:u.txdb.CT(N.ZERO_HASH160_HEX),lte:u.txdb.CT(N.MAX_HASH160_HEX),parse:t=>R.fromRaw(t,this)}))e.sender&&(e.sender.wallet=await this.get(e.sender.wid)),this.$contacts.set(e.address,e)}async delHtlc(t){if((t=new M(t)).id){this.htlcList.delete(t.id),this.htlcList.delAccount(t);let e=this.db.batch();e.del(u.txdb.VH(t.shash,t.sidx)),await e.write()}}async setSuggest(t){let e=new M(t);this.htlcList.set(e.id,e);var[t,r]=await this.getAccountByAddress(e.aa),[t,r]=(t&&this.htlcList.setAccount(e,t,r),await this.getAccountByAddress(e.ba));t&&this.htlcList.setAccount(e,t,r);let i=this.db.batch();i.put(u.txdb.VH(e.shash,e.sidx),e.toRaw()),await i.write()}async setAssent(t){let e=new M(t);this.htlcList.set(e.id,e);var[t,r]=await this.getAccountByAddress(e.ab),[t,r]=(t&&this.htlcList.setAccount(e,t,r),await this.getAccountByAddress(e.bb));t&&this.htlcList.setAccount(e,t,r);let i=this.db.batch();i.put(u.txdb.VH(e.shash,e.sidx),e.toRaw()),await i.write()}async loadHtlcList(){return this.db.values({gte:u.txdb.VH(N.ZERO_CID,0),lte:u.txdb.VH(N.MAX_CID,4294967295),parse:t=>M.fromRaw(t)})}async delComment(t){if((t=new q(t)).id){this.commentList.delete(t.id),this.commentList.delAccount(t);let e=this.db.batch();e.del(u.txdb.VC(t.shash,t.sidx)),await e.write()}}async setComment(t){let e=new q(t);this.commentList.set(e.id,e);var[t,r]=await this.getAccountByAddress(e.bob);t&&(this.commentList.setAccount(e,t,r),this.emit("comm.comment",e));let i=this.db.batch();i.put(u.txdb.VC(e.shash,e.sidx),e.toRaw()),await i.write()}async loadCommentList(){return this.db.values({gte:u.txdb.VC(N.ZERO_CID,0),lte:u.txdb.VC(N.MAX_CID,4294967295),parse:t=>q.fromRaw(t)})}async setStockRecord(t){let e=this.db.batch();switch(e.put(t.itemNo,t.toRaw()),t.type){case G.RecordType.Offer:break;case G.RecordType.Bid:{let r=this.accountList.getStockAccount(t.cid,t.addr);if(!r)break;r.stock.sum=t.sum,r.stock.price=t.price,r.stock.period=this.curHeight+10*m.BLOCK_DAY,r.seq=t.seq,e.put(r.getItemNo(),r.toRaw());break}case G.RecordType.Auction:{let i=this.accountList.getStockAccount(t.cid,t.addr);i?(r=i.sum+t.sum,i.price=(t.sum*t.price+i.sum*i.price)/r|0,i.sum=r,i.seq=t.seq):((i=new st(t.cid,t.addr,t.sum,t.price,0)).seq=t.seq,this.accountList.setStockAccount(i)),e.put(i.getItemNo(),i.toRaw());let s=this.accountList.getStockAccount(t.cid,t.to);if(!s)break;var r=s.sum-t.sum;s.sum=r,s.stock.sum-=t.sum,e.put(s.getItemNo(),s.toRaw());break}case G.RecordType.Purchase:{let i=this.accountList.getStockAccount(t.cid,t.addr);i?(r=i.sum+t.sum,i.price=(t.sum*t.price+i.sum*i.price)/r,i.sum=r,i.seq=t.seq):((i=new st(t.cid,t.addr,t.sum,t.price,0)).seq=t.seq,this.accountList.setStockAccount(i)),e.put(i.getItemNo(),i.toRaw());break}case G.RecordType.Send:{let i=this.accountList.getStockAccount(t.cid,t.addr);if(i){i.sum-=t.sum,i.seq=t.seq;let s=this.accountList.getStockAccount(t.cid,t.to);s||(s=new st(t.cid,t.to,0,0,0),this.accountList.setStockAccount(s)),r=s.sum+t.sum,s.price=(t.sum*i.price+s.sum*s.price)/r,s.sum=r,e.put(i.getItemNo(),i.toRaw()),e.put(s.getItemNo(),s.toRaw())}break}case G.RecordType.Bonus:case G.RecordType.Ads:}await e.write()}async unsetStockRecord(t){let e=this.db.batch();switch(e.del(t.itemNo),t.type){case G.RecordType.Offer:break;case G.RecordType.Bid:{let r=this.accountList.getStockAccount(t.cid,t.addr);if(!r)break;r.stock.sum=0,r.stock.price=0,r.stock.period=0,r.seq=t.seq-1,e.put(r.getItemNo(),r.toRaw());break}case G.RecordType.Auction:{let i=this.accountList.getStockAccount(t.cid,t.addr);if(!i)break;var r=i.sum-t.sum;i.price=(i.sum*i.price-t.sum*t.price)/r|0,i.sum=r,i.seq=t.seq-1,e.put(i.getItemNo(),i.toRaw());let s=this.accountList.getStockAccount(t.cid,t.to);if(!s)break;r=s.sum+t.sum,s.sum=r,s.stock.sum+=t.sum,e.put(s.getItemNo(),s.toRaw());break}case G.RecordType.Purchase:{let i=this.accountList.getStockAccount(t.cid,t.addr);i&&(r=i.sum-t.sum,i.price=(i.sum*i.price-t.sum*t.price)/r,i.sum=r,i.seq=t.seq-1,e.put(i.getItemNo(),i.toRaw()));break}case G.RecordType.Send:{let i=this.accountList.getStockAccount(t.cid,t.addr);if(i){i.sum+=t.sum,i.seq=t.seq-1,e.put(i.getItemNo(),i.toRaw());let s=this.accountList.getStockAccount(t.cid,t.to);s&&(r=s.sum-t.sum,s.price=(s.sum*s.price-t.sum*i.price)/r|0,s.sum=r,e.put(s.getItemNo(),s.toRaw()))}break}case G.RecordType.Bonus:}await e.write()}async getStockRecordById(t){return(t=await this.db.get(t))?G.fromRaw(t):null}async verifyClsTx(t,e){if(!this.spv){let r=await k.FactoryOfContract({env:this,block:e,tx:t});if(1!=(e=await r.verify()))throw new g(t,S(e),"bad-contract-verify",100)}return!0}async getStockRecord(t,e,r){let i=6,s=N.ZERO_CID_BUF,n=N.MAX_CID_BUF,a=0;return t&&(i=t,e&&(s=e,n=e,a=r||0)),t=new I,(await this.db.values({gte:G.itemNo(i,s,a,N.NULL_HASH,0),lte:G.itemNo(i,n,4294967295,N.HIGH_HASH,4294967295),parse:G.fromRaw})).reduce((t,e)=>(t.set(e.itemNo,e),t),t),t}async getStockRecordByCid(t,e){let r=new I;for(var i of Object.keys(G.RecordType))i=await this.getStockRecord(G.RecordType[i],t,e),r.merge(i);return r}async getStockAccountList(t){var e;return t?(e=st.SN(t,N.NULL_HASH),t=st.SN(t,N.HIGH_HASH),this.db.values({gte:e,lte:t,parse:st.fromRaw})):this.db.values({gte:st.SN(N.ZERO_CID_BUF,N.NULL_HASH),lte:st.SN(N.MAX_CID_BUF,N.HIGH_HASH),parse:st.fromRaw})}async delEr(t){let e=this.db.batch();e.del(u.txdb.ER(t.erid)),e.del(u.txdb.ERR(t.witness,t.erid)),await e.write()}async setEr(t,e){e&&t.source&&(i=v.fromWitnessPubkeyhash(l.hash160(Buffer.from(t.source.pubkey,"hex")),this.network),[i,e]=await this.getAccountByAddress(i,e),t.wid=i,t.account=e);let r=this.db.batch();var i=u.txdb.ERR(t.witness,t.erid);r.put(i,t.toRaw()),r.put(u.txdb.ER(t.erid),i),await r.write()}async getEr(t){return(t=(t=await this.db.get(u.txdb.ER(t)))&&await this.db.get(t))?at.fromRaw(t):null}async byPubkey(t,e,r=!1){let i=new I;var s;t=await this.db.values({gte:u.txdb.ERR(t,N.ZERO_CID),lte:u.txdb.ERR(t,N.MAX_CID),parse:t=>at.fromRaw(t)});let n=[],a=new Map;if(r){for(var o of t)(!a.get(o.source.cluster)||o.startHeight>a.get(o.source.cluster).startHeight)&&a.set(o.source.cluster,await this.caVerifyObj(o));n=a.values()}else n=t;for(s of n)i.set(s.erid,s);return i.query(e)}async caVerifyObj(t){var e={verify:!1};if(!t||t.validHeight<=this.curHeight)return e;var r=await this.erAbList.getErAb(t.erid);return r&&r.abolishHeight<this.curHeight?e:(r=gt.fromPublic(Buffer.from(t.witness,"hex"),this.network.type),t.verify(r)?(t.verify=!0,0<(r=this.cpList.query([["pubKey",t.witness]])).list.length&&(t.cpid=r.list[0].cid),t):e)}async delErAbolish(t){let e=this.db.batch();e.del(u.txdb.ERA(t.erid)),await e.write()}async setErAbolish(t){let e=this.db.batch();e.put(u.txdb.ERA(t.erid),t.toRaw()),await e.write()}async getErAbolish(t){return(t=await this.db.get(u.txdb.ERA(t)))?Y.fromRaw(t):null}loadErAbolishList(){return this.db.values({gte:u.txdb.ERA(N.ZERO_CID),lte:u.txdb.ERA(N.MAX_CID),parse:t=>Y.fromRaw(t)})}async delAudit(t){let e=this.db.batch();e.del(u.txdb.AU(t.erid)),await e.write()}async setAudit(t){let e=this.db.batch();e.put(u.txdb.AU(t.erid),t.toRaw()),await e.write()}async getAudit(t){return(t=await this.db.get(u.txdb.AU(t)))?ct.fromRaw(t):null}async loadAuditList(){return this.db.values({gte:u.txdb.AU(N.NULL_HASH),lte:u.txdb.AU(N.HIGH_HASH),parse:t=>ct.fromRaw(t)})}async delX509Cert(t){let e=this.db.batch();e.del(u.txdb.SX(t.witness,t.certSq,!0)),await e.write()}async setX509Cert(t){let e=this.db.batch();e.put(u.txdb.SX(t.witness,t.certSq,!0),t.toRaw()),await e.write()}loadX509CertList(){return this.db.values({gte:u.txdb.SX(N.ZERO_CID_BUF,N.ZERO_U32_NUM,!0),lte:u.txdb.SX(N.MAX_CID_BUF,N.MAX_U32_NUM,!0),parse:t=>J.fromRaw(t)})}async delX509Abolish(t){let e=this.db.batch();e.del(u.txdb.SX(t.witness,t.secertSqq,!1)),await e.write()}async setX509Abolish(t){let e=this.db.batch();e.put(u.txdb.SX(t.witness,t.certSq,!1),t.toRaw()),await e.write()}loadX509AbolishList(){return this.db.values({gte:u.txdb.SX(N.ZERO_CID_BUF,N.ZERO_U32_NUM,!1),lte:u.txdb.SX(N.MAX_CID_BUF,N.MAX_U32_NUM,!1),parse:t=>Q.fromRaw(t)})}async batchPut(t,e){const r=this.db.batch();r.put(t,e),await r.write()}async batchDel(t){const e=this.db.batch();e.del(t),await e.write()}async _insert(t,e,r){s(!t.mutable,"WDB: Cannot add mutable TX.");let i=await this.getWalletsByTX(t);if(i){this.logger.info("Incoming transaction for %d wallets in AccountDB (%s).",i.size,t.txid()),!e||this.state.marked||(this.logger.info("Marking AccountDB start block at %s (%d).",C.revHex(e.hash),e.height),await this.resetState(e,!0));let n=!1;for(const a of i){const i=await this.get(a);s(i),await i.add(t,e,r)&&(this.logger.info("Added transaction to wallet in AccountDB: %s (%d).",i.id,a),n=!0)}n||(i=null)}try{let r=await k.FactoryOfContract({env:this,block:e,tx:t});e?await r.confirm():await r.insert()}catch(r){e?this.logger.error("TX(%s) Smart Contract Confirm Error: %s",t.txid(),r.message):this.logger.error("TX(%s) Smart Contract Insert Error: %s",t.txid(),r.message)}return i}async _unconfirm(t,e){if(e)try{let r=await k.FactoryOfContract({env:this,block:e,tx:t});await r.unconfirm()}catch(i){this.logger.error("TX(%s) Smart Contract Unconfirm Error: %s",t.txid(),i.message)}let r,i=null;if(r=t.wids?(i=t.wids,t.hash):(i=await this.getWalletsByTX(t),t.hash("hex")),!i)return null;for(const t of i){const e=await this.get(t);s(e),await e.unconfirm(r)}}async resetChain(t){const e=await this.txLock.lock();try{return await this._resetChain(t)}finally{e()}}async _resetChain(t){if(t.height>this.curHeight)throw new Error(`WDB: Bad reset height ${t.height} while curHeight `+this.curHeight);var e;for(e of(await this.rollback(t.height)||await this.scan(),await this.getWallets())){const r=await this.get(e);for(const e of await r.getPending())try{await r.abandon(e.hash)}catch(t){}await r.resetBalance()}}async saveMSTrans(t){const e=await this.writeLock.lock();try{return await this._saveMSTrans(t)}finally{e()}}async _saveMSTrans(t){const e=this.db.batch();e.put(h.ms(v.getHash(t.addr,"hex"),t.txid),Buffer.from(JSON.stringify(t))),await e.write()}async listMSTrans(t){return t=v.getHash(t,"hex"),this.db.values({gte:h.ms(t,N.NULL_HASH),lte:h.ms(t,N.HIGH_HASH),parse:t=>JSON.parse(t.toString())})}async delMSTrans(t,e){const r=await this.writeLock.lock();try{return await this._delMSTrans(t,e)}finally{r()}}async _delMSTrans(t,e){t=v.getHash(t,"hex");const r=this.db.batch();r.del(h.ms(t,e)),await r.write()}}xt.layout=h,t.exports=xt},function(t,e,r){"use strict";
859
+ */const i=r(8),s=r(0),n=r(73),a=r(122),o=r(161),c=r(618),u=r(96),h=u.walletdb,l=r(6),p=r(162),d=r(127),f=r(171),m=r(7),g=r(38).VerifyError,y=r(46),v=r(12);r(19);const b=r(60),w=r(200),x=r(69),k=r(43),{getVerifyMsg:S,BlockFinalType:E,ContractEnvType:_}=r(5),A=r(163),R=r(620),I=r(28);var j=r(72);const C=r(1),P=r(120).sortWithSeq,O=r(35),T=r(201),F=r(65),B=r(102),N=r(3),D=N.U32,L=r(347),H=r(348),z=r(349),M=z.vpItem,U=r(621),q=U.vpItem,V=r(85),K=r(622),W=V.cpItem,G=V.stockItem,$=r(158),Y=$.ErAbolishItem,X=r(159),J=X.X509Cert,Z=r(160),Q=Z.X509Abolish,tt=r(37).broadcast,et=r(134),rt=et.vpItem,it=r(236),st=it.stockAccount,nt=r(157),at=nt.ErItem,ot=r(323),ct=ot.AuditItem,ut=r(320),ht=r(111),lt=r(623),pt=r(321),dt=r(123),ft=r(624),mt=r(226),gt=r(32),yt=r(36),vt=r(59),bt=r(78).errors,wt=r(77);class xt extends j{constructor(t){super(),this.readyLoad=!1,this.options=new c(t),this.network=this.options.network,this.logger=this.options.logger.context("wallet"),this.workers=this.options.workers,this.keys={hmacSalt:N.DefaultChainCode},t.keys&&t.keys.hmacSalt&&(s(Buffer.isBuffer(t.keys.hmacSalt)),this.keys.hmacSalt=t.keys.hmacSalt),this.client=this.options.client,this.client&&(this.client.wdb=this),this.jsonp=this.options.jsonp,this.jsonp&&(this.jsonp.wdb=this),this.spv=this.options.spv,this.feeRate=this.options.feeRate,this.db=f(this.options),this.rpc=new L(this),this.primary=null,this.state=new lt,this.wallets=new Map,this.depth=0,this.rescanning=!1,this.bound=!1,this.newRecord=!0,this.readLock=new T,this.writeLock=new O,this.txLock=new O,this.scanLock=new O,this.widCache=new F(1e4),this.pathMapCache=new F(1e5),this.filter=new B,this.middleHashMem=new Set,this.middleHashChain=new Set,this.autoTaskMgr=new A(this),this.transactionList=new H(this),this.htlcList=new z(this),this.commentList=new U(this),this.NotifyList=new I,this.propList=new et(this),this.accountList=new it(this),this.$contacts=new I,this.cpList=new V(this),this.cpMemList=new V(this),this.accountCoinList=new K(this),this.auditList=new ot(this),this.erList=new nt(this),this.erAbList=new $(this),this.x509CertList=new X(this),this.x509AbolishList=new Z(this),this.hmacConnection=[],this._init()}async logAudit(t){t.height=this.curHeight,t.time=C.now(),t.erid=l.sha256(C.stringify(t)).toString("hex"),t=new ct(t),await this.auditList.setAudit(t)}async getAccountByAddress(t,e){if(t){let i=null;if(i=e?await this.getWalletsByTX(e):await this.getWallets())for(const e of i){const i=await this.get(e);if(i){var r=await i.getPath(t);if(r)return[i.wid,r.name,i.id]}}}return[0,"",""]}_init(){let t=1e6,e=-1;this.spv&&(t=2e4,e=B.flags.ALL),this.filter=B.fromRate(t,.001,e)}async getCpSnap(){return{}}get mode(){return _.Wallet}async getTXFromAll(t){return this.getTXFromDb(t)}async checkNewRecord(){var t={createIfMissing:this.db.options.createIfMissing,errorIfExists:this.db.options.errorIfExists};this.db.options.createIfMissing=!1,this.db.options.errorIfExists=!0;try{await this.db.open();var e=await this.db.checkVersion(h,6);this.newRecord="new"==e}catch(t){if(-1!=t.message.indexOf("does not exist (create_if_missing is false)"))this.newRecord=!0;else{if(-1==t.message.indexOf("exists (error_if_exists is true)"))throw t;this.newRecord=!1}}try{await this.db.close()}catch(t){}this.db.options.createIfMissing=t.createIfMissing,this.db.options.errorIfExists=t.errorIfExists}async isNewRecord(){return await this.checkNewRecord(),this.newRecord}setmnemonic(t){if(this.options.mnemonic=this.options.mnemonic||{},t.bits)this.options.mnemonic={bits:t.bits};else if(t.entropy)this.options.mnemonic={entropy:Buffer.from(t.entropy,"hex")};else if(t.phrase){var e=this.testmnemonic(t.phrase);if(0!=e.code)throw e.msg;this.options.mnemonic={phrase:t.phrase}}t.passphrase&&(this.options.mnemonic.passphrase=t.passphrase),t.language&&(this.options.mnemonic.language=t.language)}testmnemonic(t){try{return new w(t),{code:0}}catch(t){return{code:-1,msg:t.message}}}async getContracts(t){let e=await this.db.values({gte:u.txdb.tx(N.NULL_HASH),lte:u.txdb.tx(N.HIGH_HASH),parse:t=>C.parseJson(t.toString())});return t?e.filter(e=>e.srcact==t||e.dstact==t):e}isFull(){return this.spv||this.synced||!1}async _open(t){}async handleNotify(t,e=!1){if(!e){let r=t.body.content;if("string"==typeof r)try{r=JSON.parse(t.body.content)}catch(e){return}if("object"==typeof r&&"secret"===r.type){let e={contact:t.body.src,messenger:t.body.dst};r.init&&(e.init=Buffer.from(r.init,"hex")),r.packet&&(e.packet=Buffer.from(r.packet)),await this.handleSecret(e)}}}async handleSecret(t){if(t.contact&&t.messenger&&t.contact!=t.messenger){try{v.fromString(t.contact,this.network.type),v.fromString(t.messenger,this.network.type)}catch(t){return}let e=await this.ensureContact(t);e&&await e.ensureMessenger(t).answer(t)}}async scanContact(t,e=-1){var r=async t=>{var e;t.witness&&"witnesspubkeyhash"==t.getType()&&(e=t.witness.getPubkeyhashInput()[1],t=v.fromWitness(t.witness).toString(),e&&t&&await this.ensureContact({contact:t,publicKey:e}))};if(0<=e&&e<t.inputs.length)await r(t.inputs[e]);else for(var i of t.inputs)await r(i)}async ensureContact(t){if(!t.contact||t.contact==t.messenger)return null;try{v.fromString(t.contact,this.network.type),t.messenger&&v.fromString(t.messenger,this.network.type)}catch(t){return null}t.network=this.network.type,this.$contacts.get(t.contact)||this.$contacts.set(t.contact,new R(t));let e=this.$contacts.get(t.contact);if(t.messenger){let i=e.ensureMessenger(t);if(!i.wallet){var[t,r]=await this.getAccountByAddress(i.address);if(!(t=await this.get(t)))return;i.wallet=t,i.account=r}}return e}getCps(){return this.db.values({gte:u.txdb.cp(N.ZERO_CID,"hex"),lte:u.txdb.cp(N.MAX_CID,"hex"),parse:t=>W.fromRaw(t)})}async _close(){await this.disconnect(),this.http&&this.options.listen&&await this.http.close();for(const t of this.wallets.values())await t.destroy();await this.db.close(),this.options.listen&&await this.logger.close()}async destroy(){await this.db.destroy(),this.widCache.reset(),this.pathMapCache.reset()}async load(t){if(this.readyLoad){const e=await this.txLock.lock();try{await this.init(t),await this.watch(),await this.sync()}finally{e()}setTimeout(()=>{this.resend()},5e3)}}bind(){!this.client||this.bound||(this.bound=!0,this.client.hook("htlcassent.cancel",t=>{this.setAssent(t),this.emit("htlcassent.cancel",t)}),this.client.hook("htlcassent.deal",t=>{this.setAssent(t),this.emit("htlcassent.deal",t)}),this.client.hook("htlcassent.receive",t=>{this.setAssent(t),this.emit("htlcassent.receive",t)}),this.client.hook("htlcsuggest.cancel",t=>{this.setSuggest(t),this.emit("htlcsuggest.cancel",t)}),this.client.hook("htlcsuggest.deal",t=>{this.setSuggest(t),this.emit("htlcsuggest.deal",t)}),this.client.hook("htlcsuggest.receive",t=>{this.setSuggest(t),this.emit("htlcsuggest.receive",t)}),this.on("mssendpubk/receive",async t=>{let e=await this.get(t.addr);if(!e){e=await this.ensure({id:t.addr,type:"multisig",m:t.m,n:t.n,witness:!0});var[r,i]=await this.getAccountByAddress(t.addr);let s=await this.get(r);s&&await s.send({subtractFee:!1,sort:!1,outputs:[{address:t.contract,value:1e4}],comment:JSON.stringify({oper:"scrun",params:{oper:"pubk",addr:t.addr,puba:e.account.accountKey}})},i)}if(e.account.keys.length<e.account.n-1){var s;for(s of t.data.split(","))try{await e.addSharedKey(s)}catch(s){}if(e.account.keys.length==e.account.n-1){var[r,i]=await this.getAccountByAddress(t.addr);let s=await this.get(r);s&&await s.send({subtractFee:!1,sort:!1,outputs:[{address:t.contract,value:1e4}],comment:JSON.stringify({oper:"scrun",params:{oper:"puba",addr:t.addr,puba:e.account.receive.getAddress().toString()}})},i)}}}),this.on("mssendtx/receive",async t=>{let e=await this.get(t.addr);if(e&&e.account.type==o.types.MULTISIG){const r=b.fromRaw(t.data,"hex");r.view=await e.getCoinView(r),r.isSigned()||(t.txid=r.txid(),await this.saveMSTrans(t))}}),this.client.hook("onConnect",async()=>{await this.load()}),this.client.hook("error",t=>{this.emit("error",t)}),this.client.hook("block.connect",async(t,e)=>{try{await this.addBlock(t,e)}catch(t){this.emit("error",t)}}),this.client.hook("block.disconnect",async(t,e)=>{try{await this.removeBlock(t,e)}catch(t){this.emit("error",t)}}),this.client.hook("chain.full",()=>{this.synced=!0}),this.client.hook("block.rescan",async(t,e)=>{try{await this.rescanBlock(t,e)}catch(t){this.emit("error",t)}}),this.client.hook("tx",async(t,e,r)=>{try{await this.addTX(t,null,r)}catch(t){this.emit("error",t)}}),this.client.hook("entry.remove",async(t,e)=>{try{if(e){var r=t.tx.hash("hex"),i=await this.getWalletsByTX(t.tx);if(i)for(const e of i){const i=await this.get(e);s(i),await i.remove(r),(await k.FactoryOfContract({tx:t.tx,env:this})).erase()}}}catch(e){this.emit("error",e)}}),this.client.hook("chain.reset",async t=>{try{await this.resetChain(t)}catch(t){this.emit("error",t)}}),this.jsonp&&this.jsonp.hook("error",t=>{this.emit("error",t)}))}async disconnect(){this.client&&await this.client._close(),this.jsonp&&await this.jsonp._close()}async flushCP(t,e=!1){this.client&&(t=t||[],e||(t=this.cpList.excludeCids(t),e=e||0<t.length),e&&await this.client.execute("cp.remoteQuery",[[["cid","include",t]]]))}async watch(){let t=this.db.iterator({gte:h.p(N.NULL_HASH),lte:h.p(N.HIGH_HASH)}),e=0,r=0;for(;;){var i=await t.next();if(!i)break;try{var s=h.pp(i.key);this.filter.add(s,"hex")}catch(e){throw await t.end(),e}e++}for(t=this.db.iterator({gte:h.o(N.NULL_HASH,0),lte:h.o(N.HIGH_HASH,4294967295)});;){var n=await t.next();if(!n)break;try{var[a,o]=h.oo(n.key);var c=new y(a,o).toRaw();this.filter.add(c)}catch(e){throw await t.end(),e}r++}this.logger.info("Filter: Added %d hashes to AccountDB filter.",e),this.logger.info("Filter: Added %d outpoints to AccountDB filter.",r),await this.setFilter()}async sync(){if(this.client){let e,r=this.curHeight;for(;0<=r;){var t=await this.getBlock(r);if(!t)break;if(e=await this.client.getEntry(t.hash))break;r--}e||(r=this.state.startHeight,(e=await this.client.getEntry(this.state.startHash))||(r=0)),await this.cpList.loadHistory(),await this.cpMemList.loadHistory(),await this.propList.loadHistory(),await this.htlcList.loadHistory(),await this.commentList.loadHistory(),await this.accountList.loadHistory(),await this.transactionList.loadHistory(),await this.loadContact(),await this.erList.loadHistory(),await this.auditList.loadHistory(),await this.erAbList.loadHistory(),await this.x509CertList.loadHistory(),await this.x509AbolishList.loadHistory(),await this.accountCoinList.loadHistory(),await this.scan(r,!1)}}async scan(t,e=!0){if(this.client){null==t&&(t=this.state.startHeight),s(t>>>0===t,"WDB: Must pass in a height.");var r=this.curHeight;if(!await this.rollback(t,e)||0===t){this.logger.info("AccountDB is scanning %d blocks.",r-t+1),e=await this.getTip();try{this.rescanning=!0,await this.client.rescan(e.hash)}finally{this.rescanning=!1}}}}async rescan(t){const e=await this.txLock.lock();try{return await this.scan(t,!1)}finally{e()}}async send(t){if(this.client)return this.client.send(t);this.emit("send",t)}async getTX(t){for(const r of this.wallets.values()){var e=await r.getTX(t);if(e)return e.tx}return null}async getTXFromDb(t){for(const r of this.wallets.values()){var e=await r.getTX(t);if(e)return e.tx}return null}async getExtendTX(t){for(const r of this.wallets.values()){var e=await r.getTX(t);if(e)return e}return null}async removeTX(t){this.client?await this.client.removeTX(t):this.emit("remove",t)}async estimateFee(t){return 0<this.feeRate?this.feeRate:!this.client||(t=await this.client.estimateFee(t))<this.network.feeRate?this.network.feeRate:t>this.network.maxFeeRate?this.network.maxFeeRate:t}setFilter(){return this.client?this.client.setFilter(this.filter):(this.emit("filter.set",this.filter),Promise.resolve())}addFilter(t){return this.client?this.client.addFilter(t):(this.emit("filter.add",t),Promise.resolve())}resetFilter(){return this.client?this.client.resetFilter():(this.emit("filter.reset"),Promise.resolve())}backup(t){return this.db.backup(t)}async wipe(){this.logger.warning("Wiping AccountDB TXDB..."),this.logger.warning("I hope you know what you're doing.");const t=this.db.iterator({gte:Buffer.from([0]),lte:Buffer.from([255])}),e=this.db.batch();let r=0;for(;;){var i=await t.next();if(!i)break;try{switch(i.key[0]){case 98:case 99:case 101:case 116:case 111:case 104:case 82:e.del(i.key),r++}}catch(e){throw await t.end(),e}}this.logger.warning("Wiped %d txdb records.",r),await e.write()}async getDepth(){const t=this.db.iterator({gte:h.w(0),lte:h.w(4294967295),reverse:!0,limit:1});var e=await t.next();return e?(await t.end(),h.ww(e.key)+1):1}start(t){return s(!t.current,"WDB: Batch already started."),t.current=this.db.batch(),t.accountCache.start(),t.pathCache.start(),t.current}drop(t){const e=this.batch(t);t.current=null,t.accountCache.drop(),t.pathCache.drop(),e.clear()}clear(t){const e=this.batch(t);t.accountCache.clear(),t.pathCache.clear(),e.clear()}batch(t){return s(t.current,"WDB: Batch does not exist."),t.current}async commit(t){const e=this.batch(t);try{await e.write()}catch(t){throw this.drop(),t}t.current=null,t.accountCache.commit(),t.pathCache.commit()}testFilter(t){return this.filter.test(t,"hex")}addHash(t){return this.filter.add(t,"hex"),this.addFilter(t)}addOutpoint(t,e){const r=new y(t,e);this.filter.add(r.toRaw())}dump(){return this.db.dump()}register(t){s(!this.wallets.has(t.wid)),this.wallets.set(t.wid,t)}unregister(t){s(this.wallets.has(t.wid)),this.wallets.delete(t.wid)}async getWalletID(t){if(!t)return null;if("number"==typeof t)return t;var e=this.widCache.get(t);if(e)return e;const r=await this.db.get(h.l(t));return r?(e=r.readUInt32LE(0,!0),this.widCache.set(t,e),e):null}async get(t){if(!(t=await this.getWalletID(t)))return null;const e=await this.readLock.lock(t);try{return await this._get(t)}finally{e()}}async _get(t){var e=this.wallets.get(t);if(e)return e;if(!(e=await this.db.get(h.w(t))))return null;const r=a.fromRaw(this,e);return await r.open(),this.register(r),r}async loadBackup(t){if(vt.unsupported)throw new wt(bt.INTERNAL_ERROR,"FS not available.");let e=await this.get("primary");const r=await vt.readFile(t,"utf8");var i;for(i of r.split(/\n+/))if(0!==(i=i.trim()).length&&!/^\s*#/.test(i)){const t=i.split(/\s+/);if(t.length<4)throw new wt(bt.DESERIALIZATION_ERROR,"Malformed wallet Data File.");switch(t[0]){case"W":var n=Buffer.from(t[1],"base64");n=a.fromRaw(e.db,n);if(e.wid!=n.wid)throw new wt(bt.DESERIALIZATION_ERROR,"Malformed wallet Key");await this.replace(n),e=await this.get("primary"),this.logger.info("Import Wallet %s(%s)",e.id,e.wid);break;case"C":{n=Buffer.from(t[1],"base64");const r=o.fromRaw(e.db,n);r.wallet=e,r.wid=e.wid,r.id=e.id,r.initialized=!0,r.watchOnly=e.watchOnly,r.receive=r.deriveReceive(r.receiveDepth-1),r.change=r.deriveChange(r.changeDepth-1),r.witness&&(r.nested=r.deriveNested(r.nestedDepth-1));let i=e.master.key.deriveAccount(44,r.accountIndex);i.publicKey.toString("hex")!==r.accountKey.publicKey.toString("hex")&&s(i.publicKey.toString("hex")==r.accountKey.publicKey.toString("hex")),await e.saveAccount(r),this.logger.info("Import Account %s(%s)",r.name,r.accountIndex);break}case"A":{var c=parseInt(t[5]),u=parseInt(t[7]),h=parseInt(t[9]),l=t[11].trim();let r=await e.deriveKey(c,u,h),i=await e.deriveKey(c,u,h,e.master);r.getAddress("string")!==i.getAddress("string")&&s(r.getAddress("string")==i.getAddress("string")),r.getAddress("string")!==l&&s(r.getAddress("string")==l),this.logger.info("Import Address %s %s %s %s",c,u,h,r.getAddress("string"));break}}}return e.accountCache.reset(),e}save(t){var e=t.wid,r=t.id;const i=this.batch(t);this.widCache.set(r,e),i.put(h.w(e),t.toRaw()),i.put(h.l(r),D(e))}async rename(t,e){const r=await this.writeLock.lock();try{return await this._rename(t,e)}finally{r()}}async _rename(t,e){var r=t.id;if(!n.isName(e))throw new Error("WDB: Bad wallet ID.");if(await this.has(e))throw new Error("WDB: ID not available.");this.start(t).del(h.l(r)),t.id=e,this.save(t),await this.commit(t),this.widCache.remove(r);for(const r of t.pathCache.values())r.id=e}async replace(t){const e=await this.writeLock.lock();try{return await this._replace(t)}finally{e()}}async _replace(t){const e=this.start(t);e.del(h.l(t.id)),e.del(h.w(t.wid)),this.save(t),await this.commit(t),this.widCache.remove(t.id),this.wallets.delete(t.wid)}renameAccount(t,e){var r=t.wallet;this.batch(r).del(h.i(t.wid,t.name)),t.name=e,this.saveAccount(t)}async auth(t,e){if("string"==typeof e){if(!C.isHex256(e))throw new Error("WDB Authentication: Invalid Token.");e=Buffer.from(e,"hex")}t=x.getHmac(t.toString(),this.keys.hmacSalt);const r=i.createHmac("sha256",t.random);if(t=Buffer.from(r.update(t.token).digest("hex"),"hex"),!p(e,t))throw new Error("WDB Authentication: CRC Error.")}async create(t){const e=await this.writeLock.lock();t=t||{};try{return await this._create(t)}finally{e()}}async _create(t){if(await this.has(t.id))throw new Error("WDB: Wallet already exists.");"string"==typeof t.mnemonic&&(t.mnemonic={phrase:t.mnemonic}),t.mnemonic=t.mnemonic||{},!t.mnemonic.language&&this.options.mnemonic&&this.options.mnemonic.language&&(t.mnemonic.language=this.options.mnemonic.language);const e=a.fromOptions(this,t);return e.wid=this.depth++,await e.init(t),this.register(e),this.logger.info("Created wallet %s in AccountDB.",e.id),e}async has(t){return null!=await this.getWalletID(t)}async ensure(t){return await this.get(t.id)||this.create(t)}async getAccount(t,e){return(t=await this.db.get(h.a(t,e)))?o.fromRaw(this,t):null}getAccounts(t){return this.db.values({gte:h.n(t,0),lte:h.n(t,4294967295),parse:t=>t.toString("ascii")})}async getAccountIndex(t,e){const r=await this.db.get(h.i(t,e));return r?r.readUInt32LE(0,!0):-1}async getGuider(t){return t=v.fromString(t,this.network.type).getHash("hex"),(t=await this.db.get(h.g(t)))?v.fromRaw(t).toString():null}async setGuider(t,e,r){if(r=v.fromString(r,this.network.type).getHash("hex"),!await this.db.has(h.g(r))){t=v.fromString(t,this.network.type);const i=this.db.batch();i.put(h.g(r),t.toRaw()),i.put(h.gs(t.getHash("hex"),Buffer.from(e,"ascii").toString("hex"),r),null),await i.write()}}async unsetGuider(t,e,r){t=v.fromString(t,this.network.type).getHash("hex"),r=v.fromString(r,this.network.type).getHash("hex");const i=this.db.batch();i.del(h.g(r)),i.del(h.gs(t,Buffer.from(e,"ascii").toString("hex"),r)),await i.write()}async getAccountName(t,e){const r=await this.db.get(h.n(t,e));return r?r.toString("ascii"):null}saveAccount(t){var e=t.wid;const r=t.wallet;var i=t.accountIndex,s=t.name;const n=this.batch(r);n.put(h.a(e,i),t.toRaw()),n.put(h.i(e,s),D(i)),n.put(h.n(e,i),Buffer.from(s,"ascii")),r.accountCache.push(i,t)}hasAccount(t,e){return"number"==typeof t&&"number"==typeof e&&this.db.has(h.a(t,e))}async getPathMap(t){var e=this.pathMapCache.get(t);return e||((e=await this.db.get(h.p(t)))?(e=ft.fromRaw(t,e),this.pathMapCache.set(t,e),e):null)}saveKey(t,e){return this.savePath(t,e.toPath())}async savePath(t,e){var r=t.wid,i=e.hash;const s=this.batch(t);await this.addHash(i);let n=await this.getPathMap(i);(n=n||new ft(i)).add(r)&&(this.pathMapCache.set(i,n),t.pathCache.push(i,e),s.put(h.p(i),n.toRaw()),s.put(h.P(r,i),e.toRaw()),s.put(h.r(r,e.account,i),null))}async getPath(t,e){var r=await this.db.get(h.P(t,e));if(!r)return null;const i=ht.fromRaw(r);return i.wid=t,i.hash=e,i}hasPath(t,e){return this.db.has(h.P(t,e))}getHashes(){return this.db.keys({gte:h.p(N.NULL_HASH),lte:h.p(N.HIGH_HASH),parse:h.pp})}getOutpoints(){return this.db.keys({gte:h.o(N.NULL_HASH,0),lte:h.o(N.HIGH_HASH,4294967295),parse:t=>{var[t,e]=h.oo(t);return new y(t,e)}})}getWalletHashes(t){return this.db.keys({gte:h.P(t,N.NULL_HASH),lte:h.P(t,N.HIGH_HASH),parse:h.Pp})}getAccountHashes(t,e){return this.db.keys({gte:h.r(t,e,N.NULL_HASH),lte:h.r(t,e,N.HIGH_HASH),parse:h.rr})}async getWalletPaths(t){const e=[];for(const i of await this.db.range({gte:h.P(t,N.NULL_HASH),lte:h.P(t,N.HIGH_HASH)})){var r=h.Pp(i.key);const s=ht.fromRaw(i.value);s.hash=r,s.wid=t,e.push(s)}return e}async encryptKeys(t,e){var r,i=t.wid,n=await t.getPaths();const a=this.batch(t);for(r of n)if(r.data){s(!r.encrypted);var o=Buffer.from(r.hash,"hex").slice(0,16);(r=r.clone()).data=d.encipher(r.data,e,o),r.encrypted=!0,t.pathCache.push(r.hash,r),a.put(h.P(i,r.hash),r.toRaw())}}async decryptKeys(t,e){var r,i=t.wid,n=await t.getPaths();const a=this.batch(t);for(r of n)if(r.data){s(r.encrypted);var o=Buffer.from(r.hash,"hex").slice(0,16);(r=r.clone()).data=d.decipher(r.data,e,o),r.encrypted=!1,t.pathCache.push(r.hash,r),a.put(h.P(i,r.hash),r.toRaw())}}async resend(){let t={};var e;for(const e of await this.db.keys({gte:h.w(0),lte:h.w(4294967295)})){var r,i=h.ww(e);!i||(r=await this.resendPending(i))&&Array.isArray(r)&&(t[i]=r)}for(e of Object.keys(t)){let r=await this.get(parseInt(e));if(r)for(const i of t[e]){try{await this.send(i)}catch(t){this.logger.warning("wdb resend:",t.message);try{await r.abandon(i.hash("hex"))}catch(t){this.logger.warning("wdb abandon:",t.message)}}await yt.timeout(50)}}}async resendPending(t){const e=await this.get(t);var r=await this.db.keys({gte:u.txdb.prefix(t,u.txdb.p(N.NULL_HASH)),lte:u.txdb.prefix(t,u.txdb.p(N.HIGH_HASH))});if(0!==r.length){this.logger.info("Rebroadcasting %d transactions for %d.",r.length,t);const n=[];for(const a of r){var i=u.txdb.pp(a),s=u.txdb.prefix(t,u.txdb.t(i));if(s=await this.db.get(s)){const r=mt.fromRaw(s);if(!r.tx.isCoinbase())try{let t=await k.FactoryOfContract({tx:r.tx,env:this});"notify"!=t.oper&&(await t.isBlockFinal()==E.Expired?e&&(await this.removeTX(r.tx),await e.remove(i),await t.erase()):n.push(r.tx))}catch(t){this.logger.error("TX(%s) Smart Contract Error: %s",r.tx.txid(),t.message)}}}return await P(n,this)}}getWallets(){return this.db.keys({gte:h.l("\0"),lte:h.l("ÿ"),parse:h.ll})}async getWalletsByTX(t){const e=new Set;if(!t.isCoinbase())for(const i of t.inputs){const t=i.prevout;if(this.testFilter(t.toRaw())){var r=await this.getOutpointMap(t.hash,t.index);if(r)for(const t of r.wids)e.add(t)}}for(const r of t.getOutputHashes("hex"))if(this.testFilter(r)){var i=await this.getPathMap(r);if(i)for(const t of i.wids)e.add(t)}return 0===e.size?null:e}async getState(){var t=await this.db.get(h.R);return t?lt.fromRaw(t):null}async init(t){var e=this.options.startHeight;let r;if(this.client){if(null!=e){if(!(r=await this.client.getEntry(e)))throw new Error("WDB: Could not find start block.")}else r=await this.client.getTip();r=dt.fromEntry(r)}else r=dt.fromEntry(this.network.genesis);this.logger.info("Initializing AccountDB chain state (height %d).",r.height),(e=await this.getState())?this.state=e:await this.resetState(r,!1);let i=await this.ensure({id:"primary",witness:!0,mnemonic:this.options.mnemonic});await(i=t&&t.backup?await this.loadBackup(t.backup):i).createReceive(0,1,i.master,this.network.type),await i.ensureNotifyKey()}async resetState(t,e){const r=this.state.clone(),i=(r.startHeight=t.height,r.startHash=t.hash,r.height=t.height,r.marked=e,this.db.batch()),s=this.db.iterator({gte:h.h(t.height),lte:h.h(4294967295),values:!1});for(;;){var n=await s.next();if(!n)break;try{i.del(n.key)}catch(t){throw await s.end(),t}}i.put(h.h(t.height),t.toHash()),i.put(h.R,r.toRaw()),await i.write(),this.state=r}async syncState(t){const e=this.state.clone(),r=this.db.batch();if(t.height<e.height){let s=e.height;var i=s-t.height;for(let t=0;t<i;t++)r.del(h.h(s--))}else t.height>e.height&&s(t.height===e.height+1,`Bad chain sync tip ${t.height} while state `+e.height);e.height=t.height,r.put(h.h(t.height),t.toHash()),r.put(h.R,e.toRaw()),await r.write(),this.state=e,tt("block/tips",e)}get curHeight(){return this.state.height}get tidCreator(){return u.txdb.tx}get finder(){return this.getTXFromDb.bind(this)}rpcExecute(){return this.rpc.execute.apply(this.rpc,arguments)}async getBlockMap(t){var e=await this.db.get(h.b(t));return e?pt.fromRaw(t,e):null}writeBlockMap(t,e,r){this.batch(t).put(h.b(e),r.toRaw())}unwriteBlockMap(t,e){this.batch(t).del(h.b(e))}async getOutpointMap(t,e){var r=await this.db.get(h.o(t,e));return r?ut.fromRaw(t,e,r):null}writeOutpointMap(t,e,r,i){const s=this.batch(t);this.addOutpoint(e,r),s.put(h.o(e,r),i.toRaw())}unwriteOutpointMap(t,e,r){this.batch(t).del(h.o(e,r))}async writeBalanceLog(t,e){var r=h.log(t.wid,e.aidx,e.height,e.hash);e=Buffer.from(JSON.stringify(e));const i=await this.writeLock.lock();try{this.start(t).put(r,e),await this.commit(t)}finally{i()}}async queryBalanceLog(t,e,r=0){return this.db.values({gte:h.log(t,e,r,N.NULL_HASH),lte:h.log(t,e,this.curHeight,N.HIGH_HASH),parse:t=>JSON.parse(t.toString())})}async getBlock(t){const e=await this.db.get(h.h(t));if(!e)return null;const r=new dt;return r.hash=e.toString("hex"),r.height=t,r}async getTip(){var t=await this.getBlock(this.curHeight);if(t)return t;throw new Error("WDB: Tip not found!")}async rollback(t,e=!0){if(t>this.curHeight)throw new Error("WDB: Cannot rollback to the future.");if(t===this.curHeight)return this.logger.debug("Rolled back to same height (%d).",t),!0;this.logger.info("Rolling back %d AccountDB blocks to height %d.",this.curHeight-t,t);let r=await this.getBlock(t),i=!1;return r?(await this.revert(r.height),await this.syncState(r),e):(r=new dt,t>=this.state.startHeight?(r.height=this.state.startHeight,r.hash=this.state.startHash,i=this.state.marked,this.logger.warning("Rolling back AccountDB to start block (%d).",r.height)):(r.height=0,r.hash=this.network.genesis.hash,i=!1,this.logger.warning("Rolling back AccountDB to genesis block.")),await this.revert(r.height),await this.resetState(r,i),!1)}async revert(t){const e=this.db.iterator({gte:h.b(t+1),lte:h.b(4294967295),reverse:!0,values:!0});let r=0;for(;;){var i=await e.next();if(!i)break;try{var s=h.bb(i.key);var n=pt.fromRaw(s,i.value).toArray();r+=n.length;for(let t=n.length-1;0<=t;t--)await this._unconfirm(n[t])}catch(t){throw await e.end(),t}}this.logger.info("Rolled back %d AccountDB transactions.",r)}async addBlock(t,e){const r=await this.txLock.lock();try{return await this._addBlock(t,e)}finally{r()}}async _addBlock(t,e){var r=dt.fromEntry(t);let i=0;if(r.height<this.curHeight)this.logger.warning("AccountDB is connecting low blocks (%d).",r.height);else{if(r.height===this.curHeight)this.logger.warning("Already saw AccountDB block (%d).",r.height);else if(r.height!==this.curHeight+1)throw new Error(`WDB(addBlock): Bad disconnection (height mismatch, tip ${r.height} while state ${this.curHeight})`);if(await this.syncState(r),!(this.options.checkpoints&&r.height<=this.network.lastCheckpoint)){for(const t of e)await this._insert(t,r)&&i++;0<i&&this.logger.info("Connected AccountDB block %s (tx=%d).",C.revHex(r.hash),i)}}return i}async removeBlock(t,e){const r=await this.txLock.lock();try{return await this._removeBlock(t,e)}finally{r()}}async _removeBlock(t,e){if((t=dt.fromEntry(t)).height>this.curHeight)return this.logger.warning("AccountDB is disconnecting high blocks (%d).",t.height),0;if(t.height!==this.curHeight)throw new Error(`WDB(removeBlock): Bad disconnection (height mismatch, tip ${t.height} / ${C.revHex(t.hash)} while state ${this.curHeight})`);var r=await this.getBlock(t.height-1);if(!r)throw new Error(`WDB(removeBlock): Bad disconnection (no previous block of ${t.height} / ${C.revHex(t.hash)}).`);var i=await this.getBlockMap(t.height);if(i){for(let t=e.length-1;0<=t;t--){var s=e[t];await this._unconfirm(s,i)}this.logger.warning("Disconnected wallet block %s (tx=%d).",C.revHex(t.hash),i.txs.size)}return await this.syncState(r),i?i.txs.size:0}async rescanBlock(t,e){if(this.rescanning){const r=await this.scanLock.lock();try{await this._addBlock(t,e)}catch(t){throw this.emit("error",t),t}finally{r()}}else this.logger.warning("Unsolicited rescan block: %s.",t.height)}async addTX(t,e,r){const i=await this.txLock.lock();try{return await this._insert(t,e,r)}finally{i()}}listNotify(t){return this.NotifyList.deletes([["h","<",this.curHeight-12]]),this.NotifyList.query(t)}listContact(t,e,r){return this.$contacts.query(t,e,r)}async setCp(t){await this.batchPut(u.txdb.cp(t.cid),t.toRaw())}async delCp(t){await this.batchDel(u.txdb.cp(t))}async delVp(t){let e=this.db.batch();e.del(u.txdb.VP(t.pid)),await e.write()}async setVp(t,e){let r=this.db.batch();r.put(u.txdb.VP(t.pid),t.toRaw()),await r.write()}async getVp(t){return(t=await this.db.get(u.txdb.VP(t)))?rt.fromRaw(t):null}async getVpByAddress(t){return{list:[],count:0}}async getVpByOid(t){return{list:[],count:0}}async loadVpList(){return this.db.values({gte:u.txdb.VP(N.ZERO_CID,"hex"),lte:u.txdb.VP(N.MAX_CID,"hex"),parse:t=>rt.fromRaw(t)})}async saveContact(t){let e=this.db.batch();e.put(u.txdb.CT(t.getAddress()),t.toRaw()),await e.write()}async loadContact(t){var e;for(e of await this.db.values({gte:u.txdb.CT(N.ZERO_HASH160_HEX),lte:u.txdb.CT(N.MAX_HASH160_HEX),parse:t=>R.fromRaw(t,this)}))e.sender&&(e.sender.wallet=await this.get(e.sender.wid)),this.$contacts.set(e.address,e)}async delHtlc(t){if((t=new M(t)).id){this.htlcList.delete(t.id),this.htlcList.delAccount(t);let e=this.db.batch();e.del(u.txdb.VH(t.shash,t.sidx)),await e.write()}}async setSuggest(t){let e=new M(t);this.htlcList.set(e.id,e);var[t,r]=await this.getAccountByAddress(e.aa),[t,r]=(t&&this.htlcList.setAccount(e,t,r),await this.getAccountByAddress(e.ba));t&&this.htlcList.setAccount(e,t,r);let i=this.db.batch();i.put(u.txdb.VH(e.shash,e.sidx),e.toRaw()),await i.write()}async setAssent(t){let e=new M(t);this.htlcList.set(e.id,e);var[t,r]=await this.getAccountByAddress(e.ab),[t,r]=(t&&this.htlcList.setAccount(e,t,r),await this.getAccountByAddress(e.bb));t&&this.htlcList.setAccount(e,t,r);let i=this.db.batch();i.put(u.txdb.VH(e.shash,e.sidx),e.toRaw()),await i.write()}async loadHtlcList(){return this.db.values({gte:u.txdb.VH(N.ZERO_CID,0),lte:u.txdb.VH(N.MAX_CID,4294967295),parse:t=>M.fromRaw(t)})}async delComment(t){if((t=new q(t)).id){this.commentList.delete(t.id),this.commentList.delAccount(t);let e=this.db.batch();e.del(u.txdb.VC(t.shash,t.sidx)),await e.write()}}async setComment(t){let e=new q(t);this.commentList.set(e.id,e);var[t,r]=await this.getAccountByAddress(e.bob);t&&(this.commentList.setAccount(e,t,r),this.emit("comm.comment",e));let i=this.db.batch();i.put(u.txdb.VC(e.shash,e.sidx),e.toRaw()),await i.write()}async loadCommentList(){return this.db.values({gte:u.txdb.VC(N.ZERO_CID,0),lte:u.txdb.VC(N.MAX_CID,4294967295),parse:t=>q.fromRaw(t)})}async setStockRecord(t){let e=this.db.batch();switch(e.put(t.itemNo,t.toRaw()),t.type){case G.RecordType.Offer:break;case G.RecordType.Bid:{let r=this.accountList.getStockAccount(t.cid,t.addr);if(!r)break;r.stock.sum=t.sum,r.stock.price=t.price,r.stock.period=this.curHeight+10*m.BLOCK_DAY,r.seq=t.seq,e.put(r.getItemNo(),r.toRaw());break}case G.RecordType.Auction:{let i=this.accountList.getStockAccount(t.cid,t.addr);i?(r=i.sum+t.sum,i.price=(t.sum*t.price+i.sum*i.price)/r|0,i.sum=r,i.seq=t.seq):((i=new st(t.cid,t.addr,t.sum,t.price,0)).seq=t.seq,this.accountList.setStockAccount(i)),e.put(i.getItemNo(),i.toRaw());let s=this.accountList.getStockAccount(t.cid,t.to);if(!s)break;var r=s.sum-t.sum;s.sum=r,s.stock.sum-=t.sum,e.put(s.getItemNo(),s.toRaw());break}case G.RecordType.Purchase:{let i=this.accountList.getStockAccount(t.cid,t.addr);i?(r=i.sum+t.sum,i.price=(t.sum*t.price+i.sum*i.price)/r,i.sum=r,i.seq=t.seq):((i=new st(t.cid,t.addr,t.sum,t.price,0)).seq=t.seq,this.accountList.setStockAccount(i)),e.put(i.getItemNo(),i.toRaw());break}case G.RecordType.Send:{let i=this.accountList.getStockAccount(t.cid,t.addr);if(i){i.sum-=t.sum,i.seq=t.seq;let s=this.accountList.getStockAccount(t.cid,t.to);s||(s=new st(t.cid,t.to,0,0,0),this.accountList.setStockAccount(s)),r=s.sum+t.sum,s.price=(t.sum*i.price+s.sum*s.price)/r,s.sum=r,e.put(i.getItemNo(),i.toRaw()),e.put(s.getItemNo(),s.toRaw())}break}case G.RecordType.Bonus:case G.RecordType.Ads:}await e.write()}async unsetStockRecord(t){let e=this.db.batch();switch(e.del(t.itemNo),t.type){case G.RecordType.Offer:break;case G.RecordType.Bid:{let r=this.accountList.getStockAccount(t.cid,t.addr);if(!r)break;r.stock.sum=0,r.stock.price=0,r.stock.period=0,r.seq=t.seq-1,e.put(r.getItemNo(),r.toRaw());break}case G.RecordType.Auction:{let i=this.accountList.getStockAccount(t.cid,t.addr);if(!i)break;var r=i.sum-t.sum;i.price=(i.sum*i.price-t.sum*t.price)/r|0,i.sum=r,i.seq=t.seq-1,e.put(i.getItemNo(),i.toRaw());let s=this.accountList.getStockAccount(t.cid,t.to);if(!s)break;r=s.sum+t.sum,s.sum=r,s.stock.sum+=t.sum,e.put(s.getItemNo(),s.toRaw());break}case G.RecordType.Purchase:{let i=this.accountList.getStockAccount(t.cid,t.addr);i&&(r=i.sum-t.sum,i.price=(i.sum*i.price-t.sum*t.price)/r,i.sum=r,i.seq=t.seq-1,e.put(i.getItemNo(),i.toRaw()));break}case G.RecordType.Send:{let i=this.accountList.getStockAccount(t.cid,t.addr);if(i){i.sum+=t.sum,i.seq=t.seq-1,e.put(i.getItemNo(),i.toRaw());let s=this.accountList.getStockAccount(t.cid,t.to);s&&(r=s.sum-t.sum,s.price=(s.sum*s.price-t.sum*i.price)/r|0,s.sum=r,e.put(s.getItemNo(),s.toRaw()))}break}case G.RecordType.Bonus:}await e.write()}async getStockRecordById(t){return(t=await this.db.get(t))?G.fromRaw(t):null}async verifyClsTx(t,e){if(!this.spv){let r=await k.FactoryOfContract({env:this,block:e,tx:t});if(1!=(e=await r.verify()))throw new g(t,S(e),"bad-contract-verify",100)}return!0}async getStockRecord(t,e,r){let i=6,s=N.ZERO_CID_BUF,n=N.MAX_CID_BUF,a=0;return t&&(i=t,e&&(s=e,n=e,a=r||0)),t=new I,(await this.db.values({gte:G.itemNo(i,s,a,N.NULL_HASH,0),lte:G.itemNo(i,n,4294967295,N.HIGH_HASH,4294967295),parse:G.fromRaw})).reduce((t,e)=>(t.set(e.itemNo,e),t),t),t}async getStockRecordByCid(t,e){let r=new I;for(var i of Object.keys(G.RecordType))i=await this.getStockRecord(G.RecordType[i],t,e),r.merge(i);return r}async getStockAccountList(t){var e;return t?(e=st.SN(t,N.NULL_HASH),t=st.SN(t,N.HIGH_HASH),this.db.values({gte:e,lte:t,parse:st.fromRaw})):this.db.values({gte:st.SN(N.ZERO_CID_BUF,N.NULL_HASH),lte:st.SN(N.MAX_CID_BUF,N.HIGH_HASH),parse:st.fromRaw})}async delEr(t){let e=this.db.batch();e.del(u.txdb.ER(t.erid)),e.del(u.txdb.ERR(t.witness,t.erid)),await e.write()}async setEr(t,e){e&&t.source&&(i=v.fromWitnessPubkeyhash(l.hash160(Buffer.from(t.source.pubkey,"hex")),this.network),[i,e]=await this.getAccountByAddress(i,e),t.wid=i,t.account=e);let r=this.db.batch();var i=u.txdb.ERR(t.witness,t.erid);r.put(i,t.toRaw()),r.put(u.txdb.ER(t.erid),i),await r.write()}async getEr(t){return(t=(t=await this.db.get(u.txdb.ER(t)))&&await this.db.get(t))?at.fromRaw(t):null}async byPubkey(t,e,r=!1){let i=new I;var s;t=await this.db.values({gte:u.txdb.ERR(t,N.ZERO_CID),lte:u.txdb.ERR(t,N.MAX_CID),parse:t=>at.fromRaw(t)});let n=[],a=new Map;if(r){for(var o of t)(!a.get(o.source.cluster)||o.startHeight>a.get(o.source.cluster).startHeight)&&a.set(o.source.cluster,await this.caVerifyObj(o));n=a.values()}else n=t;for(s of n)i.set(s.erid,s);return i.query(e)}async caVerifyObj(t){var e={verify:!1};if(!t||t.validHeight<=this.curHeight)return e;var r=await this.erAbList.getErAb(t.erid);return r&&r.abolishHeight<this.curHeight?e:(r=gt.fromPublic(Buffer.from(t.witness,"hex"),this.network.type),t.verify(r)?(t.verify=!0,0<(r=this.cpList.query([["pubKey",t.witness]])).list.length&&(t.cpid=r.list[0].cid),t):e)}async delErAbolish(t){let e=this.db.batch();e.del(u.txdb.ERA(t.erid)),await e.write()}async setErAbolish(t){let e=this.db.batch();e.put(u.txdb.ERA(t.erid),t.toRaw()),await e.write()}async getErAbolish(t){return(t=await this.db.get(u.txdb.ERA(t)))?Y.fromRaw(t):null}loadErAbolishList(){return this.db.values({gte:u.txdb.ERA(N.ZERO_CID),lte:u.txdb.ERA(N.MAX_CID),parse:t=>Y.fromRaw(t)})}async delAudit(t){let e=this.db.batch();e.del(u.txdb.AU(t.erid)),await e.write()}async setAudit(t){let e=this.db.batch();e.put(u.txdb.AU(t.erid),t.toRaw()),await e.write()}async getAudit(t){return(t=await this.db.get(u.txdb.AU(t)))?ct.fromRaw(t):null}async loadAuditList(){return this.db.values({gte:u.txdb.AU(N.NULL_HASH),lte:u.txdb.AU(N.HIGH_HASH),parse:t=>ct.fromRaw(t)})}async delX509Cert(t){let e=this.db.batch();e.del(u.txdb.SX(t.witness,t.certSq,!0)),await e.write()}async setX509Cert(t){let e=this.db.batch();e.put(u.txdb.SX(t.witness,t.certSq,!0),t.toRaw()),await e.write()}loadX509CertList(){return this.db.values({gte:u.txdb.SX(N.ZERO_CID_BUF,N.ZERO_U32_NUM,!0),lte:u.txdb.SX(N.MAX_CID_BUF,N.MAX_U32_NUM,!0),parse:t=>J.fromRaw(t)})}async delX509Abolish(t){let e=this.db.batch();e.del(u.txdb.SX(t.witness,t.secertSqq,!1)),await e.write()}async setX509Abolish(t){let e=this.db.batch();e.put(u.txdb.SX(t.witness,t.certSq,!1),t.toRaw()),await e.write()}loadX509AbolishList(){return this.db.values({gte:u.txdb.SX(N.ZERO_CID_BUF,N.ZERO_U32_NUM,!1),lte:u.txdb.SX(N.MAX_CID_BUF,N.MAX_U32_NUM,!1),parse:t=>Q.fromRaw(t)})}async batchPut(t,e){const r=this.db.batch();r.put(t,e),await r.write()}async batchDel(t){const e=this.db.batch();e.del(t),await e.write()}async _insert(t,e,r){s(!t.mutable,"WDB: Cannot add mutable TX.");let i=await this.getWalletsByTX(t);if(i){this.logger.info("Incoming transaction for %d wallets in AccountDB (%s).",i.size,t.txid()),!e||this.state.marked||(this.logger.info("Marking AccountDB start block at %s (%d).",C.revHex(e.hash),e.height),await this.resetState(e,!0));let n=!1;for(const a of i){const i=await this.get(a);s(i),await i.add(t,e,r)&&(this.logger.info("Added transaction to wallet in AccountDB: %s (%d).",i.id,a),n=!0)}n||(i=null)}try{let r=await k.FactoryOfContract({env:this,block:e,tx:t});e?await r.confirm():await r.insert()}catch(r){e?this.logger.error("TX(%s) Smart Contract Confirm Error: %s",t.txid(),r.message):this.logger.error("TX(%s) Smart Contract Insert Error: %s",t.txid(),r.message)}return i}async _unconfirm(t,e){if(e)try{let r=await k.FactoryOfContract({env:this,block:e,tx:t});await r.unconfirm()}catch(i){this.logger.error("TX(%s) Smart Contract Unconfirm Error: %s",t.txid(),i.message)}let r,i=null;if(r=t.wids?(i=t.wids,t.hash):(i=await this.getWalletsByTX(t),t.hash("hex")),!i)return null;for(const t of i){const e=await this.get(t);s(e),await e.unconfirm(r)}for(const t of i){const e=await this.get(t);s(e),await e.abandon(r)}}async resetChain(t){const e=await this.txLock.lock();try{return await this._resetChain(t)}finally{e()}}async _resetChain(t){if(t.height>this.curHeight)throw new Error(`WDB: Bad reset height ${t.height} while curHeight `+this.curHeight);var e;for(e of(await this.rollback(t.height)||await this.scan(),await this.getWallets())){const r=await this.get(e);for(const e of await r.getPending())try{await r.abandon(e.hash)}catch(t){}await r.resetBalance()}}async saveMSTrans(t){const e=await this.writeLock.lock();try{return await this._saveMSTrans(t)}finally{e()}}async _saveMSTrans(t){const e=this.db.batch();e.put(h.ms(v.getHash(t.addr,"hex"),t.txid),Buffer.from(JSON.stringify(t))),await e.write()}async listMSTrans(t){return t=v.getHash(t,"hex"),this.db.values({gte:h.ms(t,N.NULL_HASH),lte:h.ms(t,N.HIGH_HASH),parse:t=>JSON.parse(t.toString())})}async delMSTrans(t,e){const r=await this.writeLock.lock();try{return await this._delMSTrans(t,e)}finally{r()}}async _delMSTrans(t,e){t=v.getHash(t,"hex");const r=this.db.batch();r.del(h.ms(t,e)),await r.write()}}xt.layout=h,t.exports=xt},function(t,e,r){"use strict";
860
860
  /*!
861
861
  * txdb.js - persistent transaction pool
862
862
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
863
- */const i=r(1),s=r(65),n=r(0),a=r(34),o=r(61),c=r(53),u=r(46),h=r(320),l=r(96).txdb,p=r(3),d=r(27),f=r(17),m=r(321),g=r(226),y=r(322),v=r(615),b=r(616);r(122),r(123);const w=r(617);r(19);const x=r(43),k=r(119),S=r(21).nestingCodes;class E{constructor(t){this.wallet=t,this.walletdb=t.db,this.logger=this.walletdb.logger,this.network=this.walletdb.network,this.options=this.walletdb.options,this.coinCache=new s(this.options.coinCache),this.conserved=new Set,this.lockedCoins=new Map,this.state=null,this.pending=null,this.events=[]}async open(){let t=null;try{t=await this.getState()}catch(e){this.logger.info("TXDB State Format Error."),t=null}t?(this.state=t,this.logger.info("TXDB loaded for %s.",this.wallet.id)):(this.state=new v(this.wallet.wid,this.wallet.id),this.logger.info("TXDB created for %s.",this.wallet.id)),this.logger.info("TXDB State: tx=%d coin=%s.",this.state.tx,this.state.coin),this.logger.info("Balance: unconfirmed=%s confirmed=%s.",a.btc(this.state.unconfirmed),a.btc(this.state.confirmed)),this.pending=this.state.clone(),await this.loadLockedCoins(),this.state=this.pending}start(){return this.pending=this.state.clone(),this.coinCache.start(),this.walletdb.accountCoinList.start(),this.wallet.start()}drop(){return this.pending=null,this.events.length=0,this.coinCache.drop(),this.walletdb.accountCoinList.drop(),this.wallet.drop()}clear(){return this.pending=this.state.clone(),this.events.length=0,this.coinCache.clear(),this.walletdb.accountCoinList.clear(),this.wallet.clear()}async commit(){try{await this.wallet.commit()}catch(t){throw this.pending=null,this.events.length=0,this.coinCache.drop(),this.walletdb.accountCoinList.drop(),t}if(this.pending.committed)for(var[t,e,r]of(this.state=this.pending,this.events))this.walletdb.emit(t,this.wallet.id,e,r),"tx"==t&&this.walletdb.emit("tx.received."+e.rhash(),this.wallet.id,e,r),this.wallet.emit(t,e,r);this.pending=null,this.events.length=0,this.coinCache.commit(),this.walletdb.accountCoinList.commit()}emit(t,e,r){this.events.push([t,e,r])}prefix(t){return n(this.wallet.wid),l.prefix(this.wallet.wid,t)}put(t,e){n(this.wallet.current),this.wallet.current.put(this.prefix(t),e)}del(t){n(this.wallet.current),this.wallet.current.del(this.prefix(t))}get(t){return this.walletdb.db.get(this.prefix(t))}has(t){return this.walletdb.db.has(this.prefix(t))}range(t){return t.gte&&(t.gte=this.prefix(t.gte)),t.lte&&(t.lte=this.prefix(t.lte)),this.walletdb.db.range(t)}keys(t){return t.gte&&(t.gte=this.prefix(t.gte)),t.lte&&(t.lte=this.prefix(t.lte)),this.walletdb.db.keys(t)}values(t){return t.gte&&(t.gte=this.prefix(t.gte)),t.lte&&(t.lte=this.prefix(t.lte)),this.walletdb.db.values(t)}async getPath(t){return(t=t.getAddress())?this.wallet.getPath(t):null}async hasPath(t){return!!(t=t.getAddress())&&this.wallet.hasPath(t)}async saveCredit(t,e){const r=t.coin;var i=r.toKey(),s=t.toRaw();let n=await this.walletdb.getOutpointMap(r.hash,r.index),a=((n=n||new h(r.hash,r.index)).add(this.wallet.wid)&&this.walletdb.writeOutpointMap(this.wallet,r.hash,r.index,n),this.put(l.c(r.hash,r.index),s),this.put(l.C(e.account,r.hash,r.index),null),this.coinCache.push(i,t),new u(r.hash,r.index));a.wid=this.wallet.wid,a.account=e.account,this.walletdb.accountCoinList.push(i,a)}async removeCredit(t,e){const r=t.coin;t=r.toKey(),await this.removeOutpointMap(r.hash,r.index),this.del(l.C(e.account,r.hash,r.index)),this.del(l.c(r.hash,r.index)),this.coinCache.unpush(t),this.walletdb.accountCoinList.unpush(t)}spendCredit(t,e,r){var i=e.inputs[r].prevout;const s=u.fromTX(e,r);this.put(l.s(i.hash,i.index),s.toRaw()),this.put(l.d(s.hash,s.index),t.coin.toRaw())}unspendCredit(t,e){var r=t.inputs[e].prevout;t=u.fromTX(t,e);this.del(l.s(r.hash,r.index)),this.del(l.d(t.hash,t.index))}writeInput(t,e){var r=t.inputs[e].prevout;const i=u.fromTX(t,e);this.put(l.s(r.hash,r.index),i.toRaw())}removeInput(t,e){t=t.inputs[e].prevout,this.del(l.s(t.hash,t.index))}async resolveInput(t,e,r,i,s,a){var o=t.hash("hex");if(!(o=await this.getSpender(o,e)))return!1;if(await this.hasSpentCoin(o))return!1;var c=await this.getTX(o.hash);n(c);const u=b.fromTX(t,e,r,i);return u.own=a,this.spendCredit(u,c.tx,o.index),-1===c.height&&(u.spent=!0,-1!==r&&(this.changeConfirmed(this.pending,u.coin,1),(u.coin.lockedByLocktime(r,i)||u.coin.lockedBySequence(r,i))&&this.addLocked(u.coin)),await this.saveCredit(u,s)),!0}async isDoubleSpend(t){for(var{prevout:e}of t.inputs)if(await this.isSpent(e.hash,e.index))return!0;return!1}async isRBF(t){if(t.isRBF())return!0;for(var{prevout:e}of t.inputs)if(e=l.r(e.hash),await this.has(e))return!0;return!1}async getSpender(t,e){return(t=await this.get(l.s(t,e)))?u.fromRaw(t):null}isSpent(t,e){return this.has(l.s(t,e))}async removeOutpointMap(t,e){const r=await this.walletdb.getOutpointMap(t,e);r&&r.remove(this.wallet.wid)&&(0===r.wids.size?this.walletdb.unwriteOutpointMap(this.wallet,t,e):this.walletdb.writeOutpointMap(this.wallet,t,e,r))}async addBlockMap(t,e){let r=await this.walletdb.getBlockMap(e);(r=r||new m(e)).add(t,this.wallet.wid)&&this.walletdb.writeBlockMap(this.wallet,e,r)}async removeBlockMap(t,e){const r=await this.walletdb.getBlockMap(e);r&&r.remove(t,this.wallet.wid)&&(0===r.txs.size?this.walletdb.unwriteBlockMap(this.wallet,e):this.walletdb.writeBlockMap(this.wallet,e,r))}getBlocks(){return this.keys({gte:l.b(0),lte:l.b(4294967295),parse:t=>l.bb(t)})}async getStatusOfSC(t){let e=await this.get(l.de(t));return e?{txs:e.toString().split(",")}:{}}async _setStatusOfSC(t,e){e=e.reduce((t,e)=>(t&&(t+=","),t+e),""),this.put(l.de(t),Buffer.from(e))}async getBlock(t){return(t=await this.get(l.b(t)))?w.fromRaw(t):null}async addBlock(t,e){var r=l.b(e.height);let i,s=await this.get(r);s||(i=w.fromMeta(e),s=i.toRaw()),i=Buffer.allocUnsafe(s.length+32),s.copy(i,0),e=i.readUInt32LE(40,!0),i.writeUInt32LE(e+1,40,!0),t.copy(i,s.length),this.put(r,i)}async removeBlock(t,e){e=l.b(e);const r=await this.get(e);if(r){var i=r.readUInt32LE(40,!0);if(n(0<i),n(r.slice(-32).equals(t)),1===i)this.del(e);else{const t=r.slice(0,-32);t.writeUInt32LE(i-1,40,!0),this.put(e,t)}}}async addBlockSlow(t,e){let r=await this.getBlock(e.height);(r=r||w.fromMeta(e)).add(t)&&this.put(l.b(e.height),r.toRaw())}async removeBlockSlow(t,e){const r=await this.getBlock(e);r&&r.remove(t)&&(0===r.hashes.length?this.del(l.b(e)):this.put(l.b(e),r.toRaw()))}async _add(t,e,r){n(!t.mutable,"Cannot add mutable TX to wallet."),r=r||{};var i=t.hash("hex"),s=await this.getTX(i);if(e){if(!t.isCoinbase()){var a=await this.getSpentCredits(t);for(let r=0;r<t.inputs.length;r++){var o=t.inputs[r],c=o.prevout;let i=a[r];(i=i||await this.getCredit(c.hash,c.index))&&await this.emitCoinSpent(o,i.coin,t,e)}}if(s)return-1!==s.height&&-2!==s.height?null:this._confirm(s,e);await this.removeConflicts(t,!1),this.del(l.r(i))}else{if(s&&!r.reorg)return null;if(await this.isRBF(t))return this.put(l.r(i),null),null;if(!await this.removeConflicts(t,!0))return null}return s=g.fromTX(t,e),this.insert(s,e)}async insert(t,e){const r=t.tx;var s=t.hash,a=e?e.height:-1,o=e?e.mtp:0;const c=new _(this,t,e),u=new Set;let h=!1,p=!1;if(!r.isCoinbase())for(let t=0;t<r.inputs.length;t++){var d=r.inputs[t].prevout;const i=await this.getCredit(d.hash,d.index);if(i){if(d=i.coin,!e&&!await this.verifyInput(r,t,d))return this.clear(),null;var f=await this.getPath(d);n(f),c.setInput(t,f,d),u.add(f.account),this.spendCredit(i,r,t),this.pending.coin--,this.changeUnconfirmed(this.pending,d,-1),e?(this.changeConfirmed(this.pending,d,-1),await this.removeCredit(i,f),this.removeLocked(d)):(i.spent=!0,await this.saveCredit(i,f)),p=!0,h=!0}else this.writeInput(r,t)}for(let t=0;t<r.outputs.length;t++){var m=r.outputs[t],g=await this.getPath(m);if(g){if(c.setOutput(t,g),u.add(g.account),!await this.resolveInput(r,t,a,o,g,h)){const i=b.fromTX(r,t,a,o);i.own=h,this.pending.coin++,this.changeUnconfirmed(this.pending,m,1),e&&this.changeConfirmed(this.pending,m,1),await this.saveCredit(i,g),(i.coin.lockedByLocktime(a,o)||i.coin.lockedBySequence(a,o))&&this.addLocked(i.coin)}p=!0}}if(!p)return this.clear(),null;this.put(l.t(s),t.toRaw()),this.logger.spam("layout.t insert",i.revHex(s)),this.put(l.m(t.mtime,s),null),e?this.put(l.h(a,s),null):this.put(l.p(s),null);for(const r of u)this.put(l.T(r,s),null),this.put(l.M(r,t.mtime,s),null),e?this.put(l.H(r,a,s),null):this.put(l.P(r,s),null);return e&&(await this.addBlockMap(s,a),await this.addBlock(r.hash(),e),this.refreshLocked(a,i.now())),this.pending.tx++,this.put(l.R,this.pending.commit()),this.unConserveTX(r),this.emit("tx",r,c),this.emit("balance",this.pending.toBalance(),c),c}async _confirm(t,e){const r=t.tx;var s=t.hash,a=e.height,o=e.mtp||e.time;const c=new _(this,t,e),u=new Set;let h=!1;if(t.setBlock(e),!r.isCoinbase()){var p=await this.getSpentCredits(r);for(let e=0;e<r.inputs.length;e++){var d=r.inputs[e].prevout;let i=p[e];if(!i){if(!(i=await this.getCredit(d.hash,d.index)))continue;this.spendCredit(i,r,e),this.pending.coin--,this.changeUnconfirmed(this.pending,i.coin,-1)}d=i.coin;try{n(-1!==d.height&&-2!==d.height)}catch(t){this.logger.warning("tx(%s): coin.height = -1: %s",r.txid(),t.message)}var f=await this.getPath(d);n(f),c.setInput(e,f,d),u.add(f.account),this.changeConfirmed(this.pending,d,-1),await this.removeCredit(i,f),this.removeLocked(i.coin),h=!0}}for(let t=0;t<r.outputs.length;t++){var m=r.outputs[t],g=await this.getPath(m);if(g&&(c.setOutput(t,g),u.add(g.account),!await this.resolveInput(r,t,a,o,g,h))){let e=await this.getCredit(s,t);e||((e=b.fromTX(r,t,a,o)).own=!0,this.pending.coin++,this.changeUnconfirmed(this.pending,m,1)),e.spent&&await this.updateSpentCoin(r,t,a),this.changeConfirmed(this.pending,m,1),e.coin.time=o,e.coin.height=a,await this.saveCredit(e,g),(e.coin.lockedByLocktime(a,o)||e.coin.lockedBySequence(a,o))&&this.addLocked(e.coin)}}this.del(l.r(s)),this.put(l.t(s),t.toRaw()),this.logger.spam("layout.t confirm",i.revHex(s)),this.del(l.p(s)),this.put(l.h(a,s),null);for(const e of u)this.put(l.T(e,s),null),this.put(l.M(e,t.mtime,s),null),this.del(l.P(e,s)),this.put(l.H(e,a,s),null);return e&&(await this.addBlockMap(s,a),await this.addBlock(r.hash(),e),this.refreshLocked(a,i.now())),this.put(l.R,this.pending.commit()),this.unConserveTX(r),this.emit("confirmed",r,c),this.emit("balance",this.pending.toBalance(),c),c}async remove(t){return(t=await this.getTX(t))?this.removeRecursive(t):null}changeUnconfirmed(t,e,r){e.isColored||(1===r?t.unconfirmed+=e.value:t.unconfirmed-=e.value)}resetBalance(){balance.unconfirmed=balance.confirmed}changeConfirmed(t,e,r){e.isColored||(1===r?t.confirmed+=e.value:t.confirmed-=e.value)}changeLocked(t,e,r){e.isColored||(1===r?t.locked+=e.value:t.locked-=e.value)}async removeRecursive(t){n(t);var e=t.tx,r=t.hash;for(let t=0;t<e.outputs.length;t++){var i=await this.getSpender(r,t);i&&(i=await this.getTX(i.hash),await this.removeRecursive(i))}return this.start(),t=await this.erase(t,t.getBlock()),n(t),await this.commit(),t}async unconfirm(t){let e;this.start();try{e=await this._unconfirm(t)}catch(t){throw this.drop(),t}return await this.commit(),e}async _unconfirm(t){const e=await this.getTX(t);return e&&-1!==e.height?this.disconnect(e,e.getBlock()):null}async disconnect(t,e){n(e);const r=t.tx;var s=t.hash,a=e.height,o=e.mtp||e.time;const c=new _(this,t,e),u=new Set;if(t.unsetBlock(),!r.isCoinbase()){var h=await this.getSpentCredits(r);for(let e=0;e<r.inputs.length;e++){const i=h[e];if(i){var p=i.coin;try{n(-1!==p.height&&-2!==p.height)}catch(t){this.logger.warning("tx(%s): coin.height = -1: %s",r.txid(),t.message)}var d=await this.getPath(p);n(d),c.setInput(e,d,p),u.add(d.account),this.changeConfirmed(this.pending,p,1),i.spent=!0,await this.saveCredit(i,d),(i.coin.lockedByLocktime(a,o)||i.coin.lockedBySequence(a,o))&&this.addLocked(i.coin)}}}for(let t=0;t<r.outputs.length;t++){var f=r.outputs[t],m=await this.getPath(f);if(m){const e=await this.getCredit(s,t);e?(e.spent&&await this.updateSpentCoin(r,t,a),c.setOutput(t,m),u.add(m.account),this.changeConfirmed(this.pending,f,-1),e.coin.height=-1,await this.saveCredit(e,m)):await this.updateSpentCoin(r,t,a)}}await this.removeBlockMap(s,a),await this.removeBlock(r.hash(),a),this.refreshLocked(a,i.now()),this.put(l.t(s),t.toRaw()),this.put(l.p(s),null),this.del(l.h(a,s));for(const t of u)this.put(l.P(t,s),null),this.del(l.H(t,a,s));return this.put(l.R,this.pending.commit()),this.emit("unconfirmed",r,c),this.emit("balance",this.pending.toBalance(),c),c}async erase(t,e){const r=t.tx;var s=t.hash,a=e?e.height:-1,o=e?e.mtp:0;const c=new _(this,t,e),u=new Set;if(!r.isCoinbase()){var h,p,d=await this.getSpentCredits(r);for(let t=0;t<r.inputs.length;t++){const i=d[t];i?(h=i.coin,p=await this.getPath(h),n(p),c.setInput(t,p,h),u.add(p.account),this.pending.coin++,this.changeUnconfirmed(this.pending,h,1),e&&this.changeConfirmed(this.pending,h,1),this.unspendCredit(r,t),await this.saveCredit(i,p),(i.coin.lockedByLocktime(a,o)||i.coin.lockedBySequence(a,o))&&this.addLocked(i.coin)):this.removeInput(r,t)}}for(let t=0;t<r.outputs.length;t++){var f,m=r.outputs[t],g=await this.getPath(m);g&&(c.setOutput(t,g),u.add(g.account),f=b.fromTX(r,t,a,o),this.pending.coin--,this.changeUnconfirmed(this.pending,m,-1),e&&this.changeConfirmed(this.pending,m,-1),await this.removeCredit(f,g),this.removeLocked(f.coin))}this.del(l.r(s)),this.del(l.t(s)),this.logger.spam("layout.t erase",i.revHex(s)),this.del(l.m(t.mtime,s)),e?this.del(l.h(a,s)):this.del(l.p(s));for(const r of u)this.del(l.T(r,s)),this.del(l.M(r,t.mtime,s)),e?this.del(l.H(r,a,s)):this.del(l.P(r,s));e&&(await this.removeBlockMap(s,a),await this.removeBlockSlow(s,a),this.refreshLocked(a,i.now())),this.pending.tx--,this.put(l.R,this.pending.commit());try{let t=await x.FactoryOfContract({env:this.walletdb,tx:r,block:e});await t.erase()}catch(t){this.logger.error("TX(%s) Smart Contract Erase Error: %s",r.txid(),t.message)}return this.emit("tx.remove",r,c),this.emit("balance",this.pending.toBalance(),c),c}async removeConflict(t){if(!t)return Promise.resolve();const e=t.tx;return this.logger.warning("Handling conflicting tx: %s.",e.txid()),this.drop(),t=await this.removeRecursive(t),this.start(),this.logger.warning("Removed conflict: %s.",e.txid()),this.emit("conflict",e,t),t}async removeConflicts(t,e){var r=t.hash("hex");const i=[];if(!t.isCoinbase()){for(let a=0;a<t.inputs.length;a++){var s=t.inputs[a].prevout;if(s.hash!==p.NULL_HASH&&(s=await this.getSpender(s.hash,s.index))&&s.hash!==r){const t=await this.getTX(s.hash);if(n(t),s=t.getBlock(),e&&s)return!1;i[a]=t}}for(const t of i)await this.removeConflict(t)}return!0}async verifyInput(t,e,r){var i=f.flags.MANDATORY_VERIFY_FLAGS;return!this.options.verify||t.verifyInput(e,r,i)}conserveTX(t){if(!t.isCoinbase())for(const e of t.inputs)this.conserveCoin(e.prevout)}unConserveTX(t){if(!t.isCoinbase())for(const e of t.inputs)this.unConserveCoin(e.prevout)}conserveCoin(t){t=t.toKey(),this.conserved.add(t)}unConserveCoin(t){return t=t.toKey(),this.conserved.delete(t)}isConserved(t){return t=t.toKey(),this.conserved.has(t)}filterConserved(t){const e=[];for(const r of t)this.isConserved(r)||e.push(r);return e}getConserved(){const t=[];for(const e of this.conserved.keys())t.push(u.fromKey(e));return t}getAccountHistoryHashes(t){return this.keys({gte:l.T(t,p.NULL_HASH),lte:l.T(t,p.HIGH_HASH),parse:t=>{var[,t]=l.Tt(t);return t}})}getHistoryHashes(t){return null!=t?this.getAccountHistoryHashes(t):this.keys({gte:l.t(p.NULL_HASH),lte:l.t(p.HIGH_HASH),parse:t=>l.tt(t)})}getAccountPendingHashes(t){return this.keys({gte:l.P(t,p.NULL_HASH),lte:l.P(t,p.HIGH_HASH),parse:t=>{var[,t]=l.Pp(t);return t}})}getPendingHashes(t){return null!=t?this.getAccountPendingHashes(t):this.keys({gte:l.p(p.NULL_HASH),lte:l.p(p.HIGH_HASH),parse:t=>l.pp(t)})}getAccountOutpoints(t){return void 0!==t&&null!=t?this.walletdb.accountCoinList.getAccount(this.wallet.wid,t):this.walletdb.accountCoinList.ToArray()}getAccountHeightRangeHashes(t,e){var r=e.start||0,i=e.end||4294967295;return this.keys({gte:l.H(t,r,p.NULL_HASH),lte:l.H(t,i,p.HIGH_HASH),limit:e.limit,reverse:e.reverse,parse:t=>{var[,,t]=l.Hh(t);return t}})}getHeightRangeHashes(t,e){var r;return t&&"object"==typeof t&&(e=t,t=null),null!=t?this.getAccountHeightRangeHashes(t,e):(t=e.start||0,r=e.end||4294967295,this.keys({gte:l.h(t,p.NULL_HASH),lte:l.h(r,p.HIGH_HASH),limit:e.limit,reverse:e.reverse,parse:t=>{var[,t]=l.hh(t);return t}}))}getHeightHashes(t){return this.getHeightRangeHashes({start:t,end:t})}getAccountRangeHashes(t,e){var r=e.start||0,i=e.end||4294967295;return this.keys({gte:l.M(t,r,p.NULL_HASH),lte:l.M(t,i,p.HIGH_HASH),limit:e.limit,reverse:e.reverse,parse:t=>{var[,,t]=l.Mm(t);return t}})}getRangeHashes(t,e){var r;return t&&"object"==typeof t&&(e=t,t=null),null!=t?this.getAccountRangeHashes(t,e):(t=e.start||0,r=e.end||4294967295,this.keys({gte:l.m(t,p.NULL_HASH),lte:l.m(r,p.HIGH_HASH),limit:e.limit,reverse:e.reverse,parse:t=>{var[,t]=l.mm(t);return t}}))}async getRange(t,e){const r=[];t&&"object"==typeof t&&(e=t,t=null);for(const s of await this.getRangeHashes(t,e)){var i=await this.getTX(s);n(i),r.push(i)}return r}getLast(t,e){return this.getRange(t,{start:0,end:4294967295,reverse:!0,limit:e||10})}getHistory(t){return null!=t?this.getAccountHistory(t):this.values({gte:l.t(p.NULL_HASH),lte:l.t(p.HIGH_HASH),parse:g.fromRaw})}async getAccountHistory(t){const e=[];for(const i of await this.getHistoryHashes(t)){var r=await this.getTX(i);n(r),e.push(r)}return e}async getPending(t){const e=[];for(const i of await this.getPendingHashes(t)){var r=await this.getTX(i);n(r),e.push(r)}return e}getCredits(t){return void 0!==t&&null!=t?this.getAccountCredits(t):this.range({gte:l.c(p.NULL_HASH,0),lte:l.c(p.HIGH_HASH,4294967295),parse:(t,e)=>{var[t,r]=l.cc(t);const i=b.fromRaw(e);return e=u.toKey(t,r),i.coin.hash=t,i.coin.index=r,this.coinCache.set(e,i),i}})}async fillCoins(){var t,e=await this.keys({gte:l.C(0,p.NULL_HASH,0),lte:l.C(4294967295,p.HIGH_HASH,4294967295),parse:t=>{var[t,e,r]=l.Cc(t);let i=new u(e,r);return i.wid=this.wallet.wid,i.account=t,[i.toKey(),i]}});for(t of e){var r=await this.get(l.c(t[1].hash,t[1].index));if(r){const e=b.fromRaw(r);e.coin.hash=t[1].hash,e.coin.index=t[1].index,this.coinCache.set(t[0],e)}}this.walletdb.accountCoinList.load(e)}async getAccountCredits(t){const e=[];for(const i of await this.getAccountOutpoints(t)){var r=await this.getCredit(i.hash,i.index);r||(this.logger.warning("getAccountCredits: credit not found."),n(r)),e.push(r)}return e}async getSpentCredits(t){if(t.isCoinbase())return[];var e=t.hash("hex");const r=[];for(let e=0;e<t.inputs.length;e++)r.push(null);return await this.range({gte:l.d(e,0),lte:l.d(e,4294967295),parse:(e,i)=>{var[,e]=l.dd(e);const s=c.fromRaw(i);i=t.inputs[e],n(i),s.hash=i.prevout.hash,s.index=i.prevout.index,r[e]=new b(s)}}),r}async getCoins(t){const e=[];if(void 0!==t&&null!=t)for(const i of await this.getAccountOutpoints(t)){var r=await this.getCredit(i.hash,i.index);r||(this.logger.warning("getAccountCredits: credit not found."),n(r)),r.spent||e.push(r.coin)}else await this.range({gte:l.c(p.NULL_HASH,0),lte:l.c(p.HIGH_HASH,4294967295),parse:(t,r)=>{var[t,i]=l.cc(t);const s=b.fromRaw(r);r=u.toKey(t,i),s.coin.hash=t,s.coin.index=i,this.coinCache.set(r,s),s.spent||e.push(s.coin)}});return e}async getSpentCoins(t){if(t.isCoinbase())return[];const e=[];for(const r of await this.getSpentCredits(t))r?e.push(r.coin):e.push(null);return e}async getCoinView(t){const e=new o;if(!t.isCoinbase())for(const i of t.inputs){var r=i.prevout;(r=await this.getCoin(r.hash,r.index))&&e.addCoin(r)}return e}async getSpentView(t){const e=new o;if(!t.isCoinbase())for(const r of await this.getSpentCoins(t))r&&e.addCoin(r);return e}async getState(){var t=await this.get(l.R);return t?v.fromRaw(this.wallet.wid,this.wallet.id,t):null}async loadLockedCoins(){var t=this.walletdb.curHeight,e=i.now();for(const r of await this.wallet.getCredits()){let i=r.coin;i.getAddress()&&(i.lockedByLocktime(t,e)||i.lockedBySequence(t,e))&&this.addLocked(i)}}refreshLocked(t,e){for(const r of this.lockedCoins.values())r.lockedByLocktime(t,e)||r.lockedBySequence(t,e)||this.removeLocked(r)}addLocked(t){var e=l.prefix(this.wallet.wid,l.c(t.hash,t.index));this.lockedCoins.has(e)||(this.lockedCoins.set(e,t),this.changeLocked(this.pending,t,1))}removeLocked(t){var e=l.prefix(this.wallet.wid,l.c(t.hash,t.index));this.lockedCoins.has(e)&&(this.lockedCoins.delete(e),this.changeLocked(this.pending,t,-1))}async getTX(t){return(t=await this.get(l.t(t)))?g.fromRaw(t):null}async getDetails(t){return(t=await this.getTX(t))?this.toDetails(t):null}async toDetails(t){const e=[];if(!Array.isArray(t))return this._toDetail(t);for(const i of t){var r=await this._toDetail(i);r&&e.push(r)}return e}async _toDetail(t){var e=t.tx,r=t.getBlock();const i=new _(this,t,r);var s=await this.getSpentCoins(e);for(let t=0;t<e.inputs.length;t++){var n=s[t];let e=null;n&&(e=await this.getPath(n)),i.setInput(t,e,n)}for(let t=0;t<e.outputs.length;t++){var a=e.outputs[t];a=await this.getPath(a);i.setOutput(t,a)}return i}hasTX(t){return this.has(l.t(t))}async getCoin(t,e){return(t=await this.getCredit(t,e))?t.coin:null}async emitCoinSpent(t,e,r,i){(r={env:this.walletdb,block:i,tx:r,hash:t.prevout.hash,i:t.prevout.index,height:i.height,output:e,type:e.getReturnType(),data:e.getReturnData(S)}).data&&await k(r).spent(t)}async getCredit(t,e){var r=this.state,i=u.toKey(t,e);let s=this.coinCache.get(i);if(s)return s;if(s=await this.get(l.c(t,e))){const n=b.fromRaw(s);return n.coin.hash=t,n.coin.index=e,r===this.state&&this.coinCache.set(i,n),n}return null}async getSpentCoin(t,e){if(!(t=await this.get(l.d(t.hash,t.index))))return null;const r=c.fromRaw(t);return r.hash=e.hash,r.index=e.index,r}hasSpentCoin(t){return this.has(l.d(t.hash,t.index))}async updateSpentCoin(t,e,r){if(t=u.fromTX(t,e),e=await this.getSpender(t.hash,t.index)){const i=await this.getSpentCoin(e,t);i&&(i.height=r,this.put(l.d(e.hash,e.index),i.toRaw()))}}async hasCoin(t,e){var r=u.toKey(t,e);return!!this.coinCache.has(r)||this.has(l.c(t,e))}async getBalance(t){return null!=t?this.getAccountBalance(t):this.state.toBalance()}async getAccountBalance(t){var e=await this.getAccountCredits(t);const r=new y(this.wallet.wid,this.wallet.id,t);var i=this.walletdb.curHeight,s=this.network.now();for(const t of e){const e=t.coin;-2!==e.height&&(-1===e.height||e.isColored||(r.confirmed+=e.value),t.spent||e.isColored||(r.unconfirmed+=e.value),(e.lockedByLocktime(i,s)||e.lockedBySequence(i,s))&&this.changeLocked(r,e,1))}return r}async zap(t,e){n(i.isU32(e));var r=i.now();const s=[];for(const i of await this.getRange(t,{start:0,end:r-e}))-1===i.height&&(n(r-i.mtime>=e),this.logger.debug("Zapping TX: %s (%s)",i.tx.txid(),this.wallet.id),await this.remove(i.hash),s.push(i.hash));return s}async abandon(t){if(await this.has(l.p(t)))return this.remove(t)}}E.layout=l;class _{constructor(t,e,r){this.wallet=t.wallet,this.network=this.wallet.network,this.wid=this.wallet.wid,this.id=this.wallet.id,this.chainHeight=t.walletdb.curHeight,this.hash=e.hash,this.tx=e.tx,this.mtime=e.mtime,this.size=this.tx.getSize(),this.vsize=this.tx.getVirtualSize(),this.block=null,this.height=-1,this.time=0,r&&(this.block=r.hash,this.height=r.height,this.time=r.time),this.inputs=[],this.outputs=[],this.init()}init(){for(const t of this.tx.inputs){const e=new A;e.address=t.getAddress(),this.inputs.push(e)}for(const t of this.tx.outputs){const e=new A;e.value=t.value,e.address=t.getAddress(),this.outputs.push(e)}}setInput(t,e,r){const i=this.inputs[t];i.prevout=this.tx.inputs[t].prevout,r&&(i.value=r.value,i.address=r.getAddress()),e&&(i.path=e)}setOutput(t,e){const r=this.outputs[t];e&&(r.path=e)}getDepth(){var t;return-1===this.height||(t=this.chainHeight-this.height)<0?0:1+t}getFee(){let t=0,e=0;for(const e of this.inputs){if(!e.path)return 0;t+=e.value}for(const t of this.outputs)e+=t.value;return t-e}getRate(t){return d.getRate(this.vsize,t)}toJSON(){var t=this.getFee();let e=this.getRate(t);return Number.isSafeInteger(e)||(e=0),{wid:this.wid,id:this.id,hash:i.revHex(this.hash),height:this.height,block:this.block?i.revHex(this.block):null,time:this.time,mtime:this.mtime,date:i.date(this.time||this.mtime),size:this.size,virtualSize:this.vsize,fee:t,rate:e,confirmations:this.getDepth(),inputs:this.inputs.map(t=>t.getJSON(this.network)),outputs:this.outputs.map(t=>t.getJSON(this.network)),tx:this.tx.toRaw().toString("hex")}}}class A{constructor(){this.value=0,this.address=null,this.path=null}toJSON(){return this.getJSON()}getJSON(t){return{prevout:this.prevout?this.prevout.toJSON():null,value:this.value,address:this.address?this.address.toString(t):null,path:this.path?this.path.toJSON():null}}}t.exports=E},function(t,e,r){"use strict";
863
+ */const i=r(1),s=r(65),n=r(0),a=r(34),o=r(61),c=r(53),u=r(46),h=r(320),l=r(96).txdb,p=r(3),d=r(27),f=r(17),m=r(321),g=r(226),y=r(322),v=r(615),b=r(616);r(122),r(123);const w=r(617);r(19);const x=r(43),k=r(119),S=r(21).nestingCodes;class E{constructor(t){this.wallet=t,this.walletdb=t.db,this.logger=this.walletdb.logger,this.network=this.walletdb.network,this.options=this.walletdb.options,this.coinCache=new s(this.options.coinCache),this.conserved=new Set,this.lockedCoins=new Map,this.state=null,this.pending=null,this.events=[]}async open(){let t=null;try{t=await this.getState()}catch(e){this.logger.info("TXDB State Format Error."),t=null}t?(this.state=t,this.logger.info("TXDB loaded for %s.",this.wallet.id)):(this.state=new v(this.wallet.wid,this.wallet.id),this.logger.info("TXDB created for %s.",this.wallet.id)),this.logger.info("TXDB State: tx=%d coin=%s.",this.state.tx,this.state.coin),this.logger.info("Balance: unconfirmed=%s confirmed=%s.",a.btc(this.state.unconfirmed),a.btc(this.state.confirmed)),this.pending=this.state.clone(),await this.loadLockedCoins(),this.state=this.pending}start(){return this.pending=this.state.clone(),this.coinCache.start(),this.walletdb.accountCoinList.start(),this.wallet.start()}drop(){return this.pending=null,this.events.length=0,this.coinCache.drop(),this.walletdb.accountCoinList.drop(),this.wallet.drop()}clear(){return this.pending=this.state.clone(),this.events.length=0,this.coinCache.clear(),this.walletdb.accountCoinList.clear(),this.wallet.clear()}async commit(){try{await this.wallet.commit()}catch(t){throw this.pending=null,this.events.length=0,this.coinCache.drop(),this.walletdb.accountCoinList.drop(),t}if(this.pending.committed)for(var[t,e,r]of(this.state=this.pending,this.events))this.walletdb.emit(t,this.wallet.id,e,r),"tx"==t&&this.walletdb.emit("tx.received."+e.rhash(),this.wallet.id,e,r),this.wallet.emit(t,e,r);this.pending=null,this.events.length=0,this.coinCache.commit(),this.walletdb.accountCoinList.commit()}emit(t,e,r){this.events.push([t,e,r])}prefix(t){return n(this.wallet.wid),l.prefix(this.wallet.wid,t)}put(t,e){n(this.wallet.current),this.wallet.current.put(this.prefix(t),e)}del(t){n(this.wallet.current),this.wallet.current.del(this.prefix(t))}get(t){return this.walletdb.db.get(this.prefix(t))}has(t){return this.walletdb.db.has(this.prefix(t))}range(t){return t.gte&&(t.gte=this.prefix(t.gte)),t.lte&&(t.lte=this.prefix(t.lte)),this.walletdb.db.range(t)}keys(t){return t.gte&&(t.gte=this.prefix(t.gte)),t.lte&&(t.lte=this.prefix(t.lte)),this.walletdb.db.keys(t)}values(t){return t.gte&&(t.gte=this.prefix(t.gte)),t.lte&&(t.lte=this.prefix(t.lte)),this.walletdb.db.values(t)}async getPath(t){return(t=t.getAddress())?this.wallet.getPath(t):null}async hasPath(t){return!!(t=t.getAddress())&&this.wallet.hasPath(t)}async saveCredit(t,e){const r=t.coin;var i=r.toKey(),s=t.toRaw();let n=await this.walletdb.getOutpointMap(r.hash,r.index),a=((n=n||new h(r.hash,r.index)).add(this.wallet.wid)&&this.walletdb.writeOutpointMap(this.wallet,r.hash,r.index,n),this.put(l.c(r.hash,r.index),s),this.put(l.C(e.account,r.hash,r.index),null),this.coinCache.push(i,t),new u(r.hash,r.index));a.wid=this.wallet.wid,a.account=e.account,this.walletdb.accountCoinList.push(i,a)}async removeCredit(t,e){const r=t.coin;t=r.toKey(),await this.removeOutpointMap(r.hash,r.index),this.del(l.C(e.account,r.hash,r.index)),this.del(l.c(r.hash,r.index)),this.coinCache.unpush(t),this.walletdb.accountCoinList.unpush(t)}spendCredit(t,e,r){var i=e.inputs[r].prevout;const s=u.fromTX(e,r);this.put(l.d(s.hash,s.index),t.coin.toRaw()),this.put(l.s(i.hash,i.index),s.toRaw())}unspendCredit(t,e){var r=t.inputs[e].prevout;t=u.fromTX(t,e);this.del(l.s(r.hash,r.index)),this.del(l.d(t.hash,t.index))}writeInput(t,e){var r=t.inputs[e].prevout;const i=u.fromTX(t,e);this.put(l.s(r.hash,r.index),i.toRaw())}removeInput(t,e){t=t.inputs[e].prevout,this.del(l.s(t.hash,t.index))}async resolveInput(t,e,r,i,s,a){var o=t.hash("hex");if(!(o=await this.getSpender(o,e)))return!1;if(await this.hasSpentCoin(o))return!1;var c=await this.getTX(o.hash);n(c);const u=b.fromTX(t,e,r,i);return u.own=a,this.spendCredit(u,c.tx,o.index),-1===c.height&&(u.spent=!0,-1!==r&&(this.changeConfirmed(u.coin,1),(u.coin.lockedByLocktime(r,i)||u.coin.lockedBySequence(r,i))&&this.addLocked(u.coin)),await this.saveCredit(u,s)),!0}async isDoubleSpend(t){for(var{prevout:e}of t.inputs)if(await this.isSpent(e.hash,e.index))return!0;return!1}async isRBF(t){if(t.isRBF())return!0;for(var{prevout:e}of t.inputs)if(e=l.r(e.hash),await this.has(e))return!0;return!1}async getSpender(t,e){return(t=await this.get(l.s(t,e)))?u.fromRaw(t):null}isSpent(t,e){return this.has(l.s(t,e))}async removeOutpointMap(t,e){const r=await this.walletdb.getOutpointMap(t,e);r&&r.remove(this.wallet.wid)&&(0===r.wids.size?this.walletdb.unwriteOutpointMap(this.wallet,t,e):this.walletdb.writeOutpointMap(this.wallet,t,e,r))}async addBlockMap(t,e){let r=await this.walletdb.getBlockMap(e);(r=r||new m(e)).add(t,this.wallet.wid)&&this.walletdb.writeBlockMap(this.wallet,e,r)}async removeBlockMap(t,e){const r=await this.walletdb.getBlockMap(e);r&&r.remove(t,this.wallet.wid)&&(0===r.txs.size?this.walletdb.unwriteBlockMap(this.wallet,e):this.walletdb.writeBlockMap(this.wallet,e,r))}getBlocks(){return this.keys({gte:l.b(0),lte:l.b(4294967295),parse:t=>l.bb(t)})}async getStatusOfSC(t){let e=await this.get(l.de(t));return e?{txs:e.toString().split(",")}:{}}async _setStatusOfSC(t,e){e=e.reduce((t,e)=>(t&&(t+=","),t+e),""),this.put(l.de(t),Buffer.from(e))}async getBlock(t){return(t=await this.get(l.b(t)))?w.fromRaw(t):null}async addBlock(t,e){var r=l.b(e.height);let i,s=await this.get(r);s||(i=w.fromMeta(e),s=i.toRaw()),i=Buffer.allocUnsafe(s.length+32),s.copy(i,0),e=i.readUInt32LE(40,!0),i.writeUInt32LE(e+1,40,!0),t.copy(i,s.length),this.put(r,i)}async removeBlock(t,e){e=l.b(e);const r=await this.get(e);if(r){var i=r.readUInt32LE(40,!0);if(n(0<i),n(r.slice(-32).equals(t)),1===i)this.del(e);else{const t=r.slice(0,-32);t.writeUInt32LE(i-1,40,!0),this.put(e,t)}}}async addBlockSlow(t,e){let r=await this.getBlock(e.height);(r=r||w.fromMeta(e)).add(t)&&this.put(l.b(e.height),r.toRaw())}async removeBlockSlow(t,e){const r=await this.getBlock(e);r&&r.remove(t)&&(0===r.hashes.length?this.del(l.b(e)):this.put(l.b(e),r.toRaw()))}async _add(t,e,r){n(!t.mutable,"Cannot add mutable TX to wallet."),r=r||{};var i=t.hash("hex"),s=await this.getTX(i);if(e){if(!t.isCoinbase()){var a=await this.getSpentCredits(t);for(let r=0;r<t.inputs.length;r++){var o=t.inputs[r],c=o.prevout;let i=a[r];(i=i||await this.getCredit(c.hash,c.index))&&await this.emitCoinSpent(o,i.coin,t,e)}}if(s)return-1!==s.height&&-2!==s.height?null:this._confirm(s,e);await this.removeConflicts(t,!1),this.del(l.r(i))}else{if(s&&!r.reorg)return null;if(await this.isRBF(t))return this.put(l.r(i),null),null;if(!await this.removeConflicts(t,!0))return null}return s=g.fromTX(t,e),this.insert(s,e)}async insert(t,e){const r=t.tx;var s=t.hash,a=e?e.height:-1,o=e?e.mtp:0;const c=new _(this,t,e),u=new Set;let h=!1,p=!1;if(!r.isCoinbase())for(let t=0;t<r.inputs.length;t++){var d=r.inputs[t].prevout;const i=await this.getCredit(d.hash,d.index);if(i){if(d=i.coin,!e&&!await this.verifyInput(r,t,d))return this.clear(),null;var f=await this.getPath(d);n(f),c.setInput(t,f,d),u.add(f.account),this.spendCredit(i,r,t),this.changeUnconfirmed(d,-1),e?(this.changeConfirmed(d,-1),await this.removeCredit(i,f),this.removeLocked(d)):(i.spent=!0,await this.saveCredit(i,f)),p=!0,h=!0}else this.writeInput(r,t)}for(let t=0;t<r.outputs.length;t++){var m=r.outputs[t],g=await this.getPath(m);if(g){if(c.setOutput(t,g),u.add(g.account),!await this.resolveInput(r,t,a,o,g,h)){const i=b.fromTX(r,t,a,o);i.own=h,this.changeUnconfirmed(m,1),e&&this.changeConfirmed(m,1),await this.saveCredit(i,g),(i.coin.lockedByLocktime(a,o)||i.coin.lockedBySequence(a,o))&&this.addLocked(i.coin)}p=!0}}if(!p)return this.clear(),null;this.put(l.t(s),t.toRaw()),this.logger.spam("layout.t insert",i.revHex(s)),this.put(l.m(t.mtime,s),null),e?this.put(l.h(a,s),null):this.put(l.p(s),null);for(const r of u)this.put(l.T(r,s),null),this.put(l.M(r,t.mtime,s),null),e?this.put(l.H(r,a,s),null):this.put(l.P(r,s),null);return e&&(await this.addBlockMap(s,a),await this.addBlock(r.hash(),e),this.refreshLocked(a,i.now())),this.pending.tx++,this.put(l.R,this.pending.commit()),this.unConserveTX(r),this.emit("tx",r,c),this.emit("balance",this.pending.toBalance(),c),c}async _confirm(t,e){const r=t.tx;var s=t.hash,a=e.height,o=e.mtp||e.time;const c=new _(this,t,e),u=new Set;let h=!1;if(t.setBlock(e),!r.isCoinbase()){var p=await this.getSpentCredits(r);for(let e=0;e<r.inputs.length;e++){var d=r.inputs[e].prevout;let i=p[e];if(!i){if(!(i=await this.getCredit(d.hash,d.index)))continue;this.spendCredit(i,r,e),this.changeUnconfirmed(i.coin,-1)}d=i.coin;try{n(-1!==d.height&&-2!==d.height)}catch(t){this.logger.warning("tx(%s): coin.height = -1: %s",r.txid(),t.message)}var f=await this.getPath(d);n(f),c.setInput(e,f,d),u.add(f.account),this.changeConfirmed(d,-1),await this.removeCredit(i,f),this.removeLocked(i.coin),h=!0}}for(let t=0;t<r.outputs.length;t++){var m=r.outputs[t],g=await this.getPath(m);if(g&&(c.setOutput(t,g),u.add(g.account),!await this.resolveInput(r,t,a,o,g,h))){let e=await this.getCredit(s,t);e||((e=b.fromTX(r,t,a,o)).own=!0,this.changeUnconfirmed(m,1)),e.spent&&await this.updateSpentCoin(r,t,a),this.changeConfirmed(m,1),e.coin.time=o,e.coin.height=a,await this.saveCredit(e,g),(e.coin.lockedByLocktime(a,o)||e.coin.lockedBySequence(a,o))&&this.addLocked(e.coin)}}this.del(l.r(s)),this.put(l.t(s),t.toRaw()),this.logger.spam("layout.t confirm",i.revHex(s)),this.del(l.p(s)),this.put(l.h(a,s),null);for(const e of u)this.put(l.T(e,s),null),this.put(l.M(e,t.mtime,s),null),this.del(l.P(e,s)),this.put(l.H(e,a,s),null);return e&&(await this.addBlockMap(s,a),await this.addBlock(r.hash(),e),this.refreshLocked(a,i.now())),this.put(l.R,this.pending.commit()),this.unConserveTX(r),this.emit("confirmed",r,c),this.emit("balance",this.pending.toBalance(),c),c}async remove(t){return(t=await this.getTX(t))?this.removeRecursive(t):null}changeUnconfirmed(t,e){t.isColored||(1===e?(this.pending.coin++,this.pending.unconfirmed+=t.value):(this.pending.coin--,this.pending.unconfirmed-=t.value))}resetBalance(){this.pending.unconfirmed=this.pending.confirmed}changeConfirmed(t,e){t.isColored||(1===e?this.pending.confirmed+=t.value:this.pending.confirmed-=t.value)}changeLocked(t,e,r){e.isColored||(1===r?t.locked+=e.value:t.locked-=e.value)}async removeRecursive(t){n(t);var e=t.tx,r=t.hash;for(let t=0;t<e.outputs.length;t++){var i=await this.getSpender(r,t);i&&(i=await this.getTX(i.hash),await this.removeRecursive(i))}return this.start(),t=await this.erase(t,t.getBlock()),n(t),await this.commit(),t}async unconfirm(t){let e;this.start();try{e=await this._unconfirm(t)}catch(t){throw this.drop(),t}return await this.commit(),e}async _unconfirm(t){const e=await this.getTX(t);return e&&-1!==e.height?this.disconnect(e,e.getBlock()):null}async disconnect(t,e){n(e);const r=t.tx;var s=t.hash,a=e.height,o=e.mtp||e.time;const c=new _(this,t,e),u=new Set;if(t.unsetBlock(),!r.isCoinbase()){var h=await this.getSpentCredits(r);for(let e=0;e<r.inputs.length;e++){const i=h[e];if(i){var p=i.coin;try{n(-1!==p.height&&-2!==p.height)}catch(t){this.logger.warning("tx(%s): coin.height = -1: %s",r.txid(),t.message)}var d=await this.getPath(p);n(d),c.setInput(e,d,p),u.add(d.account),this.changeConfirmed(p,1),i.spent=!0,await this.saveCredit(i,d),(i.coin.lockedByLocktime(a,o)||i.coin.lockedBySequence(a,o))&&this.addLocked(i.coin)}}}for(let t=0;t<r.outputs.length;t++){var f=r.outputs[t],m=await this.getPath(f);if(m){const e=await this.getCredit(s,t);e?(e.spent&&await this.updateSpentCoin(r,t,a),c.setOutput(t,m),u.add(m.account),this.changeConfirmed(f,-1),e.coin.height=-1,await this.saveCredit(e,m)):await this.updateSpentCoin(r,t,a)}}await this.removeBlockMap(s,a),await this.removeBlock(r.hash(),a),this.refreshLocked(a,i.now()),this.put(l.t(s),t.toRaw()),this.put(l.p(s),null),this.del(l.h(a,s));for(const t of u)this.put(l.P(t,s),null),this.del(l.H(t,a,s));return this.put(l.R,this.pending.commit()),this.emit("unconfirmed",r,c),this.emit("balance",this.pending.toBalance(),c),c}async erase(t,e){const r=t.tx;var s=t.hash,a=e?e.height:-1,o=e?e.mtp:0;const c=new _(this,t,e),u=new Set;if(!r.isCoinbase()){var h,p,d=await this.getSpentCredits(r);for(let t=0;t<r.inputs.length;t++){const i=d[t];i?(h=i.coin,p=await this.getPath(h),n(p),c.setInput(t,p,h),u.add(p.account),this.changeUnconfirmed(h,1),e&&this.changeConfirmed(h,1),this.unspendCredit(r,t),await this.saveCredit(i,p),(i.coin.lockedByLocktime(a,o)||i.coin.lockedBySequence(a,o))&&this.addLocked(i.coin)):this.removeInput(r,t)}}for(let t=0;t<r.outputs.length;t++){var f,m=r.outputs[t],g=await this.getPath(m);g&&(c.setOutput(t,g),u.add(g.account),f=b.fromTX(r,t,a,o),this.changeUnconfirmed(m,-1),e&&this.changeConfirmed(m,-1),await this.removeCredit(f,g),this.removeLocked(f.coin))}this.del(l.r(s)),this.del(l.t(s)),this.logger.spam("layout.t erase",i.revHex(s)),this.del(l.m(t.mtime,s)),e?this.del(l.h(a,s)):this.del(l.p(s));for(const r of u)this.del(l.T(r,s)),this.del(l.M(r,t.mtime,s)),e?this.del(l.H(r,a,s)):this.del(l.P(r,s));e&&(await this.removeBlockMap(s,a),await this.removeBlockSlow(s,a),this.refreshLocked(a,i.now())),this.pending.tx--,this.put(l.R,this.pending.commit());try{let t=await x.FactoryOfContract({env:this.walletdb,tx:r,block:e});await t.erase()}catch(t){this.logger.error("TX(%s) Smart Contract Erase Error: %s",r.txid(),t.message)}return this.emit("tx.remove",r,c),this.emit("balance",this.pending.toBalance(),c),c}async removeConflict(t){if(!t)return Promise.resolve();const e=t.tx;return this.logger.warning("Handling conflicting tx: %s.",e.txid()),this.drop(),t=await this.removeRecursive(t),this.start(),this.logger.warning("Removed conflict: %s.",e.txid()),this.emit("conflict",e,t),t}async removeConflicts(t,e){var r=t.hash("hex");const i=[];if(!t.isCoinbase()){for(let a=0;a<t.inputs.length;a++){var s=t.inputs[a].prevout;if(s.hash!==p.NULL_HASH&&(s=await this.getSpender(s.hash,s.index))&&s.hash!==r){const t=await this.getTX(s.hash);if(n(t),s=t.getBlock(),e&&s)return!1;i[a]=t}}for(const t of i)await this.removeConflict(t)}return!0}async verifyInput(t,e,r){var i=f.flags.MANDATORY_VERIFY_FLAGS;return!this.options.verify||t.verifyInput(e,r,i)}conserveTX(t){if(!t.isCoinbase())for(const e of t.inputs)this.conserveCoin(e.prevout)}unConserveTX(t){if(!t.isCoinbase())for(const e of t.inputs)this.unConserveCoin(e.prevout)}conserveCoin(t){t=t.toKey(),this.conserved.add(t)}unConserveCoin(t){return t=t.toKey(),this.conserved.delete(t)}isConserved(t){return t=t.toKey(),this.conserved.has(t)}filterConserved(t){const e=[];for(const r of t)this.isConserved(r)||e.push(r);return e}getConserved(){const t=[];for(const e of this.conserved.keys())t.push(u.fromKey(e));return t}getAccountHistoryHashes(t){return this.keys({gte:l.T(t,p.NULL_HASH),lte:l.T(t,p.HIGH_HASH),parse:t=>{var[,t]=l.Tt(t);return t}})}getHistoryHashes(t){return null!=t?this.getAccountHistoryHashes(t):this.keys({gte:l.t(p.NULL_HASH),lte:l.t(p.HIGH_HASH),parse:t=>l.tt(t)})}getAccountPendingHashes(t){return this.keys({gte:l.P(t,p.NULL_HASH),lte:l.P(t,p.HIGH_HASH),parse:t=>{var[,t]=l.Pp(t);return t}})}getPendingHashes(t){return null!=t?this.getAccountPendingHashes(t):this.keys({gte:l.p(p.NULL_HASH),lte:l.p(p.HIGH_HASH),parse:t=>l.pp(t)})}getAccountOutpoints(t){return void 0!==t&&null!=t?this.walletdb.accountCoinList.getAccount(this.wallet.wid,t):this.walletdb.accountCoinList.ToArray()}getAccountHeightRangeHashes(t,e){var r=e.start||0,i=e.end||4294967295;return this.keys({gte:l.H(t,r,p.NULL_HASH),lte:l.H(t,i,p.HIGH_HASH),limit:e.limit,reverse:e.reverse,parse:t=>{var[,,t]=l.Hh(t);return t}})}getHeightRangeHashes(t,e){var r;return t&&"object"==typeof t&&(e=t,t=null),null!=t?this.getAccountHeightRangeHashes(t,e):(t=e.start||0,r=e.end||4294967295,this.keys({gte:l.h(t,p.NULL_HASH),lte:l.h(r,p.HIGH_HASH),limit:e.limit,reverse:e.reverse,parse:t=>{var[,t]=l.hh(t);return t}}))}getHeightHashes(t){return this.getHeightRangeHashes({start:t,end:t})}getAccountRangeHashes(t,e){var r=e.start||0,i=e.end||4294967295;return this.keys({gte:l.M(t,r,p.NULL_HASH),lte:l.M(t,i,p.HIGH_HASH),limit:e.limit,reverse:e.reverse,parse:t=>{var[,,t]=l.Mm(t);return t}})}getRangeHashes(t,e){var r;return t&&"object"==typeof t&&(e=t,t=null),null!=t?this.getAccountRangeHashes(t,e):(t=e.start||0,r=e.end||4294967295,this.keys({gte:l.m(t,p.NULL_HASH),lte:l.m(r,p.HIGH_HASH),limit:e.limit,reverse:e.reverse,parse:t=>{var[,t]=l.mm(t);return t}}))}async getRange(t,e){const r=[];t&&"object"==typeof t&&(e=t,t=null);for(const s of await this.getRangeHashes(t,e)){var i=await this.getTX(s);n(i),r.push(i)}return r}getLast(t,e){return this.getRange(t,{start:0,end:4294967295,reverse:!0,limit:e||10})}getHistory(t){return null!=t?this.getAccountHistory(t):this.values({gte:l.t(p.NULL_HASH),lte:l.t(p.HIGH_HASH),parse:g.fromRaw})}async getAccountHistory(t){const e=[];for(const i of await this.getHistoryHashes(t)){var r=await this.getTX(i);n(r),e.push(r)}return e}async getPending(t){const e=[];for(const i of await this.getPendingHashes(t)){var r=await this.getTX(i);n(r),e.push(r)}return e}getCredits(t){return void 0!==t&&null!=t?this.getAccountCredits(t):this.range({gte:l.c(p.NULL_HASH,0),lte:l.c(p.HIGH_HASH,4294967295),parse:(t,e)=>{var[t,r]=l.cc(t);const i=b.fromRaw(e);return e=u.toKey(t,r),i.coin.hash=t,i.coin.index=r,this.coinCache.set(e,i),i}})}async fillCoins(){var t,e=await this.keys({gte:l.C(0,p.NULL_HASH,0),lte:l.C(4294967295,p.HIGH_HASH,4294967295),parse:t=>{var[t,e,r]=l.Cc(t);let i=new u(e,r);return i.wid=this.wallet.wid,i.account=t,[i.toKey(),i]}});for(t of e){var r=await this.get(l.c(t[1].hash,t[1].index));if(r){const e=b.fromRaw(r);e.coin.hash=t[1].hash,e.coin.index=t[1].index,this.coinCache.set(t[0],e)}}this.walletdb.accountCoinList.load(e)}async getAccountCredits(t){const e=[];for(const i of await this.getAccountOutpoints(t)){var r=await this.getCredit(i.hash,i.index);r||(this.logger.warning("getAccountCredits: credit not found."),n(r)),e.push(r)}return e}async getSpentCredits(t){if(t.isCoinbase())return[];var e=t.hash("hex");const r=[];for(let e=0;e<t.inputs.length;e++)r.push(null);return await this.range({gte:l.d(e,0),lte:l.d(e,4294967295),parse:(e,i)=>{var[,e]=l.dd(e);const s=c.fromRaw(i);i=t.inputs[e],n(i),s.hash=i.prevout.hash,s.index=i.prevout.index,r[e]=new b(s)}}),r}async getCoins(t){const e=[];if(void 0!==t&&null!=t)for(const i of await this.getAccountOutpoints(t)){var r=await this.getCredit(i.hash,i.index);r||(this.logger.warning("getAccountCredits: credit not found."),n(r)),r.spent||e.push(r.coin)}else await this.range({gte:l.c(p.NULL_HASH,0),lte:l.c(p.HIGH_HASH,4294967295),parse:(t,r)=>{var[t,i]=l.cc(t);const s=b.fromRaw(r);r=u.toKey(t,i),s.coin.hash=t,s.coin.index=i,this.coinCache.set(r,s),s.spent||e.push(s.coin)}});return e}async getSpentCoins(t){if(t.isCoinbase())return[];const e=[];for(const r of await this.getSpentCredits(t))r?e.push(r.coin):e.push(null);return e}async getCoinView(t){const e=new o;if(!t.isCoinbase())for(const i of t.inputs){var r=i.prevout;(r=await this.getCoin(r.hash,r.index))&&e.addCoin(r)}return e}async getSpentView(t){const e=new o;if(!t.isCoinbase())for(const r of await this.getSpentCoins(t))r&&e.addCoin(r);return e}async getState(){var t=await this.get(l.R);return t?v.fromRaw(this.wallet.wid,this.wallet.id,t):null}async loadLockedCoins(){var t=this.walletdb.curHeight,e=i.now();for(const r of await this.wallet.getCredits()){let i=r.coin;i.getAddress()&&(i.lockedByLocktime(t,e)||i.lockedBySequence(t,e))&&this.addLocked(i)}}refreshLocked(t,e){for(const r of this.lockedCoins.values())r.lockedByLocktime(t,e)||r.lockedBySequence(t,e)||this.removeLocked(r)}addLocked(t){var e=l.prefix(this.wallet.wid,l.c(t.hash,t.index));this.lockedCoins.has(e)||(this.lockedCoins.set(e,t),this.changeLocked(this.pending,t,1))}removeLocked(t){var e=l.prefix(this.wallet.wid,l.c(t.hash,t.index));this.lockedCoins.has(e)&&(this.lockedCoins.delete(e),this.changeLocked(this.pending,t,-1))}async getTX(t){return(t=await this.get(l.t(t)))?g.fromRaw(t):null}async getDetails(t){return(t=await this.getTX(t))?this.toDetails(t):null}async toDetails(t){const e=[];if(!Array.isArray(t))return this._toDetail(t);for(const i of t){var r=await this._toDetail(i);r&&e.push(r)}return e}async _toDetail(t){var e=t.tx,r=t.getBlock();const i=new _(this,t,r);var s=await this.getSpentCoins(e);for(let t=0;t<e.inputs.length;t++){var n=s[t];let e=null;n&&(e=await this.getPath(n)),i.setInput(t,e,n)}for(let t=0;t<e.outputs.length;t++){var a=e.outputs[t];a=await this.getPath(a);i.setOutput(t,a)}return i}hasTX(t){return this.has(l.t(t))}async getCoin(t,e){return(t=await this.getCredit(t,e))?t.coin:null}async emitCoinSpent(t,e,r,i){(r={env:this.walletdb,block:i,tx:r,hash:t.prevout.hash,i:t.prevout.index,height:i.height,output:e,type:e.getReturnType(),data:e.getReturnData(S)}).data&&await k(r).spent(t)}async getCredit(t,e){var r=this.state,i=u.toKey(t,e);let s=this.coinCache.get(i);if(s)return s;if(s=await this.get(l.c(t,e))){const n=b.fromRaw(s);return n.coin.hash=t,n.coin.index=e,r===this.state&&this.coinCache.set(i,n),n}return null}async getSpentCoin(t,e){if(!(t=await this.get(l.d(t.hash,t.index))))return null;const r=c.fromRaw(t);return r.hash=e.hash,r.index=e.index,r}hasSpentCoin(t){return this.has(l.d(t.hash,t.index))}async updateSpentCoin(t,e,r){if(t=u.fromTX(t,e),e=await this.getSpender(t.hash,t.index)){const i=await this.getSpentCoin(e,t);i&&(i.height=r,this.put(l.d(e.hash,e.index),i.toRaw()))}}async hasCoin(t,e){var r=u.toKey(t,e);return!!this.coinCache.has(r)||this.has(l.c(t,e))}async getBalance(t){return null!=t?this.getAccountBalance(t):this.state.toBalance()}async getAccountBalance(t){var e=await this.getAccountCredits(t);const r=new y(this.wallet.wid,this.wallet.id,t);var i=this.walletdb.curHeight,s=this.network.now();for(const t of e){const e=t.coin;-2!==e.height&&(-1===e.height||e.isColored||(r.confirmed+=e.value),t.spent||e.isColored||(r.unconfirmed+=e.value),(e.lockedByLocktime(i,s)||e.lockedBySequence(i,s))&&this.changeLocked(r,e,1))}return r}async zap(t,e){n(i.isU32(e));var r=i.now();const s=[];for(const i of await this.getRange(t,{start:0,end:r-e}))-1===i.height&&(n(r-i.mtime>=e),this.logger.debug("Zapping TX: %s (%s)",i.tx.txid(),this.wallet.id),await this.remove(i.hash),s.push(i.hash));return s}async abandon(t){if(await this.has(l.p(t)))return this.remove(t)}}E.layout=l;class _{constructor(t,e,r){this.wallet=t.wallet,this.network=this.wallet.network,this.wid=this.wallet.wid,this.id=this.wallet.id,this.chainHeight=t.walletdb.curHeight,this.hash=e.hash,this.tx=e.tx,this.mtime=e.mtime,this.size=this.tx.getSize(),this.vsize=this.tx.getVirtualSize(),this.block=null,this.height=-1,this.time=0,r&&(this.block=r.hash,this.height=r.height,this.time=r.time),this.inputs=[],this.outputs=[],this.init()}init(){for(const t of this.tx.inputs){const e=new A;e.address=t.getAddress(),this.inputs.push(e)}for(const t of this.tx.outputs){const e=new A;e.value=t.value,e.address=t.getAddress(),this.outputs.push(e)}}setInput(t,e,r){const i=this.inputs[t];i.prevout=this.tx.inputs[t].prevout,r&&(i.value=r.value,i.address=r.getAddress()),e&&(i.path=e)}setOutput(t,e){const r=this.outputs[t];e&&(r.path=e)}getDepth(){var t;return-1===this.height||(t=this.chainHeight-this.height)<0?0:1+t}getFee(){let t=0,e=0;for(const e of this.inputs){if(!e.path)return 0;t+=e.value}for(const t of this.outputs)e+=t.value;return t-e}getRate(t){return d.getRate(this.vsize,t)}toJSON(){var t=this.getFee();let e=this.getRate(t);return Number.isSafeInteger(e)||(e=0),{wid:this.wid,id:this.id,hash:i.revHex(this.hash),height:this.height,block:this.block?i.revHex(this.block):null,time:this.time,mtime:this.mtime,date:i.date(this.time||this.mtime),size:this.size,virtualSize:this.vsize,fee:t,rate:e,confirmations:this.getDepth(),inputs:this.inputs.map(t=>t.getJSON(this.network)),outputs:this.outputs.map(t=>t.getJSON(this.network)),tx:this.tx.toRaw().toString("hex")}}}class A{constructor(){this.value=0,this.address=null,this.path=null}toJSON(){return this.getJSON()}getJSON(t){return{prevout:this.prevout?this.prevout.toJSON():null,value:this.value,address:this.address?this.address.toString(t):null,path:this.path?this.path.toJSON():null}}}t.exports=E},function(t,e,r){"use strict";
864
864
  /*!
865
865
  * masterkey.js - master bip32 key object for vallnet
866
866
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -870,7 +870,7 @@ Me=new RegExp('(?:false|true|null|[\\{\\}\\[\\]]|(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.
870
870
  * rpc.js - bitcoind-compatible json rpc for vallnet.
871
871
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
872
872
  * https://github.com/bookmansoft/gamegold
873
- */const i=r(0),s=r(319),n=r(73);r(122);const a=r(96).walletdb,o=r(161),c=r(78),u=c.errors,h=c.MAGIC_STRING,l=r(77),p=r(59),d=r(109),f=r(1),m=r(196),g=r(3),y=r(80),v=r(34),b=r(17),w=r(7),x=r(6),k=r(28),S=r(12),E=r(32),_=r(133),A=r(60),R=r(46),I=r(19),j=r(138),C=r(139),{ContractType:P,ContractState:O,PropStatus:T,HtlcStatus:F}=r(5),B=r(140),N=r(125);r(124).Mnemonic;const D=r(143),L=r(21).opcodes;t.exports=class extends c{constructor(t){super(t),i(t,"RPC requires a WalletDB."),this.wdb=t,this.keys=t.keys,this.network=t.network,this.logger=t.logger.context("rpc"),this.client=t.client,this.init()}init(){this.add("sys.alliance.create",this.allianceCreate),this.add("sys.alliance.import",this.allianceImport),this.add("sys.alliance.delete",this.allianceDelete),this.add("sys.alliance.refresh",this.refreshAlliance),this.add("sys.alliance.refresh.async",this.refreshAllianceAsync),this.add("sys.alliance.gettoken",this.getAllianceNodeToken),this.add("sys.alliance.user",this.allianceUserCreate),this.add("wallet",this.routerOfWallet),this.add("wallet.create",this.mkwallet),this.add("wallet.exportmnemonic",this.exportMnemonic),this.add("wallet.export",this.dumpWallet),this.add("wallet.import",this.importWallet),this.add("wallet.list",this.getWallets),this.add("wallet.info",this.getWalletInfo),this.add("wallet.block",this.getWalletBlock),this.add("wallet.layouth",this.getWalletLayoutH),this.add("wallet.encrypt",this.encryptWallet),this.add("wallet.decrypt",this.decryptWallet),this.add("wallet.changepassphrase",this.changePassphrase),this.add("wallet.lock",this.walletLock),this.add("wallet.unlock",this.unlock),this.add("wallet.blocks",this.getblocks),this.add("wallet.auth",this.walletAuth),this.add("key",this.routerOfKey),this.add("key.export.private",this.dumpPrivKey),this.add("key.export.public",this.getKey),this.add("key.master.admin",this.masterkey),this.add("key.import.private",this.importPrivKey),this.add("key.import.public",this.importPubkey),this.add("key.import.address",this.importAddress),this.add("key.shared.add",this.addShared),this.add("key.shared.del",this.removeShared),this.add("account",this.routerOfAccount),this.add("account.list",this.listAccounts),this.add("account.get",this.accountGet),this.add("account.create",this.accountCreate),this.add("account.received",this.getReceivedByAccount),this.add("account.listreceived",this.listReceivedByAccount),this.add("balance.confirmed",this.getBalance),this.add("balance.all",this.getBalanceAll),this.add("balance.unconfirmed",this.getUnconfirmedBalance),this.add("balance.log",this.getBalanceLog),this.add("comm.notify",this.commNotify),this.add("comm.hash",this.calcHash),this.add("comm.listNotify",this.listNotify),this.add("comm.secret",this.sendSecret),this.add("comm.listContact",this.listContact),this.add("comm.scanContact",this.scanContact),this.add("comm.comment",this.sendComment),this.add("comm.comment.query",this.commentQuery),this.add("sys.walletdb.stop",this.stop),this.add("sys.walletnode.shutdown",this.shutdown),this.add("sys.walletdb.create",this.createWalletDb),this.add("sys.walletdb.destroy",this.destroyWalletDb),this.add("sys.zap",this.zap),this.add("sys.setfee",this.setTXFee),this.add("sys.message.sign",this.signMessage),this.add("sys.rescan",this.rescan),this.add("sys.log",this.sysLog),this.add("address",this.routerOfAddress),this.add("address.list",this.getAddressesByAccount),this.add("address.index",this.getAddressesByIndex),this.add("address.receive",this.getAccountAddress),this.add("address.change",this.getAccountChangeAddress),this.add("address.nested",this.getAccountNestedAddress),this.add("address.calc",this.calcAddress),this.add("address.create",this.createAddress),this.add("address.create.admin",this.createAddressAdmin),this.add("address.receive.create",this.createAddress),this.add("address.change.create",this.createChange),this.add("address.nested.create",this.createNested),this.add("address.import",this.importAddress),this.add("address.key.admin",this.getPrivKey),this.add("address.wif.admin",this.getwif),this.add("address.has",this.hasAddress),this.add("address.amount",this.getReceivedByAddress),this.add("address.account",this.getAccount),this.add("address.received",this.getReceivedByAddress),this.add("address.received.list",this.listReceivedByAddress),this.add("cp",this.routerOfCp),this.add("cp.create",this.cpRegister),this.add("cp.create.async",this.cpRegisterAsync),this.add("cp.change",this.cpChange),this.add("cp.query",this.cpQuery),this.add("cp.mine",this.cpMine),this.add("cp.x509",this.cpX509),this.add("cp.user",this.getUserToken),this.add("sc",this.routerOfSc),this.add("sc.register",this.scRegister),this.add("sc.run",this.scRun),this.add("ca",this.routerOfCa),this.add("ca.issue",this.caIssue),this.add("ca.user.status",this.caUserStatus),this.add("ca.user.log",this.caUserLog),this.add("ca.abolish",this.caAbolish),this.add("ca.enchance",this.enchanceCp),this.add("ca.list.me",this.queryMyErlist),this.add("ca.issue.async",this.caIssueAsync),this.add("ca.abolish.async",this.caAbolishAsync),this.add("ca.issue.public",this.caIssuePublic),this.add("ca.abolish.public",this.caAbolishPublic),this.add("order",this.routerOfOrder),this.add("order.setGuider",this.setGuider),this.add("order.getGuider.wallet",this.getGuider),this.add("order.pay",this.payOrder),this.add("order.query.wallet",this.queryOrderList),this.add("prop",this.routerOfProp),this.add("prop.create",this.propCreate),this.add("prop.send",this.propExchange),this.add("prop.donate",this.propDonate),this.add("prop.receive",this.propReceive),this.add("prop.createlist",this.propCreateList),this.add("prop.sendlist",this.propSendList),this.add("prop.sendlist.admin",this.propSendListAdmin),this.add("prop.order",this.propOrder),this.add("prop.found",this.propFound),this.add("prop.sale",this.propSale),this.add("prop.buy",this.propBuy),this.add("prop.wallet.byid",this.propGet),this.add("prop.wallet.byoid",this.listPropByOid),this.add("prop.wallet.byaddress",this.listProp),this.add("contract",this.routerOfContract),this.add("contract.create",this.contractCreate),this.add("contract.promise",this.contractPromise),this.add("contract.execute",this.contractExecute),this.add("contract.mine",this.contractOfMine),this.add("htlc",this.routerOfHTLC),this.add("htlc.suggest",this.htlcSuggest),this.add("htlc.suggest.cancel",this.htlcSuggestCancel),this.add("htlc.suggest.deal",this.htlcSuggestDeal),this.add("htlc.assent",this.htlcAssent),this.add("htlc.assent.cancel",this.htlcAssentCancel),this.add("htlc.assent.deal",this.htlcAssentDeal),this.add("htlc.query",this.htlcQuery),this.add("vote.send",this.sendVote),this.add("vote.send.async",this.sendVoteAsync),this.add("oracle.send",this.sendOracle),this.add("stock.offer",this.stockOffer),this.add("stock.purchase",this.stockPurchase),this.add("stock.purchaseTo",this.stockPurchaseTo),this.add("stock.send",this.stockSend),this.add("stock.bid",this.stockBid),this.add("stock.auction",this.stockAuction),this.add("stock.list.wallet",this.stockList),this.add("stock.record.wallet",this.stockRecordList),this.add("tx.get.wallet",this.getTransaction),this.add("tx.list",this.listTransactions),this.add("tx.create",this.createTX),this.add("tx.send",this.sendTX),this.add("tx.send.async",this.sendTXAsync),this.add("tx.last",this.getLast),this.add("tx.pending",this.getPending),this.add("tx.pending.get",this.getPendingItem),this.add("tx.pending.hash",this.getPendingHash),this.add("tx.pending.count",this.getPendingCount),this.add("tx.resend.admin",this.resendWalletTransactions),this.add("tx.mstrans",this.listMSTrans),this.add("tx.mstrans.sign",this.signMSTrans),this.add("tx.history",this.getHistory),this.add("tx.history.since",this.listSinceBlock),this.add("tx.range",this.getRange),this.add("tx.abandon.admin",this.abandonTransaction),this.add("tx.abandonall.admin",this.abandonPending),this.add("tx.importprunedfunds.admin",this.importPrunedFunds),this.add("tx.removeprunedfunds.admin",this.removePrunedFunds),this.add("tx.resendall.admin",this.resend),this.add("tx.sign.admin",this.signTX),this.add("tx.fund.admin",this.fundRawTransaction),this.add("coin",this.routerOfCoin),this.add("coin.get",this.getCoin),this.add("coin.remove.admin",this.removeCoin),this.add("coin.spender",this.getSpender),this.add("coin.cache",this.getCoincacheSize),this.add("coin.list",this.listUnspent),this.add("coin.selectone",this.selectone),this.add("coin.conserved.get",this.getConservedCoins),this.add("coin.conserved.add",this.conserveCoin),this.add("coin.conserved.del",this.unConserveCoin),this.add("coin.conserved.list",this.listConservedUnspent),this.add("coin.conserved.oper.list",this.listOperUnspent),this.add("coin.locked.list",this.listLockedUnspent)}async routerOfCoin(t){throw new l(u.MISC_ERROR,"\n coin.get 查询硬币-UTXO\n coin.remove.admin 移除指定硬币(管理员判断为状态异常者)\n coin.spender 查询硬币的消费者\n coin.list 列表硬币-UTXO\n coin.conserved.get 获取钱包保持的Coin的信息\n coin.conserved.add 钱包增加需要保持的Coin\n coin.conserved.del 钱包减少需要保持的Coin\n coin.conserved.list 列表钱包保持的UTXO\n coin.conserved.oper.list 批量锁定/解锁一组UTXO \n coin.locked.list 列表目前交易层锁定的UTXO\n ")}async routerOfContract(t){throw new l(u.MISC_ERROR,"\n contract.create 发布交易对合约\n contract.promise 签署交易对合约\n contract.execute 执行交易对合约\n contract.mine 获取已签署交易对合约列表\n contract.list 查询并返回交易对\n ")}async routerOfHTLC(t){throw new l(u.MISC_ERROR,"\n htlc.suggest 发布跨链合约\n htlc.suggest.deal 兑现合约\n htlc.suggest.cancel 取消合约\n htlc.assent 响应跨链合约\n htlc.assent.deal 兑现响应\n htlc.assent.cancel 取消响应\n htlc.query 查询合约\n ")}async routerOfWallet(t){throw new l(u.MISC_ERROR,"\n wallet.create 创建钱包\n wallet.list 列表钱包\n wallet.info 查询钱包概要\n wallet.block 查询区块信息\n wallet.exportmnemonic 导出钱包助记词备份\n wallet.export 导出钱包备份\n wallet.import 导入钱包备份\n wallet.encrypt 将主私钥永久加密\n wallet.decrypt 将主私钥永久解密\n wallet.changepassphrase 在主私钥已经加密的情况下,修改其加密密码,要提交旧/新两个密码。如果尚未加密则执行失败\n wallet.lock 在主私钥已加密的前提下,清理内存中的密钥信息以确保锁定,相当于手工执行自动锁定\n wallet.unlock 在主私钥已加密的前提下,解密主私钥,持续一段时间后自动锁定\n wallet.blocks 列表钱包相关区块\n ")}async routerOfAddress(t){throw new l(u.MISC_ERROR,"\n address.list 列表指定账户下地址\n address.receive 列表指定账户下收款地址\n address.change 列表指定账户下找零地址\n address.nested 列表指定账户下嵌套地址\n address.create 创建一个收款地址\n address.create.admin 创建一个收款地址,回显私钥\n address.receive.create 创建一个收款地址\n address.change.create 创建一个找零地址\n address.nested.create 创建一个嵌套地址\n address.import 导入一个地址\n address.key.admin 查询地址的密钥\n address.amount 查询指定地址上的余额\n address.account 查询指定地址对应的账户\n address.wif.admin 查询地址对应的私钥\n address.has 判断钱包是否包含地址\n address.received 根据地址查询进项总额\n address.received.list 根据地址查询进项\n address.filter 在订单流水中,查询符合筛选条件的地址集\n ")}async routerOfAccount(t){throw new l(u.MISC_ERROR,"\n account.list 列表账户\n account.get 查询账户\n account.create 创建账户\n account.received 查询收款总额\n account.listreceived 列表收款记录\n balance.confirmed 已确认余额\n balance.all 余额\n balance.unconfirmed 未确认余额\n balance.log 查询指定账户变更日志\n ")}async routerOfKey(t){throw new l(u.MISC_ERROR,"\n key.export.private 根据输入地址,导出私钥\n key.export.public 根据输入地址,打出公钥\n key.master.admin 导出根密钥和助记词, 注意 encrypt 状态下无法导出私钥\n key.import.private 导入私钥\n key.import.public 导入公钥\n key.import.address 导入地址\n key.shared.add 新增共享公钥\n key.shared.del 删除共享公钥\n ")}async routerOfCp(t){throw new l(u.MISC_ERROR,"\n cp.create 创建CP记录\n cp.change 修改CP记录\n cp.snap 查询CP历史快照\n cp.sps 查询CP权证列表\n cp.remoteQuery 查询全节点中的CP列表\n cp.query 查询本地CP列表\n cp.byClass 根据游戏类别查询CP记录\n cp.byName 根据名称查询CP记录\n cp.byId 根据ID查询CP记录\n cp.mine 当前操作员注册的CP\n cp.x509 为CP创建根证书\n cp.user 生成用户令牌(钱包)\n ")}async routerOfSc(t){throw new l(u.MISC_ERROR,"\n sc.model 查询托管合约模板列表\n sc.register 指定托管合约模板,创建新的实例\n sc.query 查询托管合约实例列表\n sc.run 调用托管合约实例\n ")}async routerOfCa(t){throw new l(u.MISC_ERROR,"\n ca.issue 电子证书签发\n ca.abolish 电子证书废止记录\n ca.verify 电子证书验证\n ca.user.status 根据企业证书编号和用户编号查询\n ca.user.log 根据企业证书编号和用户编号查询日志\n ca.enchance CA机构间增信\n ca.rank 查询CA信用等级\n ca.list 查询电子证书列表\n ca.list.ab 查询电子证书废止记录列表\n ca.list.me 查询钱包内证书列表\n ")}async routerOfOrder(t){throw new l(u.MISC_ERROR,"\n order.pay 支付订单(钱包)\n order.query 查询订单记录\n order.query.admin 查询订单列表(特约节点)\n order.query.wallet 查询订单列表(钱包)\n order.setGuider 为指定厂商、指定用户设定推广员\n order.getGuider 查询指定地址对应的推广员\n order.getGuider.wallet 查询指定地址对应的推广员\n order.queryGuider 查询指定推广员的推广统计\n ")}async routerOfProp(t){throw new l(u.MISC_ERROR,"\n prop.create 创建道具\n prop.send 转移道具\n prop.donate 捐赠道具\n prop.receive 接收捐赠道具\n prop.createlist 批量创建道具\n prop.sendlist 批量转移道具\n prop.order 订购:制备并发送\n prop.found 熔铸道具\n prop.sale 拍卖道具\n prop.buy 购买道具\n prop.byaddress 根据地址查询自己拥有的道具\n prop.wallet.byaddress 根据地址查询自己拥有的道具\n prop.wallet.byid 根据PID查询自己拥有的道具\n prop.wallet.byoid 根据OID查询自己拥有的道具\n ")}async allianceCreate(t,e,r){if(e||t.length<3)throw new l(u.MISC_ERROR,"sys.alliance.create password nodeid alliancename (host): 创建联盟节点证书 备份密码 节点编号 盟友名称 (节点地址)");const i=new y([t]);e=i.str(0);var s=i.uint(1,0),n=i.str(2,"");t=i.str(3,"");if(!s||!e)throw new l(u.MISC_ERROR,"节点编号、备份密码都不能为空");if(!this.wdb.$parent||!this.wdb.$parent.config.identityKey)throw new l(u.MISC_ERROR,"identityKey not set yet, please run sys.alliance.gettoken without params first");let[a,o]=await this.accessControl(r,""),c=await a.createAllianceInfo(n,s),h=(this.wdb.$parent.pool.authdb.addKnown("0.0.0.0",k.publicKeyCreate(Buffer.from(this.wdb.$parent.config.identityKey,"hex"),!0)),{body:{language:c.mnemonic.language,phrase:c.mnemonic.getPhrase(),passphrase:c.mnemonic.passphrase,alliancePrivateKey:c.alliancePrivateKey.toString("hex"),allianceName:n,allianceNodeId:s,awardAddress:c.awardAddress,allianceNodeToken:{network:this.network.type,alliancename:n,sn:s,prv:c.prv.toString("hex"),pub:c.pub.toString("hex"),address:c.address},notifyAddress:a.notifyAddress,authorized:this.wdb.$parent.pool.authdb.getAuthorized()},password:e,network:this.network.type,file:this.network.type+`-${n}-${s}.keystore`}),m=N.encrypt(h);if(this.wdb.$parent){let i=!1;for(var g of this.wdb.$parent.config.alliances)if((g=g.split("|"))[0]==n&&g[1]==s){i=!0;break}i||(r=f.hashInt(n+"-"+s),this.wdb.$parent.pool.authdb.addKnown("0.0.0.0:"+r,Buffer.from(h.body.allianceNodeToken.pub,"hex")),h.body.authorized=this.wdb.$parent.pool.authdb.getAuthorized(),m=N.encrypt(h),this.wdb.$parent.config.alliances.push(`${n}|${s}|${m}|${e}|${h.body.awardAddress}|`+t),await this.wdb.$parent.saveConfigAsync())}return r={host:t,key:h.body.allianceNodeToken.pub},e=d.signObj(r,a.notifyKey.privateKey),await a.commNotify({dst:a.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:r,sig:e,pub:a.notifyKey.publicKey.toString("hex")})}),await p.writeFile(h.file,m,"utf8"),r=(await a.getAccount(o)).getReceive().toString(),await this.wdb.logAudit({address:r,oper:"node.create",hash:n+"."+s,index:0}),{nodeid:s,alliancename:n,host:t,peerPubkey:h.body.allianceNodeToken.pub,awardAddress:h.body.awardAddress,file:h.file,notifyAddress:a.notifyAddress}}async allianceImport(t,e,r){if(e||t.length<3)throw new l(u.MISC_ERROR,"sys.alliance.import password nodeid alliancename key (host): 导入联盟节点 备份密码 节点编号 盟友名称 节点公钥 (节点地址)");if(!this.wdb.$parent||!this.wdb.$parent.config.identityKey)throw new l(u.MISC_ERROR,"identityKey not set yet, please run sys.alliance.gettoken without params first");const i=new y([t]);e=i.str(0);var s=i.uint(1,0),n=i.str(2,""),a=(t=i.str(3,""),i.str(4,""));if(!s||!e||!t)throw new l(u.MISC_ERROR,"节点编号、备份密码、节点公钥都不能为空");let o,[c,h]=await this.accessControl(r,""),m=await c.createAllianceInfo(n,s,t),g=(this.wdb.$parent.pool.authdb.addKnown("0.0.0.0",k.publicKeyCreate(Buffer.from(this.wdb.$parent.config.identityKey,"hex"),!0)),{body:{alliancePrivateKey:m.alliancePrivateKey.toString("hex"),allianceName:n,allianceNodeId:s,allianceNodeToken:{network:this.network.type,alliancename:n,sn:s,pub:m.pub.toString("hex"),address:m.address},awardAddress:m.awardAddress,notifyAddress:c.notifyAddress},password:e,network:this.network.type,file:this.network.type+`-${n}-${s}.keystore`});if(this.wdb.$parent){let i=!1;for(var v of this.wdb.$parent.config.alliances)if((v=v.split("|"))[0]==n&&v[1]==s){i=!0;break}i||(r=f.hashInt(n+"-"+s),this.wdb.$parent.pool.authdb.addKnown("0.0.0.0:"+r,Buffer.from(t,"hex")),g.body.authorized=this.wdb.$parent.pool.authdb.getAuthorized(),o=N.encrypt(g),this.wdb.$parent.config.alliances.push(`${n}|${s}|${o}|${e}|${g.body.awardAddress}|`+a),await this.wdb.$parent.saveConfigAsync())}else o=N.encrypt(g);return await p.writeFile(g.file,o,"utf8"),r={host:a,key:g.body.allianceNodeToken.pub},t=d.signObj(r,c.notifyKey.privateKey),await c.commNotify({dst:c.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:r,sig:t,pub:c.notifyKey.publicKey.toString("hex")})}),e=(await c.getAccount(h)).getReceive().toString(),await this.wdb.logAudit({address:e,oper:"node.create",hash:n+"."+s,index:0}),{nodeid:s,alliancename:n,host:a,peerPubkey:g.body.allianceNodeToken.pub,awardAddress:g.body.awardAddress,file:g.file,notifyAddress:c.notifyAddress}}async refreshAlliance(t,e,r){if(e)throw new l(u.MISC_ERROR,"sys.alliance.refresh amount: 为联盟成员批量充值 充值金额");var i=new y([t]).uint(0,0);if(i<1e4||5e9<i)throw new l(u.MISC_ERROR,"无效的充值金额(10000~5000000000)");let[s,n]=await this.accessControl(r);if(this.wdb.$parent)for(var a of this.wdb.$parent.config.alliances){a=a.split("|"),S.fromString(a[4],this.network.type).isWitnessPubkeyhash()&&await s.send({outputs:[{address:a[4],value:i}]},n);var o=N.decrypt({network:this.network.type,password:a[3],body:a[2]});a=(this.wdb.$parent.rpc.addPeer&&await this.wdb.$parent.rpc.addPeer([a[5],o.allianceNodeToken.pub]),{host:a[5],key:o.allianceNodeToken.pub}),o=d.signObj(a,s.notifyKey.privateKey);await s.commNotify({dst:s.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:a,sig:o,pub:s.notifyKey.publicKey.toString("hex")})})}}async refreshAllianceAsync(t,e,r){if(e)throw new l(u.MISC_ERROR,"sys.alliance.refresh.async amount: 为联盟成员批量充值 充值金额");var i=new y([t]).uint(0,0);if(i<1e4||5e9<i)throw new l(u.MISC_ERROR,"无效的充值金额(10000~5000000000)");let[s,n]=await this.accessControl(r);if(this.wdb.$parent)for(var a of this.wdb.$parent.config.alliances){a=a.split("|"),S.fromString(a[4],this.network.type).isWitnessPubkeyhash()&&s.send({outputs:[{address:a[4],value:i}]},n);var o=N.decrypt({network:this.network.type,password:a[3],body:a[2]});a=(this.wdb.$parent.rpc.addPeer&&await this.wdb.$parent.rpc.addPeer([a[5],o.allianceNodeToken.pub]),{host:a[5],key:o.allianceNodeToken.pub}),o=d.signObj(a,s.notifyKey.privateKey);s.commNotify({dst:s.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:a,sig:o,pub:s.notifyKey.publicKey.toString("hex")})})}}async allianceDelete(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,"sys.alliance.delete nodeid alliancename: 删除联盟节点证书 节点编号 盟友名称");const i=new y([t]);var s=i.uint(0,0),n=i.str(1,"");let[a,o]=await this.accessControl(r,"");if(!s||!n)throw new l(u.MISC_ERROR,"节点编号、节点名称都不能为空");if(this.wdb.$parent)for(let t=0;t<this.wdb.$parent.config.alliances.length;t++){var c=this.wdb.$parent.config.alliances[t].split("|");c[0]==n&&c[1]==s&&(this.wdb.$parent.config.alliances.splice(t,1),await this.wdb.$parent.config.saveAsync(),c[5]&&await this.wdb.$parent.rpc.delPeer([c[5]]))}return e=(await a.getAccount(o)).getReceive().toString(),await this.wdb.logAudit({address:e,oper:"node.delete",hash:n+"."+s,index:0}),!0}async getAllianceNodeToken(t,e,r){if(e)throw new l(u.MISC_ERROR,"sys.alliance.gettoken (nodeid alliancename pubkey): 创建联盟节点信道密钥 (节点编号 盟友名称)");const i=new y([t]);e=i.uint(0,0),t=i.str(1);var s=i.str(2);if(!this.wdb.$parent)throw new l(u.MISC_ERROR,"this cmd can only run on fullnode.");let[n]=await this.accessControl(r),a=await n.createAllianceInfo(t,e,s);return t||(this.wdb.$parent.config.identityKey?(a.prv=Buffer.from(this.wdb.$parent.config.identityKey,"hex"),a.pub=k.publicKeyCreate(a.prv,!0),a.address=S.fromWitnessPubkeyhash(x.hash160(a.pub),this.network.type).toString()):(this.wdb.$parent.pool.options.identityKey=a.prv,this.wdb.$parent.config.identityKey=a.prv.toString("hex"),await this.wdb.$parent.saveConfigAsync())),{network:this.network.type,alliancename:t,sn:e,prv:a.prv.toString("hex"),pub:a.pub.toString("hex"),address:a.address}}async allianceUserCreate(t,e,r){if(e)throw new l(u.MISC_ERROR,"sys.alliance.user cid uid (alliancename): 创建企业用户 企业编号 用户编号 (盟友名称)");return this.$allianceUserCreate(t,r)}async $allianceUserCreate(t,e,r){const i=new y([t]);t=i.str(0);var s=i.uint(1),n=i.str(2,"");let a=null,o=null;o=n?([e]=await this.accessControl(e),x.hash256(Buffer.concat([Buffer.from(n),e.master.key.privateKey]))):Buffer.from(this.wdb.$parent.config.alliancePrivateKey,"hex"),n=E.fromPrivate(o,!0,this.network);let c=E.fromPrivate(x.hash256(Buffer.concat([Buffer.from(t+"-"+s),n.privateKey]),!0,this.network));return c.witness=!0,a=c.signData({cid:t,uid:s}),r&&(a.prvkey=c.privateKey.toString("hex")),a}async isReady(t){return this.wdb.isFull()}async shutdown(t,e){return this.wdb.$parent&&this.wdb.$parent.close().catch(t=>{setImmediate(()=>{throw t})}).finally(async()=>{await new Promise(t=>{setTimeout(t,1e4)}),process.exit(0)}),"Stopping."}async stop(t,e,r){if(e||0!==t.length)throw new l(u.MISC_ERROR,"sys.walletdb.stop");return this.wdb.close(),"Stopping walletdb..."}async destroyWalletDb(t,e,r){if(e||0!==t.length)throw new l(u.MISC_ERROR,"sys.walletdb.destroy: 删除钱包数据库");return await this.wdb.close(),await this.wdb.destroy(),"Destroyed."}async createWalletDb(t,e,r){if(e||0!==t.length)throw new l(u.MISC_ERROR,"sys.walletdb.create: 删除原有钱包数据库并重建");return await this.wdb.close(),await this.wdb.destroy(),await this.wdb.open(),"Created."}async fundRawTransaction(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,'tx.fund.admin "hexstring" ( options openid )');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));if(e=i.buf(0),t=i.obj(1),!e)throw new l(u.TYPE_ERROR,"Invalid hex string.");const a=A.fromRaw(e);if(0===a.outputs.length)throw new l(u.INVALID_PARAMETER,"TX must have at least one output.");let o=null,h=null;if(t){const e=new y([t]);o=e.ufixed("feeRate",8),h=(h=e.str("changeAddress"))&&c.parseAddress(h,this.network)}return await s.fund(a,{rate:o,changeAddress:h,account:n}),{hex:a.toRaw().toString("hex"),changepos:a.changeIndex,fee:v.btc(a.getFee(),!0)}}async dumpPrivKey(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"key.export.private address [account]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));if(e=i.str(0,""),!await s.belongToAccount(n,e))throw new l(u.MISC_ERROR,"Invald Account.");t=c.parseHash(e,this.network);const a=await s.getPrivateKey(t);if(a)return a.toSecret();throw new l(u.MISC_ERROR,"Key not found.")}async exportMnemonic(t,e,r){if(e||1!==t.length)throw new l(u.MISC_ERROR,"wallet.exportmnemonic password: 备份钱包助记符 备份密码");const i=new y([t]);let[s,n]=await this.accessControl(r);if(e=i.str(0),"primary"==s.id&&"default"!=n)throw new l(u.MISC_ERROR,"wallet.exportmnemonic: Invalid Account");let a={body:{phrase:s.master.mnemonic.getPhrase(),language:s.master.mnemonic.language,passphrase:s.master.mnemonic.passphrase},password:e,network:this.network,file:`./${this.network.type}-wallet${s.db.options.spv?"-spv":""}.keystore`};return this.wdb.$parent&&(a.body.awardAddress=this.wdb.$parent.config.coinbaseAddress),await N.writeEncryptFile(a),!0}async dumpWallet(t,e,r){if(e||1!==t.length)throw new l(u.MISC_ERROR,'wallet.export "filename"');const i=new y([t]);let[s,n]=await this.accessControl(r);if("primary"==s.id&&"default"!=n)throw new l(u.MISC_ERROR,"Invalid Account");if(e=i.str(0))return await s.exportToFile({file:e}),!0;throw new l(u.TYPE_ERROR,"Invalid filename.")}async encryptWallet(t,e,r){if(e||1!==t.length)throw new l(u.MISC_ERROR,'wallet.encrypt "passphrase"');const i=new y([t]);let[s,n]=await this.accessControl(r);if(e=i.str(0,""),"primary"==s.id&&"default"!=n)throw new l(u.MISC_ERROR,"Invalid Account");if(s.master.encrypted)throw new l(u.WALLET_WRONG_ENC_STATE,"Already running with an encrypted wallet.");if(e.length<1)throw new l(u.MISC_ERROR,'wallet.encrypt "passphrase"');try{await s.setPassphrase(null,e)}catch(t){throw new l(u.WALLET_ENCRYPTION_FAILED,"Encryption failed.")}return"wallet encrypted"}async getAccount(t,e,r){if(e||1!==t.length)throw new l(u.MISC_ERROR,'address.account "address"');const i=new y([t]);let[s,n]=await this.accessControl(r);return("primary"!=s.id||"default"==n)&&(e=i.str(0,""),t=c.parseHash(e,this.network),r=await s.getPath(t))?r.name:""}async getAddressesByIndex(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,'address.index "index"');const i=new y([t]);let[s,n]=await this.accessControl(r);if("primary"!=s.id||"default"==n){var a=i.uint(0);for(const t of await s.getPaths("default")){const e=t.toAddress();if(0==t.branch&&t.index==a)return e.toString(this.network)}}}async accessControl(t,e){let r=await this.wdb.get("primary");if(this.wdb.options.acl.isRoot(t.options.cid))"primary"!==t.options.wid?(r=await this.wdb.get(t.options.wid),e=null):"*"===(e=e||"default")&&(e=null);else if("primary"!==t.options.wid){if(!await r.belongToAccount(t.options.cid,t.options.wid))throw new l(u.TYPE_ERROR,"Invalid wid.");r=await this.wdb.get(t.options.wid),e=null}else e=t.options.cid;return await r.ensureAccount({name:e,witness:!0}),[r,e]}async getAddressesByAccount(t,e,r){if(e)throw new l(u.MISC_ERROR,'address.list "account"');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));const a=[],o=[],c=[];for(const t of await s.getPaths(n)){const e=t.toAddress();(0==t.branch?a:1==t.branch?o:c).push(e.toString(this.network))}return[a,o,c]}async getAccountAddress(t,e,r){if(e)throw new l(u.MISC_ERROR,'address.receive "account"');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));const a=await s.getAccount(n);if(a)return a.receive.getAddress("string")}async getAccountChangeAddress(t,e,r){if(e)throw new l(u.MISC_ERROR,"address.change account");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));const a=await s.getAccount(n);if(a)return a.change.getAddress("string")}async getAccountNestedAddress(t,e,r){if(e)throw new l(u.MISC_ERROR,'address.nested.list "account"');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));const a=await s.getAccount(n);if(a)return a.nested.getAddress("string")}async getBalance(t,e,r){if(e||3<t.length)throw new l(u.MISC_ERROR,'balance.confirmed ( "account" minconf includeWatchonly )');const i=new y([t]);let s,[n,a]=await this.accessControl(r,i.str(0,""));return e=i.u32(1,1),t=i.bool(2,!1),n.watchOnly!==t?0:(r=await n.getBalance(a),s=0<e?r.confirmed:r.unconfirmed,v.btc(s,!0))}async getBalanceLog(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,'balance.log "account" (height)');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0));return e=i.uint(1,0),s.queryBalanceLog(n,e)}async getBalanceAll(t,e,r){if(e||3<t.length)throw new l(u.MISC_ERROR,'balance.all ( "account" minconf includeWatchonly )');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0));return(await s.getBalance(n)).toJSON()}async getUserToken(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,"cp.user cid uid: 生成登录令牌 厂商编码 用户编码");const i=new y([t]);e=i.str(0),t=i.str(1);let[s]=await this.accessControl(r);return s.tokenCreate({cid:e,uid:t},t)}async masterkey(t,e,r){let[i,s]=await this.accessControl(r);if("primary"==i.id||"default"==s)return i.master.toJSON(!0)}async getHistory(t,e,r){if(e||1<t.length)throw new l(u.MISC_ERROR,"tx.history (page acct):查询交易历史记录 (页码 账号)");const i=new y([t]);var s=i.uint(0,1);if(s<1)throw new l(u.MISC_ERROR,"页面必须是大于0的数字");let[a,o]=await this.accessControl(r,i.str(1));var c;e=await a.getHistory(o);n.sortTX(e);let h=0,p=[];for(c of e){if(h<10*(s-1));else{if(h>=10*s)break;p.push(c)}h++}t=await a.toDetails(p);const d={};return d.items=t,d.pageSize=10,d.pageNum=s,d.total=e.length,d}async stockOffer(t,e,r){if(e||t.length<3)throw new l(u.MISC_ERROR,"stock.offer cid amount price (openid): 发行凭证 厂商编码 发行总量 发行单价 (玩家账号)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(3,""));if(e=i.str(0,""),!(t=i.uint(1,0))||t<w.STOCK_TRADE_SINGLE||t>w.STOCK_ADDED_SINGLE)throw new l(u.MISC_ERROR,`stock.offer amount error: must over ${w.STOCK_TRADE_SINGLE} and less `+w.STOCK_ADDED_SINGLE);if(!(r=i.uint(2,0))||r<w.GRAM||r>w.STOCK_MAX_PRICE)throw new l(u.MISC_ERROR,`stock.offer price error: must over ${w.GRAM} and less `+w.STOCK_MAX_PRICE);return s.stockOffer(e,t,r,n)}async stockPurchase(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,"stock.purchase cid amount (openid): 购买凭证 厂商编码 购买量 (资金账号)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));if(e=i.str(0,""),!(t=i.uint(1,0))||t<w.STOCK_TRADE_SINGLE||t>w.STOCK_MAX_TRADE_SINGLE)throw new l(u.MISC_ERROR,`amount error: must over ${w.STOCK_TRADE_SINGLE} and less `+w.STOCK_MAX_TRADE_SINGLE);return s.stockPurchase(e,t,n)}async stockPurchaseTo(t,e,r){if(e||t.length<3)throw new l(u.MISC_ERROR,"stock.purchaseTo cid amount dst (src): 代买凭证 厂商编码 购买量 目标账号 (资金账号)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(3,""));if(e=i.str(0,""),t=i.uint(1,0),r=i.str(2,""),!t||t<w.STOCK_TRADE_SINGLE||t>w.STOCK_MAX_TRADE_SINGLE)throw new l(u.MISC_ERROR,`amount error: must over ${w.STOCK_TRADE_SINGLE} and less `+w.STOCK_MAX_TRADE_SINGLE);let a={};return a.order=await s.stockPurchaseTo(e,t,r,n),a}async stockSend(t,e,r){if(e||t.length<3)throw new l(u.MISC_ERROR,"stock.send cid amount recvaddr (openid sendaddr): 转让凭证 厂商编码 转让量 接收地址 (玩家账号 发送地址)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(3,""));e=i.str(0,""),t=i.uint(1,0),r=i.str(2,null);var a=i.str(4,null);if(!t||t<w.STOCK_TRADE_SINGLE||t>w.STOCK_MAX_TRADE_SINGLE)throw new l(u.MISC_ERROR,`stock.send amount error: must over ${w.STOCK_TRADE_SINGLE} and less `+w.STOCK_MAX_TRADE_SINGLE);return s.stockSend(e,t,r,n,a)}async stockBid(t,e,r){if(e||t.length<3)throw new l(u.MISC_ERROR,"stock.bid cid amount price (openid srcAddr): 转让凭证 厂商编码 转让总量 转让单价 (玩家账户 凭证账户地址)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(3,""));e=i.str(0,""),t=i.uint(1,0),r=i.uint(2,0);var a=i.str(4,"");if(!t||t<w.STOCK_TRADE_SINGLE||t>w.STOCK_MAX_TRADE_SINGLE)throw new l(u.MISC_ERROR,`stock.bid amount error: must over ${w.STOCK_TRADE_SINGLE} and less `+w.STOCK_MAX_TRADE_SINGLE);return s.stockBid(e,t,r,n,a)}async stockAuction(t,e,r){if(e||t.length<4)throw new l(u.MISC_ERROR,"stock.auction cid addr amount price (openid): 购买凭证 CP编号 转让者地址 购买量 价格 (玩家账号)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(4,""));e=i.str(0,""),t=i.str(1,""),r=i.uint(2);var a=i.uint(3);if(!r||r<w.STOCK_TRADE_SINGLE)throw new l(u.MISC_ERROR,"stock.auction amount error: must over "+w.STOCK_TRADE_SINGLE);if(a)return s.stockAuction(e,t,r,a,n);throw new l(u.MISC_ERROR,"stock.auction price error")}async stockList(t,e,r){if(e)throw new l(u.MISC_ERROR,"stock.list.wallet conditions: 我的凭证列表 查询条件");return e=new y([t]).array(0,[]),this.wdb.accountList.query(e)}async stockRecordList(t,e,r){if(e)throw new l(u.MISC_ERROR,"stock.record.wallet type (cid height conditions): 查询凭证流水 流水类型(0代表全部类型) (厂商编号 最小高度 组合查询条件)");const i=new y([t]);let[s]=await this.accessControl(r);e=i.uint(0,0),t=i.str(1),r=i.uint(2,0);var n,a,o,c=i.array(3,[]);let h=null;for([n,a]of(h=e?await s.db.getStockRecord(e,t,r):await s.db.getStockRecordByCid(t,r)).data)a.account||(o=await s.getAccountByAddress(a.addr))&&(a.wid=o.wid,a.account=o.name,h.set(a.itemNo,a));return h.query(c)}async sendSecret(t,e,r){if(e||t.length<3)throw new l(u.MISC_ERROR,"comm.secret dst message (openid): 安全通信消息 收信地址 信息内容 (玩家账号)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(3,""));if(e=i.str(0,""),t=i.str(1,""),c.parseAddress(e,this.network))return s.sendSecret(e,t,n);throw new l(u.TYPE_ERROR,"Invalid Destination Address.")}async calcHash(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"comm.hash content: 计算输入的哈希值");return e=new y([t]).str(0,""),x.hash256(Buffer.from(e)).toString("hex")}async commNotify(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,"comm.notify addr content (openid): 发送点对点消息 地址 内容 (玩家账号)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));return e=i.str(0,""),t=i.obj(1,{}),s.commNotify({dst:e,content:t,account:n})}async setGuider(t,e,r){if(e||t.length<3)throw new l(u.MISC_ERROR,"order.setGuider src cid dst: 设定推广员 推广员地址 厂商编码 目标用户地址(逗分) [支付账号]");const i=new y([t]);var[,t]=await this.accessControl(r,i.str(3)),s=i.str(0,""),n=i.str(1,"");let a=i.array(2,[]);return 1==a.length&&await this.wdb.getGuider(a[0])==s?null:this.createTX([{comment:{oper:"greg",addr:s,cid:n}},a.map(t=>({address:t,value:1e4})),t],e,r)}async getGuider(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"order.getGuider.wallet dst: 查询推广员 目标用户地址");return e=new y([t]).str(0,""),this.wdb.getGuider(e)}async payOrder(t,e,r){if(e||t.length<4)throw new l(u.MISC_ERROR,"order.pay cid uid sn sum (openid): 支付订单 厂商编码 玩家游戏内编码 订单编码 总额 (玩家账号)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(4,""));e=i.str(0,""),t=i.str(1,""),r=i.str(2,"");var a=i.uint(3,0);return s.payOrder(e,t,r,a,n)}async scanContact(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,'comm.scanContact "txid" ( index )');const s=new y([t]);let[n]=await this.accessControl(r);if(e=s.hash(0),i(e,"Hash is required."),t=s.uint(1,-1),!e)throw new l(u.TYPE_ERROR,"Invalid parameter");if(r=await n.getTX(e))return this.wdb.scanContact(r.tx,t);throw new l(u.WALLET_ERROR,"TX not found.")}async listContact(t,e,r){if(e)throw new l(u.MISC_ERROR,"sys.listContact: 列表联系人");return e=new y([t]).array(0,[]),this.wdb.listContact(e,null,["address"])}async listNotify(t,e,r){if(e)throw new l(u.MISC_ERROR,"comm.listNotify (query): 通知列表 (查询条件,使用 account 参数可分账号查询)");return e=new y([t]).array(0,[]),this.wdb.listNotify(e)}async queryOrderList(t,e,r){if(e)throw new l(u.MISC_ERROR,"order.query.wallet (conditions account): 支付订单列表 (查询条件 子账户)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));return e=i.array(0,[]),s.getOrderList(e,n)}async getReceivedByAccount(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,'account.received "account" ( minconf )');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));var a=i.u32(1,0),o=this.wdb.curHeight;e=await s.getPaths(n);const c=new Set;for(const t of e)c.add(t.hash);let h=0,p=-1;for(const t of await s.getHistory(n)){var d=t.getDepth(o);if(!(d<a)){(-1===p||d<p)&&(p=d);for(const e of t.tx.outputs){var f=e.getHash("hex");f&&c.has(f)&&(h+=e.value)}}}return v.btc(h,!0)}async getReceivedByAddress(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,'address.received "address" ( minconf )');const i=new y([t]);let[s]=await this.accessControl(r);e=i.str(0,"");var n=i.u32(1,0),a=this.wdb.curHeight,o=c.parseHash(e,this.network);let h=0;for(const t of await s.getHistory())if(!(t.getDepth(a)<n))for(const e of t.tx.outputs)e.getHash("hex")===o&&(h+=e.value);return v.btc(h,!0)}async _toWalletTX(t,e){let[r]=await this.accessControl(t);const i=await r.toDetails(e);if(!i)throw new l(u.WALLET_ERROR,"TX not found.");let s=!0;for(const t of i.inputs)if(t.path){s=!1;break}const n=[];let a=0,o=0;for(let t=0;t<i.outputs.length;t++){const e=i.outputs[t];e.path?1!==e.path.branch&&(n.push({account:e.path.name,address:e.address.toString(this.network),category:"receive",amount:v.btc(e.value,!0),label:e.path.name,vout:t}),o+=e.value):s||(n.push({account:"",address:e.address?e.address.toString(this.network):null,category:"send",amount:-v.btc(e.value,!0),fee:-v.btc(i.getFee(),!0),vout:t}),a+=e.value)}return{amount:v.btc(s?o:-a,!0),confirmations:i.confirmations,blockhash:i.block?f.revHex(i.block):null,blockindex:i.index,blocktime:i.time,txid:f.revHex(i.hash),walletconflicts:[],time:i.mtime,timereceived:i.mtime,"bip125-replaceable":"no",details:n,hex:i.tx.toRaw().toString("hex")}}async getTransaction(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,'gettransaction "txid" ( includeWatchonly )');const s=new y([t]);let[n]=await this.accessControl(r);if(e=s.hash(0),i(e,"Hash is required."),t=s.bool(1,!1),!e)throw new l(u.TYPE_ERROR,"Invalid parameter");if(e=await n.getTX(e))return this._toWalletTX(r,e,t);throw new l(u.WALLET_ERROR,"TX not found.")}async abandonPending(t,e,r){if(e)throw new l(u.MISC_ERROR,"tx.abandonall.admin [account]: 废弃所有挂起的交易");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));for(const e of await s.getPending(n))try{await s.abandon(e.hash)}catch(t){this.logger.warning(t.message)}return null}async abandonTransaction(t,e,r){if(e||1!==t.length)throw new l(u.MISC_ERROR,'tx.abandon.admin "txid"');const i=new y([t]);let[s]=await this.accessControl(r);if(!(e=i.hash(0)))throw new l(u.TYPE_ERROR,"Invalid parameter.");if(await s.abandon(e))return null;throw new l(u.WALLET_ERROR,"Transaction not in wallet.")}async getUnconfirmedBalance(t,e,r){if(e||1<t.length)throw new l(u.MISC_ERROR,"balance.unconfirmed");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));return e=await s.getBalance(n),v.btc(e.unconfirmed,!0)}async importPrivKey(t,e,r){if(e||t.length<1||4<t.length)throw new l(u.MISC_ERROR,'key.import.private account "privatekey" passphrase [rescan]');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));e=i.str(1),t=i.str(2),r=i.bool(3,!1);const a=c.parseSecret(e,this.network);return a.witness=!0,await s.importKey(n,a,t),r&&await this.wdb.rescan(0),!0}async walletAuth(t,e,r){return!0}async importWallet(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,'wallet.import "filename" ( rescan )');const i=new y([t]);var[]=await this.accessControl(r);e=i.str(0),t=i.bool(1,!1);return await this.wdb.loadBackup(e),t&&await this.wdb.rescan(0),!0}async importAddress(t,e,r){if(e||t.length<1||4<t.length)throw new l(u.MISC_ERROR,"address.import account address [rescan p2sh]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,"")),a=i.str(1,"");if(e=i.bool(2,!1),i.bool(3,!1)){let t=i.buf(0);if(!t)throw new l(u.TYPE_ERROR,"Invalid parameters.");t=b.fromRaw(t),t=b.createScript(t.hash160(),b.types.SCRIPTHASH),a=S.fromScript(t)}else a=c.parseAddress(a,this.network);return await s.importAddress(n,a),e&&await this.wdb.rescan(0),!0}async importPubkey(t,e,r){if(e||t.length<1||4<t.length)throw new l(u.MISC_ERROR,"key.import.public account pubkey [rescan]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));if(e=i.buf(1),t=i.bool(2,!1),e)return r=E.fromPublic(e,this.network),await s.importKey(n,r),t&&await this.wdb.rescan(0),!0;throw new l(u.TYPE_ERROR,"Invalid parameter.")}async listAccounts(t,e,r){if(e||2<t.length)throw new l(u.MISC_ERROR,"account.list ( minconf includeWatchonly)");const i=new y([t]);let[s]=await this.accessControl(r);var n=i.u32(0,0),a=i.bool(1,!1);const o={};for(const t of await s.getAccounts()){var c=await s.getBalance(t);let e=c.unconfirmed;0<n&&(e=c.confirmed),s.watchOnly!==a&&(e=0),o[t]=v.btc(e,!0)}return o}async listConservedUnspent(t,e,r){if(e||0<t.length)throw new l(u.MISC_ERROR,"coin.conserved.list: 查询已经保持的Unspent列表");let[i]=await this.accessControl(r);const s=[];for(const t of i.getConserved())s.push({txid:t.txid(),vout:t.index});return s}async listReceivedByAccount(t,e,r){if(e||3<t.length)throw new l(u.MISC_ERROR,"account.listreceived ( minconf includeempty includeWatchonly )");const i=new y([t]);e=i.u32(0,0),t=i.bool(1,!1);var s=i.bool(2,!1);return this._listReceived(r,e,t,s,!0)}async listReceivedByAddress(t,e,r){if(e||3<t.length)throw new l(u.MISC_ERROR,"address.received.list ( minconf includeempty includeWatchonly )");const i=new y([t]);e=i.u32(0,0),t=i.bool(1,!1);var s=i.bool(2,!1);return this._listReceived(r,e,t,s,!1)}async _listReceived(t,e,r,i,s){let[n]=await this.accessControl(t);t=await n.getPaths();var a=this.wdb.curHeight;const o=new Map;for(const e of t){const t=e.toAddress();o.set(e.hash,{involvesWatchonly:n.watchOnly,address:t.toString(this.network),account:e.name,amount:0,confirmations:-1,label:""})}for(const t of await n.getHistory()){var c=t.getDepth(a);if(!(c<e))for(const e of t.tx.outputs){const t=e.getAddress();if(t){var u=t.getHash("hex");const r=o.get(u);r&&((-1===r.confirmations||c<r.confirmations)&&(r.confirmations=c),r.address=t.toString(this.network),r.amount+=e.value)}}}let h=[];for(const t of o.values())h.push(t);if(s){const t=new Map;for(const e of h){const r=t.get(e.account);r?r.amount+=e.amount:(t.set(e.account,e),e.address=void 0)}h=[];for(const e of t.values())h.push(e)}const l=[];for(const e of h)if(r||0!==e.amount){-1===e.confirmations&&(e.confirmations=0);try{e.amount=v.btc(e.amount,!0),l.push(e)}catch(t){this.logger.error("invalid amount:entry(%s) msg(%s)",JSON.stringify(e),t.message)}}return l}async listSinceBlock(t,e,r){if(e)throw new l(u.MISC_ERROR,'tx.history.since ( "blockhash" target-confirmations includeWatchonly account)');var i=this.wdb.curHeight;const s=new y([t]);let[n,a]=await this.accessControl(r,s.str(3,""));e=s.hash(0);var o,c=s.u32(1,0);t=s.bool(2,!1);if(n.watchOnly!==t)return[];let h=-1;e&&(t=await this.client.getEntry(e))&&(h=t.height),-1===h&&(h=i);const p=[];let d;for(const t of await n.getHistory(a))t.height<h||t.getDepth(i)<c||((!d||t.height>d)&&(d=t),o=await this._toListTX(r,t),p.push(o));return{transactions:p,lastblock:d&&d.block?f.revHex(d.block):g.NULL_HASH}}async _toListTX(t,e){let[r]=await this.accessControl(t);const s=await r.toDetails(e);if(!s)throw new l(u.WALLET_ERROR,"TX not found.");let n=!0;for(const t of s.inputs)if(t.path){n=!1;break}let a,o,c,h,p,d,m=0,g=0;for(let t=0;t<s.outputs.length;t++){const e=s.outputs[t];e.path?1!==e.path.branch&&(g+=e.value,o=e,h=t):(m+=e.value,a=e,c=t)}return d=n?(p=o,h):(p=a,c),p||(i(!n),n=!0,p=o,d=h),{account:p.path?p.path.name:"",address:p.address?p.address.toString(this.network):null,category:n?"receive":"send",amount:v.btc(n?g:-m,!0),label:p.path?p.path.name:void 0,vout:d,confirmations:s.getDepth(),blockhash:s.block?f.revHex(s.block):null,blockindex:s.index,blocktime:s.time,txid:f.revHex(s.hash),walletconflicts:[],time:s.mtime,timereceived:s.mtime,"bip125-replaceable":"no"}}async listTransactions(t,e,r){if(e||4<t.length)throw new l(u.MISC_ERROR,'tx.list ( "account" count from includeWatchonly)');const i=new y([t]);let[s,a]=await this.accessControl(r,i.str(0,""));e=i.u32(1,10),t=i.u32(2,0);var o=i.bool(3,!1);if(s.watchOnly!==o)return[];var c=await s.getHistory(a),h=(o=(n.sortTX(c),t+e),Math.min(o,c.length));const p=[];for(let e=t;e<h;e++){var d=c[e];d=await this._toListTX(r,d);p.push(d)}return p}async selectone(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"coin.selectone options (account)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));var a=i.obj(0,{});const o=[];for(const t of await s.getCoins(n)){var c=t.getDepth(this.wdb.curHeight);const e=t.getAddress();if(e){var h=t.getHash("hex");if(h&&!t.isColored&&!(a.value&&t.value<a.value||t.coinbase&&0<t.height&&this.wdb.curHeight<t.height+w.COINBASE_MATURITY)){const r=await s.getKey(h);if(o.push({txid:t.txid(),vout:t.index,address:e?e.toString(this.network):null,account:r?r.name:void 0,redeemScript:r&&r.script?r.script.toJSON():void 0,scriptPubKey:t.script.toJSON(),amount:v.btc(t.value,!0),confirmations:c,spendable:!s.isConserved(t),solvable:!0}),a.len&&o.length>=a.len)break}}}return o}async listUnspent(t,e,r){if(e||4<t.length)throw new l(u.MISC_ERROR,'coin.list ( minconf maxconf ["address", account] )');const i=new y([t]);let[s,a]=await this.accessControl(r,i.str(3,""));var o=i.u32(0,1),h=i.u32(1,9999999),p=i.array(2),d=this.wdb.curHeight;const f=new Set;if(p){const t=new y([p]);for(let e=0;e<p.length;e++){var m=t.str(e,"");m=c.parseHash(m,this.network);if(f.has(m))throw new l(u.INVALID_PARAMETER,"Duplicate address.");f.add(m)}}e=await s.getCoins(a),n.sortCoins(e);const g=[];for(const t of e){var b=t.getDepth(d);if(!(b<o||h<b)){const e=t.getAddress();if(e){var w=t.getHash("hex");if(!p||w&&f.has(w)){const r=await s.getKey(w);g.push({txid:t.txid(),vout:t.index,address:e?e.toString(this.network):null,account:r?r.name:void 0,redeemScript:r&&r.script?r.script.toJSON():void 0,scriptPubKey:t.script.toJSON(),amount:v.btc(t.value,!0),confirmations:b,spendable:!s.isConserved(t),solvable:!0})}}}}return g}async listProp(t,e,r){if(e||4<t.length)throw new l(u.MISC_ERROR,"prop.wallet.byaddress ( minconf maxconf [address, account] )");const i=new y([t]);let[s,a]=await this.accessControl(r,i.str(3,""));var o=i.u32(0,1),h=i.u32(1,9999999),p=i.array(2),d=this.wdb.curHeight;const f=new Set;if(p){const t=new y([p]);for(let e=0;e<p.length;e++){var m=t.str(e,"");m=c.parseHash(m,this.network);if(f.has(m))throw new l(u.INVALID_PARAMETER,"Duplicate address.");f.add(m)}}e=await s.getCoins(a),n.sortCoins(e);const g=[];for(const t of e){var b,w,x=t.getDepth(d);if(!(x<o||h<x)){const e=t.getAddress();e&&(b=t.getHash("hex"),(!p||b&&f.has(b))&&(b=await s.getKey(b),(w=t.getReturnData([L.OP_PROPCREATE,L.OP_PROPCREATE]))&&g.push({txid:t.txid(),vout:t.index,address:e?e.toString(this.network):null,account:b?b.name:void 0,amount:v.btc(t.value,!0),confirmations:x,spendable:!s.isConserved(t),solvable:!0,nd:w})))}}return g}async listPropByOid(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"prop.wallet.byoid oid");const i=new y([t]);let[s,a]=await this.accessControl(r,i.str(1,""));var o=i.str(0),c=this.wdb.curHeight;e=await s.getCoins(a);n.sortCoins(e);const h=[];for(const t of e){var p,d,f=t.getDepth(c);if(!(f<0||9999999<f)){const e=t.getAddress();e&&(p=t.getHash("hex"),p=await s.getKey(p),(d=t.getReturnData([L.OP_PROPCREATE,L.OP_PROPEXCHANGE]))&&d.oid==o&&h.push({txid:t.txid(),vout:t.index,address:e?e.toString(this.network):null,account:p?p.name:void 0,amount:v.btc(t.value,!0),confirmations:f,spendable:!s.isConserved(t),solvable:!0,nd:d}))}}return{list:h,count:h.length}}async listLockedUnspent(t,e,r){if(e||2<t.length)throw new l(u.MISC_ERROR,'coin.list.locked ["address", account]');const i=new y([t]);let[s,a]=await this.accessControl(r,i.str(1,""));var o=i.array(0),h=this.wdb.curHeight,p=f.now();const d=new Set;if(o){const t=new y([o]);for(let e=0;e<o.length;e++){var m=t.str(e,"");m=c.parseHash(m,this.network);if(d.has(m))throw new l(u.INVALID_PARAMETER,"Duplicate address.");d.add(m)}}let g;g=account?await s.getCoins(a):s.getLockedCoins(),n.sortCoins(g);const b=[];for(const t of g)if(t.lockedByLocktime(h,p)||t.lockedBySequence(h,p)){const e=t.getAddress();if(e){var w=t.getDepth(h),x=t.getHash("hex");if(!o||x&&d.has(x)){var[k,S,E]=t.getLockStatus();const r=await s.getKey(x);b.push({txid:t.txid(),vout:t.index,address:e?e.toString(this.network):null,account:r?r.name:void 0,redeemScript:r&&r.script?r.script.toJSON():void 0,scriptPubKey:t.script.toJSON(),amount:v.btc(t.value,!0),confirmations:w,spendable:!1,solvable:!0,locktype:k,lockheight:S,locktime:E})}}}return b}async listOperUnspent(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,'coin.conserved.oper.list unlock ([{"txid":"txid","vout":n},...]) 保持/解除保持一组UTXO: true/false [{"txid": "交易id","vout": "输出序号"}]');const i=new y([t]);let[s]=await this.accessControl(r);var n=i.bool(0,!1);if(!(e=i.array(1)))throw new l(u.TYPE_ERROR,"Invalid parameter.");for(const t of e){const e=new y([t]);var a=e.hash("txid"),o=e.u32("vout");if(null==a||null==o)throw new l(u.INVALID_PARAMETER,"Invalid parameter.");a=new R(a,o),n?s.unConserveCoin(a):s.conserveCoin(a)}return!0}async setTXFee(t,e,r){if(e||t.length<1||1<t.length)throw new l(u.MISC_ERROR,"sys.setfee rate");if(null==(e=new y([t]).ufixed(0,8)))throw new l(u.TYPE_ERROR,"Invalid parameter.");return this.wdb.feeRate=e,!0}async signMessage(t,e,r){if(e||2!==t.length)throw new l(u.MISC_ERROR,'sys.message.sign "address" "message"');const i=new y([t]);let[s]=await this.accessControl(r);if(!s.master.key)throw new l(u.WALLET_UNLOCK_NEEDED,"Wallet is locked.");e=i.str(0,""),t=c.parseHash(e,this.network);const n=await s.getKey(t);if(!n)throw new l(u.WALLET_ERROR,"Address not found.");r=i.str(1,"");return n.sign(x.hash256(Buffer.from(h+r,"utf8"))).toString("base64")}async changePassphrase(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,'wallet.changepassphrase "oldpassphrase" "newpassphrase"');const i=new y([t]);let[s]=await this.accessControl(r);if(e=i.str(0,""),t=i.str(1,""),!s.master.encrypted)throw new l(u.WALLET_WRONG_ENC_STATE,"Wallet is not encrypted.");if(e.length<1||t.length<1)throw new l(u.INVALID_PARAMETER,"Invalid parameter");return await s.setPassphrase(e,t),null}async unlock(t,e,r){const i=new y([t]);let[s]=await this.accessControl(r);r=i.str(0);var n=i.u32(1,60);if(e||s.master.encrypted&&0==t.length)throw new l(u.MISC_ERROR,'wallet.unlock "passphrase" timeout');if(!s.master.encrypted)throw new l(u.WALLET_WRONG_ENC_STATE,"Wallet is not encrypted.");if(r.length<1)throw new l(u.INVALID_PARAMETER,"Invalid parameter");if(null==n)throw new l(u.TYPE_ERROR,"Invalid parameter");return await s.unlock(r,n),null}async decryptWallet(t,e,r){if(e||1!==t.length)throw new l(u.MISC_ERROR,'wallet.decrypt "passphrase"');const i=new y([t]);let[s]=await this.accessControl(r);if(e=i.str(0,""),!s.master.encrypted)throw new l(u.WALLET_WRONG_ENC_STATE,"Running with an decrypted wallet.");if(e.length<1)throw new l(u.MISC_ERROR,'wallet.decrypt "passphrase"');try{await s.setPassphrase(e)}catch(t){throw new l(u.WALLET_ENCRYPTION_FAILED,"Decryption failed.")}return"wallet decrypted"}async importPrunedFunds(t,e,r){if(e||t.length<2||3<t.length)throw new l(u.MISC_ERROR,'tx.importprunedfunds.admin "rawtransaction" "txoutproof" ( "label" )');const i=new y([t]);if(e=i.buf(0),t=i.buf(1),!e||!t)throw new l(u.TYPE_ERROR,"Invalid parameter.");const s=I.fromRaw(e),n=_.fromRaw(t);if(e=n.hash("hex"),!n.verify())throw new l(u.VERIFY_ERROR,"Invalid proof.");if(!n.hasTX(s.hash("hex")))throw new l(u.VERIFY_ERROR,"Invalid proof.");if(-1===(t=await this.client.getEntry(e)))throw new l(u.VERIFY_ERROR,"Invalid proof.");if(e={hash:e,time:n.time,mtp:n.mtp,height:t},await this.wdb.addTX(s,e))return null;throw new l(u.WALLET_ERROR,"No tracked address for TX.")}async removePrunedFunds(t,e,r){if(e||1!==t.length)throw new l(u.MISC_ERROR,'tx.removeprunedfunds.admin "txid"');const i=new y([t]);let[s]=await this.accessControl(r);if(!(e=i.hash(0)))throw new l(u.TYPE_ERROR,"Invalid parameter.");if(await s.remove(e))return null;throw new l(u.WALLET_ERROR,"Transaction not in wallet.")}async getWallets(t,e,r){return this.wdb.getWallets()}async getWalletBlock(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"wallet.block height");const i=new y([t]);let[s]=await this.accessControl(r);e=i.uint(0);const n=await s.getBlock(e);return n?n.toJSON():null}async getWalletLayoutH(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"wallet.layouth height");e=new y([t]).uint(0);const i=await this.wdb.getBlock(e);return i?i.toJSON():null}async getWalletInfo(t,e,r){if(e)throw new l(u.MISC_ERROR,"wallet.info");if(e=new y([t]).str(0,"")){return(await this.wdb.get(e)).toJSON(!1)}return(await this.accessControl(r))[0].toJSON(!1)}async scRegister(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"sc.register options (account): 发布合约 合约参数列表 (子账户)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,"")),a=i.obj(0);if(!a)throw new l(u.MISC_ERROR,"sc.register: options is null");let o=1e5;switch(a.oper){case"change":if(a.oper=P.scState,!a.dst||!a.state)throw new l(u.TYPE_ERROR,"sc.register: dst or state is null.");if(!this.wdb.$parent)throw new l(u.TYPE_ERROR,"sc.register: not support this operation.");var c=await this.wdb.$parent.chain.db.getSCList([["options.dst",a.dst]]);if(!c||0==c.list.length)throw new l(u.TYPE_ERROR,"sc.register: contract not exist.");switch(c.list[0].options.state){case O.Normal:if(a.state!=O.Frozen&&a.state!=O.Destroy)throw new l(u.TYPE_ERROR,"Contract State Error");break;case O.Frozen:if(a.state!=O.Normal&&a.state!=O.Destroy)throw new l(u.TYPE_ERROR,"Contract State Error");break;default:throw new l(u.TYPE_ERROR,"Contract State Error")}if(a.addr=c.list[0].options.addr,await s.belongToAccount(n,a.addr))break;throw new l(u.MISC_ERROR,"sc.register: Invald Account.");case"update":if(a.oper=P.scUpdate,!a.dst)throw new l(u.TYPE_ERROR,"sc.register: dst is null.");if(!this.wdb.$parent)throw new l(u.TYPE_ERROR,"sc.register: not support this operation.");if(!(c=await this.wdb.$parent.chain.db.getSCList([["options.dst",a.dst]]))||0==c.list.length)throw new l(u.TYPE_ERROR,"sc.register: contract not exist.");if(c.list[0].options.state!=O.Normal)throw new l(u.TYPE_ERROR,"sc.register: contract state error.");if(a.addr=c.list[0].options.addr,await s.belongToAccount(n,a.addr))break;throw new l(u.MISC_ERROR,"sc.register: Invald Account.");default:if(o=1e8,a.oper=P.scRegister,a.addr=(await s.createReceive(n)).getAddress("string"),a.dst=s.getSCAddress(f.hashInt(a.addr)).toString(),this.wdb.$parent&&(c=await this.wdb.$parent.chain.db.getSCList([["options.dst",a.dst]]))&&0<c.list.length)throw new l(u.TYPE_ERROR,"sc.register: contract address conflict.")}let h=(await s.getPrivateKey(a.addr)).signData(a);h.data.sig=h.sig,a=h.data;const p=await s.send({subtractFee:!1,sort:!1,outputs:[{address:a.dst,value:o}],comment:JSON.stringify(a)},n);return await this.wdb.logAudit({address:a.addr,oper:a.oper,hash:p.hash("hex"),index:0}),a.txid=p.rhash(),a}async scRun(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,'sc.run str options (account): 调用合约 逗分参数字符串("合约收款地址,转账金额") 参数对象 (子账户)');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));const a=i.str(0).split(",");if(e=i.obj(1,{}),t=a.shift(),!this.wdb.$parent)throw new l(u.TYPE_ERROR,"sc.run: not support this operation.");if(!(r=await this.wdb.$parent.chain.db.getSCList([["options.dst",t]]))||0==r.list.length)throw new l(u.TYPE_ERROR,"sc.run: contract not exist.");if(1!=r.list[0].options.state)throw new l(u.TYPE_ERROR,`sc.run: contract execute disabled(state ${r.list[0].options.state}).`);if(e.ver&&e.ver!=r.list[0].options.ver)throw new l(u.TYPE_ERROR,"sc.run: contract version inconsistency.");r=(0|parseInt(a.shift()))>>>0,c.parseAddress(t,this.network);const o=await s.send({subtractFee:!1,sort:!1,outputs:[{address:t,value:r}],comment:JSON.stringify({oper:"scrun",params:e})},n),h=await s.getAccount(n);return(await this.wdb.logAudit({address:h.receive.getAddress("string"),oper:P.scRun,hash:o.hash("hex"),index:0}),await s.getDetails(o.hash("hex"))).toJSON()}async cpRegister(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,'cp.create name "ip,addr,class,rate" (openid): 注册厂商 名称(不少于4个字符) "IP地址,注册地址,类别,媒体分成比例" (子账号)');return this.$cpRegister(t,r,!1)}async cpRegisterAsync(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,'cp.create.async name "ip,addr,class,rate" (openid): 注册厂商 名称(不少于4个字符) "IP地址,注册地址,类别,媒体分成比例" (子账号)');return this.$cpRegister(t,r,!0)}async $cpRegister(t,e,r){const i=new y([t]);t=decodeURIComponent(i.str(0));var s=(o=i.str(1,"").split(","))[0],n=o[1],a=o[2],o=o[3]?parseInt(o[3]):15;let[c,h]=await this.accessControl(e,i.str(2,""));if(e=m.verifyDataFormat({name:t,ip:s,grate:o,cls:a}))throw new l(u.MISC_ERROR,e);return e={cid:D(),oper:P.cpRegister,name:t,ip:s,grate:o,cls:a},await c.cpRegister(f.isBech32(n)?n:null,e,h,r),e}async cpChange(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,'cp.change cid "newname,ip,addr,class,rate" "openid": 修改厂商信息 CP编号 "新的名称,IP,新的注册地址,类别,分成比例" 授权账号');const s=new y([t]);let[n,a]=await this.accessControl(r,s.str(2,""));e=s.str(0),r=(t=decodeURIComponent(s.str(1,"")).split(","))[0];var o=t[1];let c=t[2];var h=t[3],p=(t=parseInt(t[4])||null,m.verifyDataFormat({name:r,ip:o,grate:t,cls:h}));if(p)throw new l(u.MISC_ERROR,p);c&&(c=S.fromString(c),i(c instanceof S,"Not an address."));let d={cid:e,newName:r,ip:o,addr:c,grate:t,cls:h};var[]=await n.cpChange(d,a);return d.addr=d.addr.toString(),d}async cpQuery(t,e,r){if(e)throw new l(u.MISC_ERROR,"cp.query (conditions account): 查询钱包中的厂商列表 (复合条件 子帐号)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));var a;e=i.array(0,[]),t=s.db.cpList.query(e);for(a of t.list)a.owned=await s.belongToAccount(n,a.current.address);return t}async cpMine(t,e,r){if(e)throw new l(u.MISC_ERROR,"cp.mine (conditions account): 查询钱包中归属当前操作员/指定账户的厂商列表 (复合条件 子帐号)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));const a=i.array(0,[]);return a.push(["size",-1]),(await s.db.cpList.predict(async(t,e)=>s.belongToAccount(n,e.current.address))).query(a)}async cpX509(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,"cp.x509 cid [openid]: 生成厂商根证书 CP编号 [子账号]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));e=i.str(0);var[t]=await s.cpX509(e,n);return t}async x509Issue(t,e,r){if(e||t.length<4||5<t.length)throw new l(u.MISC_ERROR,"cp.x509.issue cid csrfile addr activetime [openid]: 签发X509证书 CP编号 请求文件 证书存放地址 证书存活时间 [子账号]");const i=new y([t]);let[n,a]=await this.accessControl(r,i.str(4,""));e=i.str(0),i.str(1),t=i.str(2),r=i.u64(3);var o=s.KEYUTIL.generateKeypair("EC","secp256k1"),[e]=(o=s.asn1.csr.CSRUtil.newCSRPEM({subject:{str:"/C=US/O=Test/CN=example.com"},sbjpubkey:o.pubKeyObj,sigalg:"SHA256withECDSA",sbjprvkey:o.prvKeyObj}),t=S.fromString(t,this.network),await n.x509Issue({cid:e,csrData:o,addr:t,activeTime:r},a));return e}async x509Abolish(t,e,r){if(e||t.length<3||4<t.length)throw new l(u.MISC_ERROR,"cp.x509.abolish cid seqno activetime [openid]: 作废X509证书 CP编号 证书编号 作废生效时间[子账号]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(3,""));e=i.str(0),t=i.u32(1),r=i.u64(2);var[e]=await s.x509Abolish({cid:e,seqno:t,activeTime:r},n);return e}async htlcSuggest(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,"htlc.suggest params [account]: 发起HTLC 参数对象({alice, bob, amount, rate}) [子账户]");const i=new y([t]),s=i.obj(0,{});let[n,a]=await this.accessControl(r,i.str(1,""));if(!s.ab)throw new l(u.MISC_ERROR,"htlc.suggest: params.ab(alice bchain address) is null");if(!Number.isInteger(s.amount))throw new l(u.MISC_ERROR,"htlc.suggest: illegal params.amount");if(s.amount=parseInt(s.amount),s.amount<0||s.amount>1e4*w.COIN)throw new l(u.MISC_ERROR,"htlc.suggest: illegal params.amount");if(s.rate=parseFloat(s.rate),s.rate<0||s.amount*s.rate>w.MAX_MONEY)throw new l(u.MISC_ERROR,"htlc.suggest: illegal params.rate");if(!s.target)throw new l(u.MISC_ERROR,"htlc.suggest: params.target is null");e=(await n.createReceive(a)).getAddress().toString(this.network),t={amount:s.amount,rate:s.rate,dst:s.target,aa:S.fromString(e).hash,ab:S.fromString(s.ab).hash,ba:S.fromString(s.ba).hash};const[o]=await n.sendContracts([t],a,j);return o?{txid:o.rhash(),aa:e}:null}async htlcAssent(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,"htlc.assent params({txid}) [account]: 响应HTLC 参数对象 [子账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));const a=i.obj(0,{});if(!Number.isInteger(a.amount))throw new l(u.MISC_ERROR,"htlc.assent: illegal params.amount");if(a.amount=parseInt(a.amount),a.amount<0||a.amount>1e4*w.COIN)throw new l(u.MISC_ERROR,"htlc.assent: illegal params.amount");if(a.rate=parseFloat(a.rate),a.rate<0||a.amount*a.rate>w.MAX_MONEY)throw new l(u.MISC_ERROR,"htlc.assent: illegal params.rate");e=(await s.createReceive(n)).getAddress().toString(this.network),t={src:a.src,dst:a.dst,hash:a.hash,index:a.index,ab:Buffer.from(a.ab,"hex"),ba:Buffer.from(a.ba,"hex"),bb:S.fromString(e).hash,amount:a.amount*a.rate};const[o]=await s.sendContracts([t],n,C);return o?{txid:o.rhash()}:null}async htlcSuggestDeal(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,"htlc.suggest.deal params({txid,index,sa}) [account]: 兑付HTLC 参数对象 [子账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));e=i.obj(0),t={suggest:!0,hash:f.revHex(e.txid),index:e.index,sa:e.sa};const[a]=await s.htlcDeal(t,n);return a?{txid:a.rhash()}:null}async htlcQuery(t,e,r){if(e)throw new l(u.MISC_ERROR,"htlc.query query: 条件查询HTLC合约 条件数组");const i=new y([t]).array(0,[]);return i.push(["pst","!=",F.Cancel]),this.wdb.htlcList.query(i)}async htlcAssentDeal(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,"htlc.assent.deal params({txid,index,sa}) [account]: 兑付HTLC 参数对象 [子账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));e=i.obj(0),t={hash:f.revHex(e.txid),index:e.index,sa:e.sa};const[a]=await s.htlcDeal(t,n);return a?{txid:a.rhash()}:null}async htlcAssentCancel(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,"htlc.assent.cancel params({txid, index, master}) [account]: 取消HTLC应答 参数对象 [子账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));e=i.obj(0),t={hash:f.revHex(e.txid),index:e.index,master:e.bb};const[a]=await s.htlcCancel(t,n);return a?{txid:a.rhash()}:null}async htlcSuggestCancel(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,"htlc.suggest.cancel params({txid, index, sa, master}) [account]: 取消HTLC请求 参数对象 [子账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));e=i.obj(0),t={suggest:!0,hash:f.revHex(e.txid),index:e.index,sa:e.sa,master:e.aa};const[a]=await s.htlcCancel(t,n);return a?{txid:a.rhash()}:null}async sendComment(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,"comm.comment params [account]: 发起附言交易 参数对象({body, bob}) [子账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));const a=i.obj(0,{});if(!Number.isInteger(a.amount))throw new l(u.MISC_ERROR,"comm.comment: illegal params.amount");if(a.amount=parseInt(a.amount),a.amount<0||a.amount>1e4*w.COIN)throw new l(u.MISC_ERROR,"comm.comment: illegal params.amount");if(e={bob:a.bob,body:a.body,amount:a.amount},!a.alice&&(a.alice=s.getAddress(),n)){let t=await s.createReceive(n);a.alice=t.getAddress()}let o=(await s.getPrivateKey(a.alice)).signData(e);o.data.sig=o.sig;const[c]=await s.sendContracts([o.data],n,B);return c?{txid:c.rhash()}:null}async commentQuery(t,e,r){if(e)throw new l(u.MISC_ERROR,"comm.comment.query query: 条件查询附言输出 条件数组");return e=new y([t]).array(0,[]),this.wdb.commentList.query(e)}async contractExecute(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,"contract.execute tid master: 执行交易对合约 交易编号 执行方(1-发起人,2-承兑人)");const i=new y([t]);let[s]=await this.accessControl(r);e=i.str(0),t=i.u32(1,2);const[n]=await s.contractExecute(e,t);return n.toJSON()}async contractPromise(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,"contract.promise tid [openid]: 签署交易对合约 交易编号(type.address) [子账号]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));e=i.str(0);const[a]=await s.contractPromise(e,n);return a.toJSON()}async contractOfMine(t,e,r){if(e||t.length<1||3<t.length)throw new l(u.MISC_ERROR,"contract.mine type page [openid]: 获取已签署交易对合约列表 交易对类型 页码 [子账号]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));return e=i.uint(0,1),t=i.uint(1,1),s.db.getContracts(e,t,n)}async contractCreate(t,e,r){if(e||t.length<4||5<t.length)throw new l(u.MISC_ERROR,"contract.create type src dst addr [openid] : 发布一个交易对合约 交易对类型 出让游戏金数值 换取兑换币数值 兑换币收款地址 [子账号]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(4,""));e=i.u64(0),t=i.u64(1),r=i.u64(2);var a=i.str(3);const[o]=await s.contractCreate(e,t,r,a,n);return o.toJSON()}async propGet(t,e,r){if(e)throw new l(u.MISC_ERROR,"prop.wallet.byid pid: 查询自己的物品 PID");e=new y([t]).str(0,"");let i=[];return(t=await this.wdb.propList.getVp(e))&&t.pst!=T.Delete&&i.push(t),i}async propBuy(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,"prop.buy pid price [openid] : 竞拍道具 道具编号 出价 [子账号]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));e=i.str(0),t=i.u64(1);const[a]=await s.propBuy(e,t,n);return a.toJSON()}async propFound(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"prop.found pid (openid): 熔铸道具 道具编号 (账号)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));if(e=i.str(0),!(t=await s.db.propList.getVp(e))||t.pst==T.Delete)throw new l(u.MISC_ERROR,"prop.found prop not exist");if(!await s.belongToAccount(n,t.current.address))throw new l(u.MISC_ERROR,"prop.found: current account not owned prop.");if(t.pst!=T.Ready)throw new l(u.MISC_ERROR,"prop.found prop can not be found on current status");const[a,,o]=await s.propFound(t.current.hash,n);if(a&&o)return{hash:a.hash("hex"),txid:a.rhash(),index:0,cid:o.cid,pid:o.pid,oid:o.oid,gold:a.outputs[0].value}}async propSale(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,"prop.sale pid fixedPrice [openid]: 拍卖道具 道具编号 一口价 [子帐号]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));if(e=i.str(0),!(t=await s.db.propList.getVp(e))||t.pst==T.Delete)throw new l(u.MISC_ERROR,"prop.sale prop not exist");if(t.pst!=T.Ready)throw new l(u.MISC_ERROR,"prop.sale prop cannt be sent on current status");r=i.u64(1,0);const[a]=await s.propSale(t.current.hash,t.current.index,r,n);return a.toJSON()}async propSendListAdmin(t,e,r){return this.propSendList(t,e,r,!0)}async propSendList(t,e,r,i=!1){if(e||t.length<1)throw new l(u.MISC_ERROR,"prop.sendlist (addr|txid|index)(n,) [openid]: 批量转移道具 道具数组(地址|交易ID|输出索引) [子账户]");const s=new y([t]);let[n,a]=await this.accessControl(r,s.str(1,"")),o=[];if((e=s.str(0).split(","))&&Array.isArray(e))for(var c of e){var h,p;3<=(c=c.split("|")).length&&(h=c[0],p=new R(f.revHex(c[1]),parseInt(c[2])),4<=c.length?o.push([p,S.fromString(h),c[3]]):o.push([p,S.fromString(h)]))}const[d,,m]=await n.propExchangeList(o,a,i);if(d&&m){let t=d.hash("hex"),e=d.rhash();return m.map(r=>({hash:t,txid:e,cid:r.cid,pid:r.pid,oid:r.oid,gold:r.gold,addr:r.addr}))}}async propReceive(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"prop.receive tx [account]: 捐赠接收函数 捐赠交易字符串 [接收账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));if(!(e=i.buf(0)))throw new l(u.TYPE_ERROR,"Invalid TX Info.");t=I.fromRaw(e);const[a,,o]=await s.propReceive(t,n);if(a&&o)return{hash:a.hash("hex"),txid:a.rhash(),cid:o.cid,pid:o.pid,oid:o.oid,gold:o.gold,addr:o.simAddr,gaddr:o.gaddr}}async propDonate(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"prop.donate pid [openid]: 捐赠道具函数 道具ID [发起账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));if(e=i.str(0),!(t=await s.db.propList.getVp(e))||t.pst==T.Delete)throw new l(u.MISC_ERROR,"prop not exist");if(t.pst!=T.Ready)throw new l(u.MISC_ERROR,"prop cannt be sent on current status");r=new R(t.current.hash,t.current.index);const[a,,o]=await s.propDonate(r,n);if(a&&o)return{hash:a.hash("hex"),txid:a.rhash(),cid:o.cid,pid:o.pid,oid:o.oid,gold:o.gold,raw:a.toRaw().toString("hex")}}async propExchange(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,"prop.send addr pid [openid]: 转移道具函数 接收地址 物品编号 [发起账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));if(e=i.str(0),t=i.str(1),!(r=await s.db.propList.getVp(t))||r.pst==T.Delete)throw new l(u.MISC_ERROR,"prop.send prop not exist");if(r.pst!=T.Ready)throw new l(u.MISC_ERROR,"prop.send prop cannt be sent on current status");const[a,,o]=await s.propExchange(new R(r.current.hash,r.current.index),S.fromString(e),n);if(a&&o)return{hash:a.hash("hex"),txid:a.rhash(),cid:o.cid,pid:o.pid,oid:o.oid,gold:o.gold,addr:e}}async propCreateList(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"prop.createlist (cid|oid|gold|pid)(n,) [openid]: 批量创建道具 道具信息数组 [发起账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,"")),a=[];if((e=i.str(0).split(","))&&Array.isArray(e))for(var o of e)if(3<=(o=o.split("|")).length){var c=o[0],h=o[1],p=parseInt(o[2]);let t=null;4<=o.length&&(t=o[3]),p<w.MINPROPVALUE||a.push([c,h,p,t])}a=a.map(t=>{var[t,e,r,i]=t;return{oper:P.propCreate,cid:t,oid:e,gold:r,pid:i}});var[t]=await s.propCreate(a,n);return t?a:null}async propCreate(t,e,r){if(e||t.length<3)throw new l(u.MISC_ERROR,"prop.create cid oid gold pid (openid): 创建道具 厂商编码 道具类别码 含金量 道具编码(可填空) [账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(4,""));e=i.str(0),t=i.str(1),r=i.u64(2,w.MINPROPVALUE);var a=i.str(3,null);if(r<w.MINPROPVALUE)throw new l(u.PROP_MINVALUE,"prop.create: not a valid value");e={oper:P.propCreate,cid:e,oid:t,gold:r,pid:a};var[t]=await s.propCreate([e],n);return t?e:null}async propOrder(t,e,r){if(e||t.length<3)throw new l(u.MISC_ERROR,"prop.order cid oid gold [addr openid]: 制备道具 厂商编码 道具原始码 含金量 [接收地址 资金账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(4,""));e=i.str(0),t=i.str(1),r=i.u64(2);let a=i.str(3);if(a)a=S.fromString(a);else if(n){a=(await s.createReceive(n)).getAddress()}else a=s.getAddress();var o,c={oper:P.propCreate,cid:e,oid:t,gold:r};const[h]=await s.propCreate([c],n);if(h){o=h.rhash(),await new Promise(t=>{s.db.once("tx.received."+o,(e,r,i)=>{t()})});let[i,,c]=await s.propExchange([h,0],a,n);if(i)return{hash:i.hash("hex"),txid:i.rhash(),cid:e,pid:c.pid,oid:t,gold:r,addr:a.toString()}}return null}async walletLock(t,e,r){if(e)throw new l(u.MISC_ERROR,"wallet.lock [passphrase]");let[i]=await this.accessControl(r);if(!i.master.encrypted){if((e=new y([t]).str(0,"")).length<1)throw new l(u.MISC_ERROR,"Wallet is not encrypted, please run wallet.lock passphrase");try{await i.setPassphrase(null,e)}catch(t){throw new l(u.WALLET_ENCRYPTION_FAILED,"Encryption failed.")}}return await i.lock(),null}async listMSTrans(t,e,r){if(e)throw new l(u.MISC_ERROR,"tx.mstrans");return e=new y([t]).str(0,""),this.wdb.listMSTrans(e)}async signMSTrans(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"tx.mstrans.sign txid");const i=new y([t]);e=i.str(0,""),t=i.str(1,"");let[s,n]=await this.accessControl(r,i.str(2,"")),c=await this.wdb.db.get(a.ms(S.getHash(e,"hex"),t));if(!c)throw new l(u.MISC_ERROR,"tx.mstrans.sign txid");if(r=JSON.parse(c.toString()),!await s.belongToAccount(n,r.addr))throw new l(u.MISC_ERROR,"tx.mstrans.sign invalid account");let h=await this.wdb.get(r.addr);if(h&&h.account.type==o.types.MULTISIG){const e=A.fromRaw(r.data,"hex");e.view=await h.getCoinView(e),await h.sign(e),e.isSigned()?await h.sendMTX(e):await s.send({subtractFee:!1,sort:!1,outputs:[{address:r.contract,value:1e4}],comment:JSON.stringify({oper:"scrun",params:{oper:"sign",addr:r.addr,tx:e.toRaw().toString("hex")}})},n),await this.wdb.delMSTrans(r.addr,t)}}async resendWalletTransactions(t,e,r){if(e||0!==t.length)throw new l(u.MISC_ERROR,"tx.resend.admin");let[i]=await this.accessControl(r);const s=[];for(const t of await i.resend())s.push(t.txid());return s}async resend(t,e,r){if(e||0!==t.length)throw new l(u.MISC_ERROR,"tx.resendall.admin: 重发挂起交易");var i=await this.wdb.resend();if(i)for(var s of Object.keys(i))if(s)for(const t of i[s])await this.wdb.send(t);return!0}async rescan(t,e,r){if(e)throw new l(u.MISC_ERROR,'sys.rescan ( "height" )');return e=new y([t]).u32(0),await this.wdb.rescan(e),this.logger.info("Rescanning..."),!0}async createAddress(t,e,r){if(e||2<t.length)throw new l(u.MISC_ERROR,'address.create ( "account" "uid" )');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));e=i.u32(1,0);const a=await s.createReceive(n,e);return a?a.toJSON():null}async calcAddress(t,e,r){if(e||t.length<3)throw new l(u.MISC_ERROR,"address.calc account(must be typeof number) branch index");const s=new y([t]);let[n,a]=await this.accessControl(r,s.int(0,0));e=s.u32(1,0),t=s.u32(2,0),"default"==a&&(a=0);r=(await n.deriveKey(a,e,t,n.master)).toJSON();const o=await n.deriveKey(a,e,t);return e=o?o.toJSON():null,i(r.address==e.address,"address derived from prv not equals which derived from pub."),e}async createAddressAdmin(t,e,r){if(e||1<t.length)throw new l(u.MISC_ERROR,'address.create.admin ( "account" )');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));const a=await s.createReceive(n,0,s.master);return a?a.toJSON(!0):null}async createChange(t,e,r){if(e||1<t.length)throw new l(u.MISC_ERROR,'address.change.create ( "account" )');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));const a=await s.createChange(n);return a?a.toJSON():null}async createNested(t,e,r){if(e||1<t.length)throw new l(u.MISC_ERROR,'address.nested.create ( "account" )');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));const a=await s.createNested(n);return a?a.toJSON():null}async mkwallet(t,e,r){const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));const a=await s.createReceive(n),o=await this.wdb.ensure({id:a.getAddress("string"),type:i.str(1),m:i.u32(2),n:i.u32(3),mnemonic:i.str(4),passphrase:i.str(5),master:i.str(6),witness:i.bool(7),watchOnly:i.bool(8),accountKey:i.str(9)});return o?o.toJSON(!1):null}async accountGet(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"account.get account: 查询账户");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));const a=await s.getAccount(n);return a?a.toJSON():null}async getPending(t,e,r){if(e)throw new l(u.MISC_ERROR,"tx.pending [account]: 查询挂起的交易");const i=new y([t]);let[s,a]=await this.accessControl(r,i.str(0,""));e=await s.getPending(a),n.sortTX(e);const o=[];for(const t of await s.toDetails(e))o.push(t.toJSON());return o}async getPendingItem(t,e,r){const i=new y([t]);var s,n=i.hash(0,"");let[a,o]=await this.accessControl(r,i.str(1,""));for(s of await a.getPending(o))if(s.hash==n)return(s=await a.toDetails(s)).toJSON()}async getPendingHash(t,e,r){const i=new y([t]);let[s,a]=await this.accessControl(r,i.str(0,""));t=await s.getPending(a),n.sortTX(t);const o=[];for(const e of await s.toDetails(t))o.push(f.revHex(e.hash));return o}async getPendingCount(t,e,r){if(e)throw new l(u.MISC_ERROR,"tx.pending.count [account]: 查询挂起的交易数");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));return e=await s.ensureIndex(n),(await s.txdb.getPendingHashes(e)).length}async accountCreate(t,e,r){const i=new y([t]);let[s]=await this.accessControl(r);t=i.obj(0),r=i.str(1);const n=new y([t]);t={name:n.str("name"),witness:n.bool("witness",!0),type:n.str("type","pubkeyhash"),m:n.u32("m",1),n:n.u32("n",1),watchOnly:n.bool("watch",!1),accountKey:n.str("key",null),lookahead:n.u32("lookahead",10)};try{let e=await s.getAccount(t.name);if(e)return e.toJSON();{let i=(e=await s.createAccount(t,r)).toJSON();return i.isNew=!0,i}}catch(e){return null}}async getblocks(t,e,r){if(e)throw new l(u.MISC_ERROR,"wallet.blocks");let[i]=await this.accessControl(r);return await i.getBlocks()}async getKey(t,e,r){if(e||1!==t.length)throw new l(u.MISC_ERROR,"key.export.public address: 查询地址的密钥");const s=new y([t]);let[n]=await this.accessControl(r);e=s.str(0),i(e,"Address is required.");const a=await n.getKey(e);return a?a.toJSON():null}async getPrivKey(t,e,r){if(e||1!==t.length)throw new l(u.MISC_ERROR,"address.key.admin address: 查询地址的密钥");const s=new y([t]);let[n]=await this.accessControl(r);e=s.str(0),i(e,"Address is required.");const a=await n.getKey(e);return a?a.toJSON(!0):null}async getwif(t,e,r){if(e||1!=t.length)throw new l(u.MISC_ERROR,"address.wif.admin address: 查询地址对应的私钥 地址");const s=new y([t]);let[n]=await this.accessControl(r);e=s.str(0),t=s.str(1),i(e,"Address is required.");const a=await n.getPrivateKey(e,t);return a?a.toSecret():null}async hasAddress(t,e,r){if(e||1!=t.length)throw new l(u.MISC_ERROR,"address.has address: 查询钱包是否包含一个地址 地址");const s=new y([t]);let[n]=await this.accessControl(r);return e=s.str(0),i(e,"Address is required."),(t=await n.hasAddress(e))||!1}async getCoin(t,e,r){const s=new y([t]);let[n]=await this.accessControl(r);t=s.hash(0),r=s.u32(1),i(t,"Hash is required."),i(null!=r,"Index is required.");const a=await n.getCoin(t,r);return a?a.getJSON(this.network):null}async removeCoin(t,e,r){const s=new y([t]);let[n]=await this.accessControl(r);t=s.hash(0),r=s.u32(1);i(t,"Hash is required."),i(null!=r,"Index is required.");const a=await n.getCredit(t,r);a&&(t=a.coin.getAddress(),(r=await n.getPath(t))&&(await n.txdb.removeCredit(a,{account:r.account}),n.txdb.changeConfirmed(n.txdb.pending,a.coin,-1),n.txdb.removeLocked(a.coin)))}async getSpender(t,e,r){const s=new y([t]);let[n]=await this.accessControl(r);return t=s.hash(0),r=s.u32(1),i(t,"Hash is required."),i(null!=r,"Index is required."),(t=await n.txdb.getSpender(t,r))?{hash:f.revHex(t.hash),index:t.index}:null}async getCoincacheSize(t,e,r){var[r]=await this.accessControl(r);return r.txdb.coinCache.size}async conserveCoin(t,e,r){if(e||2!=t.length)throw new l(u.MISC_ERROR,"coin.conserved.add txhash index: 新增需要保持的硬币: 交易Hash 输出序号");const s=new y([t]);let[n]=await this.accessControl(r);return e=s.hash(0),t=s.u32(1),i(e,"Hash is required."),i(null!=t,"Index is required."),r=new R(e,t),n.conserveCoin(r),!0}async getConservedCoins(t,e,r){if(e||0<t.length)throw new l(u.MISC_ERROR,"coin.conserved.get: 查询已经保持的Coin列表");let[i]=await this.accessControl(r);const s=[];for(const t of i.getConserved())s.push(t.toJSON());return s}async unConserveCoin(t,e,r){if(e||2!=t.length)throw new l(u.MISC_ERROR,"coin.conserved.del: 减少需要保持的硬币: 交易Hash 输出序号");const s=new y([t]);let[n]=await this.accessControl(r);return e=s.hash(0),t=s.u32(1),i(e,"Hash is required."),i(null!=t,"Index is required."),r=new R(e,t),n.unConserveCoin(r),!0}async addShared(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"key.shared.add [account] key: 新增共享公钥 [账号] 公钥");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));return e=i.str(1),await s.addSharedKey(n,e),!0}async removeShared(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"key.shared.del [account] key: 删除共享公钥 [账号] 公钥");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));return e=i.str(1),await s.removeSharedKey(n,e),!0}async zap(t,e,r){if(e)throw new l(u.MISC_ERROR,"sys.zap [age]: 移除挂起交易 挂起时长(默认三天)");const s=new y([t]);let[n]=await this.accessControl(r);return e=s.str(0),t=s.u32(1,259200),i(t,"Age is required."),await n.zap(e,t),!0}async sendOracle(t,e,r){if(e||t.length<3||4<t.length)throw new l(u.MISC_ERROR,"oracle.send k v amount [openid]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(3,""));if(e=i.str(0,null),t=i.str(1,null),null==(r=i.u64(2)))throw new l(u.TYPE_ERROR,"Invalid parameter.");if(!e||!t)throw new l(u.MISC_ERROR,"oracle.send k v amount [openid]");r={subtractFee:!1,selection:"age",sort:!1,outputs:[{address:(await s.createReceive(n)).getAddress("string"),value:r}],comment:JSON.stringify({oper:P.vote,type:"oracle",k:e,v:t})};const a=await s.send(r,n);return(await s.getDetails(a.hash("hex"))).toJSON()}async sendVote(t,e,r){if(e||t.length<2||3<t.length)throw new l(u.MISC_ERROR,"vote.send addresses amount [openid]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));const a=i.str(0);var o;if(null==(e=i.u64(1)))throw new l(u.TYPE_ERROR,"Invalid parameter.");for(o of a.split(","))if(!c.parseAddress(o,this.network))throw new l(u.TYPE_ERROR,"Invalid address.");t={subtractFee:!1,selection:"age",sort:!1,outputs:[{address:(await s.createReceive(n)).getAddress("string"),value:e}],comment:`{"oper": "${P.vote}", "type": "mine", "ca": "${a}"}`};const h=await s.send(t,n);return(await s.getDetails(h.hash("hex"))).toJSON()}async sendVoteAsync(t,e,r){if(e||t.length<2||3<t.length)throw new l(u.MISC_ERROR,"vote.send.async addresses amount [openid]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));const a=i.str(0);var o;if(null==(e=i.u64(1)))throw new l(u.TYPE_ERROR,"Invalid parameter.");for(o of a.split(","))if(!c.parseAddress(o,this.network))throw new l(u.TYPE_ERROR,"Invalid address.");t={subtractFee:!1,selection:"age",sort:!1,outputs:[{address:(await s.createReceive(n)).getAddress("string"),value:e}],comment:`{"oper": "${P.vote}", "type": "mine", "ca": "${a}"}`},s.send(t,n)}async sendTX(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,"tx.send addr amount [openid]:发送交易 地址 金额 [发起账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));e=i.str(0),t=i.u64(1);const a=await s.send({outputs:[{address:e,value:t}]},n);return(await s.getDetails(a.hash("hex"))).toJSON()}async sendTXAsync(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,"tx.send.async addr amount [openid]:发送交易 地址 金额 [发起账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));e=i.str(0),t=i.u64(1),s.send({outputs:[{address:e,value:t}]},n)}async signTX(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"tx.sign.admin txdata [sendnow passphrase]: 对交易签名/发送 交易原始数据 [立即发送 解锁密码]");const s=new y([t]);let[n]=await this.accessControl(r);e=s.buf(0),i(e,"TX is required."),t=s.bool(1,!1),r=s.str(2);const a=A.fromRaw(e);a.view=await n.getCoinView(a),await n.sign(a,r);let c=null;if(t&&a.isSigned()){c=(await n.sendMTX(a)).getJSON(this.network)}else c=a.getJSON(this.network);return n.account.type==o.types.MULTISIG&&(e=a.getMultisig(this.network),c.ms={m:e.m,n:e.n,c:e.c}),c}async createTX(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,"tx.create options outputs [openid]: 创建交易 参数对象 输出数组 [子账号]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));if(e=i.obj(0),t=i.array(1),Array.isArray(e.in))for(var a of e.in)a.hash=f.revHex(a.hash);const c=new y([e]),h={comment:c.obj("comment",null),sendnow:c.bool("sendnow",!0),account:c.str("account"),rate:c.u64("rate"),blocks:c.u32("blocks"),maxFee:c.u64("maxFee"),selection:c.str("selection"),smart:c.bool("smart"),subtractFee:c.bool("subtractFee"),subtractIndex:c.get("subtractIndex"),depth:c.u32(["confirmations","depth"]),inputs:c.array("in",null),outputs:[]};for(const e of t){const t=new y([e]);let r={value:t.u64("value")};if(r.address=t.str("address"),!r.address)if(p=t.str("account")){await s.ensureAccount({name:p,witness:!0});const t=await s.createReceive(p);if(!t)throw new l(u.MISC_ERROR,`tx.create: account ${p} not exist`);r.address=t.getAddress("string")}var p,d=((p=t.buf("script"))&&(r.script=b.fromRaw(p)),t.str("locktype"));if(d){var m=t.u64("locktime",0);if(m){if("no"!=d&&"clb"!=d&&"clt"!=d&&"csb"!=d&&"cst"!=d)throw new l(u.MISC_ERROR,'locktype should be "no"-不锁定 or "clb"-绝对高度锁定 or clt(绝对时间锁定) or "csb"-相对高度锁定 or "cst"-相对时间锁定 !');if(d==b.outputLockType.CHECKABSOLUTETIME&&m<=w.LOCKTIME_THRESHOLD)throw new l(u.MISC_ERROR,"lock absolute time should not less than 500000000!");if(d==b.outputLockType.CHECKABSOLUTEBLOCK&&m>w.LOCKTIME_THRESHOLD)throw new l(u.MISC_ERROR,"lock absolute block should not more than 500000000!");if((d==b.outputLockType.CHECKRELATIVEBLOCK||d==b.outputLockType.CHECKRELATIVETIME)&&65535<m)throw new l(u.MISC_ERROR,"lock relative block/time should not more than 65535!");r.locktype=d,r.locktime=m}}h.outputs.push(r)}n&&(h.account=n);let g=null;if(h.sendnow){const t=await s.send(h);g=(await s.getDetails(t.hash("hex"))).toJSON()}else{const t=await s.createTX(h);await s.sign(t),g=t.getJSON(this.network),s.account.type==o.types.MULTISIG&&(r=t.getMultisig(this.network),g.ms={m:r.m,n:r.n,c:r.c})}return g}async getLast(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"tx.last account [limit]: 最近的交易 账号 [最大记录数]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0));e=i.u32(1);const a=[];t=await s.getLast(n,e);for(const e of await s.toDetails(t))a.push(e.toJSON());return a}async getRange(t,e,r){if(e||t.length<4)throw new l(u.MISC_ERROR,"tx.range account start end limit [reserve]: 指定时限内的交易 账号 开始时间 结束时间 最大记录数 [反转]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));e={start:i.u32(1),end:i.u32(2),limit:i.u32(3),reverse:i.bool(4)},t=await s.getRange(n,e);const a=[];for(const e of await s.toDetails(t))a.push(e.toJSON());return a}async caUserStatus(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,"ca.user.status cid uid (query)");const i=new y([t]);e=i.str(0,""),t=i.uint(1,0);const s=i.array(2,[]);let n=null;for(let t=0;t<s.length;t++){var a=s[t];a&&Array.isArray(a)?"alliancename"==a[0]&&(n=a[1],delete s[t]):delete s[t]}let[o]=await this.accessControl(r);return e=await this.$allianceUserCreate([e,t,n],r),s.push(["pubkey",e.data.pubkey]),s.push(["merge",!0]),o.db.client.execute("ca.list",[s])}async caUserLog(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,"ca.user.log cid uid (query)");const i=new y([t]);e=i.str(0,""),t=i.uint(1,0);const s=i.array(2,[]);let n=null;for(let t=0;t<s.length;t++){var a=s[t];a&&Array.isArray(a)?"alliancename"==a[0]&&(n=a[1],delete s[t]):delete s[t]}let[o]=await this.accessControl(r,e);return e=await this.$allianceUserCreate([e,t,n],r),s.push(["pubkey",e.data.pubkey]),o.db.client.execute("ca.list",[s])}async sysLog(t,e,r){if(e)throw new l(u.MISC_ERROR,"sys.log (query openid)");const i=new y([t]);var s;e=i.array(0,[]);let[n]=await this.accessControl(r,i.str(1,"")),a=[];for(s of(await this.wdb.auditList.query(e)).list){let t=Object.assign({},s);var o=c.parseHash(s.address,this.network);(o=await n.getPath(o))&&(t.account=o.name),t.time=new Date(1e3*s.time).toLocaleString(),a.push(t)}return a}async caIssuePublic(t,e,r){if(e||t.length<3||4<t.length)throw new l(u.MISC_ERROR,"ca.issue.public cert witness pubkey [openid]: 签发证书 证书对象 见证地址 存证地址公钥 [见证账户]");const i=new y([t]),s=i.obj(0,{});e=i.str(1,""),t=i.str(2);let[n,a]=await this.accessControl(r,i.str(3,""));if(await n.belongToAccount(a,e)){if(64!=s.hash.length)throw new l(u.TYPE_ERROR,"err hash length");s.height||(s.height=w.retargetInterval);const r=await n.getPrivateKey(e);if(r)return await n.issueCreate({erid:s.hash,key:r.privateKey.toString("hex"),address:r.getAddress().toString(),witness:r.publicKey.toString("hex"),validHeight:this.wdb.curHeight+s.height,source:{subjectName:s.name,pubkey:t,subjectHash:s.hash,cluster:s.cluster}},a)}throw new l(u.TYPE_ERROR,"Invalid witness.")}async caAbolishPublic(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"ca.abolish.public array[[witness erid height [openid]]]: 废止授信交易 废止交易信息数组");let i=[];const s=new y([t]);var n;for(n of s.array(0,[])){var a=n[0],o=n[1],c=parseInt(n[2]);let[t,e]=await this.accessControl(r,n[3]);if(!await t.belongToAccount(e,a))throw new l(u.TYPE_ERROR,"Invalid witness.");const s=await t.getKey(a);if(!s)throw new l(u.TYPE_ERROR,"Invalid witness.");(a=await t.caAbolish({key:s.privateKey.toString("hex"),witness:s.publicKey.toString("hex"),address:a,erid:o,abolishHeight:c,cid:"",uid:0},e))&&i.push(a)}return i}async caIssue(t,e,r){if(e||t.length<3||4<t.length)throw new l(u.MISC_ERROR,"ca.issue cert uid cid [openid]: 签发证书 证书对象 见证人 见证人归属单位 [消费账户]");return this.$caIssue(t,r,!1)}async caIssueAsync(t,e,r){if(e||t.length<3||4<t.length)throw new l(u.MISC_ERROR,"ca.issue.async cert uid cid [openid]: 签发证书 证书对象 见证人 见证人归属单位 [消费账户]");return this.$caIssue(t,r,!0)}async $caIssue(t,e,r){const i=new y([t]),s=i.obj(0,{});t=i.uint(1,0);var n=i.str(2,"");let[a,o]=await this.accessControl(e,i.str(3,""));var c=await a.ensureCp(n);if(!c||"forbidden"==c.cls)throw new l(u.MISC_ERROR,"Invalid Account");if(64!=s.hash.length)throw new l(u.TYPE_ERROR,"err hash length");c=await this.$allianceUserCreate([n,t],e);let h=[];if(h.push(["pubkey",c.data.pubkey]),h.push(["source.subjectHash",s.hash]),0<(await a.db.client.execute("ca.list",[h])).count)throw new l(u.TYPE_ERROR,"cert.hash conflicted");if(this.wdb.$parent&&await this.wdb.$parent.chain.db.erList.getEr(s.hash))throw new l(u.TYPE_ERROR,"cert.hash conflicted");return s.height||(s.height=w.retargetInterval),c=await this.$allianceUserCreate([n,t],e,!0),await a.issueCreate({erid:s.hash,key:c.prvkey,witness:c.data.pubkey,address:c.data.addr,validHeight:this.wdb.curHeight+s.height,source:{subjectName:s.name,pubkey:c.data.pubkey,subjectHash:s.hash,cluster:s.cluster,cid:n,uid:t}},o,r)}async caAbolish(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"ca.abolish [[uid cid erid height [openid]]]: 废止授信交易 废止交易信息数组");return this.$caAbolish(t,r,!1)}async caAbolishAsync(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"ca.abolish.async [[uid cid erid height [openid]]]: 废止授信交易 废止交易信息数组");return this.$caAbolish(t,r,!0)}async $caAbolish(t,e,r){let i=[];const s=new y([t]);var n;for(n of s.array(0,[])){var a=n[0],o=n[1],c=n[2],u=parseInt(n[3]);let[t,s]=await this.accessControl(e,n[4]);var h=await this.$allianceUserCreate([o,a],e,!0);(o=await t.caAbolish({cid:o,uid:a,key:h.prvkey,witness:h.data.pubkey,address:h.data.addr,erid:c,abolishHeight:u},s,r))&&i.push(o)}return i}async enchanceCp(t,e,r){if(e||t.length<2||4<t.length)throw new l(u.MISC_ERROR,"ca.enchance toCid fromCid height [openid]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(3));e=i.str(0,0),t=i.str(1,0);let a=i.uint(2,0);(!a||a<this.wdb.curHeight)&&(a=this.wdb.curHeight+w.retargetInterval);var[r,e]=await s.enchanceCp({to:e,from:t,enchanceHeight:a},n);return r&&e?e:null}async queryMyErlist(t,e,r){if(e)throw new l(u.MISC_ERROR,"ca.list.me query: 条件查询自己的电子权利 条件数组");return e=new y([t]).array(0,[]),this.wdb.erList.query(e)}}},function(t,e,r){var i=r(29);const{ContractEnvType:s,ContractStatus:n}=r(5),a=r(6),o=r(110);t.exports=class extends i{constructor(t){super(),this.db=t}async loadHistory(){var t;for(t of await this.db.getContracts())t&&(t.period<this.db.curHeight&&t.transStatus==n.CreatedOnMem?await this.delTransContract(t,!0):(t.id=t.type+"."+t.addr,await this.saveContract(t),t.transStatus==n.Promised&&this.db.autoTaskMgr.addTask(new o(this.db.network.txcheckpoint,t),this.db.network.txchecktime[t.type])))}query(t,e){return(t=this.get(t+"."+e))?t.transStatus:n.None}async addTransContract(t,e,r=!1){e.id=e.type+"."+e.addr;var i=this.get(e.id);t===s.Mempool&&((e=i||e).transStatus||(e.transStatus=n.CreatedOnMem),await this.saveContract(e,r))}async saveContract(t,e=!1){t.id=t.id||t.type+"."+t.addr,this.set(t.id,t),e&&(e=a.hash256(Buffer.from(t.id)).toString("hex"),await this.db.batchPut(this.db.tidCreator(e),Buffer.from(JSON.stringify(t))))}async promiseContract(t,e=!1){let r=!1;var i=t.type+"."+t.addr;let s=this.get(i);return s&&s.oper==t.oper||(r=!0,s=t),(!s.transStatus||s.transStatus<n.Promised)&&(r=!0,s.transStatus=n.Promised),r&&await this.saveContract(s,e),r}async confirmContract(t,e,r){t=t.type+"."+t.addr;let i=this.get(t);!i||i.transStatus!=n.Promised||e!=n.Confirmed&&e!=n.Expired||(i.transStatus=e,await this.saveContract(i,r))}async delTransContract(t,e){var r=t.type+"."+t.addr,i=this.get(r);i&&i.oper==t.oper&&(this.delete(r),e&&(i=a.hash256(Buffer.from(r)).toString("hex"),await this.db.batchDel(this.db.tidCreator(i))))}}},function(t,e,r){const i=r(5).HtlcStatus;r=r(29);class s extends r{constructor(t){super(),this.db=t}async loadHistory(){var t,e;for(t of(this.clear(),await this.db.loadHtlcList()))this.set(t.id,t),t.wid&&t.account&&(e=t.wid+"."+t.account,this.account.get(e)||this.account.set(e,new Map),this.account.get(e).set(t.id,t))}setAccount(t,e,r){this.delAccount(t),e&&r&&(t.wid=e,t.account=r,e=t.wid+"."+t.account,this.account.get(e)||this.account.set(e,new Map),this.account.get(e).set(t.id,t))}delAccount(t){var e;t&&t.wid&&t.account&&(e=t.wid+"."+t.account,this.account.get(e)&&this.account.get(e).delete(t.id))}}s.vpItem=class t{constructor(t){this.fromOptions(t||{})}fromOptions(t){this.shash=t.shash,this.sidx=t.sidx,this.sheight=t.sheight,this.ahash=t.ahash,this.aidx=t.aidx,this.aheight=t.aheight,this.src=t.src,this.dst=t.dst,this.aa=t.aa,this.ab=t.ab,this.ba=t.ba,this.bb=t.bb,this.amount=t.amount,this.rate=t.rate,this.pst=t.pst}toRaw(){let t={};return t.shash=this.shash,t.sidx=this.sidx,t.sheight=this.sheight,t.ahash=this.ahash,t.aidx=this.aidx,t.aheight=this.aheight,t.src=this.src,t.dst=this.dst,t.amount=this.amount,t.rate=this.rate,t.pst=this.pst||i.Init,t.aa=this.aa||"",t.ab=this.ab||"",t.ba=this.ba||"",t.bb=this.bb||"",Buffer.from(JSON.stringify(t),"utf-8")}get id(){return""+this.shash+this.sidx}fromRaw(t){return t=JSON.parse(t.toString("utf8")),this.fromOptions(t),this}static fromRaw(e){return(new t).fromRaw(e)}},t.exports=s},,,,,,,,,,,,,,,function(t,e,r){"use strict";
873
+ */const i=r(0),s=r(319),n=r(73);r(122);const a=r(96).walletdb,o=r(161),c=r(78),u=c.errors,h=c.MAGIC_STRING,l=r(77),p=r(59),d=r(109),f=r(1),m=r(196),g=r(3),y=r(80),v=r(34),b=r(17),w=r(7),x=r(6),k=r(29),S=r(12),E=r(32),_=r(133),A=r(60),R=r(46),I=r(19),j=r(138),C=r(139),{ContractType:P,ContractState:O,PropStatus:T,HtlcStatus:F}=r(5),B=r(140),N=r(125);r(124).Mnemonic;const D=r(143),L=r(21).opcodes;t.exports=class extends c{constructor(t){super(t),i(t,"RPC requires a WalletDB."),this.wdb=t,this.keys=t.keys,this.network=t.network,this.logger=t.logger.context("rpc"),this.client=t.client,this.init()}init(){this.add("sys.alliance.create",this.allianceCreate),this.add("sys.alliance.import",this.allianceImport),this.add("sys.alliance.delete",this.allianceDelete),this.add("sys.alliance.refresh",this.refreshAlliance),this.add("sys.alliance.refresh.async",this.refreshAllianceAsync),this.add("sys.alliance.gettoken",this.getAllianceNodeToken),this.add("sys.alliance.user",this.allianceUserCreate),this.add("wallet",this.routerOfWallet),this.add("wallet.create",this.mkwallet),this.add("wallet.exportmnemonic",this.exportMnemonic),this.add("wallet.export",this.dumpWallet),this.add("wallet.import",this.importWallet),this.add("wallet.list",this.getWallets),this.add("wallet.info",this.getWalletInfo),this.add("wallet.block",this.getWalletBlock),this.add("wallet.layouth",this.getWalletLayoutH),this.add("wallet.encrypt",this.encryptWallet),this.add("wallet.decrypt",this.decryptWallet),this.add("wallet.changepassphrase",this.changePassphrase),this.add("wallet.lock",this.walletLock),this.add("wallet.unlock",this.unlock),this.add("wallet.blocks",this.getblocks),this.add("wallet.auth",this.walletAuth),this.add("key",this.routerOfKey),this.add("key.export.private",this.dumpPrivKey),this.add("key.export.public",this.getKey),this.add("key.master.admin",this.masterkey),this.add("key.import.private",this.importPrivKey),this.add("key.import.public",this.importPubkey),this.add("key.import.address",this.importAddress),this.add("key.shared.add",this.addShared),this.add("key.shared.del",this.removeShared),this.add("account",this.routerOfAccount),this.add("account.list",this.listAccounts),this.add("account.get",this.accountGet),this.add("account.create",this.accountCreate),this.add("account.received",this.getReceivedByAccount),this.add("account.listreceived",this.listReceivedByAccount),this.add("balance.confirmed",this.getBalance),this.add("balance.all",this.getBalanceAll),this.add("balance.unconfirmed",this.getUnconfirmedBalance),this.add("balance.log",this.getBalanceLog),this.add("comm.notify",this.commNotify),this.add("comm.hash",this.calcHash),this.add("comm.listNotify",this.listNotify),this.add("comm.secret",this.sendSecret),this.add("comm.listContact",this.listContact),this.add("comm.scanContact",this.scanContact),this.add("comm.comment",this.sendComment),this.add("comm.comment.query",this.commentQuery),this.add("sys.walletdb.stop",this.stop),this.add("sys.walletnode.shutdown",this.shutdown),this.add("sys.walletdb.create",this.createWalletDb),this.add("sys.walletdb.destroy",this.destroyWalletDb),this.add("sys.zap",this.zap),this.add("sys.setfee",this.setTXFee),this.add("sys.message.sign",this.signMessage),this.add("sys.rescan",this.rescan),this.add("sys.log",this.sysLog),this.add("address",this.routerOfAddress),this.add("address.list",this.getAddressesByAccount),this.add("address.index",this.getAddressesByIndex),this.add("address.receive",this.getAccountAddress),this.add("address.change",this.getAccountChangeAddress),this.add("address.nested",this.getAccountNestedAddress),this.add("address.calc",this.calcAddress),this.add("address.create",this.createAddress),this.add("address.create.admin",this.createAddressAdmin),this.add("address.receive.create",this.createAddress),this.add("address.change.create",this.createChange),this.add("address.nested.create",this.createNested),this.add("address.import",this.importAddress),this.add("address.key.admin",this.getPrivKey),this.add("address.wif.admin",this.getwif),this.add("address.has",this.hasAddress),this.add("address.amount",this.getReceivedByAddress),this.add("address.account",this.getAccount),this.add("address.received",this.getReceivedByAddress),this.add("address.received.list",this.listReceivedByAddress),this.add("cp",this.routerOfCp),this.add("cp.create",this.cpRegister),this.add("cp.create.async",this.cpRegisterAsync),this.add("cp.change",this.cpChange),this.add("cp.query",this.cpQuery),this.add("cp.mine",this.cpMine),this.add("cp.x509",this.cpX509),this.add("cp.user",this.getUserToken),this.add("sc",this.routerOfSc),this.add("sc.register",this.scRegister),this.add("sc.run",this.scRun),this.add("ca",this.routerOfCa),this.add("ca.issue",this.caIssue),this.add("ca.user.status",this.caUserStatus),this.add("ca.user.log",this.caUserLog),this.add("ca.abolish",this.caAbolish),this.add("ca.enchance",this.enchanceCp),this.add("ca.list.me",this.queryMyErlist),this.add("ca.issue.async",this.caIssueAsync),this.add("ca.abolish.async",this.caAbolishAsync),this.add("ca.issue.public",this.caIssuePublic),this.add("ca.abolish.public",this.caAbolishPublic),this.add("order",this.routerOfOrder),this.add("order.setGuider",this.setGuider),this.add("order.getGuider.wallet",this.getGuider),this.add("order.pay",this.payOrder),this.add("order.query.wallet",this.queryOrderList),this.add("prop",this.routerOfProp),this.add("prop.create",this.propCreate),this.add("prop.send",this.propExchange),this.add("prop.donate",this.propDonate),this.add("prop.receive",this.propReceive),this.add("prop.createlist",this.propCreateList),this.add("prop.sendlist",this.propSendList),this.add("prop.sendlist.admin",this.propSendListAdmin),this.add("prop.order",this.propOrder),this.add("prop.found",this.propFound),this.add("prop.sale",this.propSale),this.add("prop.buy",this.propBuy),this.add("prop.wallet.byid",this.propGet),this.add("prop.wallet.byoid",this.listPropByOid),this.add("prop.wallet.byaddress",this.listProp),this.add("contract",this.routerOfContract),this.add("contract.create",this.contractCreate),this.add("contract.promise",this.contractPromise),this.add("contract.execute",this.contractExecute),this.add("contract.mine",this.contractOfMine),this.add("htlc",this.routerOfHTLC),this.add("htlc.suggest",this.htlcSuggest),this.add("htlc.suggest.cancel",this.htlcSuggestCancel),this.add("htlc.suggest.deal",this.htlcSuggestDeal),this.add("htlc.assent",this.htlcAssent),this.add("htlc.assent.cancel",this.htlcAssentCancel),this.add("htlc.assent.deal",this.htlcAssentDeal),this.add("htlc.query",this.htlcQuery),this.add("vote.send",this.sendVote),this.add("vote.send.async",this.sendVoteAsync),this.add("oracle.send",this.sendOracle),this.add("stock.offer",this.stockOffer),this.add("stock.purchase",this.stockPurchase),this.add("stock.purchaseTo",this.stockPurchaseTo),this.add("stock.send",this.stockSend),this.add("stock.bid",this.stockBid),this.add("stock.auction",this.stockAuction),this.add("stock.list.wallet",this.stockList),this.add("stock.record.wallet",this.stockRecordList),this.add("tx.get.wallet",this.getTransaction),this.add("tx.list",this.listTransactions),this.add("tx.create",this.createTX),this.add("tx.send",this.sendTX),this.add("tx.send.async",this.sendTXAsync),this.add("tx.last",this.getLast),this.add("tx.pending",this.getPending),this.add("tx.pending.get",this.getPendingItem),this.add("tx.pending.hash",this.getPendingHash),this.add("tx.pending.count",this.getPendingCount),this.add("tx.resend.admin",this.resendWalletTransactions),this.add("tx.mstrans",this.listMSTrans),this.add("tx.mstrans.sign",this.signMSTrans),this.add("tx.history",this.getHistory),this.add("tx.history.since",this.listSinceBlock),this.add("tx.range",this.getRange),this.add("tx.abandon.admin",this.abandonTransaction),this.add("tx.abandonall.admin",this.abandonPending),this.add("tx.importprunedfunds.admin",this.importPrunedFunds),this.add("tx.removeprunedfunds.admin",this.removePrunedFunds),this.add("tx.resendall.admin",this.resend),this.add("tx.sign.admin",this.signTX),this.add("tx.fund.admin",this.fundRawTransaction),this.add("coin",this.routerOfCoin),this.add("coin.get",this.getCoin),this.add("coin.spender",this.getSpender),this.add("coin.cache",this.getCoincacheSize),this.add("coin.list",this.listUnspent),this.add("coin.selectone",this.selectone),this.add("coin.conserved.get",this.getConservedCoins),this.add("coin.conserved.add",this.conserveCoin),this.add("coin.conserved.del",this.unConserveCoin),this.add("coin.conserved.list",this.listConservedUnspent),this.add("coin.conserved.oper.list",this.listOperUnspent),this.add("coin.locked.list",this.listLockedUnspent)}async routerOfCoin(t){throw new l(u.MISC_ERROR,"\n coin.get 查询硬币-UTXO\n coin.remove.admin 移除指定硬币(管理员判断为状态异常者)\n coin.spender 查询硬币的消费者\n coin.list 列表硬币-UTXO\n coin.conserved.get 获取钱包保持的Coin的信息\n coin.conserved.add 钱包增加需要保持的Coin\n coin.conserved.del 钱包减少需要保持的Coin\n coin.conserved.list 列表钱包保持的UTXO\n coin.conserved.oper.list 批量锁定/解锁一组UTXO \n coin.locked.list 列表目前交易层锁定的UTXO\n ")}async routerOfContract(t){throw new l(u.MISC_ERROR,"\n contract.create 发布交易对合约\n contract.promise 签署交易对合约\n contract.execute 执行交易对合约\n contract.mine 获取已签署交易对合约列表\n contract.list 查询并返回交易对\n ")}async routerOfHTLC(t){throw new l(u.MISC_ERROR,"\n htlc.suggest 发布跨链合约\n htlc.suggest.deal 兑现合约\n htlc.suggest.cancel 取消合约\n htlc.assent 响应跨链合约\n htlc.assent.deal 兑现响应\n htlc.assent.cancel 取消响应\n htlc.query 查询合约\n ")}async routerOfWallet(t){throw new l(u.MISC_ERROR,"\n wallet.create 创建钱包\n wallet.list 列表钱包\n wallet.info 查询钱包概要\n wallet.block 查询区块信息\n wallet.exportmnemonic 导出钱包助记词备份\n wallet.export 导出钱包备份\n wallet.import 导入钱包备份\n wallet.encrypt 将主私钥永久加密\n wallet.decrypt 将主私钥永久解密\n wallet.changepassphrase 在主私钥已经加密的情况下,修改其加密密码,要提交旧/新两个密码。如果尚未加密则执行失败\n wallet.lock 在主私钥已加密的前提下,清理内存中的密钥信息以确保锁定,相当于手工执行自动锁定\n wallet.unlock 在主私钥已加密的前提下,解密主私钥,持续一段时间后自动锁定\n wallet.blocks 列表钱包相关区块\n ")}async routerOfAddress(t){throw new l(u.MISC_ERROR,"\n address.list 列表指定账户下地址\n address.receive 列表指定账户下收款地址\n address.change 列表指定账户下找零地址\n address.nested 列表指定账户下嵌套地址\n address.create 创建一个收款地址\n address.create.admin 创建一个收款地址,回显私钥\n address.receive.create 创建一个收款地址\n address.change.create 创建一个找零地址\n address.nested.create 创建一个嵌套地址\n address.import 导入一个地址\n address.key.admin 查询地址的密钥\n address.amount 查询指定地址上的余额\n address.account 查询指定地址对应的账户\n address.wif.admin 查询地址对应的私钥\n address.has 判断钱包是否包含地址\n address.received 根据地址查询进项总额\n address.received.list 根据地址查询进项\n address.filter 在订单流水中,查询符合筛选条件的地址集\n ")}async routerOfAccount(t){throw new l(u.MISC_ERROR,"\n account.list 列表账户\n account.get 查询账户\n account.create 创建账户\n account.received 查询收款总额\n account.listreceived 列表收款记录\n balance.confirmed 已确认余额\n balance.all 余额\n balance.unconfirmed 未确认余额\n balance.log 查询指定账户变更日志\n ")}async routerOfKey(t){throw new l(u.MISC_ERROR,"\n key.export.private 根据输入地址,导出私钥\n key.export.public 根据输入地址,打出公钥\n key.master.admin 导出根密钥和助记词, 注意 encrypt 状态下无法导出私钥\n key.import.private 导入私钥\n key.import.public 导入公钥\n key.import.address 导入地址\n key.shared.add 新增共享公钥\n key.shared.del 删除共享公钥\n ")}async routerOfCp(t){throw new l(u.MISC_ERROR,"\n cp.create 创建CP记录\n cp.change 修改CP记录\n cp.snap 查询CP历史快照\n cp.sps 查询CP权证列表\n cp.remoteQuery 查询全节点中的CP列表\n cp.query 查询本地CP列表\n cp.byClass 根据游戏类别查询CP记录\n cp.byName 根据名称查询CP记录\n cp.byId 根据ID查询CP记录\n cp.mine 当前操作员注册的CP\n cp.x509 为CP创建根证书\n cp.user 生成用户令牌(钱包)\n ")}async routerOfSc(t){throw new l(u.MISC_ERROR,"\n sc.model 查询托管合约模板列表\n sc.register 指定托管合约模板,创建新的实例\n sc.query 查询托管合约实例列表\n sc.run 调用托管合约实例\n ")}async routerOfCa(t){throw new l(u.MISC_ERROR,"\n ca.issue 电子证书签发\n ca.abolish 电子证书废止记录\n ca.verify 电子证书验证\n ca.user.status 根据企业证书编号和用户编号查询\n ca.user.log 根据企业证书编号和用户编号查询日志\n ca.enchance CA机构间增信\n ca.rank 查询CA信用等级\n ca.list 查询电子证书列表\n ca.list.ab 查询电子证书废止记录列表\n ca.list.me 查询钱包内证书列表\n ")}async routerOfOrder(t){throw new l(u.MISC_ERROR,"\n order.pay 支付订单(钱包)\n order.query 查询订单记录\n order.query.admin 查询订单列表(特约节点)\n order.query.wallet 查询订单列表(钱包)\n order.setGuider 为指定厂商、指定用户设定推广员\n order.getGuider 查询指定地址对应的推广员\n order.getGuider.wallet 查询指定地址对应的推广员\n order.queryGuider 查询指定推广员的推广统计\n ")}async routerOfProp(t){throw new l(u.MISC_ERROR,"\n prop.create 创建道具\n prop.send 转移道具\n prop.donate 捐赠道具\n prop.receive 接收捐赠道具\n prop.createlist 批量创建道具\n prop.sendlist 批量转移道具\n prop.order 订购:制备并发送\n prop.found 熔铸道具\n prop.sale 拍卖道具\n prop.buy 购买道具\n prop.byaddress 根据地址查询自己拥有的道具\n prop.wallet.byaddress 根据地址查询自己拥有的道具\n prop.wallet.byid 根据PID查询自己拥有的道具\n prop.wallet.byoid 根据OID查询自己拥有的道具\n ")}async allianceCreate(t,e,r){if(e||t.length<3)throw new l(u.MISC_ERROR,"sys.alliance.create password nodeid alliancename (host): 创建联盟节点证书 备份密码 节点编号 盟友名称 (节点地址)");const i=new y([t]);e=i.str(0);var s=i.uint(1,0),n=i.str(2,"");t=i.str(3,"");if(!s||!e)throw new l(u.MISC_ERROR,"节点编号、备份密码都不能为空");if(!this.wdb.$parent||!this.wdb.$parent.config.identityKey)throw new l(u.MISC_ERROR,"identityKey not set yet, please run sys.alliance.gettoken without params first");let[a,o]=await this.accessControl(r,""),c=await a.createAllianceInfo(n,s),h=(this.wdb.$parent.pool.authdb.addKnown("0.0.0.0",k.publicKeyCreate(Buffer.from(this.wdb.$parent.config.identityKey,"hex"),!0)),{body:{language:c.mnemonic.language,phrase:c.mnemonic.getPhrase(),passphrase:c.mnemonic.passphrase,alliancePrivateKey:c.alliancePrivateKey.toString("hex"),allianceName:n,allianceNodeId:s,awardAddress:c.awardAddress,allianceNodeToken:{network:this.network.type,alliancename:n,sn:s,prv:c.prv.toString("hex"),pub:c.pub.toString("hex"),address:c.address},notifyAddress:a.notifyAddress,authorized:this.wdb.$parent.pool.authdb.getAuthorized()},password:e,network:this.network.type,file:this.network.type+`-${n}-${s}.keystore`}),m=N.encrypt(h);if(this.wdb.$parent){let i=!1;for(var g of this.wdb.$parent.config.alliances)if((g=g.split("|"))[0]==n&&g[1]==s){i=!0;break}i||(r=f.hashInt(n+"-"+s),this.wdb.$parent.pool.authdb.addKnown("0.0.0.0:"+r,Buffer.from(h.body.allianceNodeToken.pub,"hex")),h.body.authorized=this.wdb.$parent.pool.authdb.getAuthorized(),m=N.encrypt(h),this.wdb.$parent.config.alliances.push(`${n}|${s}|${m}|${e}|${h.body.awardAddress}|`+t),await this.wdb.$parent.saveConfigAsync())}return r={host:t,key:h.body.allianceNodeToken.pub},e=d.signObj(r,a.notifyKey.privateKey),await a.commNotify({dst:a.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:r,sig:e,pub:a.notifyKey.publicKey.toString("hex")})}),await p.writeFile(h.file,m,"utf8"),r=(await a.getAccount(o)).getReceive().toString(),await this.wdb.logAudit({address:r,oper:"node.create",hash:n+"."+s,index:0}),{nodeid:s,alliancename:n,host:t,peerPubkey:h.body.allianceNodeToken.pub,awardAddress:h.body.awardAddress,file:h.file,notifyAddress:a.notifyAddress}}async allianceImport(t,e,r){if(e||t.length<3)throw new l(u.MISC_ERROR,"sys.alliance.import password nodeid alliancename key (host): 导入联盟节点 备份密码 节点编号 盟友名称 节点公钥 (节点地址)");if(!this.wdb.$parent||!this.wdb.$parent.config.identityKey)throw new l(u.MISC_ERROR,"identityKey not set yet, please run sys.alliance.gettoken without params first");const i=new y([t]);e=i.str(0);var s=i.uint(1,0),n=i.str(2,""),a=(t=i.str(3,""),i.str(4,""));if(!s||!e||!t)throw new l(u.MISC_ERROR,"节点编号、备份密码、节点公钥都不能为空");let o,[c,h]=await this.accessControl(r,""),m=await c.createAllianceInfo(n,s,t),g=(this.wdb.$parent.pool.authdb.addKnown("0.0.0.0",k.publicKeyCreate(Buffer.from(this.wdb.$parent.config.identityKey,"hex"),!0)),{body:{alliancePrivateKey:m.alliancePrivateKey.toString("hex"),allianceName:n,allianceNodeId:s,allianceNodeToken:{network:this.network.type,alliancename:n,sn:s,pub:m.pub.toString("hex"),address:m.address},awardAddress:m.awardAddress,notifyAddress:c.notifyAddress},password:e,network:this.network.type,file:this.network.type+`-${n}-${s}.keystore`});if(this.wdb.$parent){let i=!1;for(var v of this.wdb.$parent.config.alliances)if((v=v.split("|"))[0]==n&&v[1]==s){i=!0;break}i||(r=f.hashInt(n+"-"+s),this.wdb.$parent.pool.authdb.addKnown("0.0.0.0:"+r,Buffer.from(t,"hex")),g.body.authorized=this.wdb.$parent.pool.authdb.getAuthorized(),o=N.encrypt(g),this.wdb.$parent.config.alliances.push(`${n}|${s}|${o}|${e}|${g.body.awardAddress}|`+a),await this.wdb.$parent.saveConfigAsync())}else o=N.encrypt(g);return await p.writeFile(g.file,o,"utf8"),r={host:a,key:g.body.allianceNodeToken.pub},t=d.signObj(r,c.notifyKey.privateKey),await c.commNotify({dst:c.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:r,sig:t,pub:c.notifyKey.publicKey.toString("hex")})}),e=(await c.getAccount(h)).getReceive().toString(),await this.wdb.logAudit({address:e,oper:"node.create",hash:n+"."+s,index:0}),{nodeid:s,alliancename:n,host:a,peerPubkey:g.body.allianceNodeToken.pub,awardAddress:g.body.awardAddress,file:g.file,notifyAddress:c.notifyAddress}}async refreshAlliance(t,e,r){if(e)throw new l(u.MISC_ERROR,"sys.alliance.refresh amount: 为联盟成员批量充值 充值金额");var i=new y([t]).uint(0,0);if(i<1e4||5e9<i)throw new l(u.MISC_ERROR,"无效的充值金额(10000~5000000000)");let[s,n]=await this.accessControl(r);if(this.wdb.$parent)for(var a of this.wdb.$parent.config.alliances){a=a.split("|"),S.fromString(a[4],this.network.type).isWitnessPubkeyhash()&&await s.send({outputs:[{address:a[4],value:i}]},n);var o=N.decrypt({network:this.network.type,password:a[3],body:a[2]});a=(this.wdb.$parent.rpc.addPeer&&await this.wdb.$parent.rpc.addPeer([a[5],o.allianceNodeToken.pub]),{host:a[5],key:o.allianceNodeToken.pub}),o=d.signObj(a,s.notifyKey.privateKey);await s.commNotify({dst:s.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:a,sig:o,pub:s.notifyKey.publicKey.toString("hex")})})}}async refreshAllianceAsync(t,e,r){if(e)throw new l(u.MISC_ERROR,"sys.alliance.refresh.async amount: 为联盟成员批量充值 充值金额");var i=new y([t]).uint(0,0);if(i<1e4||5e9<i)throw new l(u.MISC_ERROR,"无效的充值金额(10000~5000000000)");let[s,n]=await this.accessControl(r);if(this.wdb.$parent)for(var a of this.wdb.$parent.config.alliances){a=a.split("|"),S.fromString(a[4],this.network.type).isWitnessPubkeyhash()&&s.send({outputs:[{address:a[4],value:i}]},n);var o=N.decrypt({network:this.network.type,password:a[3],body:a[2]});a=(this.wdb.$parent.rpc.addPeer&&await this.wdb.$parent.rpc.addPeer([a[5],o.allianceNodeToken.pub]),{host:a[5],key:o.allianceNodeToken.pub}),o=d.signObj(a,s.notifyKey.privateKey);s.commNotify({dst:s.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:a,sig:o,pub:s.notifyKey.publicKey.toString("hex")})})}}async allianceDelete(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,"sys.alliance.delete nodeid alliancename: 删除联盟节点证书 节点编号 盟友名称");const i=new y([t]);var s=i.uint(0,0),n=i.str(1,"");let[a,o]=await this.accessControl(r,"");if(!s||!n)throw new l(u.MISC_ERROR,"节点编号、节点名称都不能为空");if(this.wdb.$parent)for(let t=0;t<this.wdb.$parent.config.alliances.length;t++){var c=this.wdb.$parent.config.alliances[t].split("|");c[0]==n&&c[1]==s&&(this.wdb.$parent.config.alliances.splice(t,1),await this.wdb.$parent.config.saveAsync(),c[5]&&await this.wdb.$parent.rpc.delPeer([c[5]]))}return e=(await a.getAccount(o)).getReceive().toString(),await this.wdb.logAudit({address:e,oper:"node.delete",hash:n+"."+s,index:0}),!0}async getAllianceNodeToken(t,e,r){if(e)throw new l(u.MISC_ERROR,"sys.alliance.gettoken (nodeid alliancename pubkey): 创建联盟节点信道密钥 (节点编号 盟友名称)");const i=new y([t]);e=i.uint(0,0),t=i.str(1);var s=i.str(2);if(!this.wdb.$parent)throw new l(u.MISC_ERROR,"this cmd can only run on fullnode.");let[n]=await this.accessControl(r),a=await n.createAllianceInfo(t,e,s);return t||(this.wdb.$parent.config.identityKey?(a.prv=Buffer.from(this.wdb.$parent.config.identityKey,"hex"),a.pub=k.publicKeyCreate(a.prv,!0),a.address=S.fromWitnessPubkeyhash(x.hash160(a.pub),this.network.type).toString()):(this.wdb.$parent.pool.options.identityKey=a.prv,this.wdb.$parent.config.identityKey=a.prv.toString("hex"),await this.wdb.$parent.saveConfigAsync())),{network:this.network.type,alliancename:t,sn:e,prv:a.prv.toString("hex"),pub:a.pub.toString("hex"),address:a.address}}async allianceUserCreate(t,e,r){if(e)throw new l(u.MISC_ERROR,"sys.alliance.user cid uid (alliancename): 创建企业用户 企业编号 用户编号 (盟友名称)");return this.$allianceUserCreate(t,r)}async $allianceUserCreate(t,e,r){const i=new y([t]);t=i.str(0);var s=i.uint(1),n=i.str(2,"");let a=null,o=null;o=n?([e]=await this.accessControl(e),x.hash256(Buffer.concat([Buffer.from(n),e.master.key.privateKey]))):Buffer.from(this.wdb.$parent.config.alliancePrivateKey,"hex"),n=E.fromPrivate(o,!0,this.network);let c=E.fromPrivate(x.hash256(Buffer.concat([Buffer.from(t+"-"+s),n.privateKey]),!0,this.network));return c.witness=!0,a=c.signData({cid:t,uid:s}),r&&(a.prvkey=c.privateKey.toString("hex")),a}async isReady(t){return this.wdb.isFull()}async shutdown(t,e){return this.wdb.$parent&&this.wdb.$parent.close().catch(t=>{setImmediate(()=>{throw t})}).finally(async()=>{await new Promise(t=>{setTimeout(t,1e4)}),process.exit(0)}),"Stopping."}async stop(t,e,r){if(e||0!==t.length)throw new l(u.MISC_ERROR,"sys.walletdb.stop");return this.wdb.close(),"Stopping walletdb..."}async destroyWalletDb(t,e,r){if(e||0!==t.length)throw new l(u.MISC_ERROR,"sys.walletdb.destroy: 删除钱包数据库");return await this.wdb.close(),await this.wdb.destroy(),"Destroyed."}async createWalletDb(t,e,r){if(e||0!==t.length)throw new l(u.MISC_ERROR,"sys.walletdb.create: 删除原有钱包数据库并重建");return await this.wdb.close(),await this.wdb.destroy(),await this.wdb.open(),"Created."}async fundRawTransaction(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,'tx.fund.admin "hexstring" ( options openid )');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));if(e=i.buf(0),t=i.obj(1),!e)throw new l(u.TYPE_ERROR,"Invalid hex string.");const a=A.fromRaw(e);if(0===a.outputs.length)throw new l(u.INVALID_PARAMETER,"TX must have at least one output.");let o=null,h=null;if(t){const e=new y([t]);o=e.ufixed("feeRate",8),h=(h=e.str("changeAddress"))&&c.parseAddress(h,this.network)}return await s.fund(a,{rate:o,changeAddress:h,account:n}),{hex:a.toRaw().toString("hex"),changepos:a.changeIndex,fee:v.btc(a.getFee(),!0)}}async dumpPrivKey(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"key.export.private address [account]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));if(e=i.str(0,""),!await s.belongToAccount(n,e))throw new l(u.MISC_ERROR,"Invald Account.");t=c.parseHash(e,this.network);const a=await s.getPrivateKey(t);if(a)return a.toSecret();throw new l(u.MISC_ERROR,"Key not found.")}async exportMnemonic(t,e,r){if(e||1!==t.length)throw new l(u.MISC_ERROR,"wallet.exportmnemonic password: 备份钱包助记符 备份密码");const i=new y([t]);let[s,n]=await this.accessControl(r);if(e=i.str(0),"primary"==s.id&&"default"!=n)throw new l(u.MISC_ERROR,"wallet.exportmnemonic: Invalid Account");let a={body:{phrase:s.master.mnemonic.getPhrase(),language:s.master.mnemonic.language,passphrase:s.master.mnemonic.passphrase},password:e,network:this.network,file:`./${this.network.type}-wallet${s.db.options.spv?"-spv":""}.keystore`};return this.wdb.$parent&&(a.body.awardAddress=this.wdb.$parent.config.coinbaseAddress),await N.writeEncryptFile(a),!0}async dumpWallet(t,e,r){if(e||1!==t.length)throw new l(u.MISC_ERROR,'wallet.export "filename"');const i=new y([t]);let[s,n]=await this.accessControl(r);if("primary"==s.id&&"default"!=n)throw new l(u.MISC_ERROR,"Invalid Account");if(e=i.str(0))return await s.exportToFile({file:e}),!0;throw new l(u.TYPE_ERROR,"Invalid filename.")}async encryptWallet(t,e,r){if(e||1!==t.length)throw new l(u.MISC_ERROR,'wallet.encrypt "passphrase"');const i=new y([t]);let[s,n]=await this.accessControl(r);if(e=i.str(0,""),"primary"==s.id&&"default"!=n)throw new l(u.MISC_ERROR,"Invalid Account");if(s.master.encrypted)throw new l(u.WALLET_WRONG_ENC_STATE,"Already running with an encrypted wallet.");if(e.length<1)throw new l(u.MISC_ERROR,'wallet.encrypt "passphrase"');try{await s.setPassphrase(null,e)}catch(t){throw new l(u.WALLET_ENCRYPTION_FAILED,"Encryption failed.")}return"wallet encrypted"}async getAccount(t,e,r){if(e||1!==t.length)throw new l(u.MISC_ERROR,'address.account "address"');const i=new y([t]);let[s,n]=await this.accessControl(r);return("primary"!=s.id||"default"==n)&&(e=i.str(0,""),t=c.parseHash(e,this.network),r=await s.getPath(t))?r.name:""}async getAddressesByIndex(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,'address.index "index"');const i=new y([t]);let[s,n]=await this.accessControl(r);if("primary"!=s.id||"default"==n){var a=i.uint(0);for(const t of await s.getPaths("default")){const e=t.toAddress();if(0==t.branch&&t.index==a)return e.toString(this.network)}}}async accessControl(t,e){let r=await this.wdb.get("primary");if(this.wdb.options.acl.isRoot(t.options.cid))"primary"!==t.options.wid?(r=await this.wdb.get(t.options.wid),e=null):"*"===(e=e||"default")&&(e=null);else if("primary"!==t.options.wid){if(!await r.belongToAccount(t.options.cid,t.options.wid))throw new l(u.TYPE_ERROR,"Invalid wid.");r=await this.wdb.get(t.options.wid),e=null}else e=t.options.cid;return await r.ensureAccount({name:e,witness:!0}),[r,e]}async getAddressesByAccount(t,e,r){if(e)throw new l(u.MISC_ERROR,'address.list "account"');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));const a=[],o=[],c=[];for(const t of await s.getPaths(n)){const e=t.toAddress();(0==t.branch?a:1==t.branch?o:c).push(e.toString(this.network))}return[a,o,c]}async getAccountAddress(t,e,r){if(e)throw new l(u.MISC_ERROR,'address.receive "account"');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));const a=await s.getAccount(n);if(a)return a.receive.getAddress("string")}async getAccountChangeAddress(t,e,r){if(e)throw new l(u.MISC_ERROR,"address.change account");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));const a=await s.getAccount(n);if(a)return a.change.getAddress("string")}async getAccountNestedAddress(t,e,r){if(e)throw new l(u.MISC_ERROR,'address.nested.list "account"');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));const a=await s.getAccount(n);if(a)return a.nested.getAddress("string")}async getBalance(t,e,r){if(e||3<t.length)throw new l(u.MISC_ERROR,'balance.confirmed ( "account" minconf includeWatchonly )');const i=new y([t]);let s,[n,a]=await this.accessControl(r,i.str(0,""));return e=i.u32(1,1),t=i.bool(2,!1),n.watchOnly!==t?0:(r=await n.getBalance(a),s=0<e?r.confirmed:r.unconfirmed,v.btc(s,!0))}async getBalanceLog(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,'balance.log "account" (height)');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0));return e=i.uint(1,0),s.queryBalanceLog(n,e)}async getBalanceAll(t,e,r){if(e||3<t.length)throw new l(u.MISC_ERROR,'balance.all ( "account" minconf includeWatchonly )');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0));return(await s.getBalance(n)).toJSON()}async getUserToken(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,"cp.user cid uid: 生成登录令牌 厂商编码 用户编码");const i=new y([t]);e=i.str(0),t=i.str(1);let[s]=await this.accessControl(r);return s.tokenCreate({cid:e,uid:t},t)}async masterkey(t,e,r){let[i,s]=await this.accessControl(r);if("primary"==i.id||"default"==s)return i.master.toJSON(!0)}async getHistory(t,e,r){if(e||1<t.length)throw new l(u.MISC_ERROR,"tx.history (page acct):查询交易历史记录 (页码 账号)");const i=new y([t]);var s=i.uint(0,1);if(s<1)throw new l(u.MISC_ERROR,"页面必须是大于0的数字");let[a,o]=await this.accessControl(r,i.str(1));var c;e=await a.getHistory(o);n.sortTX(e);let h=0,p=[];for(c of e){if(h<10*(s-1));else{if(h>=10*s)break;p.push(c)}h++}t=await a.toDetails(p);const d={};return d.items=t,d.pageSize=10,d.pageNum=s,d.total=e.length,d}async stockOffer(t,e,r){if(e||t.length<3)throw new l(u.MISC_ERROR,"stock.offer cid amount price (openid): 发行凭证 厂商编码 发行总量 发行单价 (玩家账号)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(3,""));if(e=i.str(0,""),!(t=i.uint(1,0))||t<w.STOCK_TRADE_SINGLE||t>w.STOCK_ADDED_SINGLE)throw new l(u.MISC_ERROR,`stock.offer amount error: must over ${w.STOCK_TRADE_SINGLE} and less `+w.STOCK_ADDED_SINGLE);if(!(r=i.uint(2,0))||r<w.GRAM||r>w.STOCK_MAX_PRICE)throw new l(u.MISC_ERROR,`stock.offer price error: must over ${w.GRAM} and less `+w.STOCK_MAX_PRICE);return s.stockOffer(e,t,r,n)}async stockPurchase(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,"stock.purchase cid amount (openid): 购买凭证 厂商编码 购买量 (资金账号)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));if(e=i.str(0,""),!(t=i.uint(1,0))||t<w.STOCK_TRADE_SINGLE||t>w.STOCK_MAX_TRADE_SINGLE)throw new l(u.MISC_ERROR,`amount error: must over ${w.STOCK_TRADE_SINGLE} and less `+w.STOCK_MAX_TRADE_SINGLE);return s.stockPurchase(e,t,n)}async stockPurchaseTo(t,e,r){if(e||t.length<3)throw new l(u.MISC_ERROR,"stock.purchaseTo cid amount dst (src): 代买凭证 厂商编码 购买量 目标账号 (资金账号)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(3,""));if(e=i.str(0,""),t=i.uint(1,0),r=i.str(2,""),!t||t<w.STOCK_TRADE_SINGLE||t>w.STOCK_MAX_TRADE_SINGLE)throw new l(u.MISC_ERROR,`amount error: must over ${w.STOCK_TRADE_SINGLE} and less `+w.STOCK_MAX_TRADE_SINGLE);let a={};return a.order=await s.stockPurchaseTo(e,t,r,n),a}async stockSend(t,e,r){if(e||t.length<3)throw new l(u.MISC_ERROR,"stock.send cid amount recvaddr (openid sendaddr): 转让凭证 厂商编码 转让量 接收地址 (玩家账号 发送地址)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(3,""));e=i.str(0,""),t=i.uint(1,0),r=i.str(2,null);var a=i.str(4,null);if(!t||t<w.STOCK_TRADE_SINGLE||t>w.STOCK_MAX_TRADE_SINGLE)throw new l(u.MISC_ERROR,`stock.send amount error: must over ${w.STOCK_TRADE_SINGLE} and less `+w.STOCK_MAX_TRADE_SINGLE);return s.stockSend(e,t,r,n,a)}async stockBid(t,e,r){if(e||t.length<3)throw new l(u.MISC_ERROR,"stock.bid cid amount price (openid srcAddr): 转让凭证 厂商编码 转让总量 转让单价 (玩家账户 凭证账户地址)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(3,""));e=i.str(0,""),t=i.uint(1,0),r=i.uint(2,0);var a=i.str(4,"");if(!t||t<w.STOCK_TRADE_SINGLE||t>w.STOCK_MAX_TRADE_SINGLE)throw new l(u.MISC_ERROR,`stock.bid amount error: must over ${w.STOCK_TRADE_SINGLE} and less `+w.STOCK_MAX_TRADE_SINGLE);return s.stockBid(e,t,r,n,a)}async stockAuction(t,e,r){if(e||t.length<4)throw new l(u.MISC_ERROR,"stock.auction cid addr amount price (openid): 购买凭证 CP编号 转让者地址 购买量 价格 (玩家账号)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(4,""));e=i.str(0,""),t=i.str(1,""),r=i.uint(2);var a=i.uint(3);if(!r||r<w.STOCK_TRADE_SINGLE)throw new l(u.MISC_ERROR,"stock.auction amount error: must over "+w.STOCK_TRADE_SINGLE);if(a)return s.stockAuction(e,t,r,a,n);throw new l(u.MISC_ERROR,"stock.auction price error")}async stockList(t,e,r){if(e)throw new l(u.MISC_ERROR,"stock.list.wallet conditions: 我的凭证列表 查询条件");return e=new y([t]).array(0,[]),this.wdb.accountList.query(e)}async stockRecordList(t,e,r){if(e)throw new l(u.MISC_ERROR,"stock.record.wallet type (cid height conditions): 查询凭证流水 流水类型(0代表全部类型) (厂商编号 最小高度 组合查询条件)");const i=new y([t]);let[s]=await this.accessControl(r);e=i.uint(0,0),t=i.str(1),r=i.uint(2,0);var n,a,o,c=i.array(3,[]);let h=null;for([n,a]of(h=e?await s.db.getStockRecord(e,t,r):await s.db.getStockRecordByCid(t,r)).data)a.account||(o=await s.getAccountByAddress(a.addr))&&(a.wid=o.wid,a.account=o.name,h.set(a.itemNo,a));return h.query(c)}async sendSecret(t,e,r){if(e||t.length<3)throw new l(u.MISC_ERROR,"comm.secret dst message (openid): 安全通信消息 收信地址 信息内容 (玩家账号)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(3,""));if(e=i.str(0,""),t=i.str(1,""),c.parseAddress(e,this.network))return s.sendSecret(e,t,n);throw new l(u.TYPE_ERROR,"Invalid Destination Address.")}async calcHash(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"comm.hash content: 计算输入的哈希值");return e=new y([t]).str(0,""),x.hash256(Buffer.from(e)).toString("hex")}async commNotify(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,"comm.notify addr content (openid): 发送点对点消息 地址 内容 (玩家账号)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));return e=i.str(0,""),t=i.obj(1,{}),s.commNotify({dst:e,content:t,account:n})}async setGuider(t,e,r){if(e||t.length<3)throw new l(u.MISC_ERROR,"order.setGuider src cid dst: 设定推广员 推广员地址 厂商编码 目标用户地址(逗分) [支付账号]");const i=new y([t]);var[,t]=await this.accessControl(r,i.str(3)),s=i.str(0,""),n=i.str(1,"");let a=i.array(2,[]);return 1==a.length&&await this.wdb.getGuider(a[0])==s?null:this.createTX([{comment:{oper:"greg",addr:s,cid:n}},a.map(t=>({address:t,value:1e4})),t],e,r)}async getGuider(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"order.getGuider.wallet dst: 查询推广员 目标用户地址");return e=new y([t]).str(0,""),this.wdb.getGuider(e)}async payOrder(t,e,r){if(e||t.length<4)throw new l(u.MISC_ERROR,"order.pay cid uid sn sum (openid): 支付订单 厂商编码 玩家游戏内编码 订单编码 总额 (玩家账号)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(4,""));e=i.str(0,""),t=i.str(1,""),r=i.str(2,"");var a=i.uint(3,0);return s.payOrder(e,t,r,a,n)}async scanContact(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,'comm.scanContact "txid" ( index )');const s=new y([t]);let[n]=await this.accessControl(r);if(e=s.hash(0),i(e,"Hash is required."),t=s.uint(1,-1),!e)throw new l(u.TYPE_ERROR,"Invalid parameter");if(r=await n.getTX(e))return this.wdb.scanContact(r.tx,t);throw new l(u.WALLET_ERROR,"TX not found.")}async listContact(t,e,r){if(e)throw new l(u.MISC_ERROR,"sys.listContact: 列表联系人");return e=new y([t]).array(0,[]),this.wdb.listContact(e,null,["address"])}async listNotify(t,e,r){if(e)throw new l(u.MISC_ERROR,"comm.listNotify (query): 通知列表 (查询条件,使用 account 参数可分账号查询)");return e=new y([t]).array(0,[]),this.wdb.listNotify(e)}async queryOrderList(t,e,r){if(e)throw new l(u.MISC_ERROR,"order.query.wallet (conditions account): 支付订单列表 (查询条件 子账户)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));return e=i.array(0,[]),s.getOrderList(e,n)}async getReceivedByAccount(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,'account.received "account" ( minconf )');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));var a=i.u32(1,0),o=this.wdb.curHeight;e=await s.getPaths(n);const c=new Set;for(const t of e)c.add(t.hash);let h=0,p=-1;for(const t of await s.getHistory(n)){var d=t.getDepth(o);if(!(d<a)){(-1===p||d<p)&&(p=d);for(const e of t.tx.outputs){var f=e.getHash("hex");f&&c.has(f)&&(h+=e.value)}}}return v.btc(h,!0)}async getReceivedByAddress(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,'address.received "address" ( minconf )');const i=new y([t]);let[s]=await this.accessControl(r);e=i.str(0,"");var n=i.u32(1,0),a=this.wdb.curHeight,o=c.parseHash(e,this.network);let h=0;for(const t of await s.getHistory())if(!(t.getDepth(a)<n))for(const e of t.tx.outputs)e.getHash("hex")===o&&(h+=e.value);return v.btc(h,!0)}async _toWalletTX(t,e){let[r]=await this.accessControl(t);const i=await r.toDetails(e);if(!i)throw new l(u.WALLET_ERROR,"TX not found.");let s=!0;for(const t of i.inputs)if(t.path){s=!1;break}const n=[];let a=0,o=0;for(let t=0;t<i.outputs.length;t++){const e=i.outputs[t];e.path?1!==e.path.branch&&(n.push({account:e.path.name,address:e.address.toString(this.network),category:"receive",amount:v.btc(e.value,!0),label:e.path.name,vout:t}),o+=e.value):s||(n.push({account:"",address:e.address?e.address.toString(this.network):null,category:"send",amount:-v.btc(e.value,!0),fee:-v.btc(i.getFee(),!0),vout:t}),a+=e.value)}return{amount:v.btc(s?o:-a,!0),confirmations:i.confirmations,blockhash:i.block?f.revHex(i.block):null,blockindex:i.index,blocktime:i.time,txid:f.revHex(i.hash),walletconflicts:[],time:i.mtime,timereceived:i.mtime,"bip125-replaceable":"no",details:n,hex:i.tx.toRaw().toString("hex")}}async getTransaction(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,'gettransaction "txid" ( includeWatchonly )');const s=new y([t]);let[n]=await this.accessControl(r);if(e=s.hash(0),i(e,"Hash is required."),t=s.bool(1,!1),!e)throw new l(u.TYPE_ERROR,"Invalid parameter");if(e=await n.getTX(e))return this._toWalletTX(r,e,t);throw new l(u.WALLET_ERROR,"TX not found.")}async abandonPending(t,e,r){if(e)throw new l(u.MISC_ERROR,"tx.abandonall.admin [account]: 废弃所有挂起的交易");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));for(const e of await s.getPending(n))try{await s.abandon(e.hash)}catch(t){this.logger.warning(t.message)}return null}async abandonTransaction(t,e,r){if(e||1!==t.length)throw new l(u.MISC_ERROR,'tx.abandon.admin "txid"');const i=new y([t]);let[s]=await this.accessControl(r);if(!(e=i.hash(0)))throw new l(u.TYPE_ERROR,"Invalid parameter.");if(await s.abandon(e))return null;throw new l(u.WALLET_ERROR,"Transaction not in wallet.")}async getUnconfirmedBalance(t,e,r){if(e||1<t.length)throw new l(u.MISC_ERROR,"balance.unconfirmed");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));return e=await s.getBalance(n),v.btc(e.unconfirmed,!0)}async importPrivKey(t,e,r){if(e||t.length<1||4<t.length)throw new l(u.MISC_ERROR,'key.import.private account "privatekey" passphrase [rescan]');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));e=i.str(1),t=i.str(2),r=i.bool(3,!1);const a=c.parseSecret(e,this.network);return a.witness=!0,await s.importKey(n,a,t),r&&await this.wdb.rescan(0),!0}async walletAuth(t,e,r){return!0}async importWallet(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,'wallet.import "filename" ( rescan )');const i=new y([t]);var[]=await this.accessControl(r);e=i.str(0),t=i.bool(1,!1);return await this.wdb.loadBackup(e),t&&await this.wdb.rescan(0),!0}async importAddress(t,e,r){if(e||t.length<1||4<t.length)throw new l(u.MISC_ERROR,"address.import account address [rescan p2sh]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,"")),a=i.str(1,"");if(e=i.bool(2,!1),i.bool(3,!1)){let t=i.buf(0);if(!t)throw new l(u.TYPE_ERROR,"Invalid parameters.");t=b.fromRaw(t),t=b.createScript(t.hash160(),b.types.SCRIPTHASH),a=S.fromScript(t)}else a=c.parseAddress(a,this.network);return await s.importAddress(n,a),e&&await this.wdb.rescan(0),!0}async importPubkey(t,e,r){if(e||t.length<1||4<t.length)throw new l(u.MISC_ERROR,"key.import.public account pubkey [rescan]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));if(e=i.buf(1),t=i.bool(2,!1),e)return r=E.fromPublic(e,this.network),await s.importKey(n,r),t&&await this.wdb.rescan(0),!0;throw new l(u.TYPE_ERROR,"Invalid parameter.")}async listAccounts(t,e,r){if(e||2<t.length)throw new l(u.MISC_ERROR,"account.list ( minconf includeWatchonly)");const i=new y([t]);let[s]=await this.accessControl(r);var n=i.u32(0,0),a=i.bool(1,!1);const o={};for(const t of await s.getAccounts()){var c=await s.getBalance(t);let e=c.unconfirmed;0<n&&(e=c.confirmed),s.watchOnly!==a&&(e=0),o[t]=v.btc(e,!0)}return o}async listConservedUnspent(t,e,r){if(e||0<t.length)throw new l(u.MISC_ERROR,"coin.conserved.list: 查询已经保持的Unspent列表");let[i]=await this.accessControl(r);const s=[];for(const t of i.getConserved())s.push({txid:t.txid(),vout:t.index});return s}async listReceivedByAccount(t,e,r){if(e||3<t.length)throw new l(u.MISC_ERROR,"account.listreceived ( minconf includeempty includeWatchonly )");const i=new y([t]);e=i.u32(0,0),t=i.bool(1,!1);var s=i.bool(2,!1);return this._listReceived(r,e,t,s,!0)}async listReceivedByAddress(t,e,r){if(e||3<t.length)throw new l(u.MISC_ERROR,"address.received.list ( minconf includeempty includeWatchonly )");const i=new y([t]);e=i.u32(0,0),t=i.bool(1,!1);var s=i.bool(2,!1);return this._listReceived(r,e,t,s,!1)}async _listReceived(t,e,r,i,s){let[n]=await this.accessControl(t);t=await n.getPaths();var a=this.wdb.curHeight;const o=new Map;for(const e of t){const t=e.toAddress();o.set(e.hash,{involvesWatchonly:n.watchOnly,address:t.toString(this.network),account:e.name,amount:0,confirmations:-1,label:""})}for(const t of await n.getHistory()){var c=t.getDepth(a);if(!(c<e))for(const e of t.tx.outputs){const t=e.getAddress();if(t){var u=t.getHash("hex");const r=o.get(u);r&&((-1===r.confirmations||c<r.confirmations)&&(r.confirmations=c),r.address=t.toString(this.network),r.amount+=e.value)}}}let h=[];for(const t of o.values())h.push(t);if(s){const t=new Map;for(const e of h){const r=t.get(e.account);r?r.amount+=e.amount:(t.set(e.account,e),e.address=void 0)}h=[];for(const e of t.values())h.push(e)}const l=[];for(const e of h)if(r||0!==e.amount){-1===e.confirmations&&(e.confirmations=0);try{e.amount=v.btc(e.amount,!0),l.push(e)}catch(t){this.logger.error("invalid amount:entry(%s) msg(%s)",JSON.stringify(e),t.message)}}return l}async listSinceBlock(t,e,r){if(e)throw new l(u.MISC_ERROR,'tx.history.since ( "blockhash" target-confirmations includeWatchonly account)');var i=this.wdb.curHeight;const s=new y([t]);let[n,a]=await this.accessControl(r,s.str(3,""));e=s.hash(0);var o,c=s.u32(1,0);t=s.bool(2,!1);if(n.watchOnly!==t)return[];let h=-1;e&&(t=await this.client.getEntry(e))&&(h=t.height),-1===h&&(h=i);const p=[];let d;for(const t of await n.getHistory(a))t.height<h||t.getDepth(i)<c||((!d||t.height>d)&&(d=t),o=await this._toListTX(r,t),p.push(o));return{transactions:p,lastblock:d&&d.block?f.revHex(d.block):g.NULL_HASH}}async _toListTX(t,e){let[r]=await this.accessControl(t);const s=await r.toDetails(e);if(!s)throw new l(u.WALLET_ERROR,"TX not found.");let n=!0;for(const t of s.inputs)if(t.path){n=!1;break}let a,o,c,h,p,d,m=0,g=0;for(let t=0;t<s.outputs.length;t++){const e=s.outputs[t];e.path?1!==e.path.branch&&(g+=e.value,o=e,h=t):(m+=e.value,a=e,c=t)}return d=n?(p=o,h):(p=a,c),p||(i(!n),n=!0,p=o,d=h),{account:p.path?p.path.name:"",address:p.address?p.address.toString(this.network):null,category:n?"receive":"send",amount:v.btc(n?g:-m,!0),label:p.path?p.path.name:void 0,vout:d,confirmations:s.getDepth(),blockhash:s.block?f.revHex(s.block):null,blockindex:s.index,blocktime:s.time,txid:f.revHex(s.hash),walletconflicts:[],time:s.mtime,timereceived:s.mtime,"bip125-replaceable":"no"}}async listTransactions(t,e,r){if(e||4<t.length)throw new l(u.MISC_ERROR,'tx.list ( "account" count from includeWatchonly)');const i=new y([t]);let[s,a]=await this.accessControl(r,i.str(0,""));e=i.u32(1,10),t=i.u32(2,0);var o=i.bool(3,!1);if(s.watchOnly!==o)return[];var c=await s.getHistory(a),h=(o=(n.sortTX(c),t+e),Math.min(o,c.length));const p=[];for(let e=t;e<h;e++){var d=c[e];d=await this._toListTX(r,d);p.push(d)}return p}async selectone(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"coin.selectone options (account)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));var a=i.obj(0,{});const o=[];for(const t of await s.getCoins(n)){var c=t.getDepth(this.wdb.curHeight);const e=t.getAddress();if(e){var h=t.getHash("hex");if(h&&!t.isColored&&!(a.value&&t.value<a.value||t.coinbase&&0<t.height&&this.wdb.curHeight<t.height+w.COINBASE_MATURITY)){const r=await s.getKey(h);if(o.push({txid:t.txid(),vout:t.index,address:e?e.toString(this.network):null,account:r?r.name:void 0,redeemScript:r&&r.script?r.script.toJSON():void 0,scriptPubKey:t.script.toJSON(),amount:v.btc(t.value,!0),confirmations:c,spendable:!s.isConserved(t),solvable:!0}),a.len&&o.length>=a.len)break}}}return o}async listUnspent(t,e,r){if(e||4<t.length)throw new l(u.MISC_ERROR,'coin.list ( minconf maxconf ["address", account] )');const i=new y([t]);let[s,a]=await this.accessControl(r,i.str(3,""));var o=i.u32(0,1),h=i.u32(1,9999999),p=i.array(2),d=this.wdb.curHeight;const f=new Set;if(p){const t=new y([p]);for(let e=0;e<p.length;e++){var m=t.str(e,"");m=c.parseHash(m,this.network);if(f.has(m))throw new l(u.INVALID_PARAMETER,"Duplicate address.");f.add(m)}}e=await s.getCoins(a),n.sortCoins(e);const g=[];for(const t of e){var b=t.getDepth(d);if(!(b<o||h<b)){const e=t.getAddress();if(e){var w=t.getHash("hex");if(!p||w&&f.has(w)){const r=await s.getKey(w);g.push({txid:t.txid(),vout:t.index,address:e?e.toString(this.network):null,account:r?r.name:void 0,redeemScript:r&&r.script?r.script.toJSON():void 0,scriptPubKey:t.script.toJSON(),amount:v.btc(t.value,!0),confirmations:b,spendable:!s.isConserved(t),solvable:!0})}}else this.logger.error("mistaken coin: miss address",t.hash,t.index)}}return g}async listProp(t,e,r){if(e||4<t.length)throw new l(u.MISC_ERROR,"prop.wallet.byaddress ( minconf maxconf [address, account] )");const i=new y([t]);let[s,a]=await this.accessControl(r,i.str(3,""));var o=i.u32(0,1),h=i.u32(1,9999999),p=i.array(2),d=this.wdb.curHeight;const f=new Set;if(p){const t=new y([p]);for(let e=0;e<p.length;e++){var m=t.str(e,"");m=c.parseHash(m,this.network);if(f.has(m))throw new l(u.INVALID_PARAMETER,"Duplicate address.");f.add(m)}}e=await s.getCoins(a),n.sortCoins(e);const g=[];for(const t of e){var b,w,x=t.getDepth(d);if(!(x<o||h<x)){const e=t.getAddress();e&&(b=t.getHash("hex"),(!p||b&&f.has(b))&&(b=await s.getKey(b),(w=t.getReturnData([L.OP_PROPCREATE,L.OP_PROPCREATE]))&&g.push({txid:t.txid(),vout:t.index,address:e?e.toString(this.network):null,account:b?b.name:void 0,amount:v.btc(t.value,!0),confirmations:x,spendable:!s.isConserved(t),solvable:!0,nd:w})))}}return g}async listPropByOid(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"prop.wallet.byoid oid");const i=new y([t]);let[s,a]=await this.accessControl(r,i.str(1,""));var o=i.str(0),c=this.wdb.curHeight;e=await s.getCoins(a);n.sortCoins(e);const h=[];for(const t of e){var p,d,f=t.getDepth(c);if(!(f<0||9999999<f)){const e=t.getAddress();e&&(p=t.getHash("hex"),p=await s.getKey(p),(d=t.getReturnData([L.OP_PROPCREATE,L.OP_PROPEXCHANGE]))&&d.oid==o&&h.push({txid:t.txid(),vout:t.index,address:e?e.toString(this.network):null,account:p?p.name:void 0,amount:v.btc(t.value,!0),confirmations:f,spendable:!s.isConserved(t),solvable:!0,nd:d}))}}return{list:h,count:h.length}}async listLockedUnspent(t,e,r){if(e||2<t.length)throw new l(u.MISC_ERROR,'coin.list.locked ["address", account]');const i=new y([t]);let[s,a]=await this.accessControl(r,i.str(1,""));var o=i.array(0),h=this.wdb.curHeight,p=f.now();const d=new Set;if(o){const t=new y([o]);for(let e=0;e<o.length;e++){var m=t.str(e,"");m=c.parseHash(m,this.network);if(d.has(m))throw new l(u.INVALID_PARAMETER,"Duplicate address.");d.add(m)}}let g;g=account?await s.getCoins(a):s.getLockedCoins(),n.sortCoins(g);const b=[];for(const t of g)if(t.lockedByLocktime(h,p)||t.lockedBySequence(h,p)){const e=t.getAddress();if(e){var w=t.getDepth(h),x=t.getHash("hex");if(!o||x&&d.has(x)){var[k,S,E]=t.getLockStatus();const r=await s.getKey(x);b.push({txid:t.txid(),vout:t.index,address:e?e.toString(this.network):null,account:r?r.name:void 0,redeemScript:r&&r.script?r.script.toJSON():void 0,scriptPubKey:t.script.toJSON(),amount:v.btc(t.value,!0),confirmations:w,spendable:!1,solvable:!0,locktype:k,lockheight:S,locktime:E})}}}return b}async listOperUnspent(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,'coin.conserved.oper.list unlock ([{"txid":"txid","vout":n},...]) 保持/解除保持一组UTXO: true/false [{"txid": "交易id","vout": "输出序号"}]');const i=new y([t]);let[s]=await this.accessControl(r);var n=i.bool(0,!1);if(!(e=i.array(1)))throw new l(u.TYPE_ERROR,"Invalid parameter.");for(const t of e){const e=new y([t]);var a=e.hash("txid"),o=e.u32("vout");if(null==a||null==o)throw new l(u.INVALID_PARAMETER,"Invalid parameter.");a=new R(a,o),n?s.unConserveCoin(a):s.conserveCoin(a)}return!0}async setTXFee(t,e,r){if(e||t.length<1||1<t.length)throw new l(u.MISC_ERROR,"sys.setfee rate");if(null==(e=new y([t]).ufixed(0,8)))throw new l(u.TYPE_ERROR,"Invalid parameter.");return this.wdb.feeRate=e,!0}async signMessage(t,e,r){if(e||2!==t.length)throw new l(u.MISC_ERROR,'sys.message.sign "address" "message"');const i=new y([t]);let[s]=await this.accessControl(r);if(!s.master.key)throw new l(u.WALLET_UNLOCK_NEEDED,"Wallet is locked.");e=i.str(0,""),t=c.parseHash(e,this.network);const n=await s.getKey(t);if(!n)throw new l(u.WALLET_ERROR,"Address not found.");r=i.str(1,"");return n.sign(x.hash256(Buffer.from(h+r,"utf8"))).toString("base64")}async changePassphrase(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,'wallet.changepassphrase "oldpassphrase" "newpassphrase"');const i=new y([t]);let[s]=await this.accessControl(r);if(e=i.str(0,""),t=i.str(1,""),!s.master.encrypted)throw new l(u.WALLET_WRONG_ENC_STATE,"Wallet is not encrypted.");if(e.length<1||t.length<1)throw new l(u.INVALID_PARAMETER,"Invalid parameter");return await s.setPassphrase(e,t),null}async unlock(t,e,r){const i=new y([t]);let[s]=await this.accessControl(r);r=i.str(0);var n=i.u32(1,60);if(e||s.master.encrypted&&0==t.length)throw new l(u.MISC_ERROR,'wallet.unlock "passphrase" timeout');if(!s.master.encrypted)throw new l(u.WALLET_WRONG_ENC_STATE,"Wallet is not encrypted.");if(r.length<1)throw new l(u.INVALID_PARAMETER,"Invalid parameter");if(null==n)throw new l(u.TYPE_ERROR,"Invalid parameter");return await s.unlock(r,n),null}async decryptWallet(t,e,r){if(e||1!==t.length)throw new l(u.MISC_ERROR,'wallet.decrypt "passphrase"');const i=new y([t]);let[s]=await this.accessControl(r);if(e=i.str(0,""),!s.master.encrypted)throw new l(u.WALLET_WRONG_ENC_STATE,"Running with an decrypted wallet.");if(e.length<1)throw new l(u.MISC_ERROR,'wallet.decrypt "passphrase"');try{await s.setPassphrase(e)}catch(t){throw new l(u.WALLET_ENCRYPTION_FAILED,"Decryption failed.")}return"wallet decrypted"}async importPrunedFunds(t,e,r){if(e||t.length<2||3<t.length)throw new l(u.MISC_ERROR,'tx.importprunedfunds.admin "rawtransaction" "txoutproof" ( "label" )');const i=new y([t]);if(e=i.buf(0),t=i.buf(1),!e||!t)throw new l(u.TYPE_ERROR,"Invalid parameter.");const s=I.fromRaw(e),n=_.fromRaw(t);if(e=n.hash("hex"),!n.verify())throw new l(u.VERIFY_ERROR,"Invalid proof.");if(!n.hasTX(s.hash("hex")))throw new l(u.VERIFY_ERROR,"Invalid proof.");if(-1===(t=await this.client.getEntry(e)))throw new l(u.VERIFY_ERROR,"Invalid proof.");if(e={hash:e,time:n.time,mtp:n.mtp,height:t},await this.wdb.addTX(s,e))return null;throw new l(u.WALLET_ERROR,"No tracked address for TX.")}async removePrunedFunds(t,e,r){if(e||1!==t.length)throw new l(u.MISC_ERROR,'tx.removeprunedfunds.admin "txid"');const i=new y([t]);let[s]=await this.accessControl(r);if(!(e=i.hash(0)))throw new l(u.TYPE_ERROR,"Invalid parameter.");if(await s.remove(e))return null;throw new l(u.WALLET_ERROR,"Transaction not in wallet.")}async getWallets(t,e,r){return this.wdb.getWallets()}async getWalletBlock(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"wallet.block height");const i=new y([t]);let[s]=await this.accessControl(r);e=i.uint(0);const n=await s.getBlock(e);return n?n.toJSON():null}async getWalletLayoutH(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"wallet.layouth height");e=new y([t]).uint(0);const i=await this.wdb.getBlock(e);return i?i.toJSON():null}async getWalletInfo(t,e,r){if(e)throw new l(u.MISC_ERROR,"wallet.info");if(e=new y([t]).str(0,"")){return(await this.wdb.get(e)).toJSON(!1)}return(await this.accessControl(r))[0].toJSON(!1)}async scRegister(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"sc.register options (account): 发布合约 合约参数列表 (子账户)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,"")),a=i.obj(0);if(!a)throw new l(u.MISC_ERROR,"sc.register: options is null");let o=1e5;switch(a.oper){case"change":if(a.oper=P.scState,!a.dst||!a.state)throw new l(u.TYPE_ERROR,"sc.register: dst or state is null.");if(!this.wdb.$parent)throw new l(u.TYPE_ERROR,"sc.register: not support this operation.");var c=await this.wdb.$parent.chain.db.getSCList([["options.dst",a.dst]]);if(!c||0==c.list.length)throw new l(u.TYPE_ERROR,"sc.register: contract not exist.");switch(c.list[0].options.state){case O.Normal:if(a.state!=O.Frozen&&a.state!=O.Destroy)throw new l(u.TYPE_ERROR,"Contract State Error");break;case O.Frozen:if(a.state!=O.Normal&&a.state!=O.Destroy)throw new l(u.TYPE_ERROR,"Contract State Error");break;default:throw new l(u.TYPE_ERROR,"Contract State Error")}if(a.addr=c.list[0].options.addr,await s.belongToAccount(n,a.addr))break;throw new l(u.MISC_ERROR,"sc.register: Invald Account.");case"update":if(a.oper=P.scUpdate,!a.dst)throw new l(u.TYPE_ERROR,"sc.register: dst is null.");if(!this.wdb.$parent)throw new l(u.TYPE_ERROR,"sc.register: not support this operation.");if(!(c=await this.wdb.$parent.chain.db.getSCList([["options.dst",a.dst]]))||0==c.list.length)throw new l(u.TYPE_ERROR,"sc.register: contract not exist.");if(c.list[0].options.state!=O.Normal)throw new l(u.TYPE_ERROR,"sc.register: contract state error.");if(a.addr=c.list[0].options.addr,await s.belongToAccount(n,a.addr))break;throw new l(u.MISC_ERROR,"sc.register: Invald Account.");default:if(o=1e8,a.oper=P.scRegister,a.addr=(await s.createReceive(n)).getAddress("string"),a.dst=s.getSCAddress(f.hashInt(a.addr)).toString(),this.wdb.$parent&&(c=await this.wdb.$parent.chain.db.getSCList([["options.dst",a.dst]]))&&0<c.list.length)throw new l(u.TYPE_ERROR,"sc.register: contract address conflict.")}let h=(await s.getPrivateKey(a.addr)).signData(a);h.data.sig=h.sig,a=h.data;const p=await s.send({subtractFee:!1,sort:!1,outputs:[{address:a.dst,value:o}],comment:JSON.stringify(a)},n);return await this.wdb.logAudit({address:a.addr,oper:a.oper,hash:p.hash("hex"),index:0}),a.txid=p.rhash(),a}async scRun(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,'sc.run str options (account): 调用合约 逗分参数字符串("合约收款地址,转账金额") 参数对象 (子账户)');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));const a=i.str(0).split(",");if(e=i.obj(1,{}),t=a.shift(),!this.wdb.$parent)throw new l(u.TYPE_ERROR,"sc.run: not support this operation.");if(!(r=await this.wdb.$parent.chain.db.getSCList([["options.dst",t]]))||0==r.list.length)throw new l(u.TYPE_ERROR,"sc.run: contract not exist.");if(1!=r.list[0].options.state)throw new l(u.TYPE_ERROR,`sc.run: contract execute disabled(state ${r.list[0].options.state}).`);if(e.ver&&e.ver!=r.list[0].options.ver)throw new l(u.TYPE_ERROR,"sc.run: contract version inconsistency.");r=(0|parseInt(a.shift()))>>>0,c.parseAddress(t,this.network);const o=await s.send({subtractFee:!1,sort:!1,outputs:[{address:t,value:r}],comment:JSON.stringify({oper:"scrun",params:e})},n),h=await s.getAccount(n);return(await this.wdb.logAudit({address:h.receive.getAddress("string"),oper:P.scRun,hash:o.hash("hex"),index:0}),await s.getDetails(o.hash("hex"))).toJSON()}async cpRegister(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,'cp.create name "ip,addr,class,rate" (openid): 注册厂商 名称(不少于4个字符) "IP地址,注册地址,类别,媒体分成比例" (子账号)');return this.$cpRegister(t,r,!1)}async cpRegisterAsync(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,'cp.create.async name "ip,addr,class,rate" (openid): 注册厂商 名称(不少于4个字符) "IP地址,注册地址,类别,媒体分成比例" (子账号)');return this.$cpRegister(t,r,!0)}async $cpRegister(t,e,r){const i=new y([t]);t=decodeURIComponent(i.str(0));var s=(o=i.str(1,"").split(","))[0],n=o[1],a=o[2],o=o[3]?parseInt(o[3]):15;let[c,h]=await this.accessControl(e,i.str(2,""));if(e=m.verifyDataFormat({name:t,ip:s,grate:o,cls:a}))throw new l(u.MISC_ERROR,e);return e={cid:D(),oper:P.cpRegister,name:t,ip:s,grate:o,cls:a},await c.cpRegister(f.isBech32(n)?n:null,e,h,r),e}async cpChange(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,'cp.change cid "newname,ip,addr,class,rate" "openid": 修改厂商信息 CP编号 "新的名称,IP,新的注册地址,类别,分成比例" 授权账号');const s=new y([t]);let[n,a]=await this.accessControl(r,s.str(2,""));e=s.str(0),r=(t=decodeURIComponent(s.str(1,"")).split(","))[0];var o=t[1];let c=t[2];var h=t[3],p=(t=parseInt(t[4])||null,m.verifyDataFormat({name:r,ip:o,grate:t,cls:h}));if(p)throw new l(u.MISC_ERROR,p);c&&(c=S.fromString(c),i(c instanceof S,"Not an address."));let d={cid:e,newName:r,ip:o,addr:c,grate:t,cls:h};var[]=await n.cpChange(d,a);return d.addr=d.addr.toString(),d}async cpQuery(t,e,r){if(e)throw new l(u.MISC_ERROR,"cp.query (conditions account): 查询钱包中的厂商列表 (复合条件 子帐号)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));var a;e=i.array(0,[]),t=s.db.cpList.query(e);for(a of t.list)a.owned=await s.belongToAccount(n,a.current.address);return t}async cpMine(t,e,r){if(e)throw new l(u.MISC_ERROR,"cp.mine (conditions account): 查询钱包中归属当前操作员/指定账户的厂商列表 (复合条件 子帐号)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));const a=i.array(0,[]);return a.push(["size",-1]),(await s.db.cpList.predict(async(t,e)=>s.belongToAccount(n,e.current.address))).query(a)}async cpX509(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,"cp.x509 cid [openid]: 生成厂商根证书 CP编号 [子账号]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));e=i.str(0);var[t]=await s.cpX509(e,n);return t}async x509Issue(t,e,r){if(e||t.length<4||5<t.length)throw new l(u.MISC_ERROR,"cp.x509.issue cid csrfile addr activetime [openid]: 签发X509证书 CP编号 请求文件 证书存放地址 证书存活时间 [子账号]");const i=new y([t]);let[n,a]=await this.accessControl(r,i.str(4,""));e=i.str(0),i.str(1),t=i.str(2),r=i.u64(3);var o=s.KEYUTIL.generateKeypair("EC","secp256k1"),[e]=(o=s.asn1.csr.CSRUtil.newCSRPEM({subject:{str:"/C=US/O=Test/CN=example.com"},sbjpubkey:o.pubKeyObj,sigalg:"SHA256withECDSA",sbjprvkey:o.prvKeyObj}),t=S.fromString(t,this.network),await n.x509Issue({cid:e,csrData:o,addr:t,activeTime:r},a));return e}async x509Abolish(t,e,r){if(e||t.length<3||4<t.length)throw new l(u.MISC_ERROR,"cp.x509.abolish cid seqno activetime [openid]: 作废X509证书 CP编号 证书编号 作废生效时间[子账号]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(3,""));e=i.str(0),t=i.u32(1),r=i.u64(2);var[e]=await s.x509Abolish({cid:e,seqno:t,activeTime:r},n);return e}async htlcSuggest(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,"htlc.suggest params [account]: 发起HTLC 参数对象({alice, bob, amount, rate}) [子账户]");const i=new y([t]),s=i.obj(0,{});let[n,a]=await this.accessControl(r,i.str(1,""));if(!s.ab)throw new l(u.MISC_ERROR,"htlc.suggest: params.ab(alice bchain address) is null");if(!Number.isInteger(s.amount))throw new l(u.MISC_ERROR,"htlc.suggest: illegal params.amount");if(s.amount=parseInt(s.amount),s.amount<0||s.amount>1e4*w.COIN)throw new l(u.MISC_ERROR,"htlc.suggest: illegal params.amount");if(s.rate=parseFloat(s.rate),s.rate<0||s.amount*s.rate>w.MAX_MONEY)throw new l(u.MISC_ERROR,"htlc.suggest: illegal params.rate");if(!s.target)throw new l(u.MISC_ERROR,"htlc.suggest: params.target is null");e=(await n.createReceive(a)).getAddress().toString(this.network),t={amount:s.amount,rate:s.rate,dst:s.target,aa:S.fromString(e).hash,ab:S.fromString(s.ab).hash,ba:S.fromString(s.ba).hash};const[o]=await n.sendContracts([t],a,j);return o?{txid:o.rhash(),aa:e}:null}async htlcAssent(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,"htlc.assent params({txid}) [account]: 响应HTLC 参数对象 [子账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));const a=i.obj(0,{});if(!Number.isInteger(a.amount))throw new l(u.MISC_ERROR,"htlc.assent: illegal params.amount");if(a.amount=parseInt(a.amount),a.amount<0||a.amount>1e4*w.COIN)throw new l(u.MISC_ERROR,"htlc.assent: illegal params.amount");if(a.rate=parseFloat(a.rate),a.rate<0||a.amount*a.rate>w.MAX_MONEY)throw new l(u.MISC_ERROR,"htlc.assent: illegal params.rate");e=(await s.createReceive(n)).getAddress().toString(this.network),t={src:a.src,dst:a.dst,hash:a.hash,index:a.index,ab:Buffer.from(a.ab,"hex"),ba:Buffer.from(a.ba,"hex"),bb:S.fromString(e).hash,amount:a.amount*a.rate};const[o]=await s.sendContracts([t],n,C);return o?{txid:o.rhash()}:null}async htlcSuggestDeal(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,"htlc.suggest.deal params({txid,index,sa}) [account]: 兑付HTLC 参数对象 [子账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));e=i.obj(0),t={suggest:!0,hash:f.revHex(e.txid),index:e.index,sa:e.sa};const[a]=await s.htlcDeal(t,n);return a?{txid:a.rhash()}:null}async htlcQuery(t,e,r){if(e)throw new l(u.MISC_ERROR,"htlc.query query: 条件查询HTLC合约 条件数组");const i=new y([t]).array(0,[]);return i.push(["pst","!=",F.Cancel]),this.wdb.htlcList.query(i)}async htlcAssentDeal(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,"htlc.assent.deal params({txid,index,sa}) [account]: 兑付HTLC 参数对象 [子账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));e=i.obj(0),t={hash:f.revHex(e.txid),index:e.index,sa:e.sa};const[a]=await s.htlcDeal(t,n);return a?{txid:a.rhash()}:null}async htlcAssentCancel(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,"htlc.assent.cancel params({txid, index, master}) [account]: 取消HTLC应答 参数对象 [子账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));e=i.obj(0),t={hash:f.revHex(e.txid),index:e.index,master:e.bb};const[a]=await s.htlcCancel(t,n);return a?{txid:a.rhash()}:null}async htlcSuggestCancel(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,"htlc.suggest.cancel params({txid, index, sa, master}) [account]: 取消HTLC请求 参数对象 [子账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));e=i.obj(0),t={suggest:!0,hash:f.revHex(e.txid),index:e.index,sa:e.sa,master:e.aa};const[a]=await s.htlcCancel(t,n);return a?{txid:a.rhash()}:null}async sendComment(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,"comm.comment params [account]: 发起附言交易 参数对象({body, bob}) [子账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));const a=i.obj(0,{});if(!Number.isInteger(a.amount))throw new l(u.MISC_ERROR,"comm.comment: illegal params.amount");if(a.amount=parseInt(a.amount),a.amount<0||a.amount>1e4*w.COIN)throw new l(u.MISC_ERROR,"comm.comment: illegal params.amount");if(e={bob:a.bob,body:a.body,amount:a.amount},!a.alice&&(a.alice=s.getAddress(),n)){let t=await s.createReceive(n);a.alice=t.getAddress()}let o=(await s.getPrivateKey(a.alice)).signData(e);o.data.sig=o.sig;const[c]=await s.sendContracts([o.data],n,B);return c?{txid:c.rhash()}:null}async commentQuery(t,e,r){if(e)throw new l(u.MISC_ERROR,"comm.comment.query query: 条件查询附言输出 条件数组");return e=new y([t]).array(0,[]),this.wdb.commentList.query(e)}async contractExecute(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,"contract.execute tid master: 执行交易对合约 交易编号 执行方(1-发起人,2-承兑人)");const i=new y([t]);let[s]=await this.accessControl(r);e=i.str(0),t=i.u32(1,2);const[n]=await s.contractExecute(e,t);return n.toJSON()}async contractPromise(t,e,r){if(e||t.length<1||2<t.length)throw new l(u.MISC_ERROR,"contract.promise tid [openid]: 签署交易对合约 交易编号(type.address) [子账号]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));e=i.str(0);const[a]=await s.contractPromise(e,n);return a.toJSON()}async contractOfMine(t,e,r){if(e||t.length<1||3<t.length)throw new l(u.MISC_ERROR,"contract.mine type page [openid]: 获取已签署交易对合约列表 交易对类型 页码 [子账号]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));return e=i.uint(0,1),t=i.uint(1,1),s.db.getContracts(e,t,n)}async contractCreate(t,e,r){if(e||t.length<4||5<t.length)throw new l(u.MISC_ERROR,"contract.create type src dst addr [openid] : 发布一个交易对合约 交易对类型 出让游戏金数值 换取兑换币数值 兑换币收款地址 [子账号]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(4,""));e=i.u64(0),t=i.u64(1),r=i.u64(2);var a=i.str(3);const[o]=await s.contractCreate(e,t,r,a,n);return o.toJSON()}async propGet(t,e,r){if(e)throw new l(u.MISC_ERROR,"prop.wallet.byid pid: 查询自己的物品 PID");e=new y([t]).str(0,"");let i=[];return(t=await this.wdb.propList.getVp(e))&&t.pst!=T.Delete&&i.push(t),i}async propBuy(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,"prop.buy pid price [openid] : 竞拍道具 道具编号 出价 [子账号]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));e=i.str(0),t=i.u64(1);const[a]=await s.propBuy(e,t,n);return a.toJSON()}async propFound(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"prop.found pid (openid): 熔铸道具 道具编号 (账号)");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));if(e=i.str(0),!(t=await s.db.propList.getVp(e))||t.pst==T.Delete)throw new l(u.MISC_ERROR,"prop.found prop not exist");if(!await s.belongToAccount(n,t.current.address))throw new l(u.MISC_ERROR,"prop.found: current account not owned prop.");if(t.pst!=T.Ready)throw new l(u.MISC_ERROR,"prop.found prop can not be found on current status");const[a,,o]=await s.propFound(t.current.hash,n);if(a&&o)return{hash:a.hash("hex"),txid:a.rhash(),index:0,cid:o.cid,pid:o.pid,oid:o.oid,gold:a.outputs[0].value}}async propSale(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,"prop.sale pid fixedPrice [openid]: 拍卖道具 道具编号 一口价 [子帐号]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));if(e=i.str(0),!(t=await s.db.propList.getVp(e))||t.pst==T.Delete)throw new l(u.MISC_ERROR,"prop.sale prop not exist");if(t.pst!=T.Ready)throw new l(u.MISC_ERROR,"prop.sale prop cannt be sent on current status");r=i.u64(1,0);const[a]=await s.propSale(t.current.hash,t.current.index,r,n);return a.toJSON()}async propSendListAdmin(t,e,r){return this.propSendList(t,e,r,!0)}async propSendList(t,e,r,i=!1){if(e||t.length<1)throw new l(u.MISC_ERROR,"prop.sendlist (addr|txid|index)(n,) [openid]: 批量转移道具 道具数组(地址|交易ID|输出索引) [子账户]");const s=new y([t]);let[n,a]=await this.accessControl(r,s.str(1,"")),o=[];if((e=s.str(0).split(","))&&Array.isArray(e))for(var c of e){var h,p;3<=(c=c.split("|")).length&&(h=c[0],p=new R(f.revHex(c[1]),parseInt(c[2])),4<=c.length?o.push([p,S.fromString(h),c[3]]):o.push([p,S.fromString(h)]))}const[d,,m]=await n.propExchangeList(o,a,i);if(d&&m){let t=d.hash("hex"),e=d.rhash();return m.map(r=>({hash:t,txid:e,cid:r.cid,pid:r.pid,oid:r.oid,gold:r.gold,addr:r.addr}))}}async propReceive(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"prop.receive tx [account]: 捐赠接收函数 捐赠交易字符串 [接收账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));if(!(e=i.buf(0)))throw new l(u.TYPE_ERROR,"Invalid TX Info.");t=I.fromRaw(e);const[a,,o]=await s.propReceive(t,n);if(a&&o)return{hash:a.hash("hex"),txid:a.rhash(),cid:o.cid,pid:o.pid,oid:o.oid,gold:o.gold,addr:o.simAddr,gaddr:o.gaddr}}async propDonate(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"prop.donate pid [openid]: 捐赠道具函数 道具ID [发起账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,""));if(e=i.str(0),!(t=await s.db.propList.getVp(e))||t.pst==T.Delete)throw new l(u.MISC_ERROR,"prop not exist");if(t.pst!=T.Ready)throw new l(u.MISC_ERROR,"prop cannt be sent on current status");r=new R(t.current.hash,t.current.index);const[a,,o]=await s.propDonate(r,n);if(a&&o)return{hash:a.hash("hex"),txid:a.rhash(),cid:o.cid,pid:o.pid,oid:o.oid,gold:o.gold,raw:a.toRaw().toString("hex")}}async propExchange(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,"prop.send addr pid [openid]: 转移道具函数 接收地址 物品编号 [发起账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));if(e=i.str(0),t=i.str(1),!(r=await s.db.propList.getVp(t))||r.pst==T.Delete)throw new l(u.MISC_ERROR,"prop.send prop not exist");if(r.pst!=T.Ready)throw new l(u.MISC_ERROR,"prop.send prop cannt be sent on current status");const[a,,o]=await s.propExchange(new R(r.current.hash,r.current.index),S.fromString(e),n);if(a&&o)return{hash:a.hash("hex"),txid:a.rhash(),cid:o.cid,pid:o.pid,oid:o.oid,gold:o.gold,addr:e}}async propCreateList(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"prop.createlist (cid|oid|gold|pid)(n,) [openid]: 批量创建道具 道具信息数组 [发起账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(1,"")),a=[];if((e=i.str(0).split(","))&&Array.isArray(e))for(var o of e)if(3<=(o=o.split("|")).length){var c=o[0],h=o[1],p=parseInt(o[2]);let t=null;4<=o.length&&(t=o[3]),p<w.MINPROPVALUE||a.push([c,h,p,t])}a=a.map(t=>{var[t,e,r,i]=t;return{oper:P.propCreate,cid:t,oid:e,gold:r,pid:i}});var[t]=await s.propCreate(a,n);return t?a:null}async propCreate(t,e,r){if(e||t.length<3)throw new l(u.MISC_ERROR,"prop.create cid oid gold pid (openid): 创建道具 厂商编码 道具类别码 含金量 道具编码(可填空) [账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(4,""));e=i.str(0),t=i.str(1),r=i.u64(2,w.MINPROPVALUE);var a=i.str(3,null);if(r<w.MINPROPVALUE)throw new l(u.PROP_MINVALUE,"prop.create: not a valid value");e={oper:P.propCreate,cid:e,oid:t,gold:r,pid:a};var[t]=await s.propCreate([e],n);return t?e:null}async propOrder(t,e,r){if(e||t.length<3)throw new l(u.MISC_ERROR,"prop.order cid oid gold [addr openid]: 制备道具 厂商编码 道具原始码 含金量 [接收地址 资金账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(4,""));e=i.str(0),t=i.str(1),r=i.u64(2);let a=i.str(3);if(a)a=S.fromString(a);else if(n){a=(await s.createReceive(n)).getAddress()}else a=s.getAddress();var o,c={oper:P.propCreate,cid:e,oid:t,gold:r};const[h]=await s.propCreate([c],n);if(h){o=h.rhash(),await new Promise(t=>{s.db.once("tx.received."+o,(e,r,i)=>{t()})});let[i,,c]=await s.propExchange([h,0],a,n);if(i)return{hash:i.hash("hex"),txid:i.rhash(),cid:e,pid:c.pid,oid:t,gold:r,addr:a.toString()}}return null}async walletLock(t,e,r){if(e)throw new l(u.MISC_ERROR,"wallet.lock [passphrase]");let[i]=await this.accessControl(r);if(!i.master.encrypted){if((e=new y([t]).str(0,"")).length<1)throw new l(u.MISC_ERROR,"Wallet is not encrypted, please run wallet.lock passphrase");try{await i.setPassphrase(null,e)}catch(t){throw new l(u.WALLET_ENCRYPTION_FAILED,"Encryption failed.")}}return await i.lock(),null}async listMSTrans(t,e,r){if(e)throw new l(u.MISC_ERROR,"tx.mstrans");return e=new y([t]).str(0,""),this.wdb.listMSTrans(e)}async signMSTrans(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"tx.mstrans.sign txid");const i=new y([t]);e=i.str(0,""),t=i.str(1,"");let[s,n]=await this.accessControl(r,i.str(2,"")),c=await this.wdb.db.get(a.ms(S.getHash(e,"hex"),t));if(!c)throw new l(u.MISC_ERROR,"tx.mstrans.sign txid");if(r=JSON.parse(c.toString()),!await s.belongToAccount(n,r.addr))throw new l(u.MISC_ERROR,"tx.mstrans.sign invalid account");let h=await this.wdb.get(r.addr);if(h&&h.account.type==o.types.MULTISIG){const e=A.fromRaw(r.data,"hex");e.view=await h.getCoinView(e),await h.sign(e),e.isSigned()?await h.sendMTX(e):await s.send({subtractFee:!1,sort:!1,outputs:[{address:r.contract,value:1e4}],comment:JSON.stringify({oper:"scrun",params:{oper:"sign",addr:r.addr,tx:e.toRaw().toString("hex")}})},n),await this.wdb.delMSTrans(r.addr,t)}}async resendWalletTransactions(t,e,r){if(e||0!==t.length)throw new l(u.MISC_ERROR,"tx.resend.admin");let[i]=await this.accessControl(r);const s=[];for(const t of await i.resend())s.push(t.txid());return s}async resend(t,e,r){if(e||0!==t.length)throw new l(u.MISC_ERROR,"tx.resendall.admin: 重发挂起交易");var i=await this.wdb.resend();if(i)for(var s of Object.keys(i))if(s)for(const t of i[s])await this.wdb.send(t);return!0}async rescan(t,e,r){if(e)throw new l(u.MISC_ERROR,'sys.rescan ( "height" )');return e=new y([t]).u32(0),await this.wdb.rescan(e),this.logger.info("Rescanning..."),!0}async createAddress(t,e,r){if(e||2<t.length)throw new l(u.MISC_ERROR,'address.create ( "account" "uid" )');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));e=i.u32(1,0);const a=await s.createReceive(n,e);return a?a.toJSON():null}async calcAddress(t,e,r){if(e||t.length<3)throw new l(u.MISC_ERROR,"address.calc account(must be typeof number) branch index");const s=new y([t]);let[n,a]=await this.accessControl(r,s.int(0,0));e=s.u32(1,0),t=s.u32(2,0),"default"==a&&(a=0);r=(await n.deriveKey(a,e,t,n.master)).toJSON();const o=await n.deriveKey(a,e,t);return e=o?o.toJSON():null,i(r.address==e.address,"address derived from prv not equals which derived from pub."),e}async createAddressAdmin(t,e,r){if(e||1<t.length)throw new l(u.MISC_ERROR,'address.create.admin ( "account" )');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));const a=await s.createReceive(n,0,s.master);return a?a.toJSON(!0):null}async createChange(t,e,r){if(e||1<t.length)throw new l(u.MISC_ERROR,'address.change.create ( "account" )');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));const a=await s.createChange(n);return a?a.toJSON():null}async createNested(t,e,r){if(e||1<t.length)throw new l(u.MISC_ERROR,'address.nested.create ( "account" )');const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));const a=await s.createNested(n);return a?a.toJSON():null}async mkwallet(t,e,r){const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));const a=await s.createReceive(n),o=await this.wdb.ensure({id:a.getAddress("string"),type:i.str(1),m:i.u32(2),n:i.u32(3),mnemonic:i.str(4),passphrase:i.str(5),master:i.str(6),witness:i.bool(7),watchOnly:i.bool(8),accountKey:i.str(9)});return o?o.toJSON(!1):null}async accountGet(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"account.get account: 查询账户");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));const a=await s.getAccount(n);return a?a.toJSON():null}async getPending(t,e,r){if(e)throw new l(u.MISC_ERROR,"tx.pending [account]: 查询挂起的交易");const i=new y([t]);let[s,a]=await this.accessControl(r,i.str(0,""));e=await s.getPending(a),n.sortTX(e);const o=[];for(const t of await s.toDetails(e))o.push(t.toJSON());return o}async getPendingItem(t,e,r){const i=new y([t]);var s,n=i.hash(0,"");let[a,o]=await this.accessControl(r,i.str(1,""));for(s of await a.getPending(o))if(s.hash==n)return(s=await a.toDetails(s)).toJSON()}async getPendingHash(t,e,r){const i=new y([t]);let[s,a]=await this.accessControl(r,i.str(0,""));t=await s.getPending(a),n.sortTX(t);const o=[];for(const e of await s.toDetails(t))o.push(f.revHex(e.hash));return o}async getPendingCount(t,e,r){if(e)throw new l(u.MISC_ERROR,"tx.pending.count [account]: 查询挂起的交易数");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));return e=await s.ensureIndex(n),(await s.txdb.getPendingHashes(e)).length}async accountCreate(t,e,r){const i=new y([t]);let[s]=await this.accessControl(r);t=i.obj(0),r=i.str(1);const n=new y([t]);t={name:n.str("name"),witness:n.bool("witness",!0),type:n.str("type","pubkeyhash"),m:n.u32("m",1),n:n.u32("n",1),watchOnly:n.bool("watch",!1),accountKey:n.str("key",null),lookahead:n.u32("lookahead",10)};try{let e=await s.getAccount(t.name);if(e)return e.toJSON();{let i=(e=await s.createAccount(t,r)).toJSON();return i.isNew=!0,i}}catch(e){return null}}async getblocks(t,e,r){if(e)throw new l(u.MISC_ERROR,"wallet.blocks");let[i]=await this.accessControl(r);return await i.getBlocks()}async getKey(t,e,r){if(e||1!==t.length)throw new l(u.MISC_ERROR,"key.export.public address: 查询地址的密钥");const s=new y([t]);let[n]=await this.accessControl(r);e=s.str(0),i(e,"Address is required.");const a=await n.getKey(e);return a?a.toJSON():null}async getPrivKey(t,e,r){if(e||1!==t.length)throw new l(u.MISC_ERROR,"address.key.admin address: 查询地址的密钥");const s=new y([t]);let[n]=await this.accessControl(r);e=s.str(0),i(e,"Address is required.");const a=await n.getKey(e);return a?a.toJSON(!0):null}async getwif(t,e,r){if(e||1!=t.length)throw new l(u.MISC_ERROR,"address.wif.admin address: 查询地址对应的私钥 地址");const s=new y([t]);let[n]=await this.accessControl(r);e=s.str(0),t=s.str(1),i(e,"Address is required.");const a=await n.getPrivateKey(e,t);return a?a.toSecret():null}async hasAddress(t,e,r){if(e||1!=t.length)throw new l(u.MISC_ERROR,"address.has address: 查询钱包是否包含一个地址 地址");const s=new y([t]);let[n]=await this.accessControl(r);return e=s.str(0),i(e,"Address is required."),(t=await n.hasAddress(e))||!1}async getCoin(t,e,r){const s=new y([t]);let[n]=await this.accessControl(r);t=s.hash(0),r=s.u32(1),i(t,"Hash is required."),i(null!=r,"Index is required.");const a=await n.getCoin(t,r);return a?a.getJSON(this.network):null}async getSpender(t,e,r){const s=new y([t]);let[n]=await this.accessControl(r);return t=s.hash(0),r=s.u32(1),i(t,"Hash is required."),i(null!=r,"Index is required."),(t=await n.txdb.getSpender(t,r))?{hash:f.revHex(t.hash),index:t.index}:null}async getCoincacheSize(t,e,r){var[r]=await this.accessControl(r);return r.txdb.coinCache.size}async conserveCoin(t,e,r){if(e||2!=t.length)throw new l(u.MISC_ERROR,"coin.conserved.add txhash index: 新增需要保持的硬币: 交易Hash 输出序号");const s=new y([t]);let[n]=await this.accessControl(r);return e=s.hash(0),t=s.u32(1),i(e,"Hash is required."),i(null!=t,"Index is required."),r=new R(e,t),n.conserveCoin(r),!0}async getConservedCoins(t,e,r){if(e||0<t.length)throw new l(u.MISC_ERROR,"coin.conserved.get: 查询已经保持的Coin列表");let[i]=await this.accessControl(r);const s=[];for(const t of i.getConserved())s.push(t.toJSON());return s}async unConserveCoin(t,e,r){if(e||2!=t.length)throw new l(u.MISC_ERROR,"coin.conserved.del: 减少需要保持的硬币: 交易Hash 输出序号");const s=new y([t]);let[n]=await this.accessControl(r);return e=s.hash(0),t=s.u32(1),i(e,"Hash is required."),i(null!=t,"Index is required."),r=new R(e,t),n.unConserveCoin(r),!0}async addShared(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"key.shared.add [account] key: 新增共享公钥 [账号] 公钥");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));return e=i.str(1),await s.addSharedKey(n,e),!0}async removeShared(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"key.shared.del [account] key: 删除共享公钥 [账号] 公钥");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));return e=i.str(1),await s.removeSharedKey(n,e),!0}async zap(t,e,r){if(e)throw new l(u.MISC_ERROR,"sys.zap [age]: 移除挂起交易 挂起时长(默认三天)");const s=new y([t]);let[n]=await this.accessControl(r);return e=s.str(0),t=s.u32(1,259200),i(t,"Age is required."),await n.zap(e,t),!0}async sendOracle(t,e,r){if(e||t.length<3||4<t.length)throw new l(u.MISC_ERROR,"oracle.send k v amount [openid]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(3,""));if(e=i.str(0,null),t=i.str(1,null),null==(r=i.u64(2)))throw new l(u.TYPE_ERROR,"Invalid parameter.");if(!e||!t)throw new l(u.MISC_ERROR,"oracle.send k v amount [openid]");r={subtractFee:!1,selection:"age",sort:!1,outputs:[{address:(await s.createReceive(n)).getAddress("string"),value:r}],comment:JSON.stringify({oper:P.vote,type:"oracle",k:e,v:t})};const a=await s.send(r,n);return(await s.getDetails(a.hash("hex"))).toJSON()}async sendVote(t,e,r){if(e||t.length<2||3<t.length)throw new l(u.MISC_ERROR,"vote.send addresses amount [openid]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));const a=i.str(0);var o;if(null==(e=i.u64(1)))throw new l(u.TYPE_ERROR,"Invalid parameter.");for(o of a.split(","))if(!c.parseAddress(o,this.network))throw new l(u.TYPE_ERROR,"Invalid address.");t={subtractFee:!1,selection:"age",sort:!1,outputs:[{address:(await s.createReceive(n)).getAddress("string"),value:e}],comment:`{"oper": "${P.vote}", "type": "mine", "ca": "${a}"}`};const h=await s.send(t,n);return(await s.getDetails(h.hash("hex"))).toJSON()}async sendVoteAsync(t,e,r){if(e||t.length<2||3<t.length)throw new l(u.MISC_ERROR,"vote.send.async addresses amount [openid]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));const a=i.str(0);var o;if(null==(e=i.u64(1)))throw new l(u.TYPE_ERROR,"Invalid parameter.");for(o of a.split(","))if(!c.parseAddress(o,this.network))throw new l(u.TYPE_ERROR,"Invalid address.");t={subtractFee:!1,selection:"age",sort:!1,outputs:[{address:(await s.createReceive(n)).getAddress("string"),value:e}],comment:`{"oper": "${P.vote}", "type": "mine", "ca": "${a}"}`},s.send(t,n)}async sendTX(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,"tx.send addr amount [openid]:发送交易 地址 金额 [发起账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));e=i.str(0),t=i.u64(1);const a=await s.send({outputs:[{address:e,value:t}]},n);return(await s.getDetails(a.hash("hex"))).toJSON()}async sendTXAsync(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,"tx.send.async addr amount [openid]:发送交易 地址 金额 [发起账户]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));e=i.str(0),t=i.u64(1),s.send({outputs:[{address:e,value:t}]},n)}async signTX(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"tx.sign.admin txdata [sendnow passphrase]: 对交易签名/发送 交易原始数据 [立即发送 解锁密码]");const s=new y([t]);let[n]=await this.accessControl(r);e=s.buf(0),i(e,"TX is required."),t=s.bool(1,!1),r=s.str(2);const a=A.fromRaw(e);a.view=await n.getCoinView(a),await n.sign(a,r);let c=null;if(t&&a.isSigned()){c=(await n.sendMTX(a)).getJSON(this.network)}else c=a.getJSON(this.network);return n.account.type==o.types.MULTISIG&&(e=a.getMultisig(this.network),c.ms={m:e.m,n:e.n,c:e.c}),c}async createTX(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,"tx.create options outputs [openid]: 创建交易 参数对象 输出数组 [子账号]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(2,""));if(e=i.obj(0),t=i.array(1),Array.isArray(e.in))for(var a of e.in)a.hash=f.revHex(a.hash);const c=new y([e]),h={comment:c.obj("comment",null),sendnow:c.bool("sendnow",!0),account:c.str("account"),rate:c.u64("rate"),blocks:c.u32("blocks"),maxFee:c.u64("maxFee"),selection:c.str("selection"),smart:c.bool("smart"),subtractFee:c.bool("subtractFee"),subtractIndex:c.get("subtractIndex"),depth:c.u32(["confirmations","depth"]),inputs:c.array("in",null),outputs:[]};for(const e of t){const t=new y([e]);let r={value:t.u64("value")};if(r.address=t.str("address"),!r.address)if(p=t.str("account")){await s.ensureAccount({name:p,witness:!0});const t=await s.createReceive(p);if(!t)throw new l(u.MISC_ERROR,`tx.create: account ${p} not exist`);r.address=t.getAddress("string")}var p,d=((p=t.buf("script"))&&(r.script=b.fromRaw(p)),t.str("locktype"));if(d){var m=t.u64("locktime",0);if(m){if("no"!=d&&"clb"!=d&&"clt"!=d&&"csb"!=d&&"cst"!=d)throw new l(u.MISC_ERROR,'locktype should be "no"-不锁定 or "clb"-绝对高度锁定 or clt(绝对时间锁定) or "csb"-相对高度锁定 or "cst"-相对时间锁定 !');if(d==b.outputLockType.CHECKABSOLUTETIME&&m<=w.LOCKTIME_THRESHOLD)throw new l(u.MISC_ERROR,"lock absolute time should not less than 500000000!");if(d==b.outputLockType.CHECKABSOLUTEBLOCK&&m>w.LOCKTIME_THRESHOLD)throw new l(u.MISC_ERROR,"lock absolute block should not more than 500000000!");if((d==b.outputLockType.CHECKRELATIVEBLOCK||d==b.outputLockType.CHECKRELATIVETIME)&&65535<m)throw new l(u.MISC_ERROR,"lock relative block/time should not more than 65535!");r.locktype=d,r.locktime=m}}h.outputs.push(r)}n&&(h.account=n);let g=null;if(h.sendnow){const t=await s.send(h);g=(await s.getDetails(t.hash("hex"))).toJSON()}else{const t=await s.createTX(h);await s.sign(t),g=t.getJSON(this.network),s.account.type==o.types.MULTISIG&&(r=t.getMultisig(this.network),g.ms={m:r.m,n:r.n,c:r.c})}return g}async getLast(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"tx.last account [limit]: 最近的交易 账号 [最大记录数]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0));e=i.u32(1);const a=[];t=await s.getLast(n,e);for(const e of await s.toDetails(t))a.push(e.toJSON());return a}async getRange(t,e,r){if(e||t.length<4)throw new l(u.MISC_ERROR,"tx.range account start end limit [reserve]: 指定时限内的交易 账号 开始时间 结束时间 最大记录数 [反转]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(0,""));e={start:i.u32(1),end:i.u32(2),limit:i.u32(3),reverse:i.bool(4)},t=await s.getRange(n,e);const a=[];for(const e of await s.toDetails(t))a.push(e.toJSON());return a}async caUserStatus(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,"ca.user.status cid uid (query)");const i=new y([t]);e=i.str(0,""),t=i.uint(1,0);const s=i.array(2,[]);let n=null;for(let t=0;t<s.length;t++){var a=s[t];a&&Array.isArray(a)?"alliancename"==a[0]&&(n=a[1],delete s[t]):delete s[t]}let[o]=await this.accessControl(r);return e=await this.$allianceUserCreate([e,t,n],r),s.push(["pubkey",e.data.pubkey]),s.push(["merge",!0]),o.db.client.execute("ca.list",[s])}async caUserLog(t,e,r){if(e||t.length<2)throw new l(u.MISC_ERROR,"ca.user.log cid uid (query)");const i=new y([t]);e=i.str(0,""),t=i.uint(1,0);const s=i.array(2,[]);let n=null;for(let t=0;t<s.length;t++){var a=s[t];a&&Array.isArray(a)?"alliancename"==a[0]&&(n=a[1],delete s[t]):delete s[t]}let[o]=await this.accessControl(r,e);return e=await this.$allianceUserCreate([e,t,n],r),s.push(["pubkey",e.data.pubkey]),o.db.client.execute("ca.list",[s])}async sysLog(t,e,r){if(e)throw new l(u.MISC_ERROR,"sys.log (query openid)");const i=new y([t]);var s;e=i.array(0,[]);let[n]=await this.accessControl(r,i.str(1,"")),a=[];for(s of(await this.wdb.auditList.query(e)).list){let t=Object.assign({},s);var o=c.parseHash(s.address,this.network);(o=await n.getPath(o))&&(t.account=o.name),t.time=new Date(1e3*s.time).toLocaleString(),a.push(t)}return a}async caIssuePublic(t,e,r){if(e||t.length<3||4<t.length)throw new l(u.MISC_ERROR,"ca.issue.public cert witness pubkey [openid]: 签发证书 证书对象 见证地址 存证地址公钥 [见证账户]");const i=new y([t]),s=i.obj(0,{});e=i.str(1,""),t=i.str(2);let[n,a]=await this.accessControl(r,i.str(3,""));if(await n.belongToAccount(a,e)){if(64!=s.hash.length)throw new l(u.TYPE_ERROR,"err hash length");s.height||(s.height=w.retargetInterval);const r=await n.getPrivateKey(e);if(r)return await n.issueCreate({erid:s.hash,key:r.privateKey.toString("hex"),address:r.getAddress().toString(),witness:r.publicKey.toString("hex"),validHeight:this.wdb.curHeight+s.height,source:{subjectName:s.name,pubkey:t,subjectHash:s.hash,cluster:s.cluster}},a)}throw new l(u.TYPE_ERROR,"Invalid witness.")}async caAbolishPublic(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"ca.abolish.public array[[witness erid height [openid]]]: 废止授信交易 废止交易信息数组");let i=[];const s=new y([t]);var n;for(n of s.array(0,[])){var a=n[0],o=n[1],c=parseInt(n[2]);let[t,e]=await this.accessControl(r,n[3]);if(!await t.belongToAccount(e,a))throw new l(u.TYPE_ERROR,"Invalid witness.");const s=await t.getKey(a);if(!s)throw new l(u.TYPE_ERROR,"Invalid witness.");(a=await t.caAbolish({key:s.privateKey.toString("hex"),witness:s.publicKey.toString("hex"),address:a,erid:o,abolishHeight:c,cid:"",uid:0},e))&&i.push(a)}return i}async caIssue(t,e,r){if(e||t.length<3||4<t.length)throw new l(u.MISC_ERROR,"ca.issue cert uid cid [openid]: 签发证书 证书对象 见证人 见证人归属单位 [消费账户]");return this.$caIssue(t,r,!1)}async caIssueAsync(t,e,r){if(e||t.length<3||4<t.length)throw new l(u.MISC_ERROR,"ca.issue.async cert uid cid [openid]: 签发证书 证书对象 见证人 见证人归属单位 [消费账户]");return this.$caIssue(t,r,!0)}async $caIssue(t,e,r){const i=new y([t]),s=i.obj(0,{});t=i.uint(1,0);var n=i.str(2,"");let[a,o]=await this.accessControl(e,i.str(3,""));var c=await a.ensureCp(n);if(!c||"forbidden"==c.cls)throw new l(u.MISC_ERROR,"Invalid Account");if(64!=s.hash.length)throw new l(u.TYPE_ERROR,"err hash length");c=await this.$allianceUserCreate([n,t],e);let h=[];if(h.push(["pubkey",c.data.pubkey]),h.push(["source.subjectHash",s.hash]),0<(await a.db.client.execute("ca.list",[h])).count)throw new l(u.TYPE_ERROR,"cert.hash conflicted");if(this.wdb.$parent&&await this.wdb.$parent.chain.db.erList.getEr(s.hash))throw new l(u.TYPE_ERROR,"cert.hash conflicted");return s.height||(s.height=w.retargetInterval),c=await this.$allianceUserCreate([n,t],e,!0),await a.issueCreate({erid:s.hash,key:c.prvkey,witness:c.data.pubkey,address:c.data.addr,validHeight:this.wdb.curHeight+s.height,source:{subjectName:s.name,pubkey:c.data.pubkey,subjectHash:s.hash,cluster:s.cluster,cid:n,uid:t}},o,r)}async caAbolish(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"ca.abolish [[uid cid erid height [openid]]]: 废止授信交易 废止交易信息数组");return this.$caAbolish(t,r,!1)}async caAbolishAsync(t,e,r){if(e||t.length<1)throw new l(u.MISC_ERROR,"ca.abolish.async [[uid cid erid height [openid]]]: 废止授信交易 废止交易信息数组");return this.$caAbolish(t,r,!0)}async $caAbolish(t,e,r){let i=[];const s=new y([t]);var n;for(n of s.array(0,[])){var a=n[0],o=n[1],c=n[2],u=parseInt(n[3]);let[t,s]=await this.accessControl(e,n[4]);var h=await this.$allianceUserCreate([o,a],e,!0);(o=await t.caAbolish({cid:o,uid:a,key:h.prvkey,witness:h.data.pubkey,address:h.data.addr,erid:c,abolishHeight:u},s,r))&&i.push(o)}return i}async enchanceCp(t,e,r){if(e||t.length<2||4<t.length)throw new l(u.MISC_ERROR,"ca.enchance toCid fromCid height [openid]");const i=new y([t]);let[s,n]=await this.accessControl(r,i.str(3));e=i.str(0,0),t=i.str(1,0);let a=i.uint(2,0);(!a||a<this.wdb.curHeight)&&(a=this.wdb.curHeight+w.retargetInterval);var[r,e]=await s.enchanceCp({to:e,from:t,enchanceHeight:a},n);return r&&e?e:null}async queryMyErlist(t,e,r){if(e)throw new l(u.MISC_ERROR,"ca.list.me query: 条件查询自己的电子权利 条件数组");return e=new y([t]).array(0,[]),this.wdb.erList.query(e)}}},function(t,e,r){var i=r(28);const{ContractEnvType:s,ContractStatus:n}=r(5),a=r(6),o=r(110);t.exports=class extends i{constructor(t){super(),this.db=t}async loadHistory(){var t;for(t of await this.db.getContracts())t&&(t.period<this.db.curHeight&&t.transStatus==n.CreatedOnMem?await this.delTransContract(t,!0):(t.id=t.type+"."+t.addr,await this.saveContract(t),t.transStatus==n.Promised&&this.db.autoTaskMgr.addTask(new o(this.db.network.txcheckpoint,t),this.db.network.txchecktime[t.type])))}query(t,e){return(t=this.get(t+"."+e))?t.transStatus:n.None}async addTransContract(t,e,r=!1){e.id=e.type+"."+e.addr;var i=this.get(e.id);t===s.Mempool&&((e=i||e).transStatus||(e.transStatus=n.CreatedOnMem),await this.saveContract(e,r))}async saveContract(t,e=!1){t.id=t.id||t.type+"."+t.addr,this.set(t.id,t),e&&(e=a.hash256(Buffer.from(t.id)).toString("hex"),await this.db.batchPut(this.db.tidCreator(e),Buffer.from(JSON.stringify(t))))}async promiseContract(t,e=!1){let r=!1;var i=t.type+"."+t.addr;let s=this.get(i);return s&&s.oper==t.oper||(r=!0,s=t),(!s.transStatus||s.transStatus<n.Promised)&&(r=!0,s.transStatus=n.Promised),r&&await this.saveContract(s,e),r}async confirmContract(t,e,r){t=t.type+"."+t.addr;let i=this.get(t);!i||i.transStatus!=n.Promised||e!=n.Confirmed&&e!=n.Expired||(i.transStatus=e,await this.saveContract(i,r))}async delTransContract(t,e){var r=t.type+"."+t.addr,i=this.get(r);i&&i.oper==t.oper&&(this.delete(r),e&&(i=a.hash256(Buffer.from(r)).toString("hex"),await this.db.batchDel(this.db.tidCreator(i))))}}},function(t,e,r){const i=r(5).HtlcStatus;r=r(28);class s extends r{constructor(t){super(),this.db=t}async loadHistory(){var t,e;for(t of(this.clear(),await this.db.loadHtlcList()))this.set(t.id,t),t.wid&&t.account&&(e=t.wid+"."+t.account,this.account.get(e)||this.account.set(e,new Map),this.account.get(e).set(t.id,t))}setAccount(t,e,r){this.delAccount(t),e&&r&&(t.wid=e,t.account=r,e=t.wid+"."+t.account,this.account.get(e)||this.account.set(e,new Map),this.account.get(e).set(t.id,t))}delAccount(t){var e;t&&t.wid&&t.account&&(e=t.wid+"."+t.account,this.account.get(e)&&this.account.get(e).delete(t.id))}}s.vpItem=class t{constructor(t){this.fromOptions(t||{})}fromOptions(t){this.shash=t.shash,this.sidx=t.sidx,this.sheight=t.sheight,this.ahash=t.ahash,this.aidx=t.aidx,this.aheight=t.aheight,this.src=t.src,this.dst=t.dst,this.aa=t.aa,this.ab=t.ab,this.ba=t.ba,this.bb=t.bb,this.amount=t.amount,this.rate=t.rate,this.pst=t.pst}toRaw(){let t={};return t.shash=this.shash,t.sidx=this.sidx,t.sheight=this.sheight,t.ahash=this.ahash,t.aidx=this.aidx,t.aheight=this.aheight,t.src=this.src,t.dst=this.dst,t.amount=this.amount,t.rate=this.rate,t.pst=this.pst||i.Init,t.aa=this.aa||"",t.ab=this.ab||"",t.ba=this.ba||"",t.bb=this.bb||"",Buffer.from(JSON.stringify(t),"utf-8")}get id(){return""+this.shash+this.sidx}fromRaw(t){return t=JSON.parse(t.toString("utf8")),this.fromOptions(t),this}static fromRaw(e){return(new t).fromRaw(e)}},t.exports=s},,,,,,,,,,,,,,,function(t,e,r){"use strict";
874
874
  /*!
875
875
  * int64.js - int64 object for javascript.
876
876
  * Copyright (c) 2017, Christopher Jeffrey (MIT License).
@@ -1107,7 +1107,7 @@ t.exports=r(487)},function(t){t.exports=JSON.parse('{"application/1d-interleaved
1107
1107
  /*!
1108
1108
  * WalletOptions.js
1109
1109
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
1110
- */const i=r(0),s=r(39),n=r(1),a=r(15),o=r(79),c=r(96).walletdb;t.exports=class t{constructor(t){this.network=a.primary,this.logger=o.global,this.workers=null,this.client=null,this.feeRate=0,this.prefix=null,this.location=null,this.db="memory",this.maxFiles=64,this.cacheSize=16<<20,this.compression=!0,this.bufferKeys=c.binary,this.spv=!1,this.nodeType="",this.witness=!1,this.checkpoints=!1,this.startHeight=0,this.wipeNoReally=!1,this.apiKey=null,this.devMode=!1,this.acl=null,this.ssl=!1,this.host="127.0.0.1",this.listen=!1,t&&this.fromOptions(t)}fromOptions(t){if(null!=t.network&&(this.network=a.get(t.network),this.port=this.network.httpPort+2),null!=t.logger&&(i("object"==typeof t.logger),this.logger=t.logger),null!=t.coinCache&&(i("number"==typeof t.coinCache),i(0<=t.coinCache),this.coinCache=t.coinCache),null!=t.workers&&(i("object"==typeof t.workers),this.workers=t.workers),null!=t.client&&(i("object"==typeof t.client),this.client=t.client),null!=t.jsonp&&(i("object"==typeof t.jsonp),this.jsonp=t.jsonp),null!=t.feeRate&&(i(n.isU64(t.feeRate)),this.feeRate=t.feeRate),null!=t.prefix)switch(i("string"==typeof t.prefix),this.prefix=t.prefix,t.nodeType){case"wallet":this.location=s.join(this.prefix,"wallet"+(t.eid||"walletdb"));break;case"spv":this.location=s.join(this.prefix,"spv"+(t.eid||"walletdb"));break;default:this.location=s.join(this.prefix,t.eid||"walletdb")}return null!=t.location&&(i("string"==typeof t.location),this.location=t.location),null!=t.db&&(i("string"==typeof t.db),this.db=t.db),null!=t.maxFiles&&(i(n.isU32(t.maxFiles)),this.maxFiles=t.maxFiles),null!=t.cacheSize&&(i(n.isU64(t.cacheSize)),this.cacheSize=t.cacheSize),null!=t.compression&&(i("boolean"==typeof t.compression),this.compression=t.compression),null!=t.spv&&(i("boolean"==typeof t.spv),this.spv=t.spv),null!=t.nodeType&&(i("string"==typeof t.nodeType),this.nodeType=t.nodeType),null!=t.checkpoints&&(i("boolean"==typeof t.checkpoints),this.checkpoints=t.checkpoints),null!=t.startHeight&&(i("number"==typeof t.startHeight),i(0<=t.startHeight),this.startHeight=t.startHeight),null!=t.wipeNoReally&&(i("boolean"==typeof t.wipeNoReally),this.wipeNoReally=t.wipeNoReally),null!=t.apiKey&&(i("string"==typeof t.apiKey),this.apiKey=t.apiKey),this.devMode=t.devMode,null!=t.acl&&(i("object"==typeof t.acl),this.acl=t.acl),this.acl=this.acl||{},null!=t.ssl&&(i("boolean"==typeof t.ssl),this.ssl=t.ssl),null!=t.host&&(i("string"==typeof t.host),this.host=t.host),null!=t.port?(i("number"==typeof t.port),this.port=t.port+2):this.port=this.network.httpPort+2,null!=t.listen&&(i("boolean"==typeof t.listen),this.listen=t.listen),this}static fromOptions(e){return(new t).fromOptions(e)}}},function(t,e,r){let i=r(1).waiting;t.exports=class{constructor(t){this.rev=t,this.now=Date.parse(new Date)}check(){return Date.parse(new Date)-this.now>=this.rev&&(this.now=Date.parse(new Date),!0)}tick(t,e){let r=0,s=async()=>{if(this.check()){try{e(r++)}catch(t){console.log(t)}(0==t||r<t)&&s()}else await i(100),s()};s()}}},function(t,e,r){"use strict";const i=r(28),s=r(1),n=r(3),a=r(69),o=r(4),c=r(2);r(20);const u=r(12);r(122);const h=0,l=1,p=9;class d{constructor(t){t&&(this.contact=t.parent,this.address=t.messenger,this.wallet=t.wallet,this.account=t.account,this.status=t.status||h,this.privateKey=t.privateKey||i.generatePrivateKey(),this.publicKey=i.publicKeyCreate(this.privateKey,!0))}getSize(){return 0+n.sizeVarString(this.address,"utf8")+4+n.sizeVarString(this.account,"utf8")+4+n.sizeVarString(this.privateKey.toString("hex"),"ascii")}toWriter(t){return t.writeVarString(this.address,"utf8"),t.writeU32(this.wallet.wid),t.writeVarString(this.account,"utf8"),t.writeU32(this.status),t.writeVarString(this.privateKey.toString("hex"),"ascii"),t}fromReader(t,e){return this.address=t.readVarString("utf8"),this.wid=t.readU32(),this.account=t.readVarString("utf8"),this.status=t.readU32(),this.privateKey=Buffer.from(t.readVarString("ascii"),"hex"),this.publicKey=i.publicKeyCreate(this.privateKey,!0),this}static fromReader(t,e){return(new d).fromReader(t,e)}async save(){this.wallet&&await this.wallet.db.saveContact(this.contact)}encrypt(t){return this.calcSecret(),s.encrypt(this.aeskey,this.aesiv,Buffer.from(t).toString("hex"))}async send(t){let e={src:this.address,dst:this.contact.address,content:{type:"secret"},account:this.account};return t&&this.status==p?(e.content.packet=this.encrypt(t),this.wallet&&await this.wallet.commNotify(e)):(e.content.init=this.publicKey.toString("hex"),this.contact.publicKey?(this.status=p,t&&(e.content.packet=this.encrypt(t))):this.status=l,this.wallet&&(await this.save(),await this.wallet.commNotify(e))),{contact:this.address,messenger:this.contact.address,init:this.publicKey,packet:e.content.packet}}async answer(t){if(t.contact==this.contact.address&&t.messenger==this.address)switch(this.status){case h:return t.init?(this.calcSecret(t.init),await this.save(),t.packet&&this.read(t.packet),this.wallet&&await this.wallet.commNotify({src:this.address,dst:this.contact.address,content:{type:"secret",init:this.publicKey.toString("hex")},account:this.account}),{contact:this.address,messenger:this.contact.address,init:this.publicKey}):void 0;case l:t.init&&(this.calcSecret(t.init),await this.save(),t.packet&&this.read(t.packet));break;case p:t.init&&(this.calcSecret(t.init),await this.save()),t.packet&&this.read(t.packet)}}calcSecret(t){if(t&&(this.contact.publicKey=t,this.aeskey=null,this.aesiv=null),!this.aeskey||!this.aesiv){let r=i.ecdh(this.contact.publicKey,this.privateKey);var{aeskey:t,aesiv:e}=a.getAes(r.toString(),this.contact.network);this.aeskey=t,this.aesiv=e,this.status=p}}read(t){return this.calcSecret(),t=Buffer.from(s.decrypt(this.aeskey,this.aesiv,t),"hex").toString(),this.wallet&&this.wallet.db.emit("notify.secret",{from:this.contact.address,to:this.address,content:t}),t}}t.exports=class t{constructor(t){t&&(this.address=t.contact,this.network=t.network,this.publicKey=null,t.publicKey&&(Buffer.isBuffer(t.publicKey)?this.publicKey=t.publicKey:"string"==typeof t.publicKey&&(this.publicKey=Buffer.from(t.publicKey))),t.messenger&&this.ensureMessenger(t))}getAddress(){return u.fromString(this.address,this.network).getHash("hex")}ensureMessenger(t){return this.sender||((t.parent=this).sender=new d(t)),this.sender}encrypt(t){return this.sender?{payload:this.sender.encrypt(t),status:this.sender.status}:{}}async send(t){if(this.sender)return this.sender.send(t)}async answer(t){return this.ensureMessenger(t).answer(t)}read(t,e){return this.ensureMessenger({messenger:t}).read(e)}getSize(){let t=0;return t+=n.sizeVarString(this.address,"utf8"),this.publicKey?t+=n.sizeVarString(this.publicKey.toString("hex"),"ascii"):t+=n.sizeVarString("","ascii"),t+this.sender.getSize()}toRaw(){var t=this.getSize();let e=new o(t);return this.toWriter(e),this.sender.toWriter(e),e.render()}toWriter(t){return t.writeVarString(this.address,"utf8"),this.publicKey?t.writeVarString(this.publicKey.toString("hex"),"ascii"):t.writeVarString("","ascii"),t}fromReader(t){return this.address=t.readVarString("utf8"),t=t.readVarString("ascii"),this.publicKey=t?Buffer.from(t,"hex"):null,this}fromRaw(t,e){return this.network=e.network.type,t=new c(t),this.fromReader(t),this.sender=d.fromReader(t,e),this.sender.contact=this}static fromRaw(e,r){return(new t).fromRaw(e,r)}}},function(t,e,r){r=r(29);class i extends r{constructor(t){super(),this.db=t}async loadHistory(){var t,e;for(t of(this.clear(),await this.db.loadCommentList()))this.set(t.id,t),t.wid&&(e=t.wid+"."+t.account,this.account.get(e)||this.account.set(e,new Map),this.account.get(e).set(t.id,t))}setAccount(t,e,r){this.delAccount(t),e&&r&&(t.wid=e,t.account=r,e=t.wid+"."+t.account,this.account.get(e)||this.account.set(e,new Map),this.account.get(e).set(t.id,t))}delAccount(t){var e;t&&t.wid&&t.account&&(e=t.wid+"."+t.account,this.account.get(e)&&this.account.get(e).delete(t.id))}}i.vpItem=class t{constructor(t){this.fromOptions(t||{})}fromOptions(t){this.shash=t.shash,this.sidx=t.sidx,this.bob=t.bob,this.body=t.body,this.wid=t.wid||0,this.account=t.account||""}toRaw(){let t={};return t.shash=this.shash,t.sidx=this.sidx,t.bob=this.bob||"",t.body=this.body||"",t.wid=this.wid,t.account=this.account,Buffer.from(JSON.stringify(t),"utf-8")}get id(){return""+this.shash+this.sidx}fromRaw(t){return t=JSON.parse(t.toString("utf8")),this.fromOptions(t),this}static fromRaw(e){return(new t).fromRaw(e)}},t.exports=i},function(t,e,r){const i=r(0);var s=r(29);const n=r(267);t.exports=class extends s{constructor(t){super(),this.env=t,this.pending=null}async loadHistory(){for(const t of this.env.wallets.values())await t.txdb.fillCoins()}batch(){return new n(this)}start(){i(!this.pending),this.pending=this.batch()}drop(){i(this.pending),this.pending=null}clear(){i(this.pending),this.pending.clear()}commit(){i(this.pending),this.pending.commit(),this.pending=null}push(t,e){i(this.pending),this.pending.set(t,e)}unpush(t){i(this.pending),this.pending.remove(t)}}},function(t,e,r){"use strict";
1110
+ */const i=r(0),s=r(39),n=r(1),a=r(15),o=r(79),c=r(96).walletdb;t.exports=class t{constructor(t){this.network=a.primary,this.logger=o.global,this.workers=null,this.client=null,this.feeRate=0,this.prefix=null,this.location=null,this.db="memory",this.maxFiles=64,this.cacheSize=16<<20,this.compression=!0,this.bufferKeys=c.binary,this.spv=!1,this.nodeType="",this.witness=!1,this.checkpoints=!1,this.startHeight=0,this.wipeNoReally=!1,this.apiKey=null,this.devMode=!1,this.acl=null,this.ssl=!1,this.host="127.0.0.1",this.listen=!1,t&&this.fromOptions(t)}fromOptions(t){if(null!=t.network&&(this.network=a.get(t.network),this.port=this.network.httpPort+2),null!=t.logger&&(i("object"==typeof t.logger),this.logger=t.logger),null!=t.coinCache&&(i("number"==typeof t.coinCache),i(0<=t.coinCache),this.coinCache=t.coinCache),null!=t.workers&&(i("object"==typeof t.workers),this.workers=t.workers),null!=t.client&&(i("object"==typeof t.client),this.client=t.client),null!=t.jsonp&&(i("object"==typeof t.jsonp),this.jsonp=t.jsonp),null!=t.feeRate&&(i(n.isU64(t.feeRate)),this.feeRate=t.feeRate),null!=t.prefix)switch(i("string"==typeof t.prefix),this.prefix=t.prefix,t.nodeType){case"wallet":this.location=s.join(this.prefix,"wallet"+(t.eid||"walletdb"));break;case"spv":this.location=s.join(this.prefix,"spv"+(t.eid||"walletdb"));break;default:this.location=s.join(this.prefix,t.eid||"walletdb")}return null!=t.location&&(i("string"==typeof t.location),this.location=t.location),null!=t.db&&(i("string"==typeof t.db),this.db=t.db),null!=t.maxFiles&&(i(n.isU32(t.maxFiles)),this.maxFiles=t.maxFiles),null!=t.cacheSize&&(i(n.isU64(t.cacheSize)),this.cacheSize=t.cacheSize),null!=t.compression&&(i("boolean"==typeof t.compression),this.compression=t.compression),null!=t.spv&&(i("boolean"==typeof t.spv),this.spv=t.spv),null!=t.nodeType&&(i("string"==typeof t.nodeType),this.nodeType=t.nodeType),null!=t.checkpoints&&(i("boolean"==typeof t.checkpoints),this.checkpoints=t.checkpoints),null!=t.startHeight&&(i("number"==typeof t.startHeight),i(0<=t.startHeight),this.startHeight=t.startHeight),null!=t.wipeNoReally&&(i("boolean"==typeof t.wipeNoReally),this.wipeNoReally=t.wipeNoReally),null!=t.apiKey&&(i("string"==typeof t.apiKey),this.apiKey=t.apiKey),this.devMode=t.devMode,null!=t.acl&&(i("object"==typeof t.acl),this.acl=t.acl),this.acl=this.acl||{},null!=t.ssl&&(i("boolean"==typeof t.ssl),this.ssl=t.ssl),null!=t.host&&(i("string"==typeof t.host),this.host=t.host),null!=t.port?(i("number"==typeof t.port),this.port=t.port+2):this.port=this.network.httpPort+2,null!=t.listen&&(i("boolean"==typeof t.listen),this.listen=t.listen),this}static fromOptions(e){return(new t).fromOptions(e)}}},function(t,e,r){let i=r(1).waiting;t.exports=class{constructor(t){this.rev=t,this.now=Date.parse(new Date)}check(){return Date.parse(new Date)-this.now>=this.rev&&(this.now=Date.parse(new Date),!0)}tick(t,e){let r=0,s=async()=>{if(this.check()){try{e(r++)}catch(t){console.log(t)}(0==t||r<t)&&s()}else await i(100),s()};s()}}},function(t,e,r){"use strict";const i=r(29),s=r(1),n=r(3),a=r(69),o=r(4),c=r(2);r(20);const u=r(12);r(122);const h=0,l=1,p=9;class d{constructor(t){t&&(this.contact=t.parent,this.address=t.messenger,this.wallet=t.wallet,this.account=t.account,this.status=t.status||h,this.privateKey=t.privateKey||i.generatePrivateKey(),this.publicKey=i.publicKeyCreate(this.privateKey,!0))}getSize(){return 0+n.sizeVarString(this.address,"utf8")+4+n.sizeVarString(this.account,"utf8")+4+n.sizeVarString(this.privateKey.toString("hex"),"ascii")}toWriter(t){return t.writeVarString(this.address,"utf8"),t.writeU32(this.wallet.wid),t.writeVarString(this.account,"utf8"),t.writeU32(this.status),t.writeVarString(this.privateKey.toString("hex"),"ascii"),t}fromReader(t,e){return this.address=t.readVarString("utf8"),this.wid=t.readU32(),this.account=t.readVarString("utf8"),this.status=t.readU32(),this.privateKey=Buffer.from(t.readVarString("ascii"),"hex"),this.publicKey=i.publicKeyCreate(this.privateKey,!0),this}static fromReader(t,e){return(new d).fromReader(t,e)}async save(){this.wallet&&await this.wallet.db.saveContact(this.contact)}encrypt(t){return this.calcSecret(),s.encrypt(this.aeskey,this.aesiv,Buffer.from(t).toString("hex"))}async send(t){let e={src:this.address,dst:this.contact.address,content:{type:"secret"},account:this.account};return t&&this.status==p?(e.content.packet=this.encrypt(t),this.wallet&&await this.wallet.commNotify(e)):(e.content.init=this.publicKey.toString("hex"),this.contact.publicKey?(this.status=p,t&&(e.content.packet=this.encrypt(t))):this.status=l,this.wallet&&(await this.save(),await this.wallet.commNotify(e))),{contact:this.address,messenger:this.contact.address,init:this.publicKey,packet:e.content.packet}}async answer(t){if(t.contact==this.contact.address&&t.messenger==this.address)switch(this.status){case h:return t.init?(this.calcSecret(t.init),await this.save(),t.packet&&this.read(t.packet),this.wallet&&await this.wallet.commNotify({src:this.address,dst:this.contact.address,content:{type:"secret",init:this.publicKey.toString("hex")},account:this.account}),{contact:this.address,messenger:this.contact.address,init:this.publicKey}):void 0;case l:t.init&&(this.calcSecret(t.init),await this.save(),t.packet&&this.read(t.packet));break;case p:t.init&&(this.calcSecret(t.init),await this.save()),t.packet&&this.read(t.packet)}}calcSecret(t){if(t&&(this.contact.publicKey=t,this.aeskey=null,this.aesiv=null),!this.aeskey||!this.aesiv){let r=i.ecdh(this.contact.publicKey,this.privateKey);var{aeskey:t,aesiv:e}=a.getAes(r.toString(),this.contact.network);this.aeskey=t,this.aesiv=e,this.status=p}}read(t){return this.calcSecret(),t=Buffer.from(s.decrypt(this.aeskey,this.aesiv,t),"hex").toString(),this.wallet&&this.wallet.db.emit("notify.secret",{from:this.contact.address,to:this.address,content:t}),t}}t.exports=class t{constructor(t){t&&(this.address=t.contact,this.network=t.network,this.publicKey=null,t.publicKey&&(Buffer.isBuffer(t.publicKey)?this.publicKey=t.publicKey:"string"==typeof t.publicKey&&(this.publicKey=Buffer.from(t.publicKey))),t.messenger&&this.ensureMessenger(t))}getAddress(){return u.fromString(this.address,this.network).getHash("hex")}ensureMessenger(t){return this.sender||((t.parent=this).sender=new d(t)),this.sender}encrypt(t){return this.sender?{payload:this.sender.encrypt(t),status:this.sender.status}:{}}async send(t){if(this.sender)return this.sender.send(t)}async answer(t){return this.ensureMessenger(t).answer(t)}read(t,e){return this.ensureMessenger({messenger:t}).read(e)}getSize(){let t=0;return t+=n.sizeVarString(this.address,"utf8"),this.publicKey?t+=n.sizeVarString(this.publicKey.toString("hex"),"ascii"):t+=n.sizeVarString("","ascii"),t+this.sender.getSize()}toRaw(){var t=this.getSize();let e=new o(t);return this.toWriter(e),this.sender.toWriter(e),e.render()}toWriter(t){return t.writeVarString(this.address,"utf8"),this.publicKey?t.writeVarString(this.publicKey.toString("hex"),"ascii"):t.writeVarString("","ascii"),t}fromReader(t){return this.address=t.readVarString("utf8"),t=t.readVarString("ascii"),this.publicKey=t?Buffer.from(t,"hex"):null,this}fromRaw(t,e){return this.network=e.network.type,t=new c(t),this.fromReader(t),this.sender=d.fromReader(t,e),this.sender.contact=this}static fromRaw(e,r){return(new t).fromRaw(e,r)}}},function(t,e,r){r=r(28);class i extends r{constructor(t){super(),this.db=t}async loadHistory(){var t,e;for(t of(this.clear(),await this.db.loadCommentList()))this.set(t.id,t),t.wid&&(e=t.wid+"."+t.account,this.account.get(e)||this.account.set(e,new Map),this.account.get(e).set(t.id,t))}setAccount(t,e,r){this.delAccount(t),e&&r&&(t.wid=e,t.account=r,e=t.wid+"."+t.account,this.account.get(e)||this.account.set(e,new Map),this.account.get(e).set(t.id,t))}delAccount(t){var e;t&&t.wid&&t.account&&(e=t.wid+"."+t.account,this.account.get(e)&&this.account.get(e).delete(t.id))}}i.vpItem=class t{constructor(t){this.fromOptions(t||{})}fromOptions(t){this.shash=t.shash,this.sidx=t.sidx,this.bob=t.bob,this.body=t.body,this.wid=t.wid||0,this.account=t.account||""}toRaw(){let t={};return t.shash=this.shash,t.sidx=this.sidx,t.bob=this.bob||"",t.body=this.body||"",t.wid=this.wid,t.account=this.account,Buffer.from(JSON.stringify(t),"utf-8")}get id(){return""+this.shash+this.sidx}fromRaw(t){return t=JSON.parse(t.toString("utf8")),this.fromOptions(t),this}static fromRaw(e){return(new t).fromRaw(e)}},t.exports=i},function(t,e,r){const i=r(0);var s=r(28);const n=r(267);t.exports=class extends s{constructor(t){super(),this.env=t,this.pending=null}async loadHistory(){for(const t of this.env.wallets.values())await t.txdb.fillCoins()}batch(){return new n(this)}start(){i(!this.pending),this.pending=this.batch()}drop(){i(this.pending),this.pending=null}clear(){i(this.pending),this.pending.clear()}commit(){i(this.pending),this.pending.commit(),this.pending=null}push(t,e){i(this.pending),this.pending.set(t,e)}unpush(t){i(this.pending),this.pending.remove(t)}}},function(t,e,r){"use strict";
1111
1111
  /*!
1112
1112
  * ChainState.js - walletdb records
1113
1113
  * Copyright (c) 2019-2022, Bookman Software (MIT License).