gamegold 5.6.12 → 5.7.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/gamegold-worker.js +32 -32
- package/lib/gamegold.js +49 -49
- package/package.json +1 -1
package/lib/gamegold-worker.js
CHANGED
|
@@ -33,11 +33,11 @@ const path = require('path');var gpath = path.join(__dirname, '../../../', 'node
|
|
|
33
33
|
* network.js - network object for vallnet
|
|
34
34
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
35
35
|
* https://github.com/bookmansoft/gamegold
|
|
36
|
-
*/const r=i(0),a=i(2),s=i(
|
|
36
|
+
*/const r=i(0),a=i(2),s=i(142),n=i(7),o=i(236);class c{constructor(e){r(!c[e.type],"Cannot create two networks."),this.type=e.type,this.typeId=e.typeId,this.seeds=e.seeds,this.txcheckpoint=e.txcheckpoint,this.txchecktime=e.txchecktime,this.magic=e.magic,this.port=e.port,this.wsport=e.wsport,this.publicPort=e.publicPort,this.checkpointMap=e.checkpointMap,this.lastCheckpoint=e.lastCheckpoint,this.checkpoints=[],this.halvingInterval=e.halvingInterval,this.genesis=e.genesis,this.pow=e.pow,this.block=e.block,this.activationThreshold=e.activationThreshold,this.minerWindow=e.minerWindow,this.deployments=e.deployments,this.deploys=e.deploys,this.keyPrefix=e.keyPrefix,this.addressPrefix=e.addressPrefix,this.requireStandard=e.requireStandard,this.httpPort=e.httpPort,this.minRelay=e.minRelay,this.feeRate=e.feeRate,this.maxFeeRate=e.maxFeeRate,this.selfConnect=e.selfConnect,this.requestMempool=e.requestMempool,this.genesisId=e.genesisId,this.tokenFix=e.tokenFix,this.tokenReg=e.tokenReg,this.stratumHost=e.stratumHost,this.stratumPort=e.stratumPort,this.stratumPublicHost=e.stratumPublicHost,this.stratumPublicPort=e.stratumPublicPort,this.stratumMaxInbound=e.stratumMaxInbound,this.stratumDifficulty=e.stratumDifficulty,this.stratumDynamic=e.stratumDynamic,this.stratumPassword=e.stratumPassword,this.unknownBits=~n.VERSION_TOP_MASK,this.time=new o,this._init()}_init(){let e=0;for(const t of this.deploys)e|=1<<t.bit;e|=n.VERSION_TOP_MASK,this.unknownBits=~e;for(const e of Object.keys(this.checkpointMap)){var t=this.checkpointMap[e],i=Number(e);this.checkpoints.push({hash:t,height:i})}this.checkpoints.sort(h)}byBit(e){return-1===(e=a.binarySearch(this.deploys,e,u))?null:this.deploys[e]}now(){return this.time.now()}ms(){return this.time.ms()}toString(){return this.type}inspect(){return`<Network: ${this.type}>`}static create(e){return"string"==typeof e&&(e=s[e]),r(e,"Unknown network."),c[e.type]||(e=new c(e),c[e.type]=e,c.primary||(c.primary=e),e)}static set(e){return r("string"==typeof e,"Bad network."),c.primary=c.get(e),c.type=e,c.primary}static get(e){if(!e)return r(c.primary,"No default network."),c.primary;if(e instanceof c)return e;if("string"==typeof e)return c.create(e);throw new Error("Unknown network.")}static ensure(e){if(e){if(e instanceof c)return e;if("string"==typeof e&&s[e])return c.create(e)}return r(c.primary,"No default network."),c.primary}static by(e,t,i,r){if(i){if(t(i=c.get(i),e))return i;throw new Error(`Network mismatch for ${r}.`)}for(const r of s.types)if(t(i=s[r],e))return c.get(r);throw new Error(`Network not found for ${r}.`)}static fromMagic(e,t){return c.by(e,l,t,"magic number")}static fromWIF(e,t){return c.by(e,p,t,"WIF")}static fromPublic(e,t){return c.by(e,d,t,"xpubkey")}static fromPrivate(e,t){return c.by(e,f,t,"xprivkey")}static fromPublic58(e,t){return c.by(e,m,t,"xpubkey")}static fromPrivate58(e,t){return c.by(e,g,t,"xprivkey")}static fromAddress(e,t){return c.by(e,v,t,"base58 address")}static fromBech32(e,t){return c.by(e,y,t,"bech32 address")}static isNetwork(e){return e instanceof c}}function u(e,t){return e.bit-t}function h(e,t){return e.height-t.height}function l(e,t){return e.magic===t}function p(e,t){return e.keyPrefix.privkey===t}function d(e,t){return e.keyPrefix.xpubkey===t}function f(e,t){return e.keyPrefix.xprivkey===t}function m(e,t){return e.keyPrefix.xpubkey58===t}function g(e,t){return e.keyPrefix.xprivkey58===t}function v(e,t){switch(e=e.addressPrefix,t){case e.pubkeyhash:case e.scripthash:case e.witnesspubkeyhash:case e.witnessscripthash:return!0}return!1}function y(e,t){return e.addressPrefix.bech32===t}c.primary=null,c.type=null,c.main=null,c.testnet=null,c.regtest=null,c.simnet=null,c.set("testnet"),e.exports=c},function(e,t){e.exports=require("events")},function(e,t,i){"use strict";
|
|
37
37
|
/*!
|
|
38
38
|
* script.js - script interpreter for vallnet
|
|
39
39
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
40
|
-
*/const r=Buffer.alloc(0),a=i(0),s=i(238),n=i(165),o=i(128),c=i(112),u=i(99),h=i(19),l=h.opcodes,p=h.types,d=h.outputLockType,f=i(7),m=i(29),g=i(6),v=i(144),y=i(26),b=i(3),w=i(321),x=i(2),k=i(22),S=i(1),_=i(4),E=i(13),{ContractType:j,ContractStatus:A}=i(5),R=i(166),I={199:{len:11,list:[6,8]},197:{len:22,list:[9,18]},198:{len:19,list:[6,15]}},O=2;class C{constructor(e){this.raw=r,this.code=[],this.indicator=w.inst(0),e&&this.fromOptions(e)}createScript(e,t=p.PUBKEYHASH){switch(this.clear(),t){case p.PUBKEY:this.$fromPubkey(e);break;case p.PUBKEYHASH:this.$fromPubkeyhash(e);break;case p.PROPEXTEND:this.$fromPkhExtend(e);break;case p.MULTISIG:var[i,r,a]=e;this.$fromMultisig(i,r,a);break;case p.SCRIPTHASH:this.$fromScripthash(e);break;case p.NULLDATA:this.$fromNulldata(e);break;case p.WITNESS:var[i,r,a]=e;this.$fromProgram(i,r,a)}return 0<this.code.length&&this.compile(),this}static createScript(e,t=p.PUBKEYHASH){return(new C).createScript(e,t)}$fromNulldata(e){a(Buffer.isBuffer(e)),a(e.length<=m.MAX_OP_RETURN,"Nulldata too large."),this.pushOp(l.OP_RETURN),this.pushData(e)}$fromPubkey(e){a(Buffer.isBuffer(e)&&(33===e.length||65===e.length)),this.code.push(n.fromPush(e)),this.code.push(n.fromOp(l.OP_CHECKSIG))}$fromPubkeyhash(e){a(Buffer.isBuffer(e)&&20===e.length),this.code.push(n.fromOp(l.OP_DUP)),this.code.push(n.fromOp(l.OP_HASH160)),this.code.push(n.fromPush(e)),this.code.push(n.fromOp(l.OP_EQUALVERIFY)),this.code.push(n.fromOp(l.OP_CHECKSIG))}$fromPkhExtend(e){a(Buffer.isBuffer(e.info)&&e.info.length<=m.MAX_OP_INFO),a(Buffer.isBuffer(e.hash)&&20===e.hash.length),this.code.push(n.fromOp(e.opcode)),this.code.push(n.fromPush(e.info)),this.code.push(n.fromOp(l.OP_DROP)),this.code.push(n.fromOp(l.OP_DUP)),this.code.push(n.fromOp(l.OP_HASH160)),this.code.push(n.fromPush(e.hash)),this.code.push(n.fromOp(l.OP_EQUALVERIFY)),this.code.push(n.fromOp(l.OP_CHECKSIG))}$fromMultisig(e,t,i){a(x.isU8(e)&&x.isU8(t)),a(Array.isArray(i)),a(i.length===t,"`n` keys are required for multisig."),a(1<=e&&e<=t),a(1<=t&&t<=15),this.clear(),this.pushSmall(e);for(const e of i.slice().sort((e,t)=>e.compare(t)))this.pushData(e);this.pushSmall(t),this.pushOp(l.OP_CHECKMULTISIG)}$fromScripthash(e){a(Buffer.isBuffer(e)&&20===e.length),this.code.push(n.fromOp(l.OP_HASH160)),this.code.push(n.fromPush(e)),this.code.push(n.fromOp(l.OP_EQUAL))}$fromProgram(e,t,i){var r;a(x.isU8(e)&&0<=e&&e<=16),a(Buffer.isBuffer(t)&&2<=t.length&&t.length<=40),i&&(r=Buffer.from(JSON.stringify(i)),a(Buffer.isBuffer(r)&&r.length<=m.MAX_OP_INFO),h.OperCodeFromType[i.oper])&&(this.code.push(n.fromOp(h.OperCodeFromType[i.oper])),this.code.push(n.fromPush(r)),this.code.push(n.fromOp(l.OP_DROP))),this.code.push(n.fromSmall(e)),this.code.push(n.fromPush(t))}get length(){return this.code.length}set length(e){return this.code.length=e,this.code.length}fromOptions(e){if(a(e,"Script data is required."),Buffer.isBuffer(e))return this.fromRaw(e);if(Array.isArray(e))return this.fromArray(e);if(e.raw){if(!e.code)return this.fromRaw(e.raw);a(Buffer.isBuffer(e.raw),"Raw must be a Buffer."),this.raw=e.raw}if(e.code){if(!e.raw)return this.fromArray(e.code);a(Array.isArray(e.code),"Code must be an array."),this.code=e.code}return this}static fromOptions(e){return(new C).fromOptions(e)}entries(){return this.code.entries()}[Symbol.iterator](){return this.code[Symbol.iterator]()}toArray(){return this.code.slice()}fromArray(e){a(Array.isArray(e)),this.clear();for(const t of e)this.push(t);return this.compile()}static fromArray(e){return(new C).fromArray(e)}toItems(){var e=[];for(const i of this.code){var t=i.toPush();if(!t)throw new Error("Non-push opcode in script.");e.push(t)}return e}fromItems(e,t=!0){a(Array.isArray(e));var i=[];if(t)this.clear();else{let e=this.shift();for(;e;)i.push(e),e=this.shift()}for(const t of e)this.pushData(t);for(const e of i)this.push(e);return this.compile()}static fromItems(e){return(new C).fromItems(e)}toStack(){return new o(this.toItems())}fromStack(e,t=!0){return this.fromItems(e.items,t)}static fromStack(e){return(new C).fromStack(e)}clone(){return(new C).inject(this)}inject(e){return this.raw=e.raw,this.code=e.code.slice(),this}equals(e){return a(C.isScript(e)),this.raw.equals(e.raw)}compare(e){return a(C.isScript(e)),this.raw.compare(e.raw)}clear(){return this.raw=r,this.code.length=0,this}inspect(){return`<Script: ${this.toString()}>`}toString(){var e=[];for(const t of this.code)e.push(t.toFormat());return e.join(" ")}toASM(e){this.isNulldata()&&(e=!1);var t=[];for(const i of this.code)t.push(i.toASM(e));return t.join(" ")}compile(){if(0===this.code.length)return this.clear();let e=0;for(const t of this.code)e+=t.getSize();var t=new _(e);for(const e of this.code)e.toWriter(t);return this.raw=t.render(),this}toWriter(e){return e.writeVarBytes(this.raw),e}toRaw(){return this.raw}toJSON(){return this.toRaw().toString("hex")}fromJSON(e){return a("string"==typeof e,"Code must be a string."),this.fromRaw(Buffer.from(e,"hex"))}static fromJSON(e){return(new C).fromJSON(e)}getSubscript(e){if(0===e)return this.clone();var t=new C;for(let r=e;r<this.code.length;r++){var i=this.code[r];if(-1===i.value)break;t.code.push(i)}return t.compile()}removeSeparators(){let e=!1;for(const t of this.code){if(-1===t.value)break;if(t.value===l.OP_CODESEPARATOR){e=!0;break}}if(!e)return this;var t=new C;for(const e of this.code){if(-1===e.value)break;e.value!==l.OP_CODESEPARATOR&&t.code.push(e)}return t.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 e=d.NOCHECK,t=-1,i=-1;var r,a;return 2<=this.code.length&&this.getOp(1)==l.OP_CHECKLOCKTIMEVERIFY&&((r=this.getInt(0,!1,5))<f.LOCKTIME_THRESHOLD?(e=d.CHECKABSOLUTEBLOCK,t=r):(e=d.CHECKABSOLUTETIME,i=r)),2<=this.code.length&&this.getOp(1)==l.OP_CHECKSEQUENCEVERIFY&&((r=this.getInt(0,!1,5))&f.SEQUENCE_DISABLE_FLAG||(a=r&f.SEQUENCE_MASK,r&f.SEQUENCE_TYPE_FLAG?(e=d.CHECKRELATIVETIME,i=a):(e=d.CHECKRELATIVEBLOCK,t=a))),[e,t,i]}execute(e,t,i,r,s,n,o){if(null==t&&(t=C.flags.STANDARD_VERIFY_FLAGS),null==o&&(o=0),this.raw.length>f.MAX_SCRIPT_SIZE)throw new c("SCRIPT_SIZE");var h=[],p=[];let d=0,m=0,v=0,y=!1;t&C.flags.VERIFY_MINIMALDATA&&(y=!0);for(let Y=0;Y<this.code.length;Y++){var b=this.code[Y];if(-1===b.value)throw new c("BAD_OPCODE",b,Y);if(b.data&&b.data.length>f.MAX_SCRIPT_PUSH)throw new c("PUSH_SIZE",b,Y);if(b.value>l.OP_16&&++m>f.MAX_SCRIPT_OPS)throw new c("OP_COUNT",b,Y);if(b.isDisabled())throw new c("DISABLED_OPCODE",b,Y);if(v&&!b.isBranch()){if(e.length+p.length>f.MAX_SCRIPT_STACK)throw new c("STACK_SIZE",b,Y)}else if(b.data){if(y&&!b.isMinimal())throw new c("MINIMALDATA",b,Y);if(e.push(b.data),e.length+p.length>f.MAX_SCRIPT_STACK)throw new c("STACK_SIZE",b,Y)}else{switch(b.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:case l.OP_ATTACH:break;case l.OP_PROMISE:this.indicator.set(O);break;case l.OP_RETURN:throw new c("OP_RETURN",b,Y);case l.OP_0:e.pushInt(0);break;case l.OP_1NEGATE:e.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:e.pushInt(b.value-80);break;case l.OP_NOP:break;case l.OP_CHECKLOCKTIMEVERIFY:if(!(t&C.flags.VERIFY_CHECKLOCKTIMEVERIFY)){if(t&C.flags.VERIFY_DISCOURAGE_UPGRADABLE_NOPS)throw new c("DISCOURAGE_UPGRADABLE_NOPS",b,Y);break}if(!i)throw new c("UNKNOWN_ERROR","No TX passed in.");if(0===e.length)throw new c("INVALID_STACK_OPERATION",b,Y);var w=e.getNum(-1,y,5);if(w.isNeg())throw new c("NEGATIVE_LOCKTIME",b,Y);if(w=w.toDouble(),i.verifyLocktime(r,w))break;throw new c("UNSATISFIED_LOCKTIME",b,Y);case l.OP_CHECKSEQUENCEVERIFY:if(!(t&C.flags.VERIFY_CHECKSEQUENCEVERIFY)){if(t&C.flags.VERIFY_DISCOURAGE_UPGRADABLE_NOPS)throw new c("DISCOURAGE_UPGRADABLE_NOPS",b,Y);break}if(!i)throw new c("UNKNOWN_ERROR","No TX passed in.");if(0===e.length)throw new c("INVALID_STACK_OPERATION",b,Y);if((w=e.getNum(-1,y,5)).isNeg())throw new c("NEGATIVE_LOCKTIME",b,Y);var x=w.toDouble();if(i.verifySequence(r,x))break;throw new c("UNSATISFIED_LOCKTIME",b,Y);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(t&C.flags.VERIFY_DISCOURAGE_UPGRADABLE_NOPS)throw new c("DISCOURAGE_UPGRADABLE_NOPS",b,Y);break;case l.OP_IF:case l.OP_NOTIF:{let i=!1;if(!v){if(e.length<1)throw new c("UNBALANCED_CONDITIONAL",b,Y);if(1===o&&t&C.flags.VERIFY_MINIMALIF){if(1<(x=e.get(-1)).length)throw new c("MINIMALIF");if(1===x.length&&1!==x[0])throw new c("MINIMALIF")}i=e.getBool(-1),b.value===l.OP_NOTIF&&(i=!i),e.pop()}h.push(i),i||(v+=1);break}case l.OP_ELSE:if(0===h.length)throw new c("UNBALANCED_CONDITIONAL",b,Y);h[h.length-1]=!h[h.length-1],h[h.length-1]?--v:v+=1;break;case l.OP_ENDIF:if(0===h.length)throw new c("UNBALANCED_CONDITIONAL",b,Y);h.pop()||--v;break;case l.OP_VERIFY:if(0===e.length)throw new c("INVALID_STACK_OPERATION",b,Y);if(!e.getBool(-1))throw new c("VERIFY",b,Y);e.pop();break;case l.OP_TOALTSTACK:if(0===e.length)throw new c("INVALID_STACK_OPERATION",b,Y);p.push(e.pop());break;case l.OP_FROMALTSTACK:if(0===p.length)throw new c("INVALID_ALTSTACK_OPERATION",b,Y);e.push(p.pop());break;case l.OP_2DROP:if(e.length<2)throw new c("INVALID_STACK_OPERATION",b,Y);e.pop(),e.pop();break;case l.OP_2DUP:if(e.length<2)throw new c("INVALID_STACK_OPERATION",b,Y);var k=e.get(-2),S=e.get(-1);e.push(k),e.push(S);break;case l.OP_3DUP:if(e.length<3)throw new c("INVALID_STACK_OPERATION",b,Y);k=e.get(-3),S=e.get(-2);var _=e.get(-1);e.push(k),e.push(S),e.push(_);break;case l.OP_2OVER:if(e.length<4)throw new c("INVALID_STACK_OPERATION",b,Y);_=e.get(-4);var E=e.get(-3);e.push(_),e.push(E);break;case l.OP_2ROT:if(e.length<6)throw new c("INVALID_STACK_OPERATION",b,Y);E=e.get(-6);var j=e.get(-5);e.erase(-6,-4),e.push(E),e.push(j);break;case l.OP_2SWAP:if(e.length<4)throw new c("INVALID_STACK_OPERATION",b,Y);e.swap(-4,-2),e.swap(-3,-1);break;case l.OP_IFDUP:if(0===e.length)throw new c("INVALID_STACK_OPERATION",b,Y);e.getBool(-1)&&(j=e.get(-1),e.push(j));break;case l.OP_DEPTH:e.pushInt(e.length);break;case l.OP_DROP:if(0===e.length)throw new c("INVALID_STACK_OPERATION",b,Y);var A=e.pop();if(this.indicator.check(O)){this.indicator.unSet(O);try{var I=JSON.parse(A.toString());new R(I,n).run(e)}catch(n){}}break;case l.OP_DUP:if(0===e.length)throw new c("INVALID_STACK_OPERATION",b,Y);e.push(e.get(-1));break;case l.OP_NIP:if(e.length<2)throw new c("INVALID_STACK_OPERATION",b,Y);e.remove(-2);break;case l.OP_OVER:if(e.length<2)throw new c("INVALID_STACK_OPERATION",b,Y);e.push(e.get(-2));break;case l.OP_PICK:case l.OP_ROLL:if(e.length<2)throw new c("INVALID_STACK_OPERATION",b,Y);if(A=e.getInt(-1,y,4),e.pop(),A<0||A>=e.length)throw new c("INVALID_STACK_OPERATION",b,Y);var N=e.get(-A-1);b.value===l.OP_ROLL&&e.remove(-A-1),e.push(N);break;case l.OP_ROT:if(e.length<3)throw new c("INVALID_STACK_OPERATION",b,Y);e.swap(-3,-2),e.swap(-2,-1);break;case l.OP_SWAP:if(e.length<2)throw new c("INVALID_STACK_OPERATION",b,Y);e.swap(-2,-1);break;case l.OP_TUCK:if(e.length<2)throw new c("INVALID_STACK_OPERATION",b,Y);e.insert(-2,e.get(-1));break;case l.OP_SIZE:if(e.length<1)throw new c("INVALID_STACK_OPERATION",b,Y);e.pushInt(e.get(-1).length);break;case l.OP_EQUAL:case l.OP_EQUALVERIFY:if(e.length<2)throw new c("INVALID_STACK_OPERATION",b,Y);N=e.get(-2);var z=e.get(-1);z=N.equals(z);if(e.pop(),e.pop(),e.pushBool(z),b.value===l.OP_EQUALVERIFY){if(!z)throw new c("EQUALVERIFY",b,Y);e.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(e.length<1)throw new c("INVALID_STACK_OPERATION",b,Y);let t,i=e.getNum(-1,y,4);switch(b.value){case l.OP_1ADD:i.iaddn(1);break;case l.OP_1SUB:i.isubn(1);break;case l.OP_NEGATE:i.ineg();break;case l.OP_ABS:i.iabs();break;case l.OP_NOT:t=i.isZero(),i=u.fromBool(t);break;case l.OP_0NOTEQUAL:t=!i.isZero(),i=u.fromBool(t);break;default:a(!1,"Fatal script error.")}e.pop(),e.pushNum(i);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(e.length<2)throw new c("INVALID_STACK_OPERATION",b,Y);var F=e.getNum(-2,y,4),L=e.getNum(-1,y,4);let t,i;switch(b.value){case l.OP_ADD:t=F.iadd(L);break;case l.OP_SUB:t=F.isub(L);break;case l.OP_BOOLAND:i=F.toBool()&&L.toBool(),t=u.fromBool(i);break;case l.OP_BOOLOR:i=F.toBool()||L.toBool(),t=u.fromBool(i);break;case l.OP_NUMEQUAL:case l.OP_NUMEQUALVERIFY:i=F.eq(L),t=u.fromBool(i);break;case l.OP_NUMNOTEQUAL:i=!F.eq(L),t=u.fromBool(i);break;case l.OP_LESSTHAN:i=F.lt(L),t=u.fromBool(i);break;case l.OP_GREATERTHAN:i=F.gt(L),t=u.fromBool(i);break;case l.OP_LESSTHANOREQUAL:i=F.lte(L),t=u.fromBool(i);break;case l.OP_GREATERTHANOREQUAL:i=F.gte(L),t=u.fromBool(i);break;case l.OP_MIN:t=u.min(F,L);break;case l.OP_MAX:t=u.max(F,L);break;default:a(!1,"Fatal script error.")}if(e.pop(),e.pop(),e.pushNum(t),b.value===l.OP_NUMEQUALVERIFY){if(!e.getBool(-1))throw new c("NUMEQUALVERIFY",b,Y);e.pop()}break}case l.OP_WITHIN:if(e.length<3)throw new c("INVALID_STACK_OPERATION",b,Y);z=e.getNum(-3,y,4);var M=e.getNum(-2,y,4),D=e.getNum(-1,y,4);M=M.lte(z)&&z.lt(D);e.pop(),e.pop(),e.pop(),e.pushBool(M);break;case l.OP_RIPEMD160:if(0===e.length)throw new c("INVALID_STACK_OPERATION",b,Y);e.push(g.ripemd160(e.pop()));break;case l.OP_SHA1:if(0===e.length)throw new c("INVALID_STACK_OPERATION",b,Y);e.push(g.sha1(e.pop()));break;case l.OP_SHA256:if(0===e.length)throw new c("INVALID_STACK_OPERATION",b,Y);e.push(g.sha256(e.pop()));break;case l.OP_HASH160:if(0===e.length)throw new c("INVALID_STACK_OPERATION",b,Y);e.push(g.hash160(e.pop()));break;case l.OP_HASH256:if(0===e.length)throw new c("INVALID_STACK_OPERATION",b,Y);e.push(g.hash256(e.pop()));break;case l.OP_CODESEPARATOR:d=Y+1;break;case l.OP_CHECKSIG:case l.OP_CHECKSIGVERIFY:{if(!i)throw new c("UNKNOWN_ERROR","No TX passed in.");if(e.length<2)throw new c("INVALID_STACK_OPERATION",b,Y);D=e.get(-2),M=e.get(-1);var H,U=this.getSubscript(d);0===o&&U.findAndDelete(D),T(D,t),P(M,t,o);let a=!1;if(0<D.length&&(H=D[D.length-1],a=B(U=i.signatureHash(r,U,s,H,o),D,M)),!a&&t&C.flags.VERIFY_NULLFAIL&&0!==D.length)throw new c("NULLFAIL",b,Y);if(e.pop(),e.pop(),e.pushBool(a),b.value===l.OP_CHECKSIGVERIFY){if(!a)throw new c("CHECKSIGVERIFY",b,Y);e.pop()}break}case l.OP_CHECKMULTISIG:case l.OP_CHECKMULTISIGVERIFY:{if(!i)throw new c("UNKNOWN_ERROR","No TX passed in.");let a=1;if(e.length<a)throw new c("INVALID_STACK_OPERATION",b,Y);let n,u,h=e.getInt(-a,y,4),p=h+2;if(h<0||h>f.MAX_MULTISIG_PUBKEYS)throw new c("PUBKEY_COUNT",b,Y);if((m+=h)>f.MAX_SCRIPT_OPS)throw new c("OP_COUNT",b,Y);if(a+=1,n=a,a+=h,e.length<a)throw new c("INVALID_STACK_OPERATION",b,Y);let g=e.getInt(-a,y,4);if(g<0||g>h)throw new c("SIG_COUNT",b,Y);if(a+=1,u=a,a+=g,e.length<a)throw new c("INVALID_STACK_OPERATION",b,Y);var q=this.getSubscript(d);for(let t=0;t<g;t++){var V=e.get(-u-t);0===o&&q.findAndDelete(V)}let v=!0;for(;v&&0<g;){var K,W=e.get(-u),$=e.get(-n);T(W,t),P($,t,o),0<W.length&&(K=W[W.length-1],B(i.signatureHash(r,q,s,K,o),W,$))&&(u+=1,--g),n+=1,--h,g>h&&(v=!1)}for(;1<a;){if(!v&&t&C.flags.VERIFY_NULLFAIL&&0===p&&0!==e.get(-1).length)throw new c("NULLFAIL",b,Y);0<p&&--p,e.pop(),--a}if(e.length<1)throw new c("INVALID_STACK_OPERATION",b,Y);if(t&C.flags.VERIFY_NULLDUMMY&&0!==e.get(-1).length)throw new c("SIG_NULLDUMMY",b,Y);if(e.pop(),e.pushBool(v),b.value===l.OP_CHECKMULTISIGVERIFY){if(!v)throw new c("CHECKMULTISIGVERIFY",b,Y);e.pop()}break}default:throw new c("BAD_OPCODE",b,Y)}if(e.length+p.length>f.MAX_SCRIPT_STACK)throw new c("STACK_SIZE",b,Y)}}if(0!==h.length)throw new c("UNBALANCED_CONDITIONAL")}findAndDelete(e){var t=n.fromPush(e);if(this.raw.length<t.getSize())return 0;let i=!1;for(const e of this.code){if(-1===e.value)break;if(e.equals(t)){i=!0;break}}if(!i)return 0;var r=[];let a=0;for(const e of this.code){if(-1===e.value)break;e.equals(t)?a+=1:r.push(e)}return this.code=r,this.compile(),a}indexOf(e){for(let i=0;i<this.code.length;i++){var t=this.code[i];if(-1===t.value)break;if(t.data&&t.data.equals(e))return i}return-1}isCode(){for(const e of this.code){if(-1===e.value)return!1;if(e.isDisabled())return!1;switch(e.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(e.value>l.OP_PROPMAX)return!1}return!0}fromAddress(e,t){"string"==typeof e&&(e=E.fromString(e)),a(e instanceof E,"Not an address.");let i=!1;if(e.isPubkeyhash())if(t&&t.oper)switch(t.oper){case j.cpRegister:this.createScript({opcode:C.opcodes.OP_CPREGISTER,hash:e.hash,info:Buffer.from(JSON.stringify(t))},C.types.PROPEXTEND);break;case j.cpChange:this.createScript({opcode:C.opcodes.OP_CPCHANGE,hash:e.hash,info:Buffer.from(JSON.stringify(t))},C.types.PROPEXTEND);break;case j.propCreate:this.createScript({opcode:C.opcodes.OP_PROPCREATE,hash:e.hash,info:Buffer.from(JSON.stringify(t))},C.types.PROPEXTEND);break;case j.attach:this.createScript({opcode:C.opcodes.OP_ATTACH,hash:e.hash,info:Buffer.from(JSON.stringify(t))},C.types.PROPEXTEND);break;case j.propExchange:this.createScript({opcode:C.opcodes.OP_PROPEXCHANGE,hash:e.hash,info:Buffer.from(JSON.stringify(t))},C.types.PROPEXTEND);break;case j.coinbase:this.createScript({opcode:C.opcodes.OP_COINBASE,hash:e.hash,info:Buffer.from(JSON.stringify(t))},C.types.PROPEXTEND)}else this.createScript(e.hash);else e.isScripthash()?this.createScript(e.hash,C.types.SCRIPTHASH):e.isProgram()&&this.createScript([e.version,e.hash,t],C.types.WITNESS);if(t&&t.locktype&&(!t.oper||h.unspendableCodes.indexOf(t.oper)<0))switch(t.locktype){case d.CHECKABSOLUTEBLOCK:case d.CHECKABSOLUTETIME:this.code.unshift(n.fromOp(l.OP_DROP)),this.code.unshift(n.fromOp(l.OP_CHECKLOCKTIMEVERIFY)),this.code.unshift(n.fromInt(t.locktime)),i=!0;break;case d.CHECKRELATIVEBLOCK:case d.CHECKRELATIVETIME:t.locktype===d.CHECKRELATIVETIME&&(t.locktime=t.locktime|f.SEQUENCE_TYPE_FLAG),this.code.unshift(n.fromOp(l.OP_DROP)),this.code.unshift(n.fromOp(l.OP_CHECKSEQUENCEVERIFY)),this.code.unshift(n.fromInt(t.locktime)),i=!0}if(i&&this.compile(),0<this.code.length)return this;throw new Error("Unknown address type.")}static fromAddress(e,t){return(new C).fromAddress(e,t)}fromCommitment(e,t){var i=new _(36);return i.writeU32BE(2854332909),i.writeHash(e),this.clear(),this.pushOp(l.OP_RETURN),this.pushData(i.render()),t&&this.pushData(t),this.compile()}static fromCommitment(e,t){return(new C).fromCommitment(e,t)}getRedeem(){let e=null;for(const t of this.code){if(-1===t.value)return null;if(t.value>l.OP_16)return null;e=t.data}return e?C.fromRaw(e):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(e){return e?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===(e=this.getLength(0))||65===e)&&this.getOp(1)===l.OP_CHECKSIG}isPubkeyhash(e){if(e||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 t=0;for(var i of this.code)if(i.value==l.OP_DUP){t=this.code.indexOf(i);break}return this.getOp(0+t)===l.OP_DUP&&this.getOp(1+t)===l.OP_HASH160&&20===this.getLength(2+t)&&this.getOp(3+t)===l.OP_EQUALVERIFY&&this.getOp(4+t)===l.OP_CHECKSIG}isMultisig(e){if(this.code.length<4||19<this.code.length)return!1;if(this.getOp(-1)!==l.OP_CHECKMULTISIG)return!1;var t=this.getSmall(0);if(t<1)return!1;var i=this.getSmall(-2);if(i<1||i<t)return!1;if(this.code.length!==i+3)return!1;for(let t=1;t<i+1;t++){var r=this.code[t],a=r.toLength();if(33!==a&&65!==a)return!1;if(e&&!r.isMinimal())return!1}return!0}isUnknown(){return this.getType()===p.NONSTANDARD}isStandard(){var[e,t]=this.getMultisig();return-1!==e?!(t<1||3<t||e<1||t<e):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(e){if(0===this.code.length)return!1;if(this.getOp(0)!==l.OP_RETURN)return!1;if(1!==this.code.length){if(e&&this.raw.length>m.MAX_OP_RETURN_BYTES)return!1;for(let i=1;i<this.code.length;i++){var t=this.code[i];if(-1===t.value)return!1;if(t.value>l.OP_16)return!1;if(e&&!t.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(e){if(!(this.code&&this.code[0]&&this.code[1]&&this.code[1].data))return null;if(e)if(Array.isArray(e)){let i=!1;for(var t of e)if(this.code[0].value===t){i=!0;break}if(!i)return null}else if(this.code[0].value!==e)return null;try{return x.parseJson(this.code[1].data.toString())}catch(e){return null}}getReturnType(e){if(!this.code||!this.code[0])return null;if(e)if(Array.isArray(e)){let i=!1;for(var t of e)if(this.code[0].value===t){i=!0;break}if(!i)return null}else if(this.code[0].value!==e)return null;return this.code[0].value}hash160(e){let t=g.hash160(this.toRaw());return"hex"===e?t.toString("hex"):t}sha256(e){let t=g.sha256(this.toRaw());return"hex"===e?t.toString("hex"):t}getPubkey(e){return this.isPubkey(e)?e?this.raw.slice(1,1+this.raw[0]):this.getData(0):null}getMultiPubkeyhash(){var e=I[this.getOp(0)];return e&&this.code.length==e.len?e.list.map(e=>this.getData(e)):null}getPubkeyhash(e){if(this.isPubkeyhash(e)){if(e)return this.raw.slice(3,23);for(var t of this.code)if(t.value==l.OP_CHECKSIG)return this.getData(this.code.indexOf(t)-2)}return null}getMultisig(e){return this.isMultisig(e)?[this.getSmall(0),this.getSmall(-2)]:[-1,-1]}getScripthash(){return this.isScripthash()?this.getData(1):null}getNulldata(e){if(!this.isNulldata(e))return null;for(let e=1;e<this.code.length;e++){var t=this.code[e].toPush();if(t)return t}return r}getCommitment(){return this.isCommitment()?this.raw.slice(6,38):null}getProgram(){return this.isProgram()?2==this.code.length?new s(this.getSmall(0),this.getData(1)):5==this.code.length?new s(this.getSmall(3),this.getData(4)):null:null}forWitness(){var e;return this.isProgram()?this.clone():(e=this.getPubkey())?(e=g.hash160(e),C.createScript([0,e],C.types.WITNESS)):(e=this.getPubkeyhash())?C.createScript([0,e],C.types.WITNESS):C.createScript([0,this.sha256()],C.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 e,t;return 2===this.code.length&&(e=this.getLength(0),t=this.getLength(1),9<=e)&&e<=73&&(33===t||65===t)}isUnknownInput(){return this.getInputType()===p.NONSTANDARD}isPubkeyInput(){var e;return 1===this.code.length&&9<=(e=this.getLength(0))&&e<=73}isScripthashInput(){var e;return!(this.code.length<2||!(e=this.getData(-1))||0===e.length||h.isSignatureEncoding(e)||h.isKeyEncoding(e)||!(e=C.fromRaw(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 t=1;t<this.code.length;t++){var e=this.getLength(t);if(e<9||73<e)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;var e=[];for(let t=1;t<this.code.length;t++)e.push(this.getData(t));return e}getScripthashInput(){return this.isScripthashInput()?this.getData(-1):null}getCoinbaseHeight(){return C.getCoinbaseHeight(this.raw)}static getCoinbaseHeight(e){var t;return 0===e.length?-1:e[0]>=l.OP_1&&e[0]<=l.OP_16?e[0]-80:6<e[0]?-1:(t=(e=n.fromRaw(e)).toNum())?!t.isNeg()&&e.equals(n.fromNum(t))?t.toDouble():-1:1}test(e){for(const t of this.code){if(-1===t.value)break;if(t.data&&0!==t.data.length){if(e.test(t.data))return!0;if(33==t.data.length&&e.test(g.hash160(t.data)))return!0}}return!1}isPushOnly(){for(const e of this.code){if(-1===e.value)return!1;if(e.value>l.OP_16)return!1}return!0}getSigops(e){let t=0,i=-1;for(const r of this.code){if(-1===r.value)break;switch(r.value){case l.OP_CHECKSIG:case l.OP_CHECKSIGVERIFY:t+=1;break;case l.OP_CHECKMULTISIG:case l.OP_CHECKMULTISIGVERIFY:e&&i>=l.OP_1&&i<=l.OP_16?t+=i-80:t+=f.MAX_MULTISIG_PUBKEYS}i=r.value}return t}getScripthashSigops(e){return this.isScripthash()?(e=e.getRedeem())?e.getSigops(!0):0:this.getSigops(!0)}getWitnessSigops(e,t){let i=this.getProgram();if(i||this.isScripthash()&&(e=e.getRedeem())&&(i=e.getProgram()),i&&0===i.version){if(20===i.data.length)return 1;if(32===i.data.length&&0<t.items.length)return t.getRedeem().getSigops(!0)}return 0}get(e){return e<0&&(e+=this.code.length),e<0||e>=this.code.length?null:this.code[e]}pop(){return this.code.pop()||null}shift(){return this.code.shift()||null}remove(e){return e<0&&(e+=this.code.length),e<0||e>=this.code.length||0===(e=this.code.splice(e,1)).length?null:e[0]}set(e,t){return e<0&&(e+=this.code.length),a(n.isOpcode(t)),a(0<=e&&e<=this.code.length),this.code[e]=t,this}push(e){return a(n.isOpcode(e)),this.code.push(e),this}unshift(e){return a(n.isOpcode(e)),this.code.unshift(e),this}insert(e,t){return e<0&&(e+=this.code.length),a(n.isOpcode(t)),a(0<=e&&e<=this.code.length),this.code.splice(e,0,t),this}getOp(e){return(e=this.get(e))?e.value:-1}popOp(){var e=this.pop();return e?e.value:-1}shiftOp(){var e=this.shift();return e?e.value:-1}removeOp(e){return(e=this.remove(e))?e.value:-1}setOp(e,t){return this.set(e,n.fromOp(t))}pushOp(e){return this.push(n.fromOp(e))}unshiftOp(e){return this.unshift(n.fromOp(e))}insertOp(e,t){return this.insert(e,n.fromOp(t))}getData(e){return(e=this.get(e))?e.data:null}popData(){var e=this.pop();return e?e.data:null}shiftData(){var e=this.shift();return e?e.data:null}removeData(e){return(e=this.remove(e))?e.data:null}setData(e,t){return this.set(e,n.fromData(t))}pushData(e){return this.push(n.fromData(e))}unshiftData(e){return this.unshift(n.fromData(e))}insertData(e,t){return this.insert(e,n.fromData(t))}getLength(e){return(e=this.get(e))?e.toLength():-1}getPush(e){return(e=this.get(e))?e.toPush():null}popPush(){var e=this.pop();return e?e.toPush():null}shiftPush(){var e=this.shift();return e?e.toPush():null}removePush(e){return(e=this.remove(e))?e.toPush():null}setPush(e,t){return this.set(e,n.fromPush(t))}pushPush(e){return this.push(n.fromPush(e))}unshiftPush(e){return this.unshift(n.fromPush(e))}insertPush(e,t){return this.insert(e,n.fromPush(t))}getString(e,t){return(e=this.get(e))?e.toString(t):null}popString(e){var t=this.pop();return t?t.toString(e):null}shiftString(e){var t=this.shift();return t?t.toString(e):null}removeString(e,t){return(e=this.remove(e))?e.toString(t):null}setString(e,t,i){return this.set(e,n.fromString(t,i))}pushString(e,t){return this.push(n.fromString(e,t))}unshiftString(e,t){return this.unshift(n.fromString(e,t))}insertString(e,t,i){return this.insert(e,n.fromString(t,i))}getSmall(e){return(e=this.get(e))?e.toSmall():-1}popSmall(){var e=this.pop();return e?e.toSmall():-1}shiftSmall(){var e=this.shift();return e?e.toSmall():-1}removeSmall(e){return(e=this.remove(e))?e.toSmall():-1}setSmall(e,t){return this.set(e,n.fromSmall(t))}pushSmall(e){return this.push(n.fromSmall(e))}unshiftSmall(e){return this.unshift(n.fromSmall(e))}insertSmall(e,t){return this.insert(e,n.fromSmall(t))}getNum(e,t,i){return(e=this.get(e))?e.toNum(t,i):null}popNum(e,t){var i=this.pop();return i?i.toNum(e,t):null}shiftNum(e,t){var i=this.shift();return i?i.toNum(e,t):null}removeNum(e,t,i){return(e=this.remove(e))?e.toNum(t,i):null}setNum(e,t){return this.set(e,n.fromNum(t))}pushNum(e){return this.push(n.fromNum(e))}unshiftNum(e){return this.unshift(n.fromNum(e))}insertNum(e,t){return this.insert(e,n.fromNum(t))}getInt(e,t,i){return(e=this.get(e))?e.toInt(t,i):-1}popInt(e,t){var i=this.pop();return i?i.toInt(e,t):-1}shiftInt(e,t){var i=this.shift();return i?i.toInt(e,t):-1}removeInt(e,t,i){return(e=this.remove(e))?e.toInt(t,i):-1}setInt(e,t){return this.set(e,n.fromInt(t))}pushInt(e){return this.push(n.fromInt(e))}unshiftInt(e){return this.unshift(n.fromInt(e))}insertInt(e,t){return this.insert(e,n.fromInt(t))}getBool(e){return!!(e=this.get(e))&&e.toBool()}popBool(){var e=this.pop();return!!e&&e.toBool()}shiftBool(){var e=this.shift();return!!e&&e.toBool()}removeBool(e){return!!(e=this.remove(e))&&e.toBool()}setBool(e,t){return this.set(e,n.fromBool(t))}pushBool(e){return this.push(n.fromBool(e))}unshiftBool(e){return this.unshift(n.fromBool(e))}insertBool(e,t){return this.insert(e,n.fromBool(t))}getSym(e){return(e=this.get(e))?e.toSymbol():null}popSym(){var e=this.pop();return e?e.toSymbol():null}shiftSym(){var e=this.shift();return e?e.toSymbol():null}removeSym(e){return(e=this.remove(e))?e.toSymbol():null}setSym(e,t){return this.set(e,n.fromSymbol(t))}pushSym(e){return this.push(n.fromSymbol(e))}unshiftSym(e){return this.unshift(n.fromSymbol(e))}insertSym(e,t){return this.insert(e,n.fromSymbol(t))}fromString(e){if(a("string"==typeof e),0===(e=e.trim()).length)return this;e=e.split(/\s+/);var t=new k;for(const c of e){let e=c;x.isUpperCase(e)||(e=e.toUpperCase()),x.startsWith(e,"OP_")||(e="OP_"+e);var i,r,s,o=l[e];null==o?"'"===c[0]?(a("'"===c[c.length-1],"Invalid string."),i=c.slice(1,-1),i=n.fromString(i),t.writeBytes(i.toRaw())):/^-?\d+$/.test(c)?(i=u.fromString(c,10),r=n.fromNum(i),t.writeBytes(r.toRaw())):(a(0===c.indexOf("0x"),"Unknown opcode."),r=c.substring(2),s=Buffer.from(r,"hex"),a(s.length===r.length/2,"Invalid hex string."),t.writeBytes(s)):t.writeU8(o)}return this.fromRaw(t.render())}static fromString(e){return(new C).fromString(e)}static verifyScript(e,t,i,r,s,u,h,l){if((h=null==h?C.flags.STANDARD_VERIFY_FLAGS:h)&C.flags.VERIFY_SIGPUSHONLY&&!e.isPushOnly())throw new c("SIG_PUSHONLY");null==l&&(l=A.None);let p,d=new o;if(e.execute(d,h,r,s,u,l,0),h&C.flags.VERIFY_P2SH&&(p=d.clone()),i.execute(d,h,r,s,u,l,0),0===d.length||!d.getBool(-1))throw new c("EVAL_FALSE");let f=!1;if(h&C.flags.VERIFY_WITNESS&&i.isProgram()){if(f=!0,0!==e.raw.length)throw new c("WITNESS_MALLEATED");C.verifyProgram(t,i,h,r,s,u,l),d.length=1}if(h&C.flags.VERIFY_P2SH&&i.isScripthash()){if(!e.isPushOnly())throw new c("SIG_PUSHONLY");if(0===(d=p).length)throw new c("EVAL_FALSE");i=d.pop();var m=C.fromRaw(i);if(m.execute(d,h,r,s,u,l,0),0===d.length||!d.getBool(-1))throw new c("EVAL_FALSE");if(h&C.flags.VERIFY_WITNESS&&m.isProgram()){if(f=!0,!e.raw.equals(n.fromPush(i).toRaw()))throw new c("WITNESS_MALLEATED_P2SH");C.verifyProgram(t,m,h,r,s,u,l),d.length=1}}if(h&C.flags.VERIFY_CLEANSTACK&&(a(0!=(h&C.flags.VERIFY_P2SH)),1!==d.length))throw new c("CLEANSTACK");if(h&C.flags.VERIFY_WITNESS&&(a(0!=(h&C.flags.VERIFY_P2SH)),!f)&&0<t.items.length)throw new c("WITNESS_UNEXPECTED")}static verifyProgram(e,t,i,r,s,n,o){var u=t.getProgram(),h=(a(u,"verifyProgram called on non-witness-program."),a(0!=(i&C.flags.VERIFY_WITNESS)),e.toStack());let l;if(0!==u.version){if(i&C.flags.VERIFY_MAST&&1===u.version)C.verifyMast(u,h,t,i,r,s,o);else if(i&C.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(e=h.pop(),!g.sha256(e).equals(u.data))throw new c("WITNESS_PROGRAM_MISMATCH");l=C.fromRaw(e)}else{if(20!==u.data.length)throw new c("WITNESS_PROGRAM_WRONG_LENGTH");if(2!==h.length)throw new c("WITNESS_PROGRAM_MISMATCH");l=C.createScript(u.data)}for(let e=0;e<h.length;e++)if(h.get(e).length>f.MAX_SCRIPT_PUSH)throw new c("PUSH_SIZE");if(l.execute(h,i,r,s,n,o,1),1!==h.length||!h.getBool(-1))throw new c("EVAL_FALSE")}}static verifyMast(e,t,i,r,s,n,o,u){if(a(1===e.version),a(0!=(r&C.flags.VERIFY_MAST)),t.length<4)throw new c("INVALID_MAST_STACK");var h=t.get(-1);if(h.length<1||5<h.length)throw new c("INVALID_MAST_STACK");var l=h[0];if(0===l||t.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 e=1;e<h.length;e++)m|=h[e]<<8*(e-1);if(m<0&&(m+=4294967296),0<m&&r&C.flags.DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM)throw new c("DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM");let y=new k;y.writeU32(m);var b=t.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");var x=[];for(let e=0;e<w;e++)x.push(b.slice(32*e,32*e+32));var S=t.get(-3);if(4<S.length)throw new c("INVALID_MAST_STACK");let _=0;if(0<S.length){if(0===S[S.length-1])throw new c("INVALID_MAST_STACK");for(let e=0;e<S.length;e++)_|=S[e]<<8*e;_<0&&(_+=4294967296)}if(w<32&&_>=1<<w>>>0)throw new c("INVALID_MAST_STACK");let E=new k;E.writeBytes(i.raw);for(let e=0;e<l;e++){var j=t.get(-(4+e));if(0===m&&E.offset+j.length>f.MAX_SCRIPT_SIZE)throw new c("SCRIPT_SIZE");d.writeBytes(g.hash256(j)),E.writeBytes(j)}if(d=g.hash256(d.render()),d=v.verifyBranch(d,x,_),y.writeBytes(d),!(y=g.hash256(y.render())).equals(e.data))throw new c("WITNESS_PROGRAM_MISMATCH");if(0===m){t.length-=3+l;for(let e=0;e<t.length;e++)if(t.get(e).length>f.MAX_SCRIPT_PUSH)throw new c("PUSH_SIZE");if(E=E.render(),(i=C.fromRaw(E)).execute(t,r,s,n,o,u,1),0!==t.length)throw new c("EVAL_FALSE")}}fromReader(e){return this.fromRaw(e.readVarBytes())}fromRaw(e){var t=new S(e,!0);for(this.raw=e;t.left();)this.code.push(n.fromReader(t));return this}static fromReader(e){return(new C).fromReader(e)}static fromRaw(e,t){return"string"==typeof e&&(e=Buffer.from(e,t)),(new C).fromRaw(e)}static isScript(e){return e instanceof C}}function P(e,t,i){if(a(Buffer.isBuffer(e)),a("number"==typeof t),a("number"==typeof i),t&C.flags.VERIFY_STRICTENC&&!h.isKeyEncoding(e))throw new c("PUBKEYTYPE");if(1===i&&t&C.flags.VERIFY_WITNESS_PUBKEYTYPE&&!h.isCompressedEncoding(e))throw new c("WITNESS_PUBKEYTYPE")}function T(e,t){if(a(Buffer.isBuffer(e)),a("number"==typeof t),0!==e.length){if((t&C.flags.VERIFY_DERSIG||t&C.flags.VERIFY_LOW_S||t&C.flags.VERIFY_STRICTENC)&&!h.isSignatureEncoding(e))throw new c("SIG_DER");if(t&C.flags.VERIFY_LOW_S&&!h.isLowDER(e))throw new c("SIG_HIGH_S");if(t&C.flags.VERIFY_STRICTENC&&!h.isHashType(e))throw new c("SIG_HASHTYPE")}}function B(e,t,i){return y.verify(e,t.slice(0,-1),i)}C.opcodes=h.opcodes,C.opcodesByVal=h.opcodesByVal,C.flags=h.flags,C.hashType=h.hashType,C.hashTypeByVal=h.hashTypeByVal,C.types=h.types,C.typesByVal=h.typesByVal,C.outputLockType=h.outputLockType,C.unspendableCodes=h.unspendableCodes,C.TradeType={btc:1},e.exports=C},function(e,t,i){"use strict";
|
|
40
|
+
*/const r=Buffer.alloc(0),a=i(0),s=i(238),n=i(165),o=i(128),c=i(112),u=i(99),h=i(19),l=h.opcodes,p=h.types,d=h.outputLockType,f=i(7),m=i(29),g=i(6),v=i(143),y=i(26),b=i(3),w=i(321),x=i(2),k=i(22),S=i(1),_=i(4),E=i(13),{ContractType:j,ContractStatus:A}=i(5),R=i(166),I={199:{len:11,list:[6,8]},197:{len:22,list:[9,18]},198:{len:19,list:[6,15]}},O=2;class C{constructor(e){this.raw=r,this.code=[],this.indicator=w.inst(0),e&&this.fromOptions(e)}createScript(e,t=p.PUBKEYHASH){switch(this.clear(),t){case p.PUBKEY:this.$fromPubkey(e);break;case p.PUBKEYHASH:this.$fromPubkeyhash(e);break;case p.PROPEXTEND:this.$fromPkhExtend(e);break;case p.MULTISIG:var[i,r,a]=e;this.$fromMultisig(i,r,a);break;case p.SCRIPTHASH:this.$fromScripthash(e);break;case p.NULLDATA:this.$fromNulldata(e);break;case p.WITNESS:var[i,r,a]=e;this.$fromProgram(i,r,a)}return 0<this.code.length&&this.compile(),this}static createScript(e,t=p.PUBKEYHASH){return(new C).createScript(e,t)}$fromNulldata(e){a(Buffer.isBuffer(e)),a(e.length<=m.MAX_OP_RETURN,"Nulldata too large."),this.pushOp(l.OP_RETURN),this.pushData(e)}$fromPubkey(e){a(Buffer.isBuffer(e)&&(33===e.length||65===e.length)),this.code.push(n.fromPush(e)),this.code.push(n.fromOp(l.OP_CHECKSIG))}$fromPubkeyhash(e){a(Buffer.isBuffer(e)&&20===e.length),this.code.push(n.fromOp(l.OP_DUP)),this.code.push(n.fromOp(l.OP_HASH160)),this.code.push(n.fromPush(e)),this.code.push(n.fromOp(l.OP_EQUALVERIFY)),this.code.push(n.fromOp(l.OP_CHECKSIG))}$fromPkhExtend(e){a(Buffer.isBuffer(e.info)&&e.info.length<=m.MAX_OP_INFO),a(Buffer.isBuffer(e.hash)&&20===e.hash.length),this.code.push(n.fromOp(e.opcode)),this.code.push(n.fromPush(e.info)),this.code.push(n.fromOp(l.OP_DROP)),this.code.push(n.fromOp(l.OP_DUP)),this.code.push(n.fromOp(l.OP_HASH160)),this.code.push(n.fromPush(e.hash)),this.code.push(n.fromOp(l.OP_EQUALVERIFY)),this.code.push(n.fromOp(l.OP_CHECKSIG))}$fromMultisig(e,t,i){a(x.isU8(e)&&x.isU8(t)),a(Array.isArray(i)),a(i.length===t,"`n` keys are required for multisig."),a(1<=e&&e<=t),a(1<=t&&t<=15),this.clear(),this.pushSmall(e);for(const e of i.slice().sort((e,t)=>e.compare(t)))this.pushData(e);this.pushSmall(t),this.pushOp(l.OP_CHECKMULTISIG)}$fromScripthash(e){a(Buffer.isBuffer(e)&&20===e.length),this.code.push(n.fromOp(l.OP_HASH160)),this.code.push(n.fromPush(e)),this.code.push(n.fromOp(l.OP_EQUAL))}$fromProgram(e,t,i){var r;a(x.isU8(e)&&0<=e&&e<=16),a(Buffer.isBuffer(t)&&2<=t.length&&t.length<=40),i&&(r=Buffer.from(JSON.stringify(i)),a(Buffer.isBuffer(r)&&r.length<=m.MAX_OP_INFO),h.OperCodeFromType[i.oper])&&(this.code.push(n.fromOp(h.OperCodeFromType[i.oper])),this.code.push(n.fromPush(r)),this.code.push(n.fromOp(l.OP_DROP))),this.code.push(n.fromSmall(e)),this.code.push(n.fromPush(t))}get length(){return this.code.length}set length(e){return this.code.length=e,this.code.length}fromOptions(e){if(a(e,"Script data is required."),Buffer.isBuffer(e))return this.fromRaw(e);if(Array.isArray(e))return this.fromArray(e);if(e.raw){if(!e.code)return this.fromRaw(e.raw);a(Buffer.isBuffer(e.raw),"Raw must be a Buffer."),this.raw=e.raw}if(e.code){if(!e.raw)return this.fromArray(e.code);a(Array.isArray(e.code),"Code must be an array."),this.code=e.code}return this}static fromOptions(e){return(new C).fromOptions(e)}entries(){return this.code.entries()}[Symbol.iterator](){return this.code[Symbol.iterator]()}toArray(){return this.code.slice()}fromArray(e){a(Array.isArray(e)),this.clear();for(const t of e)this.push(t);return this.compile()}static fromArray(e){return(new C).fromArray(e)}toItems(){var e=[];for(const i of this.code){var t=i.toPush();if(!t)throw new Error("Non-push opcode in script.");e.push(t)}return e}fromItems(e,t=!0){a(Array.isArray(e));var i=[];if(t)this.clear();else{let e=this.shift();for(;e;)i.push(e),e=this.shift()}for(const t of e)this.pushData(t);for(const e of i)this.push(e);return this.compile()}static fromItems(e){return(new C).fromItems(e)}toStack(){return new o(this.toItems())}fromStack(e,t=!0){return this.fromItems(e.items,t)}static fromStack(e){return(new C).fromStack(e)}clone(){return(new C).inject(this)}inject(e){return this.raw=e.raw,this.code=e.code.slice(),this}equals(e){return a(C.isScript(e)),this.raw.equals(e.raw)}compare(e){return a(C.isScript(e)),this.raw.compare(e.raw)}clear(){return this.raw=r,this.code.length=0,this}inspect(){return`<Script: ${this.toString()}>`}toString(){var e=[];for(const t of this.code)e.push(t.toFormat());return e.join(" ")}toASM(e){this.isNulldata()&&(e=!1);var t=[];for(const i of this.code)t.push(i.toASM(e));return t.join(" ")}compile(){if(0===this.code.length)return this.clear();let e=0;for(const t of this.code)e+=t.getSize();var t=new _(e);for(const e of this.code)e.toWriter(t);return this.raw=t.render(),this}toWriter(e){return e.writeVarBytes(this.raw),e}toRaw(){return this.raw}toJSON(){return this.toRaw().toString("hex")}fromJSON(e){return a("string"==typeof e,"Code must be a string."),this.fromRaw(Buffer.from(e,"hex"))}static fromJSON(e){return(new C).fromJSON(e)}getSubscript(e){if(0===e)return this.clone();var t=new C;for(let r=e;r<this.code.length;r++){var i=this.code[r];if(-1===i.value)break;t.code.push(i)}return t.compile()}removeSeparators(){let e=!1;for(const t of this.code){if(-1===t.value)break;if(t.value===l.OP_CODESEPARATOR){e=!0;break}}if(!e)return this;var t=new C;for(const e of this.code){if(-1===e.value)break;e.value!==l.OP_CODESEPARATOR&&t.code.push(e)}return t.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 e=d.NOCHECK,t=-1,i=-1;var r,a;return 2<=this.code.length&&this.getOp(1)==l.OP_CHECKLOCKTIMEVERIFY&&((r=this.getInt(0,!1,5))<f.LOCKTIME_THRESHOLD?(e=d.CHECKABSOLUTEBLOCK,t=r):(e=d.CHECKABSOLUTETIME,i=r)),2<=this.code.length&&this.getOp(1)==l.OP_CHECKSEQUENCEVERIFY&&((r=this.getInt(0,!1,5))&f.SEQUENCE_DISABLE_FLAG||(a=r&f.SEQUENCE_MASK,r&f.SEQUENCE_TYPE_FLAG?(e=d.CHECKRELATIVETIME,i=a):(e=d.CHECKRELATIVEBLOCK,t=a))),[e,t,i]}execute(e,t,i,r,s,n,o){if(null==t&&(t=C.flags.STANDARD_VERIFY_FLAGS),null==o&&(o=0),this.raw.length>f.MAX_SCRIPT_SIZE)throw new c("SCRIPT_SIZE");var h=[],p=[];let d=0,m=0,v=0,y=!1;t&C.flags.VERIFY_MINIMALDATA&&(y=!0);for(let Y=0;Y<this.code.length;Y++){var b=this.code[Y];if(-1===b.value)throw new c("BAD_OPCODE",b,Y);if(b.data&&b.data.length>f.MAX_SCRIPT_PUSH)throw new c("PUSH_SIZE",b,Y);if(b.value>l.OP_16&&++m>f.MAX_SCRIPT_OPS)throw new c("OP_COUNT",b,Y);if(b.isDisabled())throw new c("DISABLED_OPCODE",b,Y);if(v&&!b.isBranch()){if(e.length+p.length>f.MAX_SCRIPT_STACK)throw new c("STACK_SIZE",b,Y)}else if(b.data){if(y&&!b.isMinimal())throw new c("MINIMALDATA",b,Y);if(e.push(b.data),e.length+p.length>f.MAX_SCRIPT_STACK)throw new c("STACK_SIZE",b,Y)}else{switch(b.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:case l.OP_ATTACH:break;case l.OP_PROMISE:this.indicator.set(O);break;case l.OP_RETURN:throw new c("OP_RETURN",b,Y);case l.OP_0:e.pushInt(0);break;case l.OP_1NEGATE:e.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:e.pushInt(b.value-80);break;case l.OP_NOP:break;case l.OP_CHECKLOCKTIMEVERIFY:if(!(t&C.flags.VERIFY_CHECKLOCKTIMEVERIFY)){if(t&C.flags.VERIFY_DISCOURAGE_UPGRADABLE_NOPS)throw new c("DISCOURAGE_UPGRADABLE_NOPS",b,Y);break}if(!i)throw new c("UNKNOWN_ERROR","No TX passed in.");if(0===e.length)throw new c("INVALID_STACK_OPERATION",b,Y);var w=e.getNum(-1,y,5);if(w.isNeg())throw new c("NEGATIVE_LOCKTIME",b,Y);if(w=w.toDouble(),i.verifyLocktime(r,w))break;throw new c("UNSATISFIED_LOCKTIME",b,Y);case l.OP_CHECKSEQUENCEVERIFY:if(!(t&C.flags.VERIFY_CHECKSEQUENCEVERIFY)){if(t&C.flags.VERIFY_DISCOURAGE_UPGRADABLE_NOPS)throw new c("DISCOURAGE_UPGRADABLE_NOPS",b,Y);break}if(!i)throw new c("UNKNOWN_ERROR","No TX passed in.");if(0===e.length)throw new c("INVALID_STACK_OPERATION",b,Y);if((w=e.getNum(-1,y,5)).isNeg())throw new c("NEGATIVE_LOCKTIME",b,Y);var x=w.toDouble();if(i.verifySequence(r,x))break;throw new c("UNSATISFIED_LOCKTIME",b,Y);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(t&C.flags.VERIFY_DISCOURAGE_UPGRADABLE_NOPS)throw new c("DISCOURAGE_UPGRADABLE_NOPS",b,Y);break;case l.OP_IF:case l.OP_NOTIF:{let i=!1;if(!v){if(e.length<1)throw new c("UNBALANCED_CONDITIONAL",b,Y);if(1===o&&t&C.flags.VERIFY_MINIMALIF){if(1<(x=e.get(-1)).length)throw new c("MINIMALIF");if(1===x.length&&1!==x[0])throw new c("MINIMALIF")}i=e.getBool(-1),b.value===l.OP_NOTIF&&(i=!i),e.pop()}h.push(i),i||(v+=1);break}case l.OP_ELSE:if(0===h.length)throw new c("UNBALANCED_CONDITIONAL",b,Y);h[h.length-1]=!h[h.length-1],h[h.length-1]?--v:v+=1;break;case l.OP_ENDIF:if(0===h.length)throw new c("UNBALANCED_CONDITIONAL",b,Y);h.pop()||--v;break;case l.OP_VERIFY:if(0===e.length)throw new c("INVALID_STACK_OPERATION",b,Y);if(!e.getBool(-1))throw new c("VERIFY",b,Y);e.pop();break;case l.OP_TOALTSTACK:if(0===e.length)throw new c("INVALID_STACK_OPERATION",b,Y);p.push(e.pop());break;case l.OP_FROMALTSTACK:if(0===p.length)throw new c("INVALID_ALTSTACK_OPERATION",b,Y);e.push(p.pop());break;case l.OP_2DROP:if(e.length<2)throw new c("INVALID_STACK_OPERATION",b,Y);e.pop(),e.pop();break;case l.OP_2DUP:if(e.length<2)throw new c("INVALID_STACK_OPERATION",b,Y);var k=e.get(-2),S=e.get(-1);e.push(k),e.push(S);break;case l.OP_3DUP:if(e.length<3)throw new c("INVALID_STACK_OPERATION",b,Y);k=e.get(-3),S=e.get(-2);var _=e.get(-1);e.push(k),e.push(S),e.push(_);break;case l.OP_2OVER:if(e.length<4)throw new c("INVALID_STACK_OPERATION",b,Y);_=e.get(-4);var E=e.get(-3);e.push(_),e.push(E);break;case l.OP_2ROT:if(e.length<6)throw new c("INVALID_STACK_OPERATION",b,Y);E=e.get(-6);var j=e.get(-5);e.erase(-6,-4),e.push(E),e.push(j);break;case l.OP_2SWAP:if(e.length<4)throw new c("INVALID_STACK_OPERATION",b,Y);e.swap(-4,-2),e.swap(-3,-1);break;case l.OP_IFDUP:if(0===e.length)throw new c("INVALID_STACK_OPERATION",b,Y);e.getBool(-1)&&(j=e.get(-1),e.push(j));break;case l.OP_DEPTH:e.pushInt(e.length);break;case l.OP_DROP:if(0===e.length)throw new c("INVALID_STACK_OPERATION",b,Y);var A=e.pop();if(this.indicator.check(O)){this.indicator.unSet(O);try{var I=JSON.parse(A.toString());new R(I,n).run(e)}catch(n){}}break;case l.OP_DUP:if(0===e.length)throw new c("INVALID_STACK_OPERATION",b,Y);e.push(e.get(-1));break;case l.OP_NIP:if(e.length<2)throw new c("INVALID_STACK_OPERATION",b,Y);e.remove(-2);break;case l.OP_OVER:if(e.length<2)throw new c("INVALID_STACK_OPERATION",b,Y);e.push(e.get(-2));break;case l.OP_PICK:case l.OP_ROLL:if(e.length<2)throw new c("INVALID_STACK_OPERATION",b,Y);if(A=e.getInt(-1,y,4),e.pop(),A<0||A>=e.length)throw new c("INVALID_STACK_OPERATION",b,Y);var N=e.get(-A-1);b.value===l.OP_ROLL&&e.remove(-A-1),e.push(N);break;case l.OP_ROT:if(e.length<3)throw new c("INVALID_STACK_OPERATION",b,Y);e.swap(-3,-2),e.swap(-2,-1);break;case l.OP_SWAP:if(e.length<2)throw new c("INVALID_STACK_OPERATION",b,Y);e.swap(-2,-1);break;case l.OP_TUCK:if(e.length<2)throw new c("INVALID_STACK_OPERATION",b,Y);e.insert(-2,e.get(-1));break;case l.OP_SIZE:if(e.length<1)throw new c("INVALID_STACK_OPERATION",b,Y);e.pushInt(e.get(-1).length);break;case l.OP_EQUAL:case l.OP_EQUALVERIFY:if(e.length<2)throw new c("INVALID_STACK_OPERATION",b,Y);N=e.get(-2);var z=e.get(-1);z=N.equals(z);if(e.pop(),e.pop(),e.pushBool(z),b.value===l.OP_EQUALVERIFY){if(!z)throw new c("EQUALVERIFY",b,Y);e.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(e.length<1)throw new c("INVALID_STACK_OPERATION",b,Y);let t,i=e.getNum(-1,y,4);switch(b.value){case l.OP_1ADD:i.iaddn(1);break;case l.OP_1SUB:i.isubn(1);break;case l.OP_NEGATE:i.ineg();break;case l.OP_ABS:i.iabs();break;case l.OP_NOT:t=i.isZero(),i=u.fromBool(t);break;case l.OP_0NOTEQUAL:t=!i.isZero(),i=u.fromBool(t);break;default:a(!1,"Fatal script error.")}e.pop(),e.pushNum(i);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(e.length<2)throw new c("INVALID_STACK_OPERATION",b,Y);var F=e.getNum(-2,y,4),L=e.getNum(-1,y,4);let t,i;switch(b.value){case l.OP_ADD:t=F.iadd(L);break;case l.OP_SUB:t=F.isub(L);break;case l.OP_BOOLAND:i=F.toBool()&&L.toBool(),t=u.fromBool(i);break;case l.OP_BOOLOR:i=F.toBool()||L.toBool(),t=u.fromBool(i);break;case l.OP_NUMEQUAL:case l.OP_NUMEQUALVERIFY:i=F.eq(L),t=u.fromBool(i);break;case l.OP_NUMNOTEQUAL:i=!F.eq(L),t=u.fromBool(i);break;case l.OP_LESSTHAN:i=F.lt(L),t=u.fromBool(i);break;case l.OP_GREATERTHAN:i=F.gt(L),t=u.fromBool(i);break;case l.OP_LESSTHANOREQUAL:i=F.lte(L),t=u.fromBool(i);break;case l.OP_GREATERTHANOREQUAL:i=F.gte(L),t=u.fromBool(i);break;case l.OP_MIN:t=u.min(F,L);break;case l.OP_MAX:t=u.max(F,L);break;default:a(!1,"Fatal script error.")}if(e.pop(),e.pop(),e.pushNum(t),b.value===l.OP_NUMEQUALVERIFY){if(!e.getBool(-1))throw new c("NUMEQUALVERIFY",b,Y);e.pop()}break}case l.OP_WITHIN:if(e.length<3)throw new c("INVALID_STACK_OPERATION",b,Y);z=e.getNum(-3,y,4);var M=e.getNum(-2,y,4),D=e.getNum(-1,y,4);M=M.lte(z)&&z.lt(D);e.pop(),e.pop(),e.pop(),e.pushBool(M);break;case l.OP_RIPEMD160:if(0===e.length)throw new c("INVALID_STACK_OPERATION",b,Y);e.push(g.ripemd160(e.pop()));break;case l.OP_SHA1:if(0===e.length)throw new c("INVALID_STACK_OPERATION",b,Y);e.push(g.sha1(e.pop()));break;case l.OP_SHA256:if(0===e.length)throw new c("INVALID_STACK_OPERATION",b,Y);e.push(g.sha256(e.pop()));break;case l.OP_HASH160:if(0===e.length)throw new c("INVALID_STACK_OPERATION",b,Y);e.push(g.hash160(e.pop()));break;case l.OP_HASH256:if(0===e.length)throw new c("INVALID_STACK_OPERATION",b,Y);e.push(g.hash256(e.pop()));break;case l.OP_CODESEPARATOR:d=Y+1;break;case l.OP_CHECKSIG:case l.OP_CHECKSIGVERIFY:{if(!i)throw new c("UNKNOWN_ERROR","No TX passed in.");if(e.length<2)throw new c("INVALID_STACK_OPERATION",b,Y);D=e.get(-2),M=e.get(-1);var H,U=this.getSubscript(d);0===o&&U.findAndDelete(D),T(D,t),P(M,t,o);let a=!1;if(0<D.length&&(H=D[D.length-1],a=B(U=i.signatureHash(r,U,s,H,o),D,M)),!a&&t&C.flags.VERIFY_NULLFAIL&&0!==D.length)throw new c("NULLFAIL",b,Y);if(e.pop(),e.pop(),e.pushBool(a),b.value===l.OP_CHECKSIGVERIFY){if(!a)throw new c("CHECKSIGVERIFY",b,Y);e.pop()}break}case l.OP_CHECKMULTISIG:case l.OP_CHECKMULTISIGVERIFY:{if(!i)throw new c("UNKNOWN_ERROR","No TX passed in.");let a=1;if(e.length<a)throw new c("INVALID_STACK_OPERATION",b,Y);let n,u,h=e.getInt(-a,y,4),p=h+2;if(h<0||h>f.MAX_MULTISIG_PUBKEYS)throw new c("PUBKEY_COUNT",b,Y);if((m+=h)>f.MAX_SCRIPT_OPS)throw new c("OP_COUNT",b,Y);if(a+=1,n=a,a+=h,e.length<a)throw new c("INVALID_STACK_OPERATION",b,Y);let g=e.getInt(-a,y,4);if(g<0||g>h)throw new c("SIG_COUNT",b,Y);if(a+=1,u=a,a+=g,e.length<a)throw new c("INVALID_STACK_OPERATION",b,Y);var q=this.getSubscript(d);for(let t=0;t<g;t++){var V=e.get(-u-t);0===o&&q.findAndDelete(V)}let v=!0;for(;v&&0<g;){var K,W=e.get(-u),$=e.get(-n);T(W,t),P($,t,o),0<W.length&&(K=W[W.length-1],B(i.signatureHash(r,q,s,K,o),W,$))&&(u+=1,--g),n+=1,--h,g>h&&(v=!1)}for(;1<a;){if(!v&&t&C.flags.VERIFY_NULLFAIL&&0===p&&0!==e.get(-1).length)throw new c("NULLFAIL",b,Y);0<p&&--p,e.pop(),--a}if(e.length<1)throw new c("INVALID_STACK_OPERATION",b,Y);if(t&C.flags.VERIFY_NULLDUMMY&&0!==e.get(-1).length)throw new c("SIG_NULLDUMMY",b,Y);if(e.pop(),e.pushBool(v),b.value===l.OP_CHECKMULTISIGVERIFY){if(!v)throw new c("CHECKMULTISIGVERIFY",b,Y);e.pop()}break}default:throw new c("BAD_OPCODE",b,Y)}if(e.length+p.length>f.MAX_SCRIPT_STACK)throw new c("STACK_SIZE",b,Y)}}if(0!==h.length)throw new c("UNBALANCED_CONDITIONAL")}findAndDelete(e){var t=n.fromPush(e);if(this.raw.length<t.getSize())return 0;let i=!1;for(const e of this.code){if(-1===e.value)break;if(e.equals(t)){i=!0;break}}if(!i)return 0;var r=[];let a=0;for(const e of this.code){if(-1===e.value)break;e.equals(t)?a+=1:r.push(e)}return this.code=r,this.compile(),a}indexOf(e){for(let i=0;i<this.code.length;i++){var t=this.code[i];if(-1===t.value)break;if(t.data&&t.data.equals(e))return i}return-1}isCode(){for(const e of this.code){if(-1===e.value)return!1;if(e.isDisabled())return!1;switch(e.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(e.value>l.OP_PROPMAX)return!1}return!0}fromAddress(e,t){"string"==typeof e&&(e=E.fromString(e)),a(e instanceof E,"Not an address.");let i=!1;if(e.isPubkeyhash())if(t&&t.oper)switch(t.oper){case j.cpRegister:this.createScript({opcode:C.opcodes.OP_CPREGISTER,hash:e.hash,info:Buffer.from(JSON.stringify(t))},C.types.PROPEXTEND);break;case j.cpChange:this.createScript({opcode:C.opcodes.OP_CPCHANGE,hash:e.hash,info:Buffer.from(JSON.stringify(t))},C.types.PROPEXTEND);break;case j.propCreate:this.createScript({opcode:C.opcodes.OP_PROPCREATE,hash:e.hash,info:Buffer.from(JSON.stringify(t))},C.types.PROPEXTEND);break;case j.attach:this.createScript({opcode:C.opcodes.OP_ATTACH,hash:e.hash,info:Buffer.from(JSON.stringify(t))},C.types.PROPEXTEND);break;case j.propExchange:this.createScript({opcode:C.opcodes.OP_PROPEXCHANGE,hash:e.hash,info:Buffer.from(JSON.stringify(t))},C.types.PROPEXTEND);break;case j.coinbase:this.createScript({opcode:C.opcodes.OP_COINBASE,hash:e.hash,info:Buffer.from(JSON.stringify(t))},C.types.PROPEXTEND)}else this.createScript(e.hash);else e.isScripthash()?this.createScript(e.hash,C.types.SCRIPTHASH):e.isProgram()&&this.createScript([e.version,e.hash,t],C.types.WITNESS);if(t&&t.locktype&&(!t.oper||h.unspendableCodes.indexOf(t.oper)<0))switch(t.locktype){case d.CHECKABSOLUTEBLOCK:case d.CHECKABSOLUTETIME:this.code.unshift(n.fromOp(l.OP_DROP)),this.code.unshift(n.fromOp(l.OP_CHECKLOCKTIMEVERIFY)),this.code.unshift(n.fromInt(t.locktime)),i=!0;break;case d.CHECKRELATIVEBLOCK:case d.CHECKRELATIVETIME:t.locktype===d.CHECKRELATIVETIME&&(t.locktime=t.locktime|f.SEQUENCE_TYPE_FLAG),this.code.unshift(n.fromOp(l.OP_DROP)),this.code.unshift(n.fromOp(l.OP_CHECKSEQUENCEVERIFY)),this.code.unshift(n.fromInt(t.locktime)),i=!0}if(i&&this.compile(),0<this.code.length)return this;throw new Error("Unknown address type.")}static fromAddress(e,t){return(new C).fromAddress(e,t)}fromCommitment(e,t){var i=new _(36);return i.writeU32BE(2854332909),i.writeHash(e),this.clear(),this.pushOp(l.OP_RETURN),this.pushData(i.render()),t&&this.pushData(t),this.compile()}static fromCommitment(e,t){return(new C).fromCommitment(e,t)}getRedeem(){let e=null;for(const t of this.code){if(-1===t.value)return null;if(t.value>l.OP_16)return null;e=t.data}return e?C.fromRaw(e):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(e){return e?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===(e=this.getLength(0))||65===e)&&this.getOp(1)===l.OP_CHECKSIG}isPubkeyhash(e){if(e||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 t=0;for(var i of this.code)if(i.value==l.OP_DUP){t=this.code.indexOf(i);break}return this.getOp(0+t)===l.OP_DUP&&this.getOp(1+t)===l.OP_HASH160&&20===this.getLength(2+t)&&this.getOp(3+t)===l.OP_EQUALVERIFY&&this.getOp(4+t)===l.OP_CHECKSIG}isMultisig(e){if(this.code.length<4||19<this.code.length)return!1;if(this.getOp(-1)!==l.OP_CHECKMULTISIG)return!1;var t=this.getSmall(0);if(t<1)return!1;var i=this.getSmall(-2);if(i<1||i<t)return!1;if(this.code.length!==i+3)return!1;for(let t=1;t<i+1;t++){var r=this.code[t],a=r.toLength();if(33!==a&&65!==a)return!1;if(e&&!r.isMinimal())return!1}return!0}isUnknown(){return this.getType()===p.NONSTANDARD}isStandard(){var[e,t]=this.getMultisig();return-1!==e?!(t<1||3<t||e<1||t<e):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(e){if(0===this.code.length)return!1;if(this.getOp(0)!==l.OP_RETURN)return!1;if(1!==this.code.length){if(e&&this.raw.length>m.MAX_OP_RETURN_BYTES)return!1;for(let i=1;i<this.code.length;i++){var t=this.code[i];if(-1===t.value)return!1;if(t.value>l.OP_16)return!1;if(e&&!t.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(e){if(!(this.code&&this.code[0]&&this.code[1]&&this.code[1].data))return null;if(e)if(Array.isArray(e)){let i=!1;for(var t of e)if(this.code[0].value===t){i=!0;break}if(!i)return null}else if(this.code[0].value!==e)return null;try{return x.parseJson(this.code[1].data.toString())}catch(e){return null}}getReturnType(e){if(!this.code||!this.code[0])return null;if(e)if(Array.isArray(e)){let i=!1;for(var t of e)if(this.code[0].value===t){i=!0;break}if(!i)return null}else if(this.code[0].value!==e)return null;return this.code[0].value}hash160(e){let t=g.hash160(this.toRaw());return"hex"===e?t.toString("hex"):t}sha256(e){let t=g.sha256(this.toRaw());return"hex"===e?t.toString("hex"):t}getPubkey(e){return this.isPubkey(e)?e?this.raw.slice(1,1+this.raw[0]):this.getData(0):null}getMultiPubkeyhash(){var e=I[this.getOp(0)];return e&&this.code.length==e.len?e.list.map(e=>this.getData(e)):null}getPubkeyhash(e){if(this.isPubkeyhash(e)){if(e)return this.raw.slice(3,23);for(var t of this.code)if(t.value==l.OP_CHECKSIG)return this.getData(this.code.indexOf(t)-2)}return null}getMultisig(e){return this.isMultisig(e)?[this.getSmall(0),this.getSmall(-2)]:[-1,-1]}getScripthash(){return this.isScripthash()?this.getData(1):null}getNulldata(e){if(!this.isNulldata(e))return null;for(let e=1;e<this.code.length;e++){var t=this.code[e].toPush();if(t)return t}return r}getCommitment(){return this.isCommitment()?this.raw.slice(6,38):null}getProgram(){return this.isProgram()?2==this.code.length?new s(this.getSmall(0),this.getData(1)):5==this.code.length?new s(this.getSmall(3),this.getData(4)):null:null}forWitness(){var e;return this.isProgram()?this.clone():(e=this.getPubkey())?(e=g.hash160(e),C.createScript([0,e],C.types.WITNESS)):(e=this.getPubkeyhash())?C.createScript([0,e],C.types.WITNESS):C.createScript([0,this.sha256()],C.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 e,t;return 2===this.code.length&&(e=this.getLength(0),t=this.getLength(1),9<=e)&&e<=73&&(33===t||65===t)}isUnknownInput(){return this.getInputType()===p.NONSTANDARD}isPubkeyInput(){var e;return 1===this.code.length&&9<=(e=this.getLength(0))&&e<=73}isScripthashInput(){var e;return!(this.code.length<2||!(e=this.getData(-1))||0===e.length||h.isSignatureEncoding(e)||h.isKeyEncoding(e)||!(e=C.fromRaw(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 t=1;t<this.code.length;t++){var e=this.getLength(t);if(e<9||73<e)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;var e=[];for(let t=1;t<this.code.length;t++)e.push(this.getData(t));return e}getScripthashInput(){return this.isScripthashInput()?this.getData(-1):null}getCoinbaseHeight(){return C.getCoinbaseHeight(this.raw)}static getCoinbaseHeight(e){var t;return 0===e.length?-1:e[0]>=l.OP_1&&e[0]<=l.OP_16?e[0]-80:6<e[0]?-1:(t=(e=n.fromRaw(e)).toNum())?!t.isNeg()&&e.equals(n.fromNum(t))?t.toDouble():-1:1}test(e){for(const t of this.code){if(-1===t.value)break;if(t.data&&0!==t.data.length){if(e.test(t.data))return!0;if(33==t.data.length&&e.test(g.hash160(t.data)))return!0}}return!1}isPushOnly(){for(const e of this.code){if(-1===e.value)return!1;if(e.value>l.OP_16)return!1}return!0}getSigops(e){let t=0,i=-1;for(const r of this.code){if(-1===r.value)break;switch(r.value){case l.OP_CHECKSIG:case l.OP_CHECKSIGVERIFY:t+=1;break;case l.OP_CHECKMULTISIG:case l.OP_CHECKMULTISIGVERIFY:e&&i>=l.OP_1&&i<=l.OP_16?t+=i-80:t+=f.MAX_MULTISIG_PUBKEYS}i=r.value}return t}getScripthashSigops(e){return this.isScripthash()?(e=e.getRedeem())?e.getSigops(!0):0:this.getSigops(!0)}getWitnessSigops(e,t){let i=this.getProgram();if(i||this.isScripthash()&&(e=e.getRedeem())&&(i=e.getProgram()),i&&0===i.version){if(20===i.data.length)return 1;if(32===i.data.length&&0<t.items.length)return t.getRedeem().getSigops(!0)}return 0}get(e){return e<0&&(e+=this.code.length),e<0||e>=this.code.length?null:this.code[e]}pop(){return this.code.pop()||null}shift(){return this.code.shift()||null}remove(e){return e<0&&(e+=this.code.length),e<0||e>=this.code.length||0===(e=this.code.splice(e,1)).length?null:e[0]}set(e,t){return e<0&&(e+=this.code.length),a(n.isOpcode(t)),a(0<=e&&e<=this.code.length),this.code[e]=t,this}push(e){return a(n.isOpcode(e)),this.code.push(e),this}unshift(e){return a(n.isOpcode(e)),this.code.unshift(e),this}insert(e,t){return e<0&&(e+=this.code.length),a(n.isOpcode(t)),a(0<=e&&e<=this.code.length),this.code.splice(e,0,t),this}getOp(e){return(e=this.get(e))?e.value:-1}popOp(){var e=this.pop();return e?e.value:-1}shiftOp(){var e=this.shift();return e?e.value:-1}removeOp(e){return(e=this.remove(e))?e.value:-1}setOp(e,t){return this.set(e,n.fromOp(t))}pushOp(e){return this.push(n.fromOp(e))}unshiftOp(e){return this.unshift(n.fromOp(e))}insertOp(e,t){return this.insert(e,n.fromOp(t))}getData(e){return(e=this.get(e))?e.data:null}popData(){var e=this.pop();return e?e.data:null}shiftData(){var e=this.shift();return e?e.data:null}removeData(e){return(e=this.remove(e))?e.data:null}setData(e,t){return this.set(e,n.fromData(t))}pushData(e){return this.push(n.fromData(e))}unshiftData(e){return this.unshift(n.fromData(e))}insertData(e,t){return this.insert(e,n.fromData(t))}getLength(e){return(e=this.get(e))?e.toLength():-1}getPush(e){return(e=this.get(e))?e.toPush():null}popPush(){var e=this.pop();return e?e.toPush():null}shiftPush(){var e=this.shift();return e?e.toPush():null}removePush(e){return(e=this.remove(e))?e.toPush():null}setPush(e,t){return this.set(e,n.fromPush(t))}pushPush(e){return this.push(n.fromPush(e))}unshiftPush(e){return this.unshift(n.fromPush(e))}insertPush(e,t){return this.insert(e,n.fromPush(t))}getString(e,t){return(e=this.get(e))?e.toString(t):null}popString(e){var t=this.pop();return t?t.toString(e):null}shiftString(e){var t=this.shift();return t?t.toString(e):null}removeString(e,t){return(e=this.remove(e))?e.toString(t):null}setString(e,t,i){return this.set(e,n.fromString(t,i))}pushString(e,t){return this.push(n.fromString(e,t))}unshiftString(e,t){return this.unshift(n.fromString(e,t))}insertString(e,t,i){return this.insert(e,n.fromString(t,i))}getSmall(e){return(e=this.get(e))?e.toSmall():-1}popSmall(){var e=this.pop();return e?e.toSmall():-1}shiftSmall(){var e=this.shift();return e?e.toSmall():-1}removeSmall(e){return(e=this.remove(e))?e.toSmall():-1}setSmall(e,t){return this.set(e,n.fromSmall(t))}pushSmall(e){return this.push(n.fromSmall(e))}unshiftSmall(e){return this.unshift(n.fromSmall(e))}insertSmall(e,t){return this.insert(e,n.fromSmall(t))}getNum(e,t,i){return(e=this.get(e))?e.toNum(t,i):null}popNum(e,t){var i=this.pop();return i?i.toNum(e,t):null}shiftNum(e,t){var i=this.shift();return i?i.toNum(e,t):null}removeNum(e,t,i){return(e=this.remove(e))?e.toNum(t,i):null}setNum(e,t){return this.set(e,n.fromNum(t))}pushNum(e){return this.push(n.fromNum(e))}unshiftNum(e){return this.unshift(n.fromNum(e))}insertNum(e,t){return this.insert(e,n.fromNum(t))}getInt(e,t,i){return(e=this.get(e))?e.toInt(t,i):-1}popInt(e,t){var i=this.pop();return i?i.toInt(e,t):-1}shiftInt(e,t){var i=this.shift();return i?i.toInt(e,t):-1}removeInt(e,t,i){return(e=this.remove(e))?e.toInt(t,i):-1}setInt(e,t){return this.set(e,n.fromInt(t))}pushInt(e){return this.push(n.fromInt(e))}unshiftInt(e){return this.unshift(n.fromInt(e))}insertInt(e,t){return this.insert(e,n.fromInt(t))}getBool(e){return!!(e=this.get(e))&&e.toBool()}popBool(){var e=this.pop();return!!e&&e.toBool()}shiftBool(){var e=this.shift();return!!e&&e.toBool()}removeBool(e){return!!(e=this.remove(e))&&e.toBool()}setBool(e,t){return this.set(e,n.fromBool(t))}pushBool(e){return this.push(n.fromBool(e))}unshiftBool(e){return this.unshift(n.fromBool(e))}insertBool(e,t){return this.insert(e,n.fromBool(t))}getSym(e){return(e=this.get(e))?e.toSymbol():null}popSym(){var e=this.pop();return e?e.toSymbol():null}shiftSym(){var e=this.shift();return e?e.toSymbol():null}removeSym(e){return(e=this.remove(e))?e.toSymbol():null}setSym(e,t){return this.set(e,n.fromSymbol(t))}pushSym(e){return this.push(n.fromSymbol(e))}unshiftSym(e){return this.unshift(n.fromSymbol(e))}insertSym(e,t){return this.insert(e,n.fromSymbol(t))}fromString(e){if(a("string"==typeof e),0===(e=e.trim()).length)return this;e=e.split(/\s+/);var t=new k;for(const c of e){let e=c;x.isUpperCase(e)||(e=e.toUpperCase()),x.startsWith(e,"OP_")||(e="OP_"+e);var i,r,s,o=l[e];null==o?"'"===c[0]?(a("'"===c[c.length-1],"Invalid string."),i=c.slice(1,-1),i=n.fromString(i),t.writeBytes(i.toRaw())):/^-?\d+$/.test(c)?(i=u.fromString(c,10),r=n.fromNum(i),t.writeBytes(r.toRaw())):(a(0===c.indexOf("0x"),"Unknown opcode."),r=c.substring(2),s=Buffer.from(r,"hex"),a(s.length===r.length/2,"Invalid hex string."),t.writeBytes(s)):t.writeU8(o)}return this.fromRaw(t.render())}static fromString(e){return(new C).fromString(e)}static verifyScript(e,t,i,r,s,u,h,l){if((h=null==h?C.flags.STANDARD_VERIFY_FLAGS:h)&C.flags.VERIFY_SIGPUSHONLY&&!e.isPushOnly())throw new c("SIG_PUSHONLY");null==l&&(l=A.None);let p,d=new o;if(e.execute(d,h,r,s,u,l,0),h&C.flags.VERIFY_P2SH&&(p=d.clone()),i.execute(d,h,r,s,u,l,0),0===d.length||!d.getBool(-1))throw new c("EVAL_FALSE");let f=!1;if(h&C.flags.VERIFY_WITNESS&&i.isProgram()){if(f=!0,0!==e.raw.length)throw new c("WITNESS_MALLEATED");C.verifyProgram(t,i,h,r,s,u,l),d.length=1}if(h&C.flags.VERIFY_P2SH&&i.isScripthash()){if(!e.isPushOnly())throw new c("SIG_PUSHONLY");if(0===(d=p).length)throw new c("EVAL_FALSE");i=d.pop();var m=C.fromRaw(i);if(m.execute(d,h,r,s,u,l,0),0===d.length||!d.getBool(-1))throw new c("EVAL_FALSE");if(h&C.flags.VERIFY_WITNESS&&m.isProgram()){if(f=!0,!e.raw.equals(n.fromPush(i).toRaw()))throw new c("WITNESS_MALLEATED_P2SH");C.verifyProgram(t,m,h,r,s,u,l),d.length=1}}if(h&C.flags.VERIFY_CLEANSTACK&&(a(0!=(h&C.flags.VERIFY_P2SH)),1!==d.length))throw new c("CLEANSTACK");if(h&C.flags.VERIFY_WITNESS&&(a(0!=(h&C.flags.VERIFY_P2SH)),!f)&&0<t.items.length)throw new c("WITNESS_UNEXPECTED")}static verifyProgram(e,t,i,r,s,n,o){var u=t.getProgram(),h=(a(u,"verifyProgram called on non-witness-program."),a(0!=(i&C.flags.VERIFY_WITNESS)),e.toStack());let l;if(0!==u.version){if(i&C.flags.VERIFY_MAST&&1===u.version)C.verifyMast(u,h,t,i,r,s,o);else if(i&C.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(e=h.pop(),!g.sha256(e).equals(u.data))throw new c("WITNESS_PROGRAM_MISMATCH");l=C.fromRaw(e)}else{if(20!==u.data.length)throw new c("WITNESS_PROGRAM_WRONG_LENGTH");if(2!==h.length)throw new c("WITNESS_PROGRAM_MISMATCH");l=C.createScript(u.data)}for(let e=0;e<h.length;e++)if(h.get(e).length>f.MAX_SCRIPT_PUSH)throw new c("PUSH_SIZE");if(l.execute(h,i,r,s,n,o,1),1!==h.length||!h.getBool(-1))throw new c("EVAL_FALSE")}}static verifyMast(e,t,i,r,s,n,o,u){if(a(1===e.version),a(0!=(r&C.flags.VERIFY_MAST)),t.length<4)throw new c("INVALID_MAST_STACK");var h=t.get(-1);if(h.length<1||5<h.length)throw new c("INVALID_MAST_STACK");var l=h[0];if(0===l||t.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 e=1;e<h.length;e++)m|=h[e]<<8*(e-1);if(m<0&&(m+=4294967296),0<m&&r&C.flags.DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM)throw new c("DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM");let y=new k;y.writeU32(m);var b=t.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");var x=[];for(let e=0;e<w;e++)x.push(b.slice(32*e,32*e+32));var S=t.get(-3);if(4<S.length)throw new c("INVALID_MAST_STACK");let _=0;if(0<S.length){if(0===S[S.length-1])throw new c("INVALID_MAST_STACK");for(let e=0;e<S.length;e++)_|=S[e]<<8*e;_<0&&(_+=4294967296)}if(w<32&&_>=1<<w>>>0)throw new c("INVALID_MAST_STACK");let E=new k;E.writeBytes(i.raw);for(let e=0;e<l;e++){var j=t.get(-(4+e));if(0===m&&E.offset+j.length>f.MAX_SCRIPT_SIZE)throw new c("SCRIPT_SIZE");d.writeBytes(g.hash256(j)),E.writeBytes(j)}if(d=g.hash256(d.render()),d=v.verifyBranch(d,x,_),y.writeBytes(d),!(y=g.hash256(y.render())).equals(e.data))throw new c("WITNESS_PROGRAM_MISMATCH");if(0===m){t.length-=3+l;for(let e=0;e<t.length;e++)if(t.get(e).length>f.MAX_SCRIPT_PUSH)throw new c("PUSH_SIZE");if(E=E.render(),(i=C.fromRaw(E)).execute(t,r,s,n,o,u,1),0!==t.length)throw new c("EVAL_FALSE")}}fromReader(e){return this.fromRaw(e.readVarBytes())}fromRaw(e){var t=new S(e,!0);for(this.raw=e;t.left();)this.code.push(n.fromReader(t));return this}static fromReader(e){return(new C).fromReader(e)}static fromRaw(e,t){return"string"==typeof e&&(e=Buffer.from(e,t)),(new C).fromRaw(e)}static isScript(e){return e instanceof C}}function P(e,t,i){if(a(Buffer.isBuffer(e)),a("number"==typeof t),a("number"==typeof i),t&C.flags.VERIFY_STRICTENC&&!h.isKeyEncoding(e))throw new c("PUBKEYTYPE");if(1===i&&t&C.flags.VERIFY_WITNESS_PUBKEYTYPE&&!h.isCompressedEncoding(e))throw new c("WITNESS_PUBKEYTYPE")}function T(e,t){if(a(Buffer.isBuffer(e)),a("number"==typeof t),0!==e.length){if((t&C.flags.VERIFY_DERSIG||t&C.flags.VERIFY_LOW_S||t&C.flags.VERIFY_STRICTENC)&&!h.isSignatureEncoding(e))throw new c("SIG_DER");if(t&C.flags.VERIFY_LOW_S&&!h.isLowDER(e))throw new c("SIG_HIGH_S");if(t&C.flags.VERIFY_STRICTENC&&!h.isHashType(e))throw new c("SIG_HASHTYPE")}}function B(e,t,i){return y.verify(e,t.slice(0,-1),i)}C.opcodes=h.opcodes,C.opcodesByVal=h.opcodesByVal,C.flags=h.flags,C.hashType=h.hashType,C.hashTypeByVal=h.hashTypeByVal,C.types=h.types,C.typesByVal=h.typesByVal,C.outputLockType=h.outputLockType,C.unspendableCodes=h.unspendableCodes,C.TradeType={btc:1},e.exports=C},function(e,t,i){"use strict";
|
|
41
41
|
/*!
|
|
42
42
|
* packetTypes.js - worker packets for vallnet
|
|
43
43
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -61,7 +61,7 @@ const path = require('path');var gpath = path.join(__dirname, '../../../', 'node
|
|
|
61
61
|
/*!
|
|
62
62
|
* writer.js - buffer writer for vallnet
|
|
63
63
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
64
|
-
*/const r=i(0),a=i(3),s=i(6);function n(){if(!(this instanceof n))return new n;this.ops=[],this.offset=0}function o(e,t,i,r){this.type=e,this.value=t,this.enc=i,this.size=r}n.prototype.render=function(){var e=Buffer.allocUnsafe(this.offset);let t=0;for(const i of this.ops)switch(i.type){case 0:t+=i.value;break;case 1:i.value>>>=0,t=e.writeUInt8(i.value,t,!0);break;case 2:i.value>>>=0,t=e.writeUInt16LE(i.value,t,!0);break;case 3:i.value>>>=0,t=e.writeUInt16BE(i.value,t,!0);break;case 4:i.value>>>=0,t=e.writeUInt32LE(i.value,t,!0);break;case 5:i.value>>>=0,t=e.writeUInt32BE(i.value,t,!0);break;case 6:t=a.writeU64(e,i.value,t);break;case 7:t=a.writeU64BE(e,i.value,t);break;case 8:t=a.writeU64N(e,i.value,t);break;case 9:t=a.writeU64BEN(e,i.value,t);break;case 10:t=e.writeInt8(i.value,t,!0);break;case 11:t=e.writeInt16LE(i.value,t,!0);break;case 12:t=e.writeInt16BE(i.value,t,!0);break;case 13:t=e.writeInt32LE(i.value,t,!0);break;case 14:t=e.writeInt32BE(i.value,t,!0);break;case 15:t=a.writeI64(e,i.value,t);break;case 16:t=a.writeI64BE(e,i.value,t);break;case 17:t=a.writeI64N(e,i.value,t);break;case 18:t=a.writeI64BEN(e,i.value,t);break;case 19:t=e.writeFloatLE(i.value,t,!0);break;case 20:t=e.writeFloatBE(i.value,t,!0);break;case 21:t=e.writeDoubleLE(i.value,t,!0);break;case 22:t=e.writeDoubleBE(i.value,t,!0);break;case 23:t=a.writeVarint(e,i.value,t);break;case 24:t=a.writeVarintN(e,i.value,t);break;case 25:t=a.writeVarint2(e,i.value,t);break;case 26:t=a.writeVarint2N(e,i.value,t);break;case 27:t+=i.value.copy(e,t);break;case 28:t+=e.write(i.value,t,i.enc);break;case 29:t+=s.hash256(e.slice(0,t)).copy(e,t,0,4);break;case 30:e.fill(i.value,t,t+i.size),t+=i.size;break;default:r(!1,"Bad type.")}return r(t===e.length),this.destroy(),e},n.prototype.getSize=function(){return this.offset},n.prototype.seek=function(e){this.offset+=e,this.ops.push(new o(0,e))},n.prototype.destroy=function(){this.ops.length=0,this.offset=0},n.prototype.writeU8=function(e){this.offset+=1,this.ops.push(new o(1,e))},n.prototype.writeU16=function(e){this.offset+=2,this.ops.push(new o(2,e))},n.prototype.writeU16BE=function(e){this.offset+=2,this.ops.push(new o(3,e))},n.prototype.writeU32=function(e){this.offset+=4,this.ops.push(new o(4,e))},n.prototype.writeU32BE=function(e){this.offset+=4,this.ops.push(new o(5,e))},n.prototype.writeU64=function(e){this.offset+=8,this.ops.push(new o(6,e))},n.prototype.writeU64BE=function(e){this.offset+=8,this.ops.push(new o(7,e))},n.prototype.writeU64N=function(e){this.offset+=8,this.ops.push(new o(8,e))},n.prototype.writeU64BEN=function(e){this.offset+=8,this.ops.push(new o(9,e))},n.prototype.writeI8=function(e){this.offset+=1,this.ops.push(new o(10,e))},n.prototype.writeI16=function(e){this.offset+=2,this.ops.push(new o(11,e))},n.prototype.writeI16BE=function(e){this.offset+=2,this.ops.push(new o(12,e))},n.prototype.writeI32=function(e){this.offset+=4,this.ops.push(new o(13,e))},n.prototype.writeI32BE=function(e){this.offset+=4,this.ops.push(new o(14,e))},n.prototype.writeI64=function(e){this.offset+=8,this.ops.push(new o(15,e))},n.prototype.writeI64BE=function(e){this.offset+=8,this.ops.push(new o(16,e))},n.prototype.writeI64N=function(e){this.offset+=8,this.ops.push(new o(17,e))},n.prototype.writeI64BEN=function(e){this.offset+=8,this.ops.push(new o(18,e))},n.prototype.writeFloat=function(e){this.offset+=4,this.ops.push(new o(19,e))},n.prototype.writeFloatBE=function(e){this.offset+=4,this.ops.push(new o(20,e))},n.prototype.writeDouble=function(e){this.offset+=8,this.ops.push(new o(21,e))},n.prototype.writeDoubleBE=function(e){this.offset+=8,this.ops.push(new o(22,e))},n.prototype.writeVarint=function(e){this.offset+=a.sizeVarint(e),this.ops.push(new o(23,e))},n.prototype.writeVarintN=function(e){this.offset+=a.sizeVarintN(e),this.ops.push(new o(24,e))},n.prototype.writeVarint2=function(e){this.offset+=a.sizeVarint2(e),this.ops.push(new o(25,e))},n.prototype.writeVarint2N=function(e){this.offset+=a.sizeVarint2N(e),this.ops.push(new o(26,e))},n.prototype.writeBytes=function(e){0!==e.length&&(this.offset+=e.length,this.ops.push(new o(27,e)))},n.prototype.writeVarBytes=function(e){this.offset+=a.sizeVarint(e.length),this.ops.push(new o(23,e.length)),0!==e.length&&(this.offset+=e.length,this.ops.push(new o(27,e)))},n.prototype.copy=function(e,t,i){r(t<=i),e=e.slice(t,i),this.writeBytes(e)},n.prototype.writeString=function(e,t){0!==e.length&&(this.offset+=Buffer.byteLength(e,t),this.ops.push(new o(28,e,t)))},n.prototype.writeHash=function(e){"string"!=typeof e?(r(32===e.length),this.writeBytes(e)):(r(64===e.length),this.writeString(e,"hex"))},n.prototype.writeVarString=function(e,t){var i;0===e.length?this.ops.push(new o(23,0)):(i=Buffer.byteLength(e,t),this.offset+=a.sizeVarint(i),this.offset+=i,this.ops.push(new o(23,i)),this.ops.push(new o(28,e,t)))},n.prototype.writeNullString=function(e,t){this.writeString(e,t),this.writeU8(0)},n.prototype.writeChecksum=function(){this.offset+=4,this.ops.push(new o(29))},n.prototype.fill=function(e,t){r(0<=t),0!==t&&(this.offset+=t,this.ops.push(new o(30,e,null,t)))},e.exports=n},function(e,t,i){e.exports=m;var r,a=i(10),s=i(30),n=i(8),o=i(101),c=i(57),u=i(178).DiffieHellman,h=(e=i(51),i(25)),l=i(24);try{r=i(274)}catch(e){}var p=e.InvalidAlgorithmError,d=e.KeyParseError,f={};function m(e){a.object(e,"options"),a.arrayOfObject(e.parts,"options.parts"),a.string(e.type,"options.type"),a.optionalString(e.comment,"options.comment");var t=s.info[e.type];if("object"!=typeof t)throw new p(e.type);for(var i,r={},n=0;n<e.parts.length;++n){var o=e.parts[n];r[o.name]=o}this.type=e.type,this.parts=e.parts,this.part=r,this.comment=void 0,this.source=e.source,this._rfc4253Cache=e._rfc4253Cache,this._hashCache={},this.curve=void 0,"ecdsa"===this.type?(i=this.part.curve.data.toString(),this.curve=i,i=s.curves[i].size):"ed25519"===this.type||"curve25519"===this.type?(i=256,this.curve="curve25519"):i=8*(i=(t=this.part[t.sizePart]).data.length)-h.countZeros(t.data),this.size=i}f.auto=i(275),f.pem=i(65),f.pkcs1=i(179),f.pkcs8=i(104),f.rfc4253=i(66),f.ssh=i(277),f["ssh-private"]=i(135),f.openssh=f["ssh-private"],f.dnssec=i(180),f.putty=i(181),f.ppk=f.putty,m.formats=f,m.prototype.toBuffer=function(e,t){return a.string(e=void 0===e?"ssh":e,"format"),a.object(f[e],"formats[format]"),a.optionalObject(t,"options"),"rfc4253"===e?(void 0===this._rfc4253Cache&&(this._rfc4253Cache=f.rfc4253.write(this)),this._rfc4253Cache):f[e].write(this,t)},m.prototype.toString=function(e,t){return this.toBuffer(e,t).toString()},m.prototype.hash=function(e,t){if(a.string(e,"algorithm"),a.optionalString(t,"type"),void 0===t&&(t="ssh"),e=e.toLowerCase(),void 0===s.hashAlgs[e])throw new p(e);var i,r=e+"||"+t;if(this._hashCache[r])return this._hashCache[r];if("ssh"===t)i=this.toBuffer("rfc4253");else{if("spki"!==t)throw new Error("Hash type "+t+" not supported");i=f.pkcs8.pkcs8ToBuffer(this)}return t=n.createHash(e).update(i).digest(),this._hashCache[r]=t},m.prototype.fingerprint=function(e,t){return void 0===t&&(t="ssh"),a.string(e=void 0===e?"sha256":e,"algorithm"),a.string(t,"type"),e={type:"key",hash:this.hash(e,t),algorithm:e,hashType:t},new o(e)},m.prototype.defaultHashAlgorithm=function(){var e="sha1";return"rsa"===this.type&&(e="sha256"),"dsa"===this.type&&1024<this.size&&(e="sha256"),"ed25519"===this.type&&(e="sha512"),"ecdsa"===this.type?this.size<=256?"sha256":this.size<=384?"sha384":"sha512":e},m.prototype.createVerify=function(e){if(void 0===e&&(e=this.defaultHashAlgorithm()),a.string(e,"hash algorithm"),"ed25519"===this.type&&void 0!==r)return new r.Verifier(this,e);if("curve25519"===this.type)throw new Error("Curve25519 keys are not suitable for signing or verification");var t,i,s;try{i=e.toUpperCase(),t=n.createVerify(i)}catch(t){s=t}(void 0===t||s instanceof Error&&s.message.match(/Unknown message digest/))&&(i="RSA-",i+=e.toUpperCase(),t=n.createVerify(i)),a.ok(t,"failed to create verifier");var o=t.verify.bind(t),u=this.toBuffer("pkcs8"),h=this.curve,l=this;return t.verify=function(t,i){if(c.isSignature(t,[2,0]))return t.type===l.type&&!(t.hashAlgorithm&&t.hashAlgorithm!==e||t.curve&&"ecdsa"===l.type&&t.curve!==h)&&o(u,t.toBuffer("asn1"));if("string"==typeof t||Buffer.isBuffer(t))return o(u,t,i);throw c.isSignature(t,[1,0])?new Error("signature was created by too old a version of sshpk and cannot be verified"):new TypeError("signature must be a string, Buffer, or Signature object")},t},m.prototype.createDH=m.prototype.createDiffieHellman=function(){if("rsa"===this.type)throw new Error("RSA keys do not support Diffie-Hellman");return new u(this)},m.parse=function(e,t,i){"string"!=typeof e&&a.buffer(e,"data"),a.string(t=void 0===t?"auto":t,"format"),a.optionalObject(i="string"==typeof i?{filename:i}:i,"options"),a.optionalString((i=void 0===i?{}:i).filename,"options.filename"),void 0===i.filename&&(i.filename="(unnamed)"),a.object(f[t],"formats[format]");try{var r=f[t].read(e,i);return(r=r instanceof l?r.toPublic():r).comment||(r.comment=i.filename),r}catch(e){if("KeyEncryptedError"===e.name)throw e;throw new d(i.filename,t,e)}},m.isKey=function(e,t){return h.isCompatible(e,m,t)},m.prototype._sshpkApiVersion=[1,7],m._oldVersionDetect=function(e){return a.func(e.toBuffer),a.func(e.fingerprint),e.createDH?[1,4]:e.defaultHashAlgorithm?[1,3]:e.formats.auto?[1,2]:e.formats.pkcs1?[1,1]:[1,0]}},function(e,t,i){e.exports=y;var r=i(10),a=i(12).Buffer,s=i(30),n=i(8),o=(i(101),i(57)),c=(e=i(51),i(9)),u=i(25),h=i(178),l=h.generateECDSA,p=h.generateED25519,d=i(274),f=i(103),m=i(23),g=(e.InvalidAlgorithmError,e.KeyParseError),v=(e.KeyEncryptedError,{});function y(e){r.object(e,"options"),m.call(this,e),this._pubCache=void 0}v.auto=i(275),v.pem=i(65),v.pkcs1=i(179),v.pkcs8=i(104),v.rfc4253=i(66),v["ssh-private"]=i(135),v.openssh=v["ssh-private"],v.ssh=v["ssh-private"],v.dnssec=i(180),v.putty=i(181),c.inherits(y,m),y.formats=v,y.prototype.toBuffer=function(e,t){return r.string(e=void 0===e?"pkcs1":e,"format"),r.object(v[e],"formats[format]"),r.optionalObject(t,"options"),v[e].write(this,t)},y.prototype.hash=function(e,t){return this.toPublic().hash(e,t)},y.prototype.fingerprint=function(e,t){return this.toPublic().fingerprint(e,t)},y.prototype.toPublic=function(){if(!this._pubCache){for(var e=s.info[this.type],t=[],i=0;i<e.parts.length;++i){var r=e.parts[i];t.push(this.part[r])}this._pubCache=new m({type:this.type,source:this,parts:t}),this.comment&&(this._pubCache.comment=this.comment)}return this._pubCache},y.prototype.derive=function(e){var t,i,s;if(r.string(e,"type"),"ed25519"===this.type&&"curve25519"===e)return 0===(t=this.part.k.data)[0]&&(t=t.slice(1)),s=f.box.keyPair.fromSecretKey(new Uint8Array(t)),i=a.from(s.publicKey),new y({type:"curve25519",parts:[{name:"A",data:u.mpNormalize(i)},{name:"k",data:u.mpNormalize(t)}]});if("curve25519"===this.type&&"ed25519"===e)return 0===(t=this.part.k.data)[0]&&(t=t.slice(1)),s=f.sign.keyPair.fromSeed(new Uint8Array(t)),i=a.from(s.publicKey),new y({type:"ed25519",parts:[{name:"A",data:u.mpNormalize(i)},{name:"k",data:u.mpNormalize(t)}]});throw new Error("Key derivation not supported from "+this.type+" to "+e)},y.prototype.createVerify=function(e){return this.toPublic().createVerify(e)},y.prototype.createSign=function(e){if(void 0===e&&(e=this.defaultHashAlgorithm()),r.string(e,"hash algorithm"),"ed25519"===this.type&&void 0!==d)return new d.Signer(this,e);if("curve25519"===this.type)throw new Error("Curve25519 keys are not suitable for signing or verification");var t,i,s;try{i=e.toUpperCase(),t=n.createSign(i)}catch(t){s=t}(void 0===t||s instanceof Error&&s.message.match(/Unknown message digest/))&&(i="RSA-",i+=e.toUpperCase(),t=n.createSign(i)),r.ok(t,"failed to create verifier");var c=t.sign.bind(t),u=this.toBuffer("pkcs1"),h=this.type,l=this.curve;return t.sign=function(){var t=c(u);return"string"==typeof t&&(t=a.from(t,"binary")),(t=o.parse(t,h,"asn1")).hashAlgorithm=e,t.curve=l,t},t},y.parse=function(e,t,i){"string"!=typeof e&&r.buffer(e,"data"),r.string(t=void 0===t?"auto":t,"format"),r.optionalObject(i="string"==typeof i?{filename:i}:i,"options"),r.optionalString((i=void 0===i?{}:i).filename,"options.filename"),void 0===i.filename&&(i.filename="(unnamed)"),r.object(v[t],"formats[format]");try{var a=v[t].read(e,i);return r.ok(a instanceof y,"key is not a private key"),a.comment||(a.comment=i.filename),a}catch(e){if("KeyEncryptedError"===e.name)throw e;throw new g(i.filename,t,e)}},y.isPrivateKey=function(e,t){return u.isCompatible(e,y,t)},y.generate=function(e,t){switch(r.object(t=void 0===t?{}:t,"options"),e){case"ecdsa":return void 0===t.curve&&(t.curve="nistp256"),r.string(t.curve,"options.curve"),l(t.curve);case"ed25519":return p();default:throw new Error('Key generation not supported with key type "'+e+'"')}},y.prototype._sshpkApiVersion=[1,6],y._oldVersionDetect=function(e){return r.func(e.toPublic),r.func(e.createSign),e.derive?[1,3]:e.defaultHashAlgorithm?[1,2]:e.formats.auto?[1,1]:[1,0]}},function(e,t,i){e.exports={bufferSplit:function(e,t){r.buffer(e),r.string(t);for(var i=[],a=0,s=0,n=0;n<e.length;++n){var o;e[n]===t.charCodeAt(s)?++s:s=e[n]===t.charCodeAt(0)?1:0,s>=t.length&&(o=n+1,i.push(e.slice(a,o-s)),a=o,s=0)}return a<=e.length&&i.push(e.slice(a,e.length)),i},addRSAMissing:function(e){r.object(e),f(e,s,[1,1]);var t,i,a=new l(e.part.d.data);e.part.dmodp||(t=new l(e.part.p.data),t=y(t=a.mod(t.subtract(1))),e.part.dmodp={name:"dmodp",data:t},e.parts.push(e.part.dmodp)),e.part.dmodq||(i=new l(e.part.q.data),t=y(a=a.mod(i.subtract(1))),e.part.dmodq={name:"dmodq",data:t},e.parts.push(e.part.dmodq))},calculateDSAPublic:function(e,t,i){return r.buffer(e),r.buffer(t),r.buffer(i),e=new l(e),t=new l(t),i=new l(i),y(e.modPow(i,t))},calculateED25519Public:function(e){return r.buffer(e),e=p.sign.keyPair.fromSeed(new Uint8Array(e)),a.from(e.publicKey)},calculateX25519Public:function(e){return r.buffer(e),e=p.box.keyPair.fromSeed(new Uint8Array(e)),a.from(e.publicKey)},mpNormalize:v,mpDenormalize:function(e){for(r.buffer(e);1<e.length&&0===e[0];)e=e.slice(1);return e},ecNormalize:function(e,t){if(r.buffer(e),0===e[0]&&4===e[1])return t?e:e.slice(1);if(4!==e[0]){for(;0===e[0];)e=e.slice(1);if(2===e[0]||3===e[0])throw new Error("Compressed elliptic curve points are not supported");if(4!==e[0])throw new Error("Not a valid elliptic curve point")}return t?((t=a.alloc(e.length+1))[0]=0,e.copy(t,1),t):e},countZeros:function(e){for(var t=0,i=8;t<e.length;){var r=1<<i;if((e[t]&r)==r)break;--i<0&&(t++,i=8)}return 8*t+(8-i)-1},assertCompatible:f,isCompatible:function(e,t,i){if(null===e||"object"!=typeof e)return!1;if(void 0===i&&(i=t.prototype._sshpkApiVersion),e instanceof t&&t.prototype._sshpkApiVersion[0]==i[0])return!0;for(var r=Object.getPrototypeOf(e),a=0;r.constructor.name!==t.name;)if(!(r=Object.getPrototypeOf(r))||++a>d)return!1;if(r.constructor.name!==t.name)return!1;var s=r._sshpkApiVersion;return void 0===s&&(s=t._oldVersionDetect(e)),!(s[0]!=i[0]||s[1]<i[1])},opensslKeyDeriv:function(e,t,i,s){r.buffer(t,"salt"),r.buffer(i,"passphrase"),r.number(s,"iteration count");for(var n,c,u,h=m[e],l=(r.object(h,"supported cipher"),t=t.slice(0,g),a.alloc(0));l.length<h.key+h.iv;){u=[],c&&u.push(c),u.push(i),u.push(t),n=a.concat(u);for(var p=0;p<s;++p)n=o.createHash("md5").update(n).digest();l=a.concat([l,n]),c=n}return{key:l.slice(0,h.key),iv:l.slice(h.key,h.key+h.iv)}},opensshCipherInfo:function(e){var t={};switch(e){case"3des-cbc":t.keySize=24,t.blockSize=8,t.opensslName="des-ede3-cbc";break;case"blowfish-cbc":t.keySize=16,t.blockSize=8,t.opensslName="bf-cbc";break;case"aes128-cbc":case"aes128-ctr":case"aes128-gcm@openssh.com":t.keySize=16,t.blockSize=16,t.opensslName="aes-128-"+e.slice(7,10);break;case"aes192-cbc":case"aes192-ctr":case"aes192-gcm@openssh.com":t.keySize=24,t.blockSize=16,t.opensslName="aes-192-"+e.slice(7,10);break;case"aes256-cbc":case"aes256-ctr":case"aes256-gcm@openssh.com":t.keySize=32,t.blockSize=16,t.opensslName="aes-256-"+e.slice(7,10);break;default:throw new Error('Unsupported openssl cipher "'+e+'"')}return t},publicFromPrivateECDSA:function(e,t){r.string(e,"curveName"),r.buffer(t);var i=c.curves[e],s=new l(i.p),o=new l(i.a),u=new l(i.b);o=(s=new h.ECCurveFp(s,o,u)).decodePointHex(i.G.toString("hex")),u=new l(v(t)),i=o.multiply(u);return(t=(i=a.from(s.encodePointHex(i),"hex"),[])).push({name:"curve",data:a.from(e)}),t.push({name:"Q",data:i}),new n({type:"ecdsa",curve:s,parts:t})},zeroPadToLength:function(e,t){for(r.buffer(e),r.number(t);e.length>t;)r.equal(e[0],0),e=e.slice(1);for(;e.length<t;){var i=a.alloc(e.length+1);i[0]=0,e.copy(i,1),e=i}return e},writeBitString:function(e,t,i){void 0===i&&(i=u.Ber.BitString);var r=a.alloc(t.length+1);r[0]=0,t.copy(r,1),e.writeBuffer(r,i)},readBitString:function(e,t){return void 0===t&&(t=u.Ber.BitString),e=e.readString(t,!0),r.strictEqual(e[0],0,"bit strings with unused bits are not supported (0x"+e[0].toString(16)+")"),e.slice(1)},pbkdf2:function(e,t,i,r,s){for(var n=a.alloc(t.length+4),c=(t.copy(n),0),u=[],h=1;c<r;){var l=function(t){n.writeUInt32BE(t,n.length-4);for(var r=o.createHmac(e,s),a=(r.update(n),r.digest()),c=a,u=1;u++<i;){(r=o.createHmac(e,s)).update(c),c=r.digest();for(var h=0;h<a.length;++h)a[h]^=c[h]}return a}(h++);c+=l.length,u.push(l)}return a.concat(u).slice(0,r)}};var r=i(10),a=i(12).Buffer,s=i(24),n=i(23),o=i(8),c=i(30),u=i(58),h=i(134),l=i(102).BigInteger,p=i(103),d=3;function f(e,t,i,a){if(r.ok(e,(a=void 0===a?"object":a)+" must not be null"),r.object(e,a+" must be an object"),void 0===i&&(i=t.prototype._sshpkApiVersion),!(e instanceof t&&t.prototype._sshpkApiVersion[0]==i[0])){for(var s=Object.getPrototypeOf(e),n=0;s.constructor.name!==t.name;)s=Object.getPrototypeOf(s),r.ok(s&&++n<=d,a+" must be a "+t.name+" instance");r.strictEqual(s.constructor.name,t.name,a+" must be a "+t.name+" instance");var o=s._sshpkApiVersion;void 0===o&&(o=t._oldVersionDetect(e)),r.ok(o[0]==i[0]&&o[1]>=i[1],a+" must be compatible with "+t.name+" klass version "+i[0]+"."+i[1])}}var m={"des-ede3-cbc":{key:24,iv:8},"aes-128-cbc":{key:16,iv:16},"aes-256-cbc":{key:32,iv:16}},g=8;function v(e){for(r.buffer(e);1<e.length&&0===e[0]&&0==(128&e[1]);)e=e.slice(1);var t;return 128==(128&e[0])&&((t=a.alloc(e.length+1))[0]=0,e.copy(t,1),e=t),e}function y(e){return v(a.from(e.toByteArray()))}},function(e,t,i){"use strict";
|
|
64
|
+
*/const r=i(0),a=i(3),s=i(6);function n(){if(!(this instanceof n))return new n;this.ops=[],this.offset=0}function o(e,t,i,r){this.type=e,this.value=t,this.enc=i,this.size=r}n.prototype.render=function(){var e=Buffer.allocUnsafe(this.offset);let t=0;for(const i of this.ops)switch(i.type){case 0:t+=i.value;break;case 1:i.value>>>=0,t=e.writeUInt8(i.value,t,!0);break;case 2:i.value>>>=0,t=e.writeUInt16LE(i.value,t,!0);break;case 3:i.value>>>=0,t=e.writeUInt16BE(i.value,t,!0);break;case 4:i.value>>>=0,t=e.writeUInt32LE(i.value,t,!0);break;case 5:i.value>>>=0,t=e.writeUInt32BE(i.value,t,!0);break;case 6:t=a.writeU64(e,i.value,t);break;case 7:t=a.writeU64BE(e,i.value,t);break;case 8:t=a.writeU64N(e,i.value,t);break;case 9:t=a.writeU64BEN(e,i.value,t);break;case 10:t=e.writeInt8(i.value,t,!0);break;case 11:t=e.writeInt16LE(i.value,t,!0);break;case 12:t=e.writeInt16BE(i.value,t,!0);break;case 13:t=e.writeInt32LE(i.value,t,!0);break;case 14:t=e.writeInt32BE(i.value,t,!0);break;case 15:t=a.writeI64(e,i.value,t);break;case 16:t=a.writeI64BE(e,i.value,t);break;case 17:t=a.writeI64N(e,i.value,t);break;case 18:t=a.writeI64BEN(e,i.value,t);break;case 19:t=e.writeFloatLE(i.value,t,!0);break;case 20:t=e.writeFloatBE(i.value,t,!0);break;case 21:t=e.writeDoubleLE(i.value,t,!0);break;case 22:t=e.writeDoubleBE(i.value,t,!0);break;case 23:t=a.writeVarint(e,i.value,t);break;case 24:t=a.writeVarintN(e,i.value,t);break;case 25:t=a.writeVarint2(e,i.value,t);break;case 26:t=a.writeVarint2N(e,i.value,t);break;case 27:t+=i.value.copy(e,t);break;case 28:t+=e.write(i.value,t,i.enc);break;case 29:t+=s.hash256(e.slice(0,t)).copy(e,t,0,4);break;case 30:e.fill(i.value,t,t+i.size),t+=i.size;break;default:r(!1,"Bad type.")}return r(t===e.length),this.destroy(),e},n.prototype.getSize=function(){return this.offset},n.prototype.seek=function(e){this.offset+=e,this.ops.push(new o(0,e))},n.prototype.destroy=function(){this.ops.length=0,this.offset=0},n.prototype.writeU8=function(e){this.offset+=1,this.ops.push(new o(1,e))},n.prototype.writeU16=function(e){this.offset+=2,this.ops.push(new o(2,e))},n.prototype.writeU16BE=function(e){this.offset+=2,this.ops.push(new o(3,e))},n.prototype.writeU32=function(e){this.offset+=4,this.ops.push(new o(4,e))},n.prototype.writeU32BE=function(e){this.offset+=4,this.ops.push(new o(5,e))},n.prototype.writeU64=function(e){this.offset+=8,this.ops.push(new o(6,e))},n.prototype.writeU64BE=function(e){this.offset+=8,this.ops.push(new o(7,e))},n.prototype.writeU64N=function(e){this.offset+=8,this.ops.push(new o(8,e))},n.prototype.writeU64BEN=function(e){this.offset+=8,this.ops.push(new o(9,e))},n.prototype.writeI8=function(e){this.offset+=1,this.ops.push(new o(10,e))},n.prototype.writeI16=function(e){this.offset+=2,this.ops.push(new o(11,e))},n.prototype.writeI16BE=function(e){this.offset+=2,this.ops.push(new o(12,e))},n.prototype.writeI32=function(e){this.offset+=4,this.ops.push(new o(13,e))},n.prototype.writeI32BE=function(e){this.offset+=4,this.ops.push(new o(14,e))},n.prototype.writeI64=function(e){this.offset+=8,this.ops.push(new o(15,e))},n.prototype.writeI64BE=function(e){this.offset+=8,this.ops.push(new o(16,e))},n.prototype.writeI64N=function(e){this.offset+=8,this.ops.push(new o(17,e))},n.prototype.writeI64BEN=function(e){this.offset+=8,this.ops.push(new o(18,e))},n.prototype.writeFloat=function(e){this.offset+=4,this.ops.push(new o(19,e))},n.prototype.writeFloatBE=function(e){this.offset+=4,this.ops.push(new o(20,e))},n.prototype.writeDouble=function(e){this.offset+=8,this.ops.push(new o(21,e))},n.prototype.writeDoubleBE=function(e){this.offset+=8,this.ops.push(new o(22,e))},n.prototype.writeVarint=function(e){this.offset+=a.sizeVarint(e),this.ops.push(new o(23,e))},n.prototype.writeVarintN=function(e){this.offset+=a.sizeVarintN(e),this.ops.push(new o(24,e))},n.prototype.writeVarint2=function(e){this.offset+=a.sizeVarint2(e),this.ops.push(new o(25,e))},n.prototype.writeVarint2N=function(e){this.offset+=a.sizeVarint2N(e),this.ops.push(new o(26,e))},n.prototype.writeBytes=function(e){0!==e.length&&(this.offset+=e.length,this.ops.push(new o(27,e)))},n.prototype.writeVarBytes=function(e){this.offset+=a.sizeVarint(e.length),this.ops.push(new o(23,e.length)),0!==e.length&&(this.offset+=e.length,this.ops.push(new o(27,e)))},n.prototype.copy=function(e,t,i){r(t<=i),e=e.slice(t,i),this.writeBytes(e)},n.prototype.writeString=function(e,t){0!==e.length&&(this.offset+=Buffer.byteLength(e,t),this.ops.push(new o(28,e,t)))},n.prototype.writeHash=function(e){"string"!=typeof e?(r(32===e.length),this.writeBytes(e)):(r(64===e.length),this.writeString(e,"hex"))},n.prototype.writeVarString=function(e,t){var i;0===e.length?this.ops.push(new o(23,0)):(i=Buffer.byteLength(e,t),this.offset+=a.sizeVarint(i),this.offset+=i,this.ops.push(new o(23,i)),this.ops.push(new o(28,e,t)))},n.prototype.writeNullString=function(e,t){this.writeString(e,t),this.writeU8(0)},n.prototype.writeChecksum=function(){this.offset+=4,this.ops.push(new o(29))},n.prototype.fill=function(e,t){r(0<=t),0!==t&&(this.offset+=t,this.ops.push(new o(30,e,null,t)))},e.exports=n},function(e,t,i){e.exports=m;var r,a=i(10),s=i(30),n=i(8),o=i(101),c=i(57),u=i(178).DiffieHellman,h=(e=i(51),i(25)),l=i(24);try{r=i(274)}catch(e){}var p=e.InvalidAlgorithmError,d=e.KeyParseError,f={};function m(e){a.object(e,"options"),a.arrayOfObject(e.parts,"options.parts"),a.string(e.type,"options.type"),a.optionalString(e.comment,"options.comment");var t=s.info[e.type];if("object"!=typeof t)throw new p(e.type);for(var i,r={},n=0;n<e.parts.length;++n){var o=e.parts[n];r[o.name]=o}this.type=e.type,this.parts=e.parts,this.part=r,this.comment=void 0,this.source=e.source,this._rfc4253Cache=e._rfc4253Cache,this._hashCache={},this.curve=void 0,"ecdsa"===this.type?(i=this.part.curve.data.toString(),this.curve=i,i=s.curves[i].size):"ed25519"===this.type||"curve25519"===this.type?(i=256,this.curve="curve25519"):i=8*(i=(t=this.part[t.sizePart]).data.length)-h.countZeros(t.data),this.size=i}f.auto=i(275),f.pem=i(65),f.pkcs1=i(179),f.pkcs8=i(104),f.rfc4253=i(66),f.ssh=i(277),f["ssh-private"]=i(134),f.openssh=f["ssh-private"],f.dnssec=i(180),f.putty=i(181),f.ppk=f.putty,m.formats=f,m.prototype.toBuffer=function(e,t){return a.string(e=void 0===e?"ssh":e,"format"),a.object(f[e],"formats[format]"),a.optionalObject(t,"options"),"rfc4253"===e?(void 0===this._rfc4253Cache&&(this._rfc4253Cache=f.rfc4253.write(this)),this._rfc4253Cache):f[e].write(this,t)},m.prototype.toString=function(e,t){return this.toBuffer(e,t).toString()},m.prototype.hash=function(e,t){if(a.string(e,"algorithm"),a.optionalString(t,"type"),void 0===t&&(t="ssh"),e=e.toLowerCase(),void 0===s.hashAlgs[e])throw new p(e);var i,r=e+"||"+t;if(this._hashCache[r])return this._hashCache[r];if("ssh"===t)i=this.toBuffer("rfc4253");else{if("spki"!==t)throw new Error("Hash type "+t+" not supported");i=f.pkcs8.pkcs8ToBuffer(this)}return t=n.createHash(e).update(i).digest(),this._hashCache[r]=t},m.prototype.fingerprint=function(e,t){return void 0===t&&(t="ssh"),a.string(e=void 0===e?"sha256":e,"algorithm"),a.string(t,"type"),e={type:"key",hash:this.hash(e,t),algorithm:e,hashType:t},new o(e)},m.prototype.defaultHashAlgorithm=function(){var e="sha1";return"rsa"===this.type&&(e="sha256"),"dsa"===this.type&&1024<this.size&&(e="sha256"),"ed25519"===this.type&&(e="sha512"),"ecdsa"===this.type?this.size<=256?"sha256":this.size<=384?"sha384":"sha512":e},m.prototype.createVerify=function(e){if(void 0===e&&(e=this.defaultHashAlgorithm()),a.string(e,"hash algorithm"),"ed25519"===this.type&&void 0!==r)return new r.Verifier(this,e);if("curve25519"===this.type)throw new Error("Curve25519 keys are not suitable for signing or verification");var t,i,s;try{i=e.toUpperCase(),t=n.createVerify(i)}catch(t){s=t}(void 0===t||s instanceof Error&&s.message.match(/Unknown message digest/))&&(i="RSA-",i+=e.toUpperCase(),t=n.createVerify(i)),a.ok(t,"failed to create verifier");var o=t.verify.bind(t),u=this.toBuffer("pkcs8"),h=this.curve,l=this;return t.verify=function(t,i){if(c.isSignature(t,[2,0]))return t.type===l.type&&!(t.hashAlgorithm&&t.hashAlgorithm!==e||t.curve&&"ecdsa"===l.type&&t.curve!==h)&&o(u,t.toBuffer("asn1"));if("string"==typeof t||Buffer.isBuffer(t))return o(u,t,i);throw c.isSignature(t,[1,0])?new Error("signature was created by too old a version of sshpk and cannot be verified"):new TypeError("signature must be a string, Buffer, or Signature object")},t},m.prototype.createDH=m.prototype.createDiffieHellman=function(){if("rsa"===this.type)throw new Error("RSA keys do not support Diffie-Hellman");return new u(this)},m.parse=function(e,t,i){"string"!=typeof e&&a.buffer(e,"data"),a.string(t=void 0===t?"auto":t,"format"),a.optionalObject(i="string"==typeof i?{filename:i}:i,"options"),a.optionalString((i=void 0===i?{}:i).filename,"options.filename"),void 0===i.filename&&(i.filename="(unnamed)"),a.object(f[t],"formats[format]");try{var r=f[t].read(e,i);return(r=r instanceof l?r.toPublic():r).comment||(r.comment=i.filename),r}catch(e){if("KeyEncryptedError"===e.name)throw e;throw new d(i.filename,t,e)}},m.isKey=function(e,t){return h.isCompatible(e,m,t)},m.prototype._sshpkApiVersion=[1,7],m._oldVersionDetect=function(e){return a.func(e.toBuffer),a.func(e.fingerprint),e.createDH?[1,4]:e.defaultHashAlgorithm?[1,3]:e.formats.auto?[1,2]:e.formats.pkcs1?[1,1]:[1,0]}},function(e,t,i){e.exports=y;var r=i(10),a=i(12).Buffer,s=i(30),n=i(8),o=(i(101),i(57)),c=(e=i(51),i(9)),u=i(25),h=i(178),l=h.generateECDSA,p=h.generateED25519,d=i(274),f=i(103),m=i(23),g=(e.InvalidAlgorithmError,e.KeyParseError),v=(e.KeyEncryptedError,{});function y(e){r.object(e,"options"),m.call(this,e),this._pubCache=void 0}v.auto=i(275),v.pem=i(65),v.pkcs1=i(179),v.pkcs8=i(104),v.rfc4253=i(66),v["ssh-private"]=i(134),v.openssh=v["ssh-private"],v.ssh=v["ssh-private"],v.dnssec=i(180),v.putty=i(181),c.inherits(y,m),y.formats=v,y.prototype.toBuffer=function(e,t){return r.string(e=void 0===e?"pkcs1":e,"format"),r.object(v[e],"formats[format]"),r.optionalObject(t,"options"),v[e].write(this,t)},y.prototype.hash=function(e,t){return this.toPublic().hash(e,t)},y.prototype.fingerprint=function(e,t){return this.toPublic().fingerprint(e,t)},y.prototype.toPublic=function(){if(!this._pubCache){for(var e=s.info[this.type],t=[],i=0;i<e.parts.length;++i){var r=e.parts[i];t.push(this.part[r])}this._pubCache=new m({type:this.type,source:this,parts:t}),this.comment&&(this._pubCache.comment=this.comment)}return this._pubCache},y.prototype.derive=function(e){var t,i,s;if(r.string(e,"type"),"ed25519"===this.type&&"curve25519"===e)return 0===(t=this.part.k.data)[0]&&(t=t.slice(1)),s=f.box.keyPair.fromSecretKey(new Uint8Array(t)),i=a.from(s.publicKey),new y({type:"curve25519",parts:[{name:"A",data:u.mpNormalize(i)},{name:"k",data:u.mpNormalize(t)}]});if("curve25519"===this.type&&"ed25519"===e)return 0===(t=this.part.k.data)[0]&&(t=t.slice(1)),s=f.sign.keyPair.fromSeed(new Uint8Array(t)),i=a.from(s.publicKey),new y({type:"ed25519",parts:[{name:"A",data:u.mpNormalize(i)},{name:"k",data:u.mpNormalize(t)}]});throw new Error("Key derivation not supported from "+this.type+" to "+e)},y.prototype.createVerify=function(e){return this.toPublic().createVerify(e)},y.prototype.createSign=function(e){if(void 0===e&&(e=this.defaultHashAlgorithm()),r.string(e,"hash algorithm"),"ed25519"===this.type&&void 0!==d)return new d.Signer(this,e);if("curve25519"===this.type)throw new Error("Curve25519 keys are not suitable for signing or verification");var t,i,s;try{i=e.toUpperCase(),t=n.createSign(i)}catch(t){s=t}(void 0===t||s instanceof Error&&s.message.match(/Unknown message digest/))&&(i="RSA-",i+=e.toUpperCase(),t=n.createSign(i)),r.ok(t,"failed to create verifier");var c=t.sign.bind(t),u=this.toBuffer("pkcs1"),h=this.type,l=this.curve;return t.sign=function(){var t=c(u);return"string"==typeof t&&(t=a.from(t,"binary")),(t=o.parse(t,h,"asn1")).hashAlgorithm=e,t.curve=l,t},t},y.parse=function(e,t,i){"string"!=typeof e&&r.buffer(e,"data"),r.string(t=void 0===t?"auto":t,"format"),r.optionalObject(i="string"==typeof i?{filename:i}:i,"options"),r.optionalString((i=void 0===i?{}:i).filename,"options.filename"),void 0===i.filename&&(i.filename="(unnamed)"),r.object(v[t],"formats[format]");try{var a=v[t].read(e,i);return r.ok(a instanceof y,"key is not a private key"),a.comment||(a.comment=i.filename),a}catch(e){if("KeyEncryptedError"===e.name)throw e;throw new g(i.filename,t,e)}},y.isPrivateKey=function(e,t){return u.isCompatible(e,y,t)},y.generate=function(e,t){switch(r.object(t=void 0===t?{}:t,"options"),e){case"ecdsa":return void 0===t.curve&&(t.curve="nistp256"),r.string(t.curve,"options.curve"),l(t.curve);case"ed25519":return p();default:throw new Error('Key generation not supported with key type "'+e+'"')}},y.prototype._sshpkApiVersion=[1,6],y._oldVersionDetect=function(e){return r.func(e.toPublic),r.func(e.createSign),e.derive?[1,3]:e.defaultHashAlgorithm?[1,2]:e.formats.auto?[1,1]:[1,0]}},function(e,t,i){e.exports={bufferSplit:function(e,t){r.buffer(e),r.string(t);for(var i=[],a=0,s=0,n=0;n<e.length;++n){var o;e[n]===t.charCodeAt(s)?++s:s=e[n]===t.charCodeAt(0)?1:0,s>=t.length&&(o=n+1,i.push(e.slice(a,o-s)),a=o,s=0)}return a<=e.length&&i.push(e.slice(a,e.length)),i},addRSAMissing:function(e){r.object(e),f(e,s,[1,1]);var t,i,a=new l(e.part.d.data);e.part.dmodp||(t=new l(e.part.p.data),t=y(t=a.mod(t.subtract(1))),e.part.dmodp={name:"dmodp",data:t},e.parts.push(e.part.dmodp)),e.part.dmodq||(i=new l(e.part.q.data),t=y(a=a.mod(i.subtract(1))),e.part.dmodq={name:"dmodq",data:t},e.parts.push(e.part.dmodq))},calculateDSAPublic:function(e,t,i){return r.buffer(e),r.buffer(t),r.buffer(i),e=new l(e),t=new l(t),i=new l(i),y(e.modPow(i,t))},calculateED25519Public:function(e){return r.buffer(e),e=p.sign.keyPair.fromSeed(new Uint8Array(e)),a.from(e.publicKey)},calculateX25519Public:function(e){return r.buffer(e),e=p.box.keyPair.fromSeed(new Uint8Array(e)),a.from(e.publicKey)},mpNormalize:v,mpDenormalize:function(e){for(r.buffer(e);1<e.length&&0===e[0];)e=e.slice(1);return e},ecNormalize:function(e,t){if(r.buffer(e),0===e[0]&&4===e[1])return t?e:e.slice(1);if(4!==e[0]){for(;0===e[0];)e=e.slice(1);if(2===e[0]||3===e[0])throw new Error("Compressed elliptic curve points are not supported");if(4!==e[0])throw new Error("Not a valid elliptic curve point")}return t?((t=a.alloc(e.length+1))[0]=0,e.copy(t,1),t):e},countZeros:function(e){for(var t=0,i=8;t<e.length;){var r=1<<i;if((e[t]&r)==r)break;--i<0&&(t++,i=8)}return 8*t+(8-i)-1},assertCompatible:f,isCompatible:function(e,t,i){if(null===e||"object"!=typeof e)return!1;if(void 0===i&&(i=t.prototype._sshpkApiVersion),e instanceof t&&t.prototype._sshpkApiVersion[0]==i[0])return!0;for(var r=Object.getPrototypeOf(e),a=0;r.constructor.name!==t.name;)if(!(r=Object.getPrototypeOf(r))||++a>d)return!1;if(r.constructor.name!==t.name)return!1;var s=r._sshpkApiVersion;return void 0===s&&(s=t._oldVersionDetect(e)),!(s[0]!=i[0]||s[1]<i[1])},opensslKeyDeriv:function(e,t,i,s){r.buffer(t,"salt"),r.buffer(i,"passphrase"),r.number(s,"iteration count");for(var n,c,u,h=m[e],l=(r.object(h,"supported cipher"),t=t.slice(0,g),a.alloc(0));l.length<h.key+h.iv;){u=[],c&&u.push(c),u.push(i),u.push(t),n=a.concat(u);for(var p=0;p<s;++p)n=o.createHash("md5").update(n).digest();l=a.concat([l,n]),c=n}return{key:l.slice(0,h.key),iv:l.slice(h.key,h.key+h.iv)}},opensshCipherInfo:function(e){var t={};switch(e){case"3des-cbc":t.keySize=24,t.blockSize=8,t.opensslName="des-ede3-cbc";break;case"blowfish-cbc":t.keySize=16,t.blockSize=8,t.opensslName="bf-cbc";break;case"aes128-cbc":case"aes128-ctr":case"aes128-gcm@openssh.com":t.keySize=16,t.blockSize=16,t.opensslName="aes-128-"+e.slice(7,10);break;case"aes192-cbc":case"aes192-ctr":case"aes192-gcm@openssh.com":t.keySize=24,t.blockSize=16,t.opensslName="aes-192-"+e.slice(7,10);break;case"aes256-cbc":case"aes256-ctr":case"aes256-gcm@openssh.com":t.keySize=32,t.blockSize=16,t.opensslName="aes-256-"+e.slice(7,10);break;default:throw new Error('Unsupported openssl cipher "'+e+'"')}return t},publicFromPrivateECDSA:function(e,t){r.string(e,"curveName"),r.buffer(t);var i=c.curves[e],s=new l(i.p),o=new l(i.a),u=new l(i.b);o=(s=new h.ECCurveFp(s,o,u)).decodePointHex(i.G.toString("hex")),u=new l(v(t)),i=o.multiply(u);return(t=(i=a.from(s.encodePointHex(i),"hex"),[])).push({name:"curve",data:a.from(e)}),t.push({name:"Q",data:i}),new n({type:"ecdsa",curve:s,parts:t})},zeroPadToLength:function(e,t){for(r.buffer(e),r.number(t);e.length>t;)r.equal(e[0],0),e=e.slice(1);for(;e.length<t;){var i=a.alloc(e.length+1);i[0]=0,e.copy(i,1),e=i}return e},writeBitString:function(e,t,i){void 0===i&&(i=u.Ber.BitString);var r=a.alloc(t.length+1);r[0]=0,t.copy(r,1),e.writeBuffer(r,i)},readBitString:function(e,t){return void 0===t&&(t=u.Ber.BitString),e=e.readString(t,!0),r.strictEqual(e[0],0,"bit strings with unused bits are not supported (0x"+e[0].toString(16)+")"),e.slice(1)},pbkdf2:function(e,t,i,r,s){for(var n=a.alloc(t.length+4),c=(t.copy(n),0),u=[],h=1;c<r;){var l=function(t){n.writeUInt32BE(t,n.length-4);for(var r=o.createHmac(e,s),a=(r.update(n),r.digest()),c=a,u=1;u++<i;){(r=o.createHmac(e,s)).update(c),c=r.digest();for(var h=0;h<a.length;++h)a[h]^=c[h]}return a}(h++);c+=l.length,u.push(l)}return a.concat(u).slice(0,r)}};var r=i(10),a=i(12).Buffer,s=i(24),n=i(23),o=i(8),c=i(30),u=i(58),h=i(133),l=i(102).BigInteger,p=i(103),d=3;function f(e,t,i,a){if(r.ok(e,(a=void 0===a?"object":a)+" must not be null"),r.object(e,a+" must be an object"),void 0===i&&(i=t.prototype._sshpkApiVersion),!(e instanceof t&&t.prototype._sshpkApiVersion[0]==i[0])){for(var s=Object.getPrototypeOf(e),n=0;s.constructor.name!==t.name;)s=Object.getPrototypeOf(s),r.ok(s&&++n<=d,a+" must be a "+t.name+" instance");r.strictEqual(s.constructor.name,t.name,a+" must be a "+t.name+" instance");var o=s._sshpkApiVersion;void 0===o&&(o=t._oldVersionDetect(e)),r.ok(o[0]==i[0]&&o[1]>=i[1],a+" must be compatible with "+t.name+" klass version "+i[0]+"."+i[1])}}var m={"des-ede3-cbc":{key:24,iv:8},"aes-128-cbc":{key:16,iv:16},"aes-256-cbc":{key:32,iv:16}},g=8;function v(e){for(r.buffer(e);1<e.length&&0===e[0]&&0==(128&e[1]);)e=e.slice(1);var t;return 128==(128&e[0])&&((t=a.alloc(e.length+1))[0]=0,e.copy(t,1),e=t),e}function y(e){return v(a.from(e.toByteArray()))}},function(e,t,i){"use strict";
|
|
65
65
|
/*!
|
|
66
66
|
* secp256k1.js - ecdsa wrapper for secp256k1 and elliptic
|
|
67
67
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -141,7 +141,7 @@ let r=[];[i(558),i(559),i(560),i(561),i(562),i(563),i(564),i(565),i(566),i(567),
|
|
|
141
141
|
/*!
|
|
142
142
|
* coinview.js - coin viewpoint object for vallnet
|
|
143
143
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
144
|
-
*/const r=i(322),a=i(247),s=i(
|
|
144
|
+
*/const r=i(322),a=i(247),s=i(145);e.exports=class e{constructor(){this.map=new Map,this.undo=new a}clone(){var t,i,r=new e;for([t,i]of this.map)r.map.set(t,i.clone());return r.undo=a.fromRaw(this.undo.toRaw()),r}get(e){return this.map.get(e)}has(e){return this.map.has(e)}add(e,t){return this.map.set(e,t),t}ensure(e){return this.map.get(e)||this.add(e,new r)}remove(e){var t=this.map.get(e);return t?(this.map.delete(e),t):null}addTX(e,t,i){var a=e.hash("hex");e=r.fromTX(e,t,i);return this.add(a,e)}removeTX(e,t,i){var a=e.hash("hex");for(const a of(e=r.fromTX(e,t,i)).outputs.values())a.spent=!0;return this.add(a,e)}addEntry(e,t){var{hash:e,index:i}=e;return this.ensure(e).add(i,t)}addIndex(e,t,i,r){var a=e.hash("hex");return this.ensure(a).add(t,s.fromTX(e,t,i,r))}addCoin(e){return this.ensure(e.hash).addCoin(e)}addOutput(e,t){var{hash:e,index:i}=e;return this.ensure(e).addOutput(i,t)}spendEntry(e){var{hash:e,index:t}=e;return(e=(e=this.get(e))&&e.spend(t))?(this.undo.push(e),e):null}removeEntry(e){var{hash:e,index:t}=e;return(e=this.get(e))?e.remove(t):null}hasEntry(e){var{hash:e,index:t}=e;return!!(e=this.get(e))&&e.has(t)}getEntry(e){var{hash:e,index:t}=e;return(e=this.get(e))?e.get(t):null}isUnspent(e){var{hash:e,index:t}=e;return!!(e=this.get(e))&&e.isUnspent(t)}getCoin(e){var t=this.get(e.hash);return t?t.getCoin(e):null}getOutput(e){var{hash:e,index:t}=e;return(e=this.get(e))?e.getOutput(t):null}getHeight(e){return(e=this.getEntry(e))?e.height:-1}isCoinbase(e){return!!(e=this.getEntry(e))&&e.coinbase}hasEntryFor(e){return this.hasEntry(e.prevout)}getEntryFor(e){return this.getEntry(e.prevout)}isUnspentFor(e){return this.isUnspent(e.prevout)}getCoinFor(e){return this.getCoin(e.prevout)}getOutputFor(e){return this.getOutput(e.prevout)}getHeightFor(e){return this.getHeight(e.prevout)}isCoinbaseFor(e){return this.isCoinbase(e.prevout)}async readCoin(e,t){var i=this.getEntry(t);return i||((i=await e.readCoin(t))?this.addEntry(t,i):null)}async readInputs(e,t){let i=!0;for(var{prevout:r}of t.inputs)await this.readCoin(e,r)||(i=!1);return i}async spendInputs(e,t){let i=0;for(;i<t.inputs.length;){for(var r=Math.min(i+4,t.inputs.length),a=[];i<r;i++){var s=t.inputs[i].prevout;a.push(this.readCoin(e,s))}for(const e of await Promise.all(a)){if(!e||e.spent)return!1;e.spent=!0,this.undo.push(e)}}return!0}getSize(e){let t=0;for(var{prevout:i}of(t+=e.inputs.length,e.inputs))(i=this.getEntry(i))&&(t+=i.getSize());return t}toWriter(e,t){for(var{prevout:i}of t.inputs)(i=this.getEntry(i))?(e.writeU8(1),i.toWriter(e)):e.writeU8(0);return e}fromReader(e,t){for(var{prevout:i}of t.inputs){var r;0!==e.readU8()&&(r=s.fromReader(e),this.addEntry(i,r))}return this}static fromReader(t,i){return(new e).fromReader(t,i)}}},function(e,t){e.exports=require("http")},function(e,t,i){"use strict";
|
|
145
145
|
/*!
|
|
146
146
|
* invitem.js - inv item object for vallnet
|
|
147
147
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -149,12 +149,12 @@ let r=[];[i(558),i(559),i(560),i(561),i(562),i(563),i(564),i(565),i(566),i(567),
|
|
|
149
149
|
/*!
|
|
150
150
|
* lru.js - LRU cache for vallnet
|
|
151
151
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
152
|
-
*/const r=i(0),a=i(258);function s(e,t){this.key=e,this.value=t,this.next=null,this.prev=null}e.exports=class{constructor(e=1e3,t){this.map=new Map,this.size=0,this.items=0,this.head=null,this.tail=null,this.pending=null,r("number"==typeof e,"Capacity must be a number."),r(0<=e,"Capacity cannot be negative."),r(!t||"function"==typeof t,"Bad size callback."),this.capacity=e,this.getSize=t}_getSize(e){return this.getSize?120+Math.floor(1.375*e.key.length)+this.getSize(e.value):1}_compact(){if(!(this.size<=this.capacity)){let e,t;for(e=this.head;e&&!(this.size<=this.capacity);e=t)this.size-=this._getSize(e),this.items--,this.map.delete(e.key),t=e.next,e.prev=null,e.next=null;e?(this.head=e).prev=null:(this.head=null,this.tail=null)}}reset(){let e,t;for(e=this.head;e;e=t)this.map.delete(e.key),this.items--,t=e.next,e.prev=null,e.next=null;r(!e),this.size=0,this.head=null,this.tail=null}set(e,t){if(0!==this.capacity){e=String(e);let i=this.map.get(e);i?(this.size-=this._getSize(i),i.value=t,this.size+=this._getSize(i),this._removeList(i),this._appendList(i)):(i=new s(e,t),this.map.set(e,i),this._appendList(i),this.size+=this._getSize(i),this.items++),this._compact()}}get(e){return 0===this.capacity?null:(e=String(e),(e=this.map.get(e))?(this._removeList(e),this._appendList(e),e.value):null)}has(e){return 0!==this.capacity&&this.map.has(String(e))}remove(e){if(0===this.capacity)return!1;e=String(e);var t=this.map.get(e);return!!t&&(this.size-=this._getSize(t),this.items--,this.map.delete(e),this._removeList(t),!0)}_prependList(e){this._insertList(null,e)}_appendList(e){this._insertList(this.tail,e)}_insertList(e,t){r(!t.next),r(!t.prev),null==e?this.head?((this.head.prev=t).next=this.head,this.head=t):(this.head=t,this.tail=t):(t.next=e.next,(t.prev=e).next=t,e===this.tail&&(this.tail=t))}_removeList(e){e.prev&&(e.prev.next=e.next),e.next&&(e.next.prev=e.prev),e===this.head&&(this.head=e.next),e===this.tail&&(this.tail=e.prev||this.head),this.head||r(!this.tail),this.tail||r(!this.head),e.prev=null,e.next=null}keys(){var e=[];for(let t=this.head;t;t=t.next)t===this.head&&r(!t.prev),t.prev||r(t===this.head),t.next||r(t===this.tail),e.push(t.key);return e}values(){var e=[];for(let t=this.head;t;t=t.next)e.push(t.value);return e}toArray(){var e=[];for(let t=this.head;t;t=t.next)e.push(t);return e}batch(){return new a(this)}start(){r(!this.pending),this.pending=this.batch()}clear(){r(this.pending),this.pending.clear()}drop(){r(this.pending),this.pending=null}commit(){r(this.pending),this.pending.commit(),this.pending=null}push(e,t){r(this.pending),0!==this.capacity&&this.pending.set(e,t)}unpush(e){r(this.pending),0!==this.capacity&&this.pending.remove(e)}}},function(e,t,i){"use strict";var r,a,s=i(76),n=s.freeze,o=(i=i(11)).inherits,c=i.notEnumerableProp;function u(e,t){function i(r){if(!(this instanceof i))return new i(r);c(this,"message","string"==typeof r?r:t),c(this,"name",e),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this)}return o(i,Error),i}i=u("Warning","warning");var h=u("CancellationError","cancellation error"),l=u("TimeoutError","timeout error"),p=u("AggregateError","aggregate error");try{r=TypeError,a=RangeError}catch(e){r=u("TypeError","type error"),a=u("RangeError","range error")}for(var d="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),f=0;f<d.length;++f)"function"==typeof Array.prototype[d[f]]&&(p.prototype[d[f]]=Array.prototype[d[f]]);s.defineProperty(p.prototype,"length",{value:0,configurable:!1,writable:!0,enumerable:!0}),p.prototype.isOperational=!0;var m=0;function g(e){if(!(this instanceof g))return new g(e);c(this,"name","OperationalError"),c(this,"message",e),this.cause=e,this.isOperational=!0,e instanceof Error?(c(this,"message",e.message),c(this,"stack",e.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}p.prototype.toString=function(){var e="\n"+Array(4*m+1).join(" ")+"AggregateError of:\n";m++;for(var t=Array(4*m+1).join(" "),i=0;i<this.length;++i){for(var r=this[i]===this?"[Circular AggregateError]":this[i]+"",a=r.split("\n"),s=0;s<a.length;++s)a[s]=t+a[s];e+=(r=a.join("\n"))+"\n"}return m--,e},o(g,Error);var v=Error.__BluebirdErrorTypes__;v||(v=n({CancellationError:h,TimeoutError:l,OperationalError:g,RejectionError:g,AggregateError:p}),s.defineProperty(Error,"__BluebirdErrorTypes__",{value:v,writable:!1,enumerable:!1,configurable:!1})),e.exports={Error:Error,TypeError:r,RangeError:a,CancellationError:v.CancellationError,OperationalError:v.OperationalError,TimeoutError:v.TimeoutError,AggregateError:v.AggregateError,Warning:i}},function(e,t,i){e.exports={read:function(e,t,i){var c=e;"string"!=typeof e&&(r.buffer(e,"buf"),e=e.toString("ascii"));for(var u,b,w=e.trim().split(/[\r\n]+/g),x=-1;!u&&x<w.length;)u=w[++x].match(/[-]+[ ]*BEGIN ([A-Z0-9][A-Za-z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/);r.ok(u,"invalid PEM header");for(var k=w.length;!b&&0<k;)b=w[--k].match(/[-]+[ ]*END ([A-Z0-9][A-Za-z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/);r.ok(b,"invalid PEM footer"),r.equal(u[2],b[2]);var S,_=u[2].toLowerCase();u[1]&&(r.equal(u[1],b[1],"PEM header and footer mismatch"),S=u[1].trim()),w=w.slice(x,k+1);for(var E,j,A,R,I={};u=(w=w.slice(1))[0].match(/^([A-Za-z0-9-]+): (.+)$/);)I[u[1].toLowerCase()]=u[2];if((w=w.slice(0,-1).join(""),e=n.from(w,"base64"),I["proc-type"])&&("4"===(O=I["proc-type"].split(","))[0]&&"ENCRYPTED"===O[1])){if("string"==typeof t.passphrase&&(t.passphrase=n.from(t.passphrase,"utf-8")),!n.isBuffer(t.passphrase))throw new f.KeyEncryptedError(t.filename,"PEM");O=I["dek-info"].split(","),r.ok(2===O.length),E=O[0].toLowerCase(),A=n.from(O[1],"hex"),j=o.opensslKeyDeriv(E,A,t.passphrase,1).key}if(S&&"encrypted"===S.toLowerCase()){var O;if((C=((O=new a.BerReader(e)).readSequence(),O.readSequence(),R=O.offset+O.length,O.readOID()))!==m)throw new Error("Unsupported PEM/PKCS8 encryption scheme: "+C);O.readSequence(),O.readSequence();var C=O.offset+O.length;if((P=O.readOID())!==g)throw new Error("Unsupported PBES2 KDF: "+P);O.readSequence();var P=O.readString(a.Ber.OctetString,!0),T=O.readInt(),B="sha1";if(O.offset<C){O.readSequence();var N=O.readOID();if(void 0===(B=y[N]))throw new Error("Unsupported PBKDF2 hash: "+N)}if(O._offset=C,O.readSequence(),N=O.readOID(),void 0===(E=v[N]))throw new Error("Unsupported PBES2 cipher: "+N);if(A=O.readString(a.Ber.OctetString,!0),O._offset=R,e=O.readString(a.Ber.OctetString,!0),"string"==typeof t.passphrase&&(t.passphrase=n.from(t.passphrase,"utf-8")),!n.isBuffer(t.passphrase))throw new f.KeyEncryptedError(t.filename,"PEM");E=(C=o.opensshCipherInfo(E)).opensslName,j=o.pbkdf2(B,P,T,C.keySize,t.passphrase),S=void 0}if(E&&j&&A){var z,F=s.createDecipheriv(E,j,A),L=[];for(F.once("error",(function(e){if(-1!==e.toString().indexOf("bad decrypt"))throw new Error("Incorrect passphrase supplied, could not decrypt key");throw e})),F.write(e),F.end();null!==(z=F.read());)L.push(z);e=n.concat(L)}return S&&"openssh"===S.toLowerCase()?p.readSSHPrivate(_,e,t):S&&"ssh2"===S.toLowerCase()?d.readType(_,e,t):((N=new a.BerReader(e)).originalInput=c,N.readSequence(),S?(i&&r.strictEqual(i,"pkcs1"),h.readPkcs1(S,_,N)):(i&&r.strictEqual(i,"pkcs8"),l.readPkcs8(S,_,N)))},write:function(e,t,i){r.object(e);var s,o={ecdsa:"EC",rsa:"RSA",dsa:"DSA",ed25519:"EdDSA"}[e.type],p=new a.BerWriter;if(u.isPrivateKey(e))i&&"pkcs8"===i?(s="PRIVATE KEY",l.writePkcs8(p,e)):(i&&r.strictEqual(i,"pkcs1"),s=o+" PRIVATE KEY",h.writePkcs1(p,e));else{if(!c.isKey(e))throw new Error("key is not a Key or PrivateKey");i&&"pkcs1"===i?(s=o+" PUBLIC KEY",h.writePkcs1(p,e)):(i&&r.strictEqual(i,"pkcs8"),s="PUBLIC KEY",l.writePkcs8(p,e))}var d=p.buffer.toString("base64"),f=(o=d.length+d.length/64+18+16+2*s.length+10,n.alloc(o)),m=0;m+=f.write("-----BEGIN "+s+"-----\n",m);for(var g=0;g<d.length;){var v=g+64;v>d.length&&(v=d.length),m+=f.write(d.slice(g,v),m),f[m++]=10,g=v}return m+=f.write("-----END "+s+"-----\n",m),f.slice(0,m)}};var r=i(10),a=i(58),s=i(8),n=i(12).Buffer,o=(i(30),i(25)),c=i(23),u=i(24),h=i(179),l=i(104),p=i(135),d=i(66),f=i(51),m="1.2.840.113549.1.5.13",g="1.2.840.113549.1.5.12",v={"1.2.840.113549.3.7":"3des-cbc","2.16.840.1.101.3.4.1.2":"aes128-cbc","2.16.840.1.101.3.4.1.42":"aes256-cbc"},y=(Object.keys(v).forEach((function(e){v[e]})),{"1.2.840.113549.2.7":"sha1","1.2.840.113549.2.9":"sha256","1.2.840.113549.2.11":"sha512"});Object.keys(y).forEach((function(e){y[e]}))},function(e,t,i){e.exports={read:p.bind(void 0,!1,void 0),readType:p.bind(void 0,!1),write:function(e,t){r.object(e);var i,o=l(e),h=s.info[e.type];c.isPrivateKey(e)&&(h=s.privInfo[e.type]);var p=h.parts,d=new u({});for(d.writeString(o),i=0;i<p.length;++i){var f=e.part[p[i]].data;!1!==h.normalize&&(f="ed25519"===e.type?n.zeroPadToLength(f,32):n.mpNormalize(f)),"ed25519"===e.type&&"k"===p[i]&&(f=a.concat([f,e.part.A.data])),d.writeBuffer(f)}return d.toBuffer()},readPartial:p.bind(void 0,!0),readInternal:p,keyTypeToAlg:l,algToKeyType:h};var r=i(10),a=i(12).Buffer,s=i(30),n=i(25),o=i(23),c=i(24),u=i(91);function h(e){if(r.string(e),"ssh-dss"===e)return"dsa";if("ssh-rsa"===e)return"rsa";if("ssh-ed25519"===e)return"ed25519";if("ssh-curve25519"===e)return"curve25519";if(e.match(/^ecdsa-sha2-/))return"ecdsa";throw new Error("Unknown algorithm "+e)}function l(e){if(r.object(e),"dsa"===e.type)return"ssh-dss";if("rsa"===e.type)return"ssh-rsa";if("ed25519"===e.type)return"ssh-ed25519";if("curve25519"===e.type)return"ssh-curve25519";if("ecdsa"===e.type)return"ecdsa-sha2-"+e.part.curve.data.toString();throw new Error("Unknown key type "+e.type)}function p(e,t,i,l){"string"==typeof i&&(i=a.from(i)),r.buffer(i,"buf");var p={},d=p.parts=[],f=new u({buffer:i}),m=(i=f.readString(),r.ok(!f.atEnd(),"key must have at least one part"),p.type=h(i),s.info[p.type].parts.length);for(t&&"private"===t&&(m=s.privInfo[p.type].parts.length);!f.atEnd()&&d.length<m;)d.push(f.readPart());for(;!e&&!f.atEnd();)d.push(f.readPart());r.ok(1<=d.length,"key must have at least one part"),r.ok(e||f.atEnd(),"leftover bytes at end of key");for(var g=o,v=s.info[p.type],y=("private"!==t&&v.parts.length===d.length||(v=s.privInfo[p.type],g=c),r.strictEqual(v.parts.length,d.length),"ecdsa"===p.type&&(t=/^ecdsa-sha2-(.+)$/.exec(i),r.ok(null!==t),r.strictEqual(t[1],d[0].data.toString())),!0),b=0;b<v.parts.length;++b){var w,x=d[b];x.name=v.parts[b],"ed25519"===p.type&&"k"===x.name&&(x.data=x.data.slice(0,32)),"curve"!==x.name&&!1!==v.normalize&&(w="ed25519"===p.type?n.zeroPadToLength(x.data,32):n.mpNormalize(x.data)).toString("binary")!==x.data.toString("binary")&&(x.data=w,y=!1)}return y&&(p._rfc4253Cache=f.toBuffer()),e&&"object"==typeof e&&(e.remainder=f.remainder(),e.consumed=f._offset),new g(p)}},function(e,t,i){"use strict";
|
|
152
|
+
*/const r=i(0),a=i(258);function s(e,t){this.key=e,this.value=t,this.next=null,this.prev=null}e.exports=class{constructor(e=1e3,t){this.map=new Map,this.size=0,this.items=0,this.head=null,this.tail=null,this.pending=null,r("number"==typeof e,"Capacity must be a number."),r(0<=e,"Capacity cannot be negative."),r(!t||"function"==typeof t,"Bad size callback."),this.capacity=e,this.getSize=t}_getSize(e){return this.getSize?120+Math.floor(1.375*e.key.length)+this.getSize(e.value):1}_compact(){if(!(this.size<=this.capacity)){let e,t;for(e=this.head;e&&!(this.size<=this.capacity);e=t)this.size-=this._getSize(e),this.items--,this.map.delete(e.key),t=e.next,e.prev=null,e.next=null;e?(this.head=e).prev=null:(this.head=null,this.tail=null)}}reset(){let e,t;for(e=this.head;e;e=t)this.map.delete(e.key),this.items--,t=e.next,e.prev=null,e.next=null;r(!e),this.size=0,this.head=null,this.tail=null}set(e,t){if(0!==this.capacity){e=String(e);let i=this.map.get(e);i?(this.size-=this._getSize(i),i.value=t,this.size+=this._getSize(i),this._removeList(i),this._appendList(i)):(i=new s(e,t),this.map.set(e,i),this._appendList(i),this.size+=this._getSize(i),this.items++),this._compact()}}get(e){return 0===this.capacity?null:(e=String(e),(e=this.map.get(e))?(this._removeList(e),this._appendList(e),e.value):null)}has(e){return 0!==this.capacity&&this.map.has(String(e))}remove(e){if(0===this.capacity)return!1;e=String(e);var t=this.map.get(e);return!!t&&(this.size-=this._getSize(t),this.items--,this.map.delete(e),this._removeList(t),!0)}_prependList(e){this._insertList(null,e)}_appendList(e){this._insertList(this.tail,e)}_insertList(e,t){r(!t.next),r(!t.prev),null==e?this.head?((this.head.prev=t).next=this.head,this.head=t):(this.head=t,this.tail=t):(t.next=e.next,(t.prev=e).next=t,e===this.tail&&(this.tail=t))}_removeList(e){e.prev&&(e.prev.next=e.next),e.next&&(e.next.prev=e.prev),e===this.head&&(this.head=e.next),e===this.tail&&(this.tail=e.prev||this.head),this.head||r(!this.tail),this.tail||r(!this.head),e.prev=null,e.next=null}keys(){var e=[];for(let t=this.head;t;t=t.next)t===this.head&&r(!t.prev),t.prev||r(t===this.head),t.next||r(t===this.tail),e.push(t.key);return e}values(){var e=[];for(let t=this.head;t;t=t.next)e.push(t.value);return e}toArray(){var e=[];for(let t=this.head;t;t=t.next)e.push(t);return e}batch(){return new a(this)}start(){r(!this.pending),this.pending=this.batch()}clear(){r(this.pending),this.pending.clear()}drop(){r(this.pending),this.pending=null}commit(){r(this.pending),this.pending.commit(),this.pending=null}push(e,t){r(this.pending),0!==this.capacity&&this.pending.set(e,t)}unpush(e){r(this.pending),0!==this.capacity&&this.pending.remove(e)}}},function(e,t,i){"use strict";var r,a,s=i(76),n=s.freeze,o=(i=i(11)).inherits,c=i.notEnumerableProp;function u(e,t){function i(r){if(!(this instanceof i))return new i(r);c(this,"message","string"==typeof r?r:t),c(this,"name",e),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this)}return o(i,Error),i}i=u("Warning","warning");var h=u("CancellationError","cancellation error"),l=u("TimeoutError","timeout error"),p=u("AggregateError","aggregate error");try{r=TypeError,a=RangeError}catch(e){r=u("TypeError","type error"),a=u("RangeError","range error")}for(var d="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),f=0;f<d.length;++f)"function"==typeof Array.prototype[d[f]]&&(p.prototype[d[f]]=Array.prototype[d[f]]);s.defineProperty(p.prototype,"length",{value:0,configurable:!1,writable:!0,enumerable:!0}),p.prototype.isOperational=!0;var m=0;function g(e){if(!(this instanceof g))return new g(e);c(this,"name","OperationalError"),c(this,"message",e),this.cause=e,this.isOperational=!0,e instanceof Error?(c(this,"message",e.message),c(this,"stack",e.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}p.prototype.toString=function(){var e="\n"+Array(4*m+1).join(" ")+"AggregateError of:\n";m++;for(var t=Array(4*m+1).join(" "),i=0;i<this.length;++i){for(var r=this[i]===this?"[Circular AggregateError]":this[i]+"",a=r.split("\n"),s=0;s<a.length;++s)a[s]=t+a[s];e+=(r=a.join("\n"))+"\n"}return m--,e},o(g,Error);var v=Error.__BluebirdErrorTypes__;v||(v=n({CancellationError:h,TimeoutError:l,OperationalError:g,RejectionError:g,AggregateError:p}),s.defineProperty(Error,"__BluebirdErrorTypes__",{value:v,writable:!1,enumerable:!1,configurable:!1})),e.exports={Error:Error,TypeError:r,RangeError:a,CancellationError:v.CancellationError,OperationalError:v.OperationalError,TimeoutError:v.TimeoutError,AggregateError:v.AggregateError,Warning:i}},function(e,t,i){e.exports={read:function(e,t,i){var c=e;"string"!=typeof e&&(r.buffer(e,"buf"),e=e.toString("ascii"));for(var u,b,w=e.trim().split(/[\r\n]+/g),x=-1;!u&&x<w.length;)u=w[++x].match(/[-]+[ ]*BEGIN ([A-Z0-9][A-Za-z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/);r.ok(u,"invalid PEM header");for(var k=w.length;!b&&0<k;)b=w[--k].match(/[-]+[ ]*END ([A-Z0-9][A-Za-z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/);r.ok(b,"invalid PEM footer"),r.equal(u[2],b[2]);var S,_=u[2].toLowerCase();u[1]&&(r.equal(u[1],b[1],"PEM header and footer mismatch"),S=u[1].trim()),w=w.slice(x,k+1);for(var E,j,A,R,I={};u=(w=w.slice(1))[0].match(/^([A-Za-z0-9-]+): (.+)$/);)I[u[1].toLowerCase()]=u[2];if((w=w.slice(0,-1).join(""),e=n.from(w,"base64"),I["proc-type"])&&("4"===(O=I["proc-type"].split(","))[0]&&"ENCRYPTED"===O[1])){if("string"==typeof t.passphrase&&(t.passphrase=n.from(t.passphrase,"utf-8")),!n.isBuffer(t.passphrase))throw new f.KeyEncryptedError(t.filename,"PEM");O=I["dek-info"].split(","),r.ok(2===O.length),E=O[0].toLowerCase(),A=n.from(O[1],"hex"),j=o.opensslKeyDeriv(E,A,t.passphrase,1).key}if(S&&"encrypted"===S.toLowerCase()){var O;if((C=((O=new a.BerReader(e)).readSequence(),O.readSequence(),R=O.offset+O.length,O.readOID()))!==m)throw new Error("Unsupported PEM/PKCS8 encryption scheme: "+C);O.readSequence(),O.readSequence();var C=O.offset+O.length;if((P=O.readOID())!==g)throw new Error("Unsupported PBES2 KDF: "+P);O.readSequence();var P=O.readString(a.Ber.OctetString,!0),T=O.readInt(),B="sha1";if(O.offset<C){O.readSequence();var N=O.readOID();if(void 0===(B=y[N]))throw new Error("Unsupported PBKDF2 hash: "+N)}if(O._offset=C,O.readSequence(),N=O.readOID(),void 0===(E=v[N]))throw new Error("Unsupported PBES2 cipher: "+N);if(A=O.readString(a.Ber.OctetString,!0),O._offset=R,e=O.readString(a.Ber.OctetString,!0),"string"==typeof t.passphrase&&(t.passphrase=n.from(t.passphrase,"utf-8")),!n.isBuffer(t.passphrase))throw new f.KeyEncryptedError(t.filename,"PEM");E=(C=o.opensshCipherInfo(E)).opensslName,j=o.pbkdf2(B,P,T,C.keySize,t.passphrase),S=void 0}if(E&&j&&A){var z,F=s.createDecipheriv(E,j,A),L=[];for(F.once("error",(function(e){if(-1!==e.toString().indexOf("bad decrypt"))throw new Error("Incorrect passphrase supplied, could not decrypt key");throw e})),F.write(e),F.end();null!==(z=F.read());)L.push(z);e=n.concat(L)}return S&&"openssh"===S.toLowerCase()?p.readSSHPrivate(_,e,t):S&&"ssh2"===S.toLowerCase()?d.readType(_,e,t):((N=new a.BerReader(e)).originalInput=c,N.readSequence(),S?(i&&r.strictEqual(i,"pkcs1"),h.readPkcs1(S,_,N)):(i&&r.strictEqual(i,"pkcs8"),l.readPkcs8(S,_,N)))},write:function(e,t,i){r.object(e);var s,o={ecdsa:"EC",rsa:"RSA",dsa:"DSA",ed25519:"EdDSA"}[e.type],p=new a.BerWriter;if(u.isPrivateKey(e))i&&"pkcs8"===i?(s="PRIVATE KEY",l.writePkcs8(p,e)):(i&&r.strictEqual(i,"pkcs1"),s=o+" PRIVATE KEY",h.writePkcs1(p,e));else{if(!c.isKey(e))throw new Error("key is not a Key or PrivateKey");i&&"pkcs1"===i?(s=o+" PUBLIC KEY",h.writePkcs1(p,e)):(i&&r.strictEqual(i,"pkcs8"),s="PUBLIC KEY",l.writePkcs8(p,e))}var d=p.buffer.toString("base64"),f=(o=d.length+d.length/64+18+16+2*s.length+10,n.alloc(o)),m=0;m+=f.write("-----BEGIN "+s+"-----\n",m);for(var g=0;g<d.length;){var v=g+64;v>d.length&&(v=d.length),m+=f.write(d.slice(g,v),m),f[m++]=10,g=v}return m+=f.write("-----END "+s+"-----\n",m),f.slice(0,m)}};var r=i(10),a=i(58),s=i(8),n=i(12).Buffer,o=(i(30),i(25)),c=i(23),u=i(24),h=i(179),l=i(104),p=i(134),d=i(66),f=i(51),m="1.2.840.113549.1.5.13",g="1.2.840.113549.1.5.12",v={"1.2.840.113549.3.7":"3des-cbc","2.16.840.1.101.3.4.1.2":"aes128-cbc","2.16.840.1.101.3.4.1.42":"aes256-cbc"},y=(Object.keys(v).forEach((function(e){v[e]})),{"1.2.840.113549.2.7":"sha1","1.2.840.113549.2.9":"sha256","1.2.840.113549.2.11":"sha512"});Object.keys(y).forEach((function(e){y[e]}))},function(e,t,i){e.exports={read:p.bind(void 0,!1,void 0),readType:p.bind(void 0,!1),write:function(e,t){r.object(e);var i,o=l(e),h=s.info[e.type];c.isPrivateKey(e)&&(h=s.privInfo[e.type]);var p=h.parts,d=new u({});for(d.writeString(o),i=0;i<p.length;++i){var f=e.part[p[i]].data;!1!==h.normalize&&(f="ed25519"===e.type?n.zeroPadToLength(f,32):n.mpNormalize(f)),"ed25519"===e.type&&"k"===p[i]&&(f=a.concat([f,e.part.A.data])),d.writeBuffer(f)}return d.toBuffer()},readPartial:p.bind(void 0,!0),readInternal:p,keyTypeToAlg:l,algToKeyType:h};var r=i(10),a=i(12).Buffer,s=i(30),n=i(25),o=i(23),c=i(24),u=i(91);function h(e){if(r.string(e),"ssh-dss"===e)return"dsa";if("ssh-rsa"===e)return"rsa";if("ssh-ed25519"===e)return"ed25519";if("ssh-curve25519"===e)return"curve25519";if(e.match(/^ecdsa-sha2-/))return"ecdsa";throw new Error("Unknown algorithm "+e)}function l(e){if(r.object(e),"dsa"===e.type)return"ssh-dss";if("rsa"===e.type)return"ssh-rsa";if("ed25519"===e.type)return"ssh-ed25519";if("curve25519"===e.type)return"ssh-curve25519";if("ecdsa"===e.type)return"ecdsa-sha2-"+e.part.curve.data.toString();throw new Error("Unknown key type "+e.type)}function p(e,t,i,l){"string"==typeof i&&(i=a.from(i)),r.buffer(i,"buf");var p={},d=p.parts=[],f=new u({buffer:i}),m=(i=f.readString(),r.ok(!f.atEnd(),"key must have at least one part"),p.type=h(i),s.info[p.type].parts.length);for(t&&"private"===t&&(m=s.privInfo[p.type].parts.length);!f.atEnd()&&d.length<m;)d.push(f.readPart());for(;!e&&!f.atEnd();)d.push(f.readPart());r.ok(1<=d.length,"key must have at least one part"),r.ok(e||f.atEnd(),"leftover bytes at end of key");for(var g=o,v=s.info[p.type],y=("private"!==t&&v.parts.length===d.length||(v=s.privInfo[p.type],g=c),r.strictEqual(v.parts.length,d.length),"ecdsa"===p.type&&(t=/^ecdsa-sha2-(.+)$/.exec(i),r.ok(null!==t),r.strictEqual(t[1],d[0].data.toString())),!0),b=0;b<v.parts.length;++b){var w,x=d[b];x.name=v.parts[b],"ed25519"===p.type&&"k"===x.name&&(x.data=x.data.slice(0,32)),"curve"!==x.name&&!1!==v.normalize&&(w="ed25519"===p.type?n.zeroPadToLength(x.data,32):n.mpNormalize(x.data)).toString("binary")!==x.data.toString("binary")&&(x.data=w,y=!1)}return y&&(p._rfc4253Cache=f.toBuffer()),e&&"object"==typeof e&&(e.remainder=f.remainder(),e.consumed=f._offset),new g(p)}},function(e,t,i){"use strict";
|
|
153
153
|
/*!
|
|
154
154
|
* private.js - hd private keys for vallnet
|
|
155
155
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
156
156
|
* https://github.com/bookmansoft/gamegold
|
|
157
|
-
*/const r=i(0),a=i(2),s=i(6),n=i(94),o=i(70),c=i(26),u=i(15),h=i(4),l=i(1),p=i(69),d=i(3),f=i(
|
|
157
|
+
*/const r=i(0),a=i(2),s=i(6),n=i(94),o=i(70),c=i(26),u=i(15),h=i(4),l=i(1),p=i(69),d=i(3),f=i(139),m=i(197),g=i(304);class v{constructor(e){if(!(this instanceof v))return new v(e);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,e&&this.fromOptions(e)}static getHmac(e,t){t=t||d.DefaultChainCode;t=v.fromKey(s.sha256(Buffer.concat([Buffer.from(e),t])),t);var i={id:"primary"};i.cid=e,i.pubkey=t.publicKey.toString("hex"),i.time=a.now()/3600|0,e=s.hash256(Buffer.from(a.stringify(i))),e=c.sign(e,t.privateKey).toString("hex");return{token:i.pubkey,random:e}}fromOptions(e){return r(e,"No options for HD private key."),r(a.isU8(e.depth)),r(a.isU32(e.parentFingerPrint)),r(a.isU32(e.childIndex)),r(Buffer.isBuffer(e.chainCode)),r(Buffer.isBuffer(e.privateKey)),e.network&&(this.network=u.get(e.network)),this.depth=e.depth,this.parentFingerPrint=e.parentFingerPrint,this.childIndex=e.childIndex,this.chainCode=e.chainCode,this.privateKey=e.privateKey,this.publicKey=c.publicKeyCreate(e.privateKey,!0),this}static fromOptions(e){return(new v).fromOptions(e)}toPublic(){let e=this._hdPublicKey;return e||((e=new g).network=this.network,e.depth=this.depth,e.parentFingerPrint=this.parentFingerPrint,e.childIndex=this.childIndex,e.chainCode=this.chainCode,e.publicKey=this.publicKey,this._hdPublicKey=e),e}xprivkey(){return this._xprivkey||(this._xprivkey=this.toBase58()),this._xprivkey}xpubkey(){return this.toPublic().xpubkey()}destroy(e){this.depth=0,this.childIndex=0,this.parentFingerPrint=0,n(this.chainCode),n(this.privateKey),n(this.publicKey),this.fingerPrint=-1,this._hdPublicKey&&(e&&this._hdPublicKey.destroy(),this._hdPublicKey=null),this._xprivkey=null}derive(e,t){if(r("number"==typeof e),e>>>0!==e)throw new Error("Index out of range.");if(255<=this.depth)throw new Error("Depth too high.");if((t&&(e=(e|f.HARDENED)>>>0),t=this.getID(e),!this.disableCache)&&(i=f.cache.get(t)))return i;var i=h.pool(37),a=(i=(e&f.HARDENED?(i.writeU8(0),i.writeBytes(this.privateKey)):i.writeBytes(this.publicKey),i.writeU32BE(e),i.render()),(i=s.hmac("sha512",i,this.chainCode)).slice(0,32));i=i.slice(32,64);let n;try{n=c.privateKeyTweakAdd(this.privateKey,a)}catch(t){return this.derive(e+1)}return-1===this.fingerPrint&&(a=s.hash160(this.publicKey),this.fingerPrint=a.readUInt32BE(0,!0)),(a=new v).disableCache=this.disableCache,a.network=this.network,a.depth=this.depth+1,a.parentFingerPrint=this.fingerPrint,a.childIndex=e,a.chainCode=i,a.privateKey=n,a.publicKey=c.publicKeyCreate(n,!0),this.disableCache||f.cache.set(t,a),a}getID(e){return this.network.keyPrefix.xprivkey58+this.publicKey.toString("hex")+e}deriveAccount(e,t){return r(a.isU32(e),"Purpose must be a number."),r(a.isU32(t),"Account index must be a number."),r(this.isMaster(),"Cannot derive account index."),this.derive(e,!0).derive(this.network.keyPrefix.coinType,!0).derive(t,!0)}isMaster(){return f.isMaster(this)}isAccount(e){return f.isAccount(this,e)}static isBase58(e,t){if("string"!=typeof e)return!1;if(e.length<4)return!1;e=e.substring(0,4);try{return u.fromPrivate58(e,t),!0}catch(e){return!1}}static isRaw(e,t){if(!Buffer.isBuffer(e))return!1;if(e.length<4)return!1;e=e.readUInt32BE(0,!0);try{return u.fromPrivate(e,t),!0}catch(e){return!1}}static isValidPath(e){try{return f.parsePath(e,!0),!0}catch(e){return!1}}derivePath(e){let t=this;for(const i of f.parsePath(e,!0))t=t.derive(i);return t}equals(e){return r(v.isHDPrivateKey(e)),this.network===e.network&&this.depth===e.depth&&this.parentFingerPrint===e.parentFingerPrint&&this.childIndex===e.childIndex&&this.chainCode.equals(e.chainCode)&&this.privateKey.equals(e.privateKey)}compare(e){r(v.isHDPrivateKey(e));var t=this.depth-e.depth;return 0!=t||0!=(t=this.parentFingerPrint-e.parentFingerPrint)||0!=(t=this.childIndex-e.childIndex)||0!==(t=this.chainCode.compare(e.chainCode))||0!==(t=this.privateKey.compare(e.privateKey))?t:0}fromSeed(e,t){if(e instanceof Buffer?r(Buffer.isBuffer(e)):(r("object"==typeof e&&0<e.length),e=Buffer.from(e)),8*e.length<f.MIN_ENTROPY||8*e.length>f.MAX_ENTROPY)throw new Error("Entropy not in range.");var i=(e=s.hmac("sha512",e,d.SEED_SALT)).slice(0,32);e=e.slice(32,64);if(c.privateKeyVerify(i))return this.network=u.get(t),this.depth=0,this.parentFingerPrint=0,this.childIndex=0,this.chainCode=e,this.privateKey=i,this.publicKey=c.publicKeyCreate(i,!0),this;throw new Error("Master private key is invalid.")}static fromSeed(e,t){return(new v).fromSeed(e,t)}fromMnemonic(e,t){return r(e instanceof m),this.fromSeed(e.toSeed(),t)}static fromMnemonic(e,t){return(new v).fromMnemonic(e,t)}fromPhrase(e,t){return e=m.fromPhrase(e),this.fromMnemonic(e,t),this}static fromPhrase(e,t){return(new v).fromPhrase(e,t)}static getAes(e,t){var i=Buffer.from(e),r=Buffer.alloc(32);for(let e=0;e<Math.max(32,i.length);e++){var a=e%32;r[a]=i[a]^d.RANDOM_HASH[a]}return v.fromKey(d.RANDOM_HASH,r,t).getAes(e)}fromKey(e,t,i){return r(Buffer.isBuffer(e)&&32===e.length),r(Buffer.isBuffer(t)&&32===t.length),this.network=u.get(i),this.depth=0,this.parentFingerPrint=0,this.childIndex=0,this.chainCode=t,this.privateKey=e,this.publicKey=c.publicKeyCreate(e,!0),this}getAes(e){e=v.getHmac(e,this.chainCode).token;let t=s.hash256(Buffer.from(e));return{aeskey:t.toString("base64").slice(0,32),aesiv:(t=s.hash256(t)).toString("base64").slice(0,16)}}static fromKey(e,t,i){return(new v).fromKey(e,t,i)}static eccEncrypt(e,t){var i=v.generate(),{aeskey:t,aesiv:r}=(t=c.ecdh(t,i.privateKey),v.getAes(t.toString()));return{pub:i.publicKey,msg:a.encrypt(t,r,Buffer.from(e).toString("hex"))}}static eccDecrypt(e,t){t=c.ecdh(e.pub,t);var{aeskey:t,aesiv:i}=v.getAes(t.toString());return Buffer.from(a.decrypt(t,i,e.msg),"hex").toString()}static generate(e){var t=c.generatePrivateKey(),i=o.randomBytes(32);return v.fromKey(t,i,e)}fromBase58(e,t){return r("string"==typeof e),this._xprivkey=e,this.fromRaw(p.decode(e),t)}fromReader(e,t){var i=e.readU32BE();return this.network=u.fromPrivate(i,t),this.depth=e.readU8(),this.parentFingerPrint=e.readU32BE(),this.childIndex=e.readU32BE(),this.chainCode=e.readBytes(32),r(0===e.readU8()),this.privateKey=e.readBytes(32),this.publicKey=c.publicKeyCreate(this.privateKey,!0),e.verifyChecksum(),this}fromRaw(e,t){return this.fromReader(new l(e),t)}toBase58(e){return p.encode(this.toRaw(e))}getSize(){return 82}toWriter(e,t){return t=t||this.network,t=u.get(t),e.writeU32BE(t.keyPrefix.xprivkey),e.writeU8(this.depth),e.writeU32BE(this.parentFingerPrint),e.writeU32BE(this.childIndex),e.writeBytes(this.chainCode),e.writeU8(0),e.writeBytes(this.privateKey),e.writeChecksum(),e}toRaw(e){return this.toWriter(new h(82),e).render()}static fromBase58(e,t){return(new v).fromBase58(e,t)}static fromReader(e,t){return(new v).fromReader(e,t)}static fromRaw(e,t){return(new v).fromRaw(e,t)}toJSON(){return{xprivkey:this.xprivkey(),pubkey:this.publicKey.toString("hex")}}fromJSON(e,t){return r(e.xprivkey,"Could not handle key JSON."),this.fromBase58(e.xprivkey,t),this}static fromJSON(e,t){return(new v).fromJSON(e,t)}static isHDPrivateKey(e){return e instanceof v}}e.exports=v},function(e,t,i){"use strict";
|
|
158
158
|
/*!
|
|
159
159
|
* mtx.js - mutable transaction object for vallnet
|
|
160
160
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -181,12 +181,12 @@ let r=[];[i(558),i(559),i(560),i(561),i(562),i(563),i(564),i(565),i(566),i(567),
|
|
|
181
181
|
/*!
|
|
182
182
|
* block.js - block object for vallnet
|
|
183
183
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
184
|
-
*/const r=i(0),a=i(2),s=i(3),n=i(6),o=i(
|
|
184
|
+
*/const r=i(0),a=i(2),s=i(3),n=i(6),o=i(143),c=i(7);var u=i(115);const h=i(1),l=i(4),p=i(20),d=i(131),f=i(89),m=i(15),g=i(146),v=i(19).opcodes,y=i(5).PropStatus;class b extends u{constructor(e,t){super(),this.txs=t||[],this._raw=null,this._size=-1,this._witness=-1,e&&this.fromOptions(e)}fromOptions(e){if(this.parseOptions(e),e.txs){r(Array.isArray(e.txs));for(const t of e.txs)r(t instanceof p),this.txs.push(t)}}static fromOptions(e){return(new b).fromOptions(e)}async propViewer(){if(!this.pviewer)for(var e of(this.pviewer=new g,this.txs))for(let r=0;r<e.outputs.length;r++){var t=e.outputs[r],i=t.getReturnData([v.OP_PROPEXCHANGE,v.OP_PROPCREATE]);!i||t.getReturnType(v.OP_PROPCREATE)&&!await this.pviewer.getVp(i.pid)&&(i.current={hash:e.hash("hex"),index:r,address:t.getAddress().toString()},i.gold=t.value,i.height=this.height,i.pst=y.Ready,await this.pviewer.setVp(i))}return this.pviewer}refresh(e){if(this._refresh(),this._raw=null,this._size=-1,this._witness=-1,e)for(const e of this.txs)e.refresh()}toRaw(){return this.frame().data}toNormal(){return this.hasWitness()?this.frameNormal().data:this.toRaw()}toWriter(e){var t;return this.mutable?this.writeWitness(e):(t=this.frame(),e.writeBytes(t.data),e)}toNormalWriter(e){return this.hasWitness()?(this.writeNormal(e),e):this.toWriter(e)}frame(){if(this.mutable)return r(!this._raw),this.frameWitness();if(this._raw){r(0<=this._size),r(0<=this._witness);const e=new w(this._size,this._witness);return e.data=this._raw,e}const e=this.frameWitness();return this._raw=e.data,this._size=e.size,this._witness=e.witness,e}getSizes(){return this.mutable?this.getWitnessSizes():this.frame()}getVirtualSize(){var e=c.WITNESS_SCALE_FACTOR;return(this.getWeight()+e-1)/e|0}getWeight(){var e=this.getSizes();return(e.size-e.witness)*(c.WITNESS_SCALE_FACTOR-1)+e.size}getSize(){return this.getSizes().size}getBaseSize(){var e=this.getSizes();return e.size-e.witness}hasWitness(){if(-1!==this._witness)return 0!==this._witness;for(const e of this.txs)if(e.hasWitness())return!0;return!1}hasTX(e){return-1!==this.indexOf(e)}indexOf(e){for(let t=0;t<this.txs.length;t++)if(this.txs[t].hash("hex")===e)return t;return-1}createMerkleRoot(e){var t=[];for(const e of this.txs)t.push(e.hash());var[i,r]=o.createRoot(t);return r?null:"hex"===e?i.toString("hex"):i}createWitnessNonce(){return Buffer.from(s.ZERO_HASH)}createCommitmentHash(e){var t=this.getWitnessNonce(),i=[];r(t,"No witness nonce present."),i.push(s.ZERO_HASH);for(let e=1;e<this.txs.length;e++){var a=this.txs[e];i.push(a.witnessHash())}var[c]=o.createRoot(i),c=n.root256(c,t);return"hex"===e?c.toString("hex"):c}getMerkleRoot(e){return"hex"===e?this.merkleRoot:Buffer.from(this.merkleRoot,"hex")}getWitnessNonce(){var e;return 0===this.txs.length||1!==(e=this.txs[0]).inputs.length||1!==(e=e.inputs[0]).witness.items.length||32!==e.witness.items[0].length?null:e.witness.items[0]}getCommitmentHash(e){if(0===this.txs.length)return null;var t=this.txs[0];let i;for(let e=t.outputs.length-1;0<=e;e--){var r=t.outputs[e];if(r.script.isCommitment()){i=r.script.getCommitment();break}}return i?"hex"===e?i.toString("hex"):i:null}verifyBody(){var[e]=this.checkBody();return e}checkBody(){var e=this.createMerkleRoot("hex");if(!e)return[!1,"bad-txns-duplicate",100];if(this.merkleRoot!==e)return[!1,"bad-txnmrklroot",100];if(0===this.txs.length||this.txs.length>(c.MAX_BLOCK_SIZE-81)/60||this.getBaseSize()>c.MAX_BLOCK_SIZE)return[!1,"bad-blk-length",100];if(0===this.txs.length||!this.txs[0].isCoinbase())return[!1,"bad-cb-missing",100];var t=c.WITNESS_SCALE_FACTOR;let i=0;for(let e=0;e<this.txs.length;e++){var r=this.txs[e];if(0<e&&r.isCoinbase())return[!1,"bad-cb-multiple",100];var[a,s,n]=r.checkSanity();if(!a)return[a,s,n];if((i+=r.getLegacySigops())*t>c.MAX_BLOCK_SIGOPS_COST)return[!1,"bad-blk-sigops",100]}return[!0,"valid",0]}get height(){return this.getCoinbaseHeight()}getCoinbaseHeight(){var e;return this.version<2||0===this.txs.length||0===(e=this.txs[0]).inputs.length?-1:e.inputs[0].script.getCoinbaseHeight()}getClaimed(){return r(0<this.txs.length),r(this.txs[0].isCoinbase()),this.txs[0].getOutputValue()}getPrevout(){var e=Object.create(null);for(let t=1;t<this.txs.length;t++)for(const i of this.txs[t].inputs)e[i.prevout.hash]=!0;return Object.keys(e)}inspect(){return this.format()}format(e,t){var i=this.getCommitmentHash("hex");return{hash:this.rhash(),height:null!=t?t:-1,size:this.getSize(),virtualSize:this.getVirtualSize(),date:a.date(this.time),version:a.hex32(this.version),prevBlock:a.revHex(this.prevBlock),merkleRoot:a.revHex(this.merkleRoot),commitmentHash:i?a.revHex(i):null,time:this.time,bits:this.bits,nonce:this.nonce,txs:this.txs.map((t,i)=>t.format(e,null,i))}}formatInsight(){return{hash:this.rhash(),rhash:()=>this.hash,version:a.hex32(this.version),prevBlock:a.revHex(this.prevBlock),merkleRoot:a.revHex(this.merkleRoot),raw:this.toRaw(),ts:this.time,bits:this.bits,nonce:this.nonce,txs:this.txs.map((e,t)=>e.formatInsight(t,this.time))}}toJSON(){return this.getJSON()}getJSON(e,t,i,r){return e=m.get(e),{hash:this.rhash(),height:i,confirmations:r,version:this.version,prevBlock:a.revHex(this.prevBlock),merkleRoot:a.revHex(this.merkleRoot),time:this.time,bits:this.bits,nonce:this.nonce,txs:this.txs.map((i,r)=>i.getJSON(e,t,null,r))}}fromJSON(e){r(e,"Block data is required."),r(Array.isArray(e.txs)),this.parseJSON(e);for(const t of e.txs)this.txs.push(p.fromJSON(t));return this}static fromJSON(e){return(new b).fromJSON(e)}fromReader(e){e.start(),this.readHead(e);var t=e.readVarint();let i=0;for(let a=0;a<t;a++){var r=p.fromReader(e);i+=r._witness,this.txs.push(r)}return this.mutable||(this._raw=e.endData(),this._size=this._raw.length,this._witness=i),this}fromRaw(e){return this.fromReader(new h(e))}static fromReader(e){return(new b).fromReader(e)}static fromRaw(e,t){return"string"==typeof e&&(e=Buffer.from(e,t)),(new b).fromRaw(e)}toMerkle(e){return d.fromBlock(this,e)}writeNormal(e){this.writeHead(e),e.writeVarint(this.txs.length);for(const t of this.txs)t.toNormalWriter(e);return e}writeWitness(e){this.writeHead(e),e.writeVarint(this.txs.length);for(const t of this.txs)t.toWriter(e);return e}frameNormal(){var e=this.getNormalSizes(),t=new l(e.size);return this.writeNormal(t),e.data=t.render(),e}frameWitness(){var e=this.getWitnessSizes(),t=new l(e.size);return this.writeWitness(t),e.data=t.render(),e}toHeaders(){return f.fromBlock(this)}getNormalSizes(){let e=0;e=(e+=80)+s.sizeVarint(this.txs.length);for(const t of this.txs)e+=t.getBaseSize();return new w(e,0)}getWitnessSizes(){let e=0,t=0;e=(e+=80)+s.sizeVarint(this.txs.length);for(const r of this.txs){var i=r.getSizes();e+=i.size,t+=i.witness}return new w(e,t)}static isBlock(e){return e instanceof b}}function w(e,t){this.data=null,this.size=e,this.witness=t}e.exports=b},function(e,t){var i,r,a,s=function(){"use strict";return void 0===this}();s?e.exports={freeze:Object.freeze,defineProperty:Object.defineProperty,getDescriptor:Object.getOwnPropertyDescriptor,keys:Object.keys,names:Object.getOwnPropertyNames,getPrototypeOf:Object.getPrototypeOf,isArray:Array.isArray,isES5:s,propertyIsWritable:function(e,t){return!((e=Object.getOwnPropertyDescriptor(e,t))&&!e.writable&&!e.set)}}:(i={}.hasOwnProperty,r={}.toString,a={}.constructor.prototype,e.exports={isArray:function(e){try{return"[object Array]"===r.call(e)}catch(e){return!1}},keys:e=function(e){var t,r=[];for(t in e)i.call(e,t)&&r.push(t);return r},names:e,defineProperty:function(e,t,i){return e[t]=i.value,e},getDescriptor:function(e,t){return{value:e[t]}},freeze:function(e){return e},getPrototypeOf:function(e){try{return Object(e).constructor.prototype}catch(e){return a}},isES5:s,propertyIsWritable:function(){return!0}})},function(e,t,i){const r=i(0);class a extends Error{constructor(e,t){super(),r("number"==typeof e),r("string"==typeof t),this.type="RPCError",this.message=String(t),this.code=e>>>0,Error.captureStackTrace&&Error.captureStackTrace(this,a)}}e.exports=a},function(e,t,i){"use strict";
|
|
185
185
|
/*!
|
|
186
186
|
* rpcbase.js - json rpc for vallnet.
|
|
187
187
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
188
188
|
* https://github.com/bookmansoft/gamegold
|
|
189
|
-
*/const r=i(0);var a=i(16);const s=i(35),n=i(79),o=i(77),c=i(13),u=i(38),h=i(
|
|
189
|
+
*/const r=i(0);var a=i(16);const s=i(35),n=i(79),o=i(77),c=i(13),u=i(38),h=i(138),l=i(55),p=i(67),d=i(6),f=i(72).signObj,m=i(7),g=i(107);class v extends a{constructor(e){super(),this.logger=n.global,this.calls=Object.create(null),this.mounts=[],this.locker=new s,this.network=e.network}async isReady(){return!0}async execute(e,t,i){(e="string"==typeof e?{method:e}:e).params||(e.params=[]),e.cid||(e.cid=m.ROOT);var r=this.calls[e.method];if(r){if(await this.isReady(i))return r.call(this,e.params,t,i);throw new o(v.errors.METHOD_NOT_FOUND,`sync not ready: ${e.method}.`)}for(const r of this.mounts)if(r.calls[e.method])return r.execute(e,t,i);throw new o(v.errors.METHOD_NOT_FOUND,`Method not found: ${e.method}.`)}async calles(e,t){let i=e,r=[],a=!0;Array.isArray(i)||(i=[i],a=!1);for(const a of i)if(a&&"object"==typeof a)if(a.id&&"object"==typeof a.id)r.push({result:null,code:v.errors.INVALID_REQUEST,error:{type:"RPCError",message:"Invalid ID."},id:null});else if(a.id||(a.id=null),a.params||(a.params=[]),"string"!=typeof a.method)r.push({code:v.errors.METHOD_NOT_FOUND,result:null,error:{type:"RPCError",message:"Method not found."},id:a.id});else if(Array.isArray(a.params)){let i;"getwork"!==a.method&&"block.template.admin"!==a.method&&"block.best"!==a.method&&(this.logger.debug("Handling RPC call: %s.",a.method),"block.submit.admin"!==a.method)&&"getmemorypool"!==a.method&&this.logger.debug(a.params);try{i=await this.execute(a,!1,t)}catch(e){let t;switch(e.type){case"RPCError":t=e.code;break;case"ValidationError":t=v.errors.TYPE_ERROR;break;case"EncodingError":t=v.errors.DESERIALIZATION_ERROR;break;case"FundingError":t=v.errors.WALLET_INSUFFICIENT_FUNDS;break;default:t=v.errors.INTERNAL_ERROR,this.logger.error("RPC internal error."),this.logger.error(e)}r.push({code:t,error:{type:e.type,message:e.message},result:null,id:a.id});continue}void 0===i&&(i=null);var s=p.getHmac(a.cid,this.keys.hmacSalt).token;s=g.generateKey(d.hash256(Buffer.from(s)));let n=null;null!=i&&(n=f(i,s.private)),r.push({code:0,error:null,result:i,sig:n,id:a.id})}else r.push({code:v.errors.INVALID_PARAMS,result:null,error:{type:"RPCError",message:"Invalid params."},id:a.id});else r.push({code:v.errors.INVALID_REQUEST,result:null,error:{type:"RPCError",message:"Invalid request."},id:null});return a||delete(r=r[0]).id,r}add(e,t){try{r("function"==typeof t,"Handler must be a function."),Array.isArray(e)?e.map(e=>this.add(e,t)):(r(!this.calls[e],`Duplicate RPC call ${e}.`),this.calls[e]=t)}catch(e){console.error(e)}}mount(e){r(e,"RPC must be an object."),r("function"==typeof e.execute,"Execute must be a method."),this.mounts.push(e)}static parseAddress(e,t){try{return c.fromString(e,t)}catch(e){throw new o(v.errors.INVALID_ADDRESS_OR_KEY,"Invalid address.")}}static parseSecret(e,t){try{return u.fromSecret(e,t)}catch(e){throw new o(v.errors.INVALID_ADDRESS_OR_KEY,"Invalid key.")}}static parseHash(e,t){return v.parseAddress(e,t).getHash("hex")}static parseNetAddress(e,t){try{return h.fromHostname(e,t)}catch(e){throw new o(v.errors.CLIENT_INVALID_IP_OR_SUBNET,"Invalid IP address or subnet.")}}static parseIP(e,t){try{return l.fromHostname(e,t.port)}catch(e){throw new o(errs.CLIENT_INVALID_IP_OR_SUBNET,"Invalid IP address or subnet.")}}}v.errors={INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,PARSE_ERROR:-32700,MISC_ERROR:-1,FORBIDDEN_BY_SAFE_MODE:-2,TYPE_ERROR:-3,INVALID_ADDRESS_OR_KEY:-5,OUT_OF_MEMORY:-7,INVALID_PARAMETER:-8,DATABASE_ERROR:-20,DESERIALIZATION_ERROR:-22,VERIFY_ERROR:-25,VERIFY_REJECTED:-26,VERIFY_ALREADY_IN_CHAIN:-27,IN_WARMUP:-28,TRANSACTION_ERROR:-25,TRANSACTION_REJECTED:-26,TRANSACTION_ALREADY_IN_CHAIN:-27,CLIENT_NOT_CONNECTED:-9,CLIENT_IN_INITIAL_DOWNLOAD:-10,CLIENT_NODE_ALREADY_ADDED:-23,CLIENT_NODE_NOT_ADDED:-24,CLIENT_NODE_NOT_CONNECTED:-29,CLIENT_INVALID_IP_OR_SUBNET:-30,CLIENT_P2P_DISABLED:-31,WALLET_ERROR:-4,WALLET_INSUFFICIENT_FUNDS:-6,WALLET_INVALID_ACCOUNT_NAME:-11,WALLET_KEYPOOL_RAN_OUT:-12,WALLET_UNLOCK_NEEDED:-13,WALLET_PASSPHRASE_INCORRECT:-14,WALLET_WRONG_ENC_STATE:-15,WALLET_ENCRYPTION_FAILED:-16,WALLET_ALREADY_UNLOCKED:-17,PROP_MINVALUE:-1001},v.MAGIC_STRING="Gamegold Signed Message:\n",e.exports=v},function(e,t,i){"use strict";
|
|
190
190
|
/*!
|
|
191
191
|
* logger.js - basic logger for vallnet
|
|
192
192
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -201,7 +201,7 @@ let r=[];[i(558),i(559),i(560),i(561),i(562),i(563),i(564),i(565),i(566),i(567),
|
|
|
201
201
|
* pkg.js - package constants
|
|
202
202
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
203
203
|
* https://github.com/bookmansoft/gamegold
|
|
204
|
-
*/t.protocol="vallnet",t.version="5.
|
|
204
|
+
*/t.protocol="vallnet",t.version="5.7.3",t.url="https://github.com/bookmansoft/gamegold"},function(e,t,i){"use strict";
|
|
205
205
|
/*!
|
|
206
206
|
* common.js - p2p constants for vallnet
|
|
207
207
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -235,12 +235,12 @@ let r=[];[i(558),i(559),i(560),i(561),i(562),i(563),i(564),i(565),i(566),i(567),
|
|
|
235
235
|
/*!
|
|
236
236
|
* bloom.js - bloom filter for vallnet
|
|
237
237
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
238
|
-
*/const r=i(0),a=i(145),s=i(1),n=i(4),o=i(3),c=a.sum32,u=a.mul32,h=Buffer.alloc(0);class l{constructor(e,t,i,r){this.filter=h,this.size=0,this.n=0,this.tweak=0,this.update=l.flags.NONE,null!=e&&this.fromOptions(e,t,i,r)}fromOptions(e,t,i,a){r("number"==typeof e,"`size` must be a number."),r(0<e,"`size` must be greater than zero."),r(Number.isSafeInteger(e),"`size` must be an integer."),e-=e%8;var s=Buffer.allocUnsafe(e/8);return s.fill(0),null!=i&&-1!==i||(i=4294967296*Math.random()>>>0),"string"==typeof(a=null!=a&&-1!==a?a:l.flags.NONE)&&(a=l.flags[a.toUpperCase()],r(null!=a,"Unknown update flag.")),r(0<e,"`size` must be greater than zero."),r(0<t,"`n` must be greater than zero."),r(Number.isSafeInteger(t),"`n` must be an integer."),r("number"==typeof i,"`tweak` must be a number."),r(Number.isSafeInteger(i),"`tweak` must be an integer."),r(l.flagsByVal[a],"Unknown update flag."),this.filter=s,this.size=e,this.n=t,this.tweak=i,this.update=a,this}static fromOptions(e,t,i,r){return(new l).fromOptions(e,t,i,r)}hash(e,t){return a(e,c(u(t,4221880213),this.tweak))%this.size}reset(){this.filter.fill(0)}add(e,t){"string"==typeof e&&(e=Buffer.from(e,t));for(let t=0;t<this.n;t++){var i=this.hash(e,t);this.filter[i>>>3]|=1<<(7&i)}}test(e,t){"string"==typeof e&&(e=Buffer.from(e,t));for(let t=0;t<this.n;t++){var i=this.hash(e,t);if(0==(this.filter[i>>>3]&1<<(7&i)))return!1}return!0}added(e,t){let i=!1;"string"==typeof e&&(e=Buffer.from(e,t));for(let t=0;t<this.n;t++){var r=this.hash(e,t);i||0!=(this.filter[r>>>3]&1<<(7&r))||(i=!0),this.filter[r>>>3]|=1<<(7&r)}return i}static fromRate(e,t,i){return r("number"==typeof e,"`items` must be a number."),r(0<e,"`items` must be greater than zero."),r(Number.isSafeInteger(e),"`items` must be an integer."),r("number"==typeof t,"`rate` must be a number."),r(0<=t&&t<=1,"`rate` must be between 0.0 and 1.0."),t=-2.0813689810056077*e*Math.log(t)|0,t=Math.max(8,t),-1!==i&&r(t<=8*l.MAX_BLOOM_FILTER_SIZE,"Bloom filter size violates policy limits!"),e=Math.max(1,t/e*.6931471805599453|0),-1!==i&&r(e<=l.MAX_HASH_FUNCS,"Bloom filter size violates policy limits!"),new l(t,e,-1,i)}isWithinConstraints(){return!(this.size>8*l.MAX_BLOOM_FILTER_SIZE||this.n>l.MAX_HASH_FUNCS)}getSize(){return o.sizeVarBytes(this.filter)+13}toWriter(e){return e.writeVarBytes(this.filter),e.writeU32(this.n),e.writeU32(this.tweak),e.writeU32(this.size),e.writeU8(this.update),e}toRaw(){var e=this.getSize();return this.toWriter(new n(e)).render()}fromReader(e){return this.filter=e.readVarBytes(),this.n=e.readU32(),this.tweak=e.readU32(),this.size=e.readU32(),this.update=e.readU8(),r(null!=l.flagsByVal[this.update],"Unknown update flag."),this}fromRaw(e){return this.fromReader(new s(e))}static fromReader(e){return(new l).fromReader(e)}static fromRaw(e,t){return"string"==typeof e&&(e=Buffer.from(e,t)),(new l).fromRaw(e)}}l.MAX_BLOOM_FILTER_SIZE=36e3,l.MAX_HASH_FUNCS=50,l.flags={NONE:0,ALL:1,PUBKEY_ONLY:2},l.flagsByVal={0:"NONE",1:"ALL",2:"PUBKEY_ONLY"},e.exports=l},function(e,t,i){e.exports=d;var r=i(10),a=i(12).Buffer,s=i(30),n=i(8),o=(e=i(51),i(23)),c=i(24),u=i(105),h=i(25),l=e.FingerprintFormatError,p=e.InvalidAlgorithmError;function d(e){if(r.object(e,"options"),r.string(e.type,"options.type"),r.buffer(e.hash,"options.hash"),r.string(e.algorithm,"options.algorithm"),this.algorithm=e.algorithm.toLowerCase(),!0!==s.hashAlgs[this.algorithm])throw new p(this.algorithm);this.hash=e.hash,this.type=e.type,this.hashType=e.hashType}d.prototype.toString=function(e){switch(void 0===e&&(e="md5"===this.algorithm||"spki"===this.hashType?"hex":"base64"),r.string(e),e){case"hex":return"spki"===this.hashType?this.hash.toString("hex"):this.hash.toString("hex").replace(/(.{2})(?=.)/g,"$1:");case"base64":return"spki"===this.hashType?this.hash.toString("base64"):(t=this.algorithm,i=this.hash.toString("base64"),t.toUpperCase()+":"+i.replace(/=*$/,""));default:throw new l(void 0,e)}var t,i},d.prototype.matches=function(e){return r.object(e,"key or certificate"),"key"===this.type&&"ssh"!==this.hashType?(h.assertCompatible(e,o,[1,7],"key with spki"),c.isPrivateKey(e)&&h.assertCompatible(e,c,[1,6],"privatekey with spki support")):"key"===this.type?h.assertCompatible(e,o,[1,0],"key"):h.assertCompatible(e,u,[1,0],"certificate"),e=e.hash(this.algorithm,this.hashType),e=n.createHash(this.algorithm).update(e).digest("base64"),void 0===this.hash2&&(this.hash2=n.createHash(this.algorithm).update(this.hash).digest("base64")),this.hash2===e};var f=/^[A-Za-z0-9+\/=]+$/,m=/^[a-fA-F0-9]+$/;d.parse=function(e,t){r.string(e,"fingerprint"),Array.isArray(t)&&(o=t,t={}),r.optionalObject(t,"options"),void 0!==(t=void 0===t?{}:t).enAlgs&&(o=t.enAlgs),void 0!==t.algorithms&&(o=t.algorithms),r.optionalArrayOfString(o,"algorithms");var i,n,o,c="ssh",u=(void 0!==t.hashType&&(c=t.hashType),r.string(c,"options.hashType"),e.split(":"));if(2==u.length){if(i=u[0].toLowerCase(),!f.test(u[1]))throw new l(e);try{n=a.from(u[1],"base64")}catch(t){throw new l(e)}}else if(2<u.length){if(u=(u=(u=(i="md5")===u[0].toLowerCase()?u.slice(1):u).map((function(t){for(;t.length<2;)t="0"+t;if(2<t.length)throw new l(e);return t}))).join(""),!m.test(u)||u.length%2!=0)throw new l(e);try{n=a.from(u,"hex")}catch(t){throw new l(e)}}else{if(m.test(e))n=a.from(e,"hex");else{if(!f.test(e))throw new l(e);n=a.from(e,"base64")}switch(n.length){case 32:i="sha256";break;case 16:i="md5";break;case 20:i="sha1";break;case 64:i="sha512";break;default:throw new l(e)}void 0===t.hashType&&(c="spki")}if(void 0===i)throw new l(e);if(void 0===s.hashAlgs[i])throw new p(i);if(void 0!==o&&-1===(o=o.map((function(e){return e.toLowerCase()}))).indexOf(i))throw new p(i);return new d({algorithm:i,hash:n,type:t.type||"key",hashType:c})},d.isFingerprint=function(e,t){return h.isCompatible(e,d,t)},d.prototype._sshpkApiVersion=[1,2],d._oldVersionDetect=function(e){return r.func(e.toString),r.func(e.matches),[1,0]}},function(e,t,i){(function(){function t(e,t,i){null!=e&&("number"==typeof e?this.fromNumber(e,t,i):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}function i(){return new t(null)}for(var r=(r="undefined"!=typeof navigator)&&"Microsoft Internet Explorer"==navigator.appName?(t.prototype.am=function(e,t,i,r,a,s){for(var n=32767&t,o=t>>15;0<=--s;){var c=32767&this[e],u=this[e++]>>15,h=o*c+u*n;a=((c=n*c+((32767&h)<<15)+i[r]+(1073741823&a))>>>30)+(h>>>15)+o*u+(a>>>30),i[r++]=1073741823&c}return a},30):r&&"Netscape"!=navigator.appName?(t.prototype.am=function(e,t,i,r,a,s){for(;0<=--s;){var n=t*this[e++]+i[r]+a;a=Math.floor(n/67108864),i[r++]=67108863&n}return a},26):(t.prototype.am=function(e,t,i,r,a,s){for(var n=16383&t,o=t>>14;0<=--s;){var c=16383&this[e],u=this[e++]>>14,h=o*c+u*n;a=((c=n*c+((16383&h)<<14)+i[r]+a)>>28)+(h>>14)+o*u,i[r++]=268435455&c}return a},28),a=(t.prototype.DB=r,t.prototype.DM=(1<<r)-1,t.prototype.DV=1<<r,t.prototype.FV=Math.pow(2,52),t.prototype.F1=52-r,t.prototype.F2=2*r-52,"0123456789abcdefghijklmnopqrstuvwxyz"),s=new Array,n="0".charCodeAt(0),o=0;o<=9;++o)s[n++]=o;for(n="a".charCodeAt(0),o=10;o<36;++o)s[n++]=o;for(n="A".charCodeAt(0),o=10;o<36;++o)s[n++]=o;function c(e){return a.charAt(e)}function u(e,t){return null==(e=s[e.charCodeAt(t)])?-1:e}function h(e){var t=i();return t.fromInt(e),t}function l(e){var t,i=1;return 0!=(t=e>>>16)&&(e=t,i+=16),0!=(t=e>>8)&&(e=t,i+=8),0!=(t=e>>4)&&(e=t,i+=4),0!=(t=e>>2)&&(e=t,i+=2),0!=(t=e>>1)&&(e=t,i+=1),i}function p(e){this.m=e}function d(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}function f(e,t){return e&t}function m(e,t){return e|t}function g(e,t){return e^t}function v(e,t){return e&~t}function y(){}function b(e){return e}function w(e){this.r2=i(),this.q3=i(),t.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}p.prototype.convert=function(e){return e.s<0||0<=e.compareTo(this.m)?e.mod(this.m):e},p.prototype.revert=function(e){return e},p.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},p.prototype.mulTo=function(e,t,i){e.multiplyTo(t,i),this.reduce(i)},p.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},d.prototype.convert=function(e){var r=i();return e.abs().dlShiftTo(this.m.t,r),r.divRemTo(this.m,null,r),e.s<0&&0<r.compareTo(t.ZERO)&&this.m.subTo(r,r),r},d.prototype.revert=function(e){var t=i();return e.copyTo(t),this.reduce(t),t},d.prototype.reduce=function(e){for(;e.t<=this.mt2;)e[e.t++]=0;for(var t=0;t<this.m.t;++t){var i=32767&e[t],r=i*this.mpl+((i*this.mph+(e[t]>>15)*this.mpl&this.um)<<15)&e.DM;for(e[i=t+this.m.t]+=this.m.am(0,r,e,t,0,this.m.t);e[i]>=e.DV;)e[i]-=e.DV,e[++i]++}e.clamp(),e.drShiftTo(this.m.t,e),0<=e.compareTo(this.m)&&e.subTo(this.m,e)},d.prototype.mulTo=function(e,t,i){e.multiplyTo(t,i),this.reduce(i)},d.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},t.prototype.copyTo=function(e){for(var t=this.t-1;0<=t;--t)e[t]=this[t];e.t=this.t,e.s=this.s},t.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,0<e?this[0]=e:e<-1?this[0]=e+this.DV:this.t=0},t.prototype.fromString=function(e,i){var r;if(16==i)r=4;else if(8==i)r=3;else if(256==i)r=8;else if(2==i)r=1;else if(32==i)r=5;else{if(4!=i)return void this.fromRadix(e,i);r=2}this.t=0,this.s=0;for(var a=e.length,s=!1,n=0;0<=--a;){var o=8==r?255&e[a]:u(e,a);o<0?"-"==e.charAt(a)&&(s=!0):(s=!1,0==n?this[this.t++]=o:n+r>this.DB?(this[this.t-1]|=(o&(1<<this.DB-n)-1)<<n,this[this.t++]=o>>this.DB-n):this[this.t-1]|=o<<n,(n+=r)>=this.DB&&(n-=this.DB))}8==r&&0!=(128&e[0])&&(this.s=-1,0<n)&&(this[this.t-1]|=(1<<this.DB-n)-1<<n),this.clamp(),s&&t.ZERO.subTo(this,this)},t.prototype.clamp=function(){for(var e=this.s&this.DM;0<this.t&&this[this.t-1]==e;)--this.t},t.prototype.dlShiftTo=function(e,t){for(var i=this.t-1;0<=i;--i)t[i+e]=this[i];for(i=e-1;0<=i;--i)t[i]=0;t.t=this.t+e,t.s=this.s},t.prototype.drShiftTo=function(e,t){for(var i=e;i<this.t;++i)t[i-e]=this[i];t.t=Math.max(this.t-e,0),t.s=this.s},t.prototype.lShiftTo=function(e,t){for(var i=e%this.DB,r=this.DB-i,a=(1<<r)-1,s=Math.floor(e/this.DB),n=this.s<<i&this.DM,o=this.t-1;0<=o;--o)t[o+s+1]=this[o]>>r|n,n=(this[o]&a)<<i;for(o=s-1;0<=o;--o)t[o]=0;t[s]=n,t.t=this.t+s+1,t.s=this.s,t.clamp()},t.prototype.rShiftTo=function(e,t){t.s=this.s;var i=Math.floor(e/this.DB);if(i>=this.t)t.t=0;else{var r=e%this.DB,a=this.DB-r,s=(1<<r)-1;t[0]=this[i]>>r;for(var n=i+1;n<this.t;++n)t[n-i-1]|=(this[n]&s)<<a,t[n-i]=this[n]>>r;0<r&&(t[this.t-i-1]|=(this.s&s)<<a),t.t=this.t-i,t.clamp()}},t.prototype.subTo=function(e,t){for(var i=0,r=0,a=Math.min(e.t,this.t);i<a;)r+=this[i]-e[i],t[i++]=r&this.DM,r>>=this.DB;if(e.t<this.t){for(r-=e.s;i<this.t;)r+=this[i],t[i++]=r&this.DM,r>>=this.DB;r+=this.s}else{for(r+=this.s;i<e.t;)r-=e[i],t[i++]=r&this.DM,r>>=this.DB;r-=e.s}t.s=r<0?-1:0,r<-1?t[i++]=this.DV+r:0<r&&(t[i++]=r),t.t=i,t.clamp()},t.prototype.multiplyTo=function(e,i){var r=this.abs(),a=e.abs(),s=r.t;for(i.t=s+a.t;0<=--s;)i[s]=0;for(s=0;s<a.t;++s)i[s+r.t]=r.am(0,a[s],i,s,0,r.t);i.s=0,i.clamp(),this.s!=e.s&&t.ZERO.subTo(i,i)},t.prototype.squareTo=function(e){for(var t=this.abs(),i=e.t=2*t.t;0<=--i;)e[i]=0;for(i=0;i<t.t-1;++i){var r=t.am(i,t[i],e,2*i,0,1);(e[i+t.t]+=t.am(i+1,2*t[i],e,2*i+1,r,t.t-i-1))>=t.DV&&(e[i+t.t]-=t.DV,e[i+t.t+1]=1)}0<e.t&&(e[e.t-1]+=t.am(i,t[i],e,2*i,0,1)),e.s=0,e.clamp()},t.prototype.divRemTo=function(e,r,a){if(!((p=e.abs()).t<=0)){var s=this.abs();if(s.t<p.t)null!=r&&r.fromInt(0),null!=a&&this.copyTo(a);else{null==a&&(a=i());var n=i(),o=this.s,c=(e=e.s,this.DB-l(p[p.t-1])),u=(0<c?(p.lShiftTo(c,n),s.lShiftTo(c,a)):(p.copyTo(n),s.copyTo(a)),n.t),h=n[u-1];if(0!=h){var p=h*(1<<this.F1)+(1<u?n[u-2]>>this.F2:0),d=this.FV/p,f=(1<<this.F1)/p,m=1<<this.F2,g=a.t,v=g-u,y=null==r?i():r;for(n.dlShiftTo(v,y),0<=a.compareTo(y)&&(a[a.t++]=1,a.subTo(y,a)),t.ONE.dlShiftTo(u,y),y.subTo(n,n);n.t<u;)n[n.t++]=0;for(;0<=--v;){var b=a[--g]==h?this.DM:Math.floor(a[g]*d+(a[g-1]+m)*f);if((a[g]+=n.am(0,b,a,v,0,u))<b)for(n.dlShiftTo(v,y),a.subTo(y,a);a[g]<--b;)a.subTo(y,a)}null!=r&&(a.drShiftTo(u,r),o!=e)&&t.ZERO.subTo(r,r),a.t=u,a.clamp(),0<c&&a.rShiftTo(c,a),o<0&&t.ZERO.subTo(a,a)}}}},t.prototype.invDigit=function(){var e,t;return this.t<1||0==(1&(e=this[0]))?0:0<(t=(t=(t=(t=(t=3&e)*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)?this.DV-t:-t},t.prototype.isEven=function(){return 0==(0<this.t?1&this[0]:this.s)},t.prototype.exp=function(e,r){if(4294967295<e||e<1)return t.ONE;var a,s=i(),n=i(),o=r.convert(this),c=l(e)-1;for(o.copyTo(s);0<=--c;)r.sqrTo(s,n),0<(e&1<<c)?r.mulTo(n,o,s):(a=s,s=n,n=a);return r.revert(s)},t.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var i,r=(1<<t)-1,a=!1,s="",n=this.t,o=this.DB-n*this.DB%t;if(0<n--)for(o<this.DB&&0<(i=this[n]>>o)&&(a=!0,s=c(i));0<=n;)o<t?(i=(this[n]&(1<<o)-1)<<t-o,i|=this[--n]>>(o+=this.DB-t)):(i=this[n]>>(o-=t)&r,o<=0&&(o+=this.DB,--n)),(a=0<i||a)&&(s+=c(i));return a?s:"0"},t.prototype.negate=function(){var e=i();return t.ZERO.subTo(this,e),e},t.prototype.abs=function(){return this.s<0?this.negate():this},t.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var i=this.t;if(0!=(t=i-e.t))return this.s<0?-t:t;for(;0<=--i;)if(0!=(t=this[i]-e[i]))return t;return 0},t.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+l(this[this.t-1]^this.s&this.DM)},t.prototype.mod=function(e){var r=i();return this.abs().divRemTo(e,null,r),this.s<0&&0<r.compareTo(t.ZERO)&&e.subTo(r,r),r},t.prototype.modPowInt=function(e,t){return t=new(e<256||t.isEven()?p:d)(t),this.exp(e,t)},t.ZERO=h(0),t.ONE=h(1),y.prototype.convert=b,y.prototype.revert=b,y.prototype.mulTo=function(e,t,i){e.multiplyTo(t,i)},y.prototype.sqrTo=function(e,t){e.squareTo(t)},w.prototype.convert=function(e){var t;return e.s<0||e.t>2*this.m.t?e.mod(this.m):e.compareTo(this.m)<0?e:(t=i(),e.copyTo(t),this.reduce(t),t)},w.prototype.revert=function(e){return e},w.prototype.reduce=function(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);0<=e.compareTo(this.m);)e.subTo(this.m,e)},w.prototype.mulTo=function(e,t,i){e.multiplyTo(t,i),this.reduce(i)},w.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var x,k=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],S=(1<<26)/k[k.length-1];function _(){var e;e=(new Date).getTime(),E[j++]^=255&e,E[j++]^=e>>8&255,E[j++]^=e>>16&255,E[j++]^=e>>24&255,T<=j&&(j-=T)}if(t.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},t.prototype.toRadix=function(e){if(null==e&&(e=10),0==this.signum()||e<2||36<e)return"0";var t=this.chunkSize(e),r=Math.pow(e,t),a=h(r),s=i(),n=i(),o="";for(this.divRemTo(a,s,n);0<s.signum();)o=(r+n.intValue()).toString(e).substr(1)+o,s.divRemTo(a,s,n);return n.intValue().toString(e)+o},t.prototype.fromRadix=function(e,i){this.fromInt(0);for(var r=this.chunkSize(i=null==i?10:i),a=Math.pow(i,r),s=!1,n=0,o=0,c=0;c<e.length;++c){var h=u(e,c);h<0?"-"==e.charAt(c)&&0==this.signum()&&(s=!0):(o=i*o+h,++n>=r&&(this.dMultiply(a),this.dAddOffset(o,0),o=n=0))}0<n&&(this.dMultiply(Math.pow(i,n)),this.dAddOffset(o,0)),s&&t.ZERO.subTo(this,this)},t.prototype.fromNumber=function(e,i,r){if("number"==typeof i)if(e<2)this.fromInt(1);else for(this.fromNumber(e,r),this.testBit(e-1)||this.bitwiseTo(t.ONE.shiftLeft(e-1),m,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(i);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(t.ONE.shiftLeft(e-1),this);else{var a=7&e;(r=new Array).length=1+(e>>3),i.nextBytes(r),0<a?r[0]&=(1<<a)-1:r[0]=0,this.fromString(r,256)}},t.prototype.bitwiseTo=function(e,t,i){for(var r,a=Math.min(e.t,this.t),s=0;s<a;++s)i[s]=t(this[s],e[s]);if(e.t<this.t){for(r=e.s&this.DM,s=a;s<this.t;++s)i[s]=t(this[s],r);i.t=this.t}else{for(r=this.s&this.DM,s=a;s<e.t;++s)i[s]=t(r,e[s]);i.t=e.t}i.s=t(this.s,e.s),i.clamp()},t.prototype.changeBit=function(e,i){return e=t.ONE.shiftLeft(e),this.bitwiseTo(e,i,e),e},t.prototype.addTo=function(e,t){for(var i=0,r=0,a=Math.min(e.t,this.t);i<a;)r+=this[i]+e[i],t[i++]=r&this.DM,r>>=this.DB;if(e.t<this.t){for(r+=e.s;i<this.t;)r+=this[i],t[i++]=r&this.DM,r>>=this.DB;r+=this.s}else{for(r+=this.s;i<e.t;)r+=e[i],t[i++]=r&this.DM,r>>=this.DB;r+=e.s}t.s=r<0?-1:0,0<r?t[i++]=r:r<-1&&(t[i++]=this.DV+r),t.t=i,t.clamp()},t.prototype.dMultiply=function(e){this[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},t.prototype.dAddOffset=function(e,t){if(0!=e){for(;this.t<=t;)this[this.t++]=0;for(this[t]+=e;this[t]>=this.DV;)this[t]-=this.DV,++t>=this.t&&(this[this.t++]=0),++this[t]}},t.prototype.multiplyLowerTo=function(e,t,i){var r,a=Math.min(this.t+e.t,t);for(i.s=0,i.t=a;0<a;)i[--a]=0;for(r=i.t-this.t;a<r;++a)i[a+this.t]=this.am(0,e[a],i,a,0,this.t);for(r=Math.min(e.t,t);a<r;++a)this.am(0,e[a],i,a,0,t-a);i.clamp()},t.prototype.multiplyUpperTo=function(e,t,i){var r=i.t=this.t+e.t- --t;for(i.s=0;0<=--r;)i[r]=0;for(r=Math.max(t-this.t,0);r<e.t;++r)i[this.t+r-t]=this.am(t-r,e[r],i,0,0,this.t+r-t);i.clamp(),i.drShiftTo(1,i)},t.prototype.modInt=function(e){if(e<=0)return 0;var t=this.DV%e,i=this.s<0?e-1:0;if(0<this.t)if(0==t)i=this[0]%e;else for(var r=this.t-1;0<=r;--r)i=(t*i+this[r])%e;return i},t.prototype.millerRabin=function(e){var r=this.subtract(t.ONE),a=r.getLowestSetBit();if(a<=0)return!1;for(var s=r.shiftRight(a),n=(k.length<(e=e+1>>1)&&(e=k.length),i()),o=0;o<e;++o){n.fromInt(k[Math.floor(Math.random()*k.length)]);var c=n.modPow(s,this);if(0!=c.compareTo(t.ONE)&&0!=c.compareTo(r)){for(var u=1;u++<a&&0!=c.compareTo(r);)if(0==(c=c.modPowInt(2,this)).compareTo(t.ONE))return!1;if(0!=c.compareTo(r))return!1}}return!0},t.prototype.clone=function(){var e=i();return this.copyTo(e),e},t.prototype.intValue=function(){if(this.s<0){if(1==this.t)return this[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this[0];if(0==this.t)return 0}return(this[1]&(1<<32-this.DB)-1)<<this.DB|this[0]},t.prototype.byteValue=function(){return 0==this.t?this.s:this[0]<<24>>24},t.prototype.shortValue=function(){return 0==this.t?this.s:this[0]<<16>>16},t.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this[0]<=0?0:1},t.prototype.toByteArray=function(){var e,t=this.t,i=new Array,r=(i[0]=this.s,this.DB-t*this.DB%8),a=0;if(0<t--)for(r<this.DB&&(e=this[t]>>r)!=(this.s&this.DM)>>r&&(i[a++]=e|this.s<<this.DB-r);0<=t;)r<8?(e=(this[t]&(1<<r)-1)<<8-r,e|=this[--t]>>(r+=this.DB-8)):(e=this[t]>>(r-=8)&255,r<=0&&(r+=this.DB,--t)),0!=(128&e)&&(e|=-256),0==a&&(128&this.s)!=(128&e)&&++a,(0<a||e!=this.s)&&(i[a++]=e);return i},t.prototype.equals=function(e){return 0==this.compareTo(e)},t.prototype.min=function(e){return this.compareTo(e)<0?this:e},t.prototype.max=function(e){return 0<this.compareTo(e)?this:e},t.prototype.and=function(e){var t=i();return this.bitwiseTo(e,f,t),t},t.prototype.or=function(e){var t=i();return this.bitwiseTo(e,m,t),t},t.prototype.xor=function(e){var t=i();return this.bitwiseTo(e,g,t),t},t.prototype.andNot=function(e){var t=i();return this.bitwiseTo(e,v,t),t},t.prototype.not=function(){for(var e=i(),t=0;t<this.t;++t)e[t]=this.DM&~this[t];return e.t=this.t,e.s=~this.s,e},t.prototype.shiftLeft=function(e){var t=i();return e<0?this.rShiftTo(-e,t):this.lShiftTo(e,t),t},t.prototype.shiftRight=function(e){var t=i();return e<0?this.lShiftTo(-e,t):this.rShiftTo(e,t),t},t.prototype.getLowestSetBit=function(){for(var e,t,i=0;i<this.t;++i)if(0!=this[i])return i*this.DB+(t=void 0,0==(e=this[i])?-1:((t=0)==(65535&e)&&(e>>=16,t+=16),0==(255&e)&&(e>>=8,t+=8),0==(15&e)&&(e>>=4,t+=4),0==(3&e)&&(e>>=2,t+=2),0==(1&e)&&++t,t));return this.s<0?this.t*this.DB:-1},t.prototype.bitCount=function(){for(var e=0,t=this.s&this.DM,i=0;i<this.t;++i)e+=function(e){for(var t=0;0!=e;)e&=e-1,++t;return t}(this[i]^t);return e},t.prototype.testBit=function(e){var t=Math.floor(e/this.DB);return t>=this.t?0!=this.s:0!=(this[t]&1<<e%this.DB)},t.prototype.setBit=function(e){return this.changeBit(e,m)},t.prototype.clearBit=function(e){return this.changeBit(e,v)},t.prototype.flipBit=function(e){return this.changeBit(e,g)},t.prototype.add=function(e){var t=i();return this.addTo(e,t),t},t.prototype.subtract=function(e){var t=i();return this.subTo(e,t),t},t.prototype.multiply=function(e){var t=i();return this.multiplyTo(e,t),t},t.prototype.divide=function(e){var t=i();return this.divRemTo(e,t,null),t},t.prototype.remainder=function(e){var t=i();return this.divRemTo(e,null,t),t},t.prototype.divideAndRemainder=function(e){var t=i(),r=i();return this.divRemTo(e,t,r),new Array(t,r)},t.prototype.modPow=function(e,t){var r=e.bitLength(),a=h(1);if(r<=0)return a;var s=r<18?1:r<48?3:r<144?4:r<768?5:6,n=new(r<8?p:t.isEven()?w:d)(t),o=new Array,c=3,u=s-1,f=(1<<s)-1;if(o[1]=n.convert(this),1<s){var m=i();for(n.sqrTo(o[1],m);c<=f;)o[c]=i(),n.mulTo(m,o[c-2],o[c]),c+=2}var g,v,y=e.t-1,b=!0,x=i();for(r=l(e[y])-1;0<=y;){for(u<=r?g=e[y]>>r-u&f:(g=(e[y]&(1<<r+1)-1)<<u-r,0<y&&(g|=e[y-1]>>this.DB+r-u)),c=s;0==(1&g);)g>>=1,--c;if((r-=c)<0&&(r+=this.DB,--y),b)o[g].copyTo(a),b=!1;else{for(;1<c;)n.sqrTo(a,x),n.sqrTo(x,a),c-=2;0<c?n.sqrTo(a,x):(v=a,a=x,x=v),n.mulTo(x,o[g],a)}for(;0<=y&&0==(e[y]&1<<r);)n.sqrTo(a,x),v=a,a=x,x=v,--r<0&&(r=this.DB-1,--y)}return n.revert(a)},t.prototype.modInverse=function(e){var i=e.isEven();if(this.isEven()&&i||0==e.signum())return t.ZERO;for(var r=e.clone(),a=this.clone(),s=h(1),n=h(0),o=h(0),c=h(1);0!=r.signum();){for(;r.isEven();)r.rShiftTo(1,r),i?(s.isEven()&&n.isEven()||(s.addTo(this,s),n.subTo(e,n)),s.rShiftTo(1,s)):n.isEven()||n.subTo(e,n),n.rShiftTo(1,n);for(;a.isEven();)a.rShiftTo(1,a),i?(o.isEven()&&c.isEven()||(o.addTo(this,o),c.subTo(e,c)),o.rShiftTo(1,o)):c.isEven()||c.subTo(e,c),c.rShiftTo(1,c);0<=r.compareTo(a)?(r.subTo(a,r),i&&s.subTo(o,s),n.subTo(c,n)):(a.subTo(r,a),i&&o.subTo(s,o),c.subTo(n,c))}return 0!=a.compareTo(t.ONE)?t.ZERO:0<=c.compareTo(e)?c.subtract(e):c.signum()<0&&(c.addTo(e,c),c.signum()<0)?c.add(e):c},t.prototype.pow=function(e){return this.exp(e,new y)},t.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),i=e.s<0?e.negate():e.clone(),r=(t.compareTo(i)<0&&(e=t,t=i,i=e),t.getLowestSetBit());if((e=i.getLowestSetBit())<0)return t;for(0<(e=r<e?r:e)&&(t.rShiftTo(e,t),i.rShiftTo(e,i));0<t.signum();)0<(r=t.getLowestSetBit())&&t.rShiftTo(r,t),0<(r=i.getLowestSetBit())&&i.rShiftTo(r,i),0<=t.compareTo(i)?(t.subTo(i,t),t.rShiftTo(1,t)):(i.subTo(t,i),i.rShiftTo(1,i));return 0<e&&i.lShiftTo(e,i),i},t.prototype.isProbablePrime=function(e){var t,i=this.abs();if(1==i.t&&i[0]<=k[k.length-1]){for(t=0;t<k.length;++t)if(i[0]==k[t])return!0;return!1}if(i.isEven())return!1;for(t=1;t<k.length;){for(var r=k[t],a=t+1;a<k.length&&r<S;)r*=k[a++];for(r=i.modInt(r);t<a;)if(r%k[t++]==0)return!1}return i.millerRabin(e)},t.prototype.square=function(){var e=i();return this.squareTo(e),e},t.prototype.Barrett=w,null==E){var E=new Array,j=0;if("undefined"!=typeof window&&window.crypto)if(window.crypto.getRandomValues){var A=new Uint8Array(32);for(window.crypto.getRandomValues(A),I=0;I<32;++I)E[j++]=A[I]}else if("Netscape"==navigator.appName&&navigator.appVersion<"5")for(var R=window.crypto.random(32),I=0;I<R.length;++I)E[j++]=255&R.charCodeAt(I);for(;j<T;)I=Math.floor(65536*Math.random()),E[j++]=I>>>8,E[j++]=255&I;j=0,_()}function O(){if(null==x){for(_(),(x=new P).init(E),j=0;j<E.length;++j)E[j]=0;j=0}return x.next()}function C(){}function P(){this.i=0,this.j=0,this.S=new Array}C.prototype.nextBytes=function(e){for(var t=0;t<e.length;++t)e[t]=O()},P.prototype.init=function(e){for(var t,i,r=0;r<256;++r)this.S[r]=r;for(r=t=0;r<256;++r)t=t+this.S[r]+e[r%e.length]&255,i=this.S[r],this.S[r]=this.S[t],this.S[t]=i;this.i=0,this.j=0},P.prototype.next=function(){var e;return this.i=this.i+1&255,this.j=this.j+this.S[this.i]&255,e=this.S[this.i],this.S[this.i]=this.S[this.j],this.S[this.j]=e,this.S[e+this.S[this.i]&255]};var T=256;t.SecureRandom=C,e.exports=t.BigInteger=t}).call(this)},function(e,t,i){!function(e){"use strict";var t=function(e){var t,i=new Float64Array(16);if(e)for(t=0;t<e.length;t++)i[t]=e[t];return i},r=function(){throw new Error("no PRNG")},a=new Uint8Array(16),s=new Uint8Array(32),n=(s[0]=9,t()),o=t([1]),c=t([56129,1]),u=t([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),h=t([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),l=t([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),p=t([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),d=t([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function f(e,t,i,r){e[t]=i>>24&255,e[t+1]=i>>16&255,e[t+2]=i>>8&255,e[t+3]=255&i,e[t+4]=r>>24&255,e[t+5]=r>>16&255,e[t+6]=r>>8&255,e[t+7]=255&r}function m(e,t,i,r,a){for(var s=0,n=0;n<a;n++)s|=e[t+n]^i[r+n];return(1&s-1>>>8)-1}function g(e,t,i,r){return m(e,t,i,r,16)}function v(e,t,i,r){return m(e,t,i,r,32)}function y(e,t,i,r){for(var a,s=255&(r=r)[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,n=255&i[0]|(255&i[1])<<8|(255&i[2])<<16|(255&i[3])<<24,o=255&i[4]|(255&i[5])<<8|(255&i[6])<<16|(255&i[7])<<24,c=255&i[8]|(255&i[9])<<8|(255&i[10])<<16|(255&i[11])<<24,u=255&i[12]|(255&i[13])<<8|(255&i[14])<<16|(255&i[15])<<24,h=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,l=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,p=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,d=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,f=(t=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24),m=255&i[16]|(255&i[17])<<8|(255&i[18])<<16|(255&i[19])<<24,g=255&i[20]|(255&i[21])<<8|(255&i[22])<<16|(255&i[23])<<24,v=255&i[24]|(255&i[25])<<8|(255&i[26])<<16|(255&i[27])<<24,y=s,b=n,w=o,x=c,k=u,S=h,_=l,E=p,j=d,A=t,R=f,I=m,O=g,C=v,P=i=255&i[28]|(255&i[29])<<8|(255&i[30])<<16|(255&i[31])<<24,T=r=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,B=0;B<20;B+=2)y^=(a=(O^=(a=(j^=(a=(k^=(a=y+O|0)<<7|a>>>25)+y|0)<<9|a>>>23)+k|0)<<13|a>>>19)+j|0)<<18|a>>>14,S^=(a=(b^=(a=(C^=(a=(A^=(a=S+b|0)<<7|a>>>25)+S|0)<<9|a>>>23)+A|0)<<13|a>>>19)+C|0)<<18|a>>>14,R^=(a=(_^=(a=(w^=(a=(P^=(a=R+_|0)<<7|a>>>25)+R|0)<<9|a>>>23)+P|0)<<13|a>>>19)+w|0)<<18|a>>>14,T^=(a=(I^=(a=(E^=(a=(x^=(a=T+I|0)<<7|a>>>25)+T|0)<<9|a>>>23)+x|0)<<13|a>>>19)+E|0)<<18|a>>>14,y^=(a=(x^=(a=(w^=(a=(b^=(a=y+x|0)<<7|a>>>25)+y|0)<<9|a>>>23)+b|0)<<13|a>>>19)+w|0)<<18|a>>>14,S^=(a=(k^=(a=(E^=(a=(_^=(a=S+k|0)<<7|a>>>25)+S|0)<<9|a>>>23)+_|0)<<13|a>>>19)+E|0)<<18|a>>>14,R^=(a=(A^=(a=(j^=(a=(I^=(a=R+A|0)<<7|a>>>25)+R|0)<<9|a>>>23)+I|0)<<13|a>>>19)+j|0)<<18|a>>>14,T^=(a=(P^=(a=(C^=(a=(O^=(a=T+P|0)<<7|a>>>25)+T|0)<<9|a>>>23)+O|0)<<13|a>>>19)+C|0)<<18|a>>>14;b=b+n|0,w=w+o|0,x=x+c|0,k=k+u|0,S=S+h|0,_=_+l|0,E=E+p|0,j=j+d|0,A=A+t|0,R=R+f|0,I=I+m|0,O=O+g|0,C=C+v|0,P=P+i|0,T=T+r|0,e[0]=(y=y+s|0)>>>0&255,e[1]=y>>>8&255,e[2]=y>>>16&255,e[3]=y>>>24&255,e[4]=b>>>0&255,e[5]=b>>>8&255,e[6]=b>>>16&255,e[7]=b>>>24&255,e[8]=w>>>0&255,e[9]=w>>>8&255,e[10]=w>>>16&255,e[11]=w>>>24&255,e[12]=x>>>0&255,e[13]=x>>>8&255,e[14]=x>>>16&255,e[15]=x>>>24&255,e[16]=k>>>0&255,e[17]=k>>>8&255,e[18]=k>>>16&255,e[19]=k>>>24&255,e[20]=S>>>0&255,e[21]=S>>>8&255,e[22]=S>>>16&255,e[23]=S>>>24&255,e[24]=_>>>0&255,e[25]=_>>>8&255,e[26]=_>>>16&255,e[27]=_>>>24&255,e[28]=E>>>0&255,e[29]=E>>>8&255,e[30]=E>>>16&255,e[31]=E>>>24&255,e[32]=j>>>0&255,e[33]=j>>>8&255,e[34]=j>>>16&255,e[35]=j>>>24&255,e[36]=A>>>0&255,e[37]=A>>>8&255,e[38]=A>>>16&255,e[39]=A>>>24&255,e[40]=R>>>0&255,e[41]=R>>>8&255,e[42]=R>>>16&255,e[43]=R>>>24&255,e[44]=I>>>0&255,e[45]=I>>>8&255,e[46]=I>>>16&255,e[47]=I>>>24&255,e[48]=O>>>0&255,e[49]=O>>>8&255,e[50]=O>>>16&255,e[51]=O>>>24&255,e[52]=C>>>0&255,e[53]=C>>>8&255,e[54]=C>>>16&255,e[55]=C>>>24&255,e[56]=P>>>0&255,e[57]=P>>>8&255,e[58]=P>>>16&255,e[59]=P>>>24&255,e[60]=T>>>0&255,e[61]=T>>>8&255,e[62]=T>>>16&255,e[63]=T>>>24&255}function b(e,t,i,r){for(var a,s=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,n=255&i[0]|(255&i[1])<<8|(255&i[2])<<16|(255&i[3])<<24,o=255&i[4]|(255&i[5])<<8|(255&i[6])<<16|(255&i[7])<<24,c=255&i[8]|(255&i[9])<<8|(255&i[10])<<16|(255&i[11])<<24,u=255&i[12]|(255&i[13])<<8|(255&i[14])<<16|(255&i[15])<<24,h=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,l=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,p=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,d=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,f=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,m=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,g=255&i[16]|(255&i[17])<<8|(255&i[18])<<16|(255&i[19])<<24,v=255&i[20]|(255&i[21])<<8|(255&i[22])<<16|(255&i[23])<<24,y=255&i[24]|(255&i[25])<<8|(255&i[26])<<16|(255&i[27])<<24,b=255&i[28]|(255&i[29])<<8|(255&i[30])<<16|(255&i[31])<<24,w=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,x=0;x<20;x+=2)s^=(a=(v^=(a=(d^=(a=(u^=(a=s+v|0)<<7|a>>>25)+s|0)<<9|a>>>23)+u|0)<<13|a>>>19)+d|0)<<18|a>>>14,h^=(a=(n^=(a=(y^=(a=(f^=(a=h+n|0)<<7|a>>>25)+h|0)<<9|a>>>23)+f|0)<<13|a>>>19)+y|0)<<18|a>>>14,m^=(a=(l^=(a=(o^=(a=(b^=(a=m+l|0)<<7|a>>>25)+m|0)<<9|a>>>23)+b|0)<<13|a>>>19)+o|0)<<18|a>>>14,w^=(a=(g^=(a=(p^=(a=(c^=(a=w+g|0)<<7|a>>>25)+w|0)<<9|a>>>23)+c|0)<<13|a>>>19)+p|0)<<18|a>>>14,s^=(a=(c^=(a=(o^=(a=(n^=(a=s+c|0)<<7|a>>>25)+s|0)<<9|a>>>23)+n|0)<<13|a>>>19)+o|0)<<18|a>>>14,h^=(a=(u^=(a=(p^=(a=(l^=(a=h+u|0)<<7|a>>>25)+h|0)<<9|a>>>23)+l|0)<<13|a>>>19)+p|0)<<18|a>>>14,m^=(a=(f^=(a=(d^=(a=(g^=(a=m+f|0)<<7|a>>>25)+m|0)<<9|a>>>23)+g|0)<<13|a>>>19)+d|0)<<18|a>>>14,w^=(a=(b^=(a=(y^=(a=(v^=(a=w+b|0)<<7|a>>>25)+w|0)<<9|a>>>23)+v|0)<<13|a>>>19)+y|0)<<18|a>>>14;e[0]=s>>>0&255,e[1]=s>>>8&255,e[2]=s>>>16&255,e[3]=s>>>24&255,e[4]=h>>>0&255,e[5]=h>>>8&255,e[6]=h>>>16&255,e[7]=h>>>24&255,e[8]=m>>>0&255,e[9]=m>>>8&255,e[10]=m>>>16&255,e[11]=m>>>24&255,e[12]=w>>>0&255,e[13]=w>>>8&255,e[14]=w>>>16&255,e[15]=w>>>24&255,e[16]=l>>>0&255,e[17]=l>>>8&255,e[18]=l>>>16&255,e[19]=l>>>24&255,e[20]=p>>>0&255,e[21]=p>>>8&255,e[22]=p>>>16&255,e[23]=p>>>24&255,e[24]=d>>>0&255,e[25]=d>>>8&255,e[26]=d>>>16&255,e[27]=d>>>24&255,e[28]=f>>>0&255,e[29]=f>>>8&255,e[30]=f>>>16&255,e[31]=f>>>24&255}var w=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function x(e,t,i,r,a,s,n){for(var o,c=new Uint8Array(16),u=new Uint8Array(64),h=0;h<16;h++)c[h]=0;for(h=0;h<8;h++)c[h]=s[h];for(;64<=a;){for(y(u,c,n,w),h=0;h<64;h++)e[t+h]=i[r+h]^u[h];for(o=1,h=8;h<16;h++)o=o+(255&c[h])|0,c[h]=255&o,o>>>=8;a-=64,t+=64,r+=64}if(0<a)for(y(u,c,n,w),h=0;h<a;h++)e[t+h]=i[r+h]^u[h];return 0}function k(e,t,i,r,a){for(var s,n=new Uint8Array(16),o=new Uint8Array(64),c=0;c<16;c++)n[c]=0;for(c=0;c<8;c++)n[c]=r[c];for(;64<=i;){for(y(o,n,a,w),c=0;c<64;c++)e[t+c]=o[c];for(s=1,c=8;c<16;c++)s=s+(255&n[c])|0,n[c]=255&s,s>>>=8;i-=64,t+=64}if(0<i)for(y(o,n,a,w),c=0;c<i;c++)e[t+c]=o[c];return 0}function S(e,t,i,r,a){for(var s=new Uint8Array(32),n=(b(s,r,a,w),new Uint8Array(8)),o=0;o<8;o++)n[o]=r[o+16];return k(e,t,i,n,s)}function _(e,t,i,r,a,s,n){for(var o=new Uint8Array(32),c=(b(o,s,n,w),new Uint8Array(8)),u=0;u<8;u++)c[u]=s[u+16];return x(e,t,i,r,a,c,o)}var E=function(e){var t,i;this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,t=255&e[this.fin=0]|(255&e[1])<<8,this.r[0]=8191&t,i=255&e[2]|(255&e[3])<<8,this.r[1]=8191&(t>>>13|i<<3),t=255&e[4]|(255&e[5])<<8,this.r[2]=7939&(i>>>10|t<<6),i=255&e[6]|(255&e[7])<<8,this.r[3]=8191&(t>>>7|i<<9),t=255&e[8]|(255&e[9])<<8,this.r[4]=255&(i>>>4|t<<12),this.r[5]=t>>>1&8190,i=255&e[10]|(255&e[11])<<8,this.r[6]=8191&(t>>>14|i<<2),t=255&e[12]|(255&e[13])<<8,this.r[7]=8065&(i>>>11|t<<5),i=255&e[14]|(255&e[15])<<8,this.r[8]=8191&(t>>>8|i<<8),this.r[9]=i>>>5&127,this.pad[0]=255&e[16]|(255&e[17])<<8,this.pad[1]=255&e[18]|(255&e[19])<<8,this.pad[2]=255&e[20]|(255&e[21])<<8,this.pad[3]=255&e[22]|(255&e[23])<<8,this.pad[4]=255&e[24]|(255&e[25])<<8,this.pad[5]=255&e[26]|(255&e[27])<<8,this.pad[6]=255&e[28]|(255&e[29])<<8,this.pad[7]=255&e[30]|(255&e[31])<<8};function j(e,t,i,r,a,s){return(s=new E(s)).update(i,r,a),s.finish(e,t),0}function A(e,t,i,r,a,s){var n=new Uint8Array(16);return j(n,0,i,r,a,s),g(e,t,n,0)}function R(e,t,i,r,a){var s;if(i<32)return-1;for(_(e,0,t,0,i,r,a),j(e,16,e,32,i-32,e),s=0;s<16;s++)e[s]=0;return 0}function I(e,t,i,r,a){var s,n=new Uint8Array(32);if(i<32)return-1;if(S(n,0,32,r,a),0!==A(t,16,t,32,i-32,n))return-1;for(_(e,0,t,0,i,r,a),s=0;s<32;s++)e[s]=0;return 0}function O(e,t){for(var i=0;i<16;i++)e[i]=0|t[i]}function C(e){for(var t,i=1,r=0;r<16;r++)t=e[r]+i+65535,i=Math.floor(t/65536),e[r]=t-65536*i;e[0]+=i-1+37*(i-1)}function P(e,t,i){for(var r,a=~(i-1),s=0;s<16;s++)r=a&(e[s]^t[s]),e[s]^=r,t[s]^=r}function T(e,i){for(var r,a,s=t(),n=t(),o=0;o<16;o++)n[o]=i[o];for(C(n),C(n),C(n),r=0;r<2;r++){for(s[0]=n[0]-65517,o=1;o<15;o++)s[o]=n[o]-65535-(s[o-1]>>16&1),s[o-1]&=65535;s[15]=n[15]-32767-(s[14]>>16&1),a=s[15]>>16&1,s[14]&=65535,P(n,s,1-a)}for(o=0;o<16;o++)e[2*o]=255&n[o],e[2*o+1]=n[o]>>8}function B(e,t){var i=new Uint8Array(32),r=new Uint8Array(32);return T(i,e),T(r,t),v(i,0,r,0)}function N(e){var t=new Uint8Array(32);return T(t,e),1&t[0]}function z(e,t){for(var i=0;i<16;i++)e[i]=t[2*i]+(t[2*i+1]<<8);e[15]&=32767}function F(e,t,i){for(var r=0;r<16;r++)e[r]=t[r]+i[r]}function L(e,t,i){for(var r=0;r<16;r++)e[r]=t[r]-i[r]}function M(e,t,i){var r=0,a=0,s=0,n=0,o=0,c=0,u=0,h=0,l=0,p=0,d=0,f=0,m=0,g=0,v=0,y=0,b=0,w=0,x=0,k=0,S=0,_=0,E=0,j=0,A=0,R=0,I=0,O=0,C=0,P=0,T=0,B=i[0],N=i[1],z=i[2],F=i[3],L=i[4],M=i[5],D=i[6],H=i[7],U=i[8],q=i[9],V=i[10],K=i[11],W=i[12],$=i[13],Y=i[14],G=(i=i[15],t[0]);r+=G*B,s+=G*z,n+=G*F,o+=G*L,c+=G*M,u+=G*D,h+=G*H,l+=G*U,p+=G*q,d+=G*V,f+=G*K,m+=G*W,g+=G*$,v+=G*Y,y+=G*i,a=0+G*N+(G=t[1])*B,n+=G*z,o+=G*F,c+=G*L,u+=G*M,h+=G*D,l+=G*H,p+=G*U,d+=G*q,f+=G*V,m+=G*K,g+=G*W,v+=G*$,y+=G*Y,b+=G*i,s=s+G*N+(G=t[2])*B,o+=G*z,c+=G*F,u+=G*L,h+=G*M,l+=G*D,p+=G*H,d+=G*U,f+=G*q,m+=G*V,g+=G*K,v+=G*W,y+=G*$,b+=G*Y,w+=G*i,n=n+G*N+(G=t[3])*B,c+=G*z,u+=G*F,h+=G*L,l+=G*M,p+=G*D,d+=G*H,f+=G*U,m+=G*q,g+=G*V,v+=G*K,y+=G*W,b+=G*$,w+=G*Y,x+=G*i,o=o+G*N+(G=t[4])*B,u+=G*z,h+=G*F,l+=G*L,p+=G*M,d+=G*D,f+=G*H,m+=G*U,g+=G*q,v+=G*V,y+=G*K,b+=G*W,w+=G*$,x+=G*Y,k+=G*i,c=c+G*N+(G=t[5])*B,h+=G*z,l+=G*F,p+=G*L,d+=G*M,f+=G*D,m+=G*H,g+=G*U,v+=G*q,y+=G*V,b+=G*K,w+=G*W,x+=G*$,k+=G*Y,S+=G*i,u=u+G*N+(G=t[6])*B,l+=G*z,p+=G*F,d+=G*L,f+=G*M,m+=G*D,g+=G*H,v+=G*U,y+=G*q,b+=G*V,w+=G*K,x+=G*W,k+=G*$,S+=G*Y,_+=G*i,h=h+G*N+(G=t[7])*B,p+=G*z,d+=G*F,f+=G*L,m+=G*M,g+=G*D,v+=G*H,y+=G*U,b+=G*q,w+=G*V,x+=G*K,k+=G*W,S+=G*$,_+=G*Y,E+=G*i,l=l+G*N+(G=t[8])*B,d+=G*z,f+=G*F,m+=G*L,g+=G*M,v+=G*D,y+=G*H,b+=G*U,w+=G*q,x+=G*V,k+=G*K,S+=G*W,_+=G*$,E+=G*Y,j+=G*i,p=p+G*N+(G=t[9])*B,f+=G*z,m+=G*F,g+=G*L,v+=G*M,y+=G*D,b+=G*H,w+=G*U,x+=G*q,k+=G*V,S+=G*K,_+=G*W,E+=G*$,j+=G*Y,A+=G*i,d=d+G*N+(G=t[10])*B,m+=G*z,g+=G*F,v+=G*L,y+=G*M,b+=G*D,w+=G*H,x+=G*U,k+=G*q,S+=G*V,_+=G*K,E+=G*W,j+=G*$,A+=G*Y,R+=G*i,f=f+G*N+(G=t[11])*B,g+=G*z,v+=G*F,y+=G*L,b+=G*M,w+=G*D,x+=G*H,k+=G*U,S+=G*q,_+=G*V,E+=G*K,j+=G*W,A+=G*$,R+=G*Y,I+=G*i,m=m+G*N+(G=t[12])*B,v+=G*z,y+=G*F,b+=G*L,w+=G*M,x+=G*D,k+=G*H,S+=G*U,_+=G*q,E+=G*V,j+=G*K,A+=G*W,R+=G*$,I+=G*Y,O+=G*i,g=g+G*N+(G=t[13])*B,y+=G*z,b+=G*F,w+=G*L,x+=G*M,k+=G*D,S+=G*H,_+=G*U,E+=G*q,j+=G*V,A+=G*K,R+=G*W,I+=G*$,O+=G*Y,C+=G*i,v=v+G*N+(G=t[14])*B,b+=G*z,w+=G*F,x+=G*L,k+=G*M,S+=G*D,_+=G*H,E+=G*U,j+=G*q,A+=G*V,R+=G*K,I+=G*W,O+=G*$,C+=G*Y,P+=G*i,y=y+G*N+(G=t[15])*B,a+=38*(w+=G*z),s+=38*(x+=G*F),n+=38*(k+=G*L),o+=38*(S+=G*M),c+=38*(_+=G*D),u+=38*(E+=G*H),h+=38*(j+=G*U),l+=38*(A+=G*q),p+=38*(R+=G*V),d+=38*(I+=G*K),f+=38*(O+=G*W),m+=38*(C+=G*$),g+=38*(P+=G*Y),v+=38*(T+=G*i),r=(G=1+(r+=38*(b+=G*N))+65535)-65536*(t=Math.floor(G/65536)),a=(G=a+t+65535)-65536*(t=Math.floor(G/65536)),s=(G=s+t+65535)-65536*(t=Math.floor(G/65536)),n=(G=n+t+65535)-65536*(t=Math.floor(G/65536)),o=(G=o+t+65535)-65536*(t=Math.floor(G/65536)),c=(G=c+t+65535)-65536*(t=Math.floor(G/65536)),u=(G=u+t+65535)-65536*(t=Math.floor(G/65536)),h=(G=h+t+65535)-65536*(t=Math.floor(G/65536)),l=(G=l+t+65535)-65536*(t=Math.floor(G/65536)),p=(G=p+t+65535)-65536*(t=Math.floor(G/65536)),d=(G=d+t+65535)-65536*(t=Math.floor(G/65536)),f=(G=f+t+65535)-65536*(t=Math.floor(G/65536)),m=(G=m+t+65535)-65536*(t=Math.floor(G/65536)),g=(G=g+t+65535)-65536*(t=Math.floor(G/65536)),v=(G=v+t+65535)-65536*(t=Math.floor(G/65536)),y=(G=y+t+65535)-65536*(t=Math.floor(G/65536)),r=(G=1+(r+=t-1+37*(t-1))+65535)-65536*(t=Math.floor(G/65536)),a=(G=a+t+65535)-65536*(t=Math.floor(G/65536)),s=(G=s+t+65535)-65536*(t=Math.floor(G/65536)),n=(G=n+t+65535)-65536*(t=Math.floor(G/65536)),o=(G=o+t+65535)-65536*(t=Math.floor(G/65536)),c=(G=c+t+65535)-65536*(t=Math.floor(G/65536)),u=(G=u+t+65535)-65536*(t=Math.floor(G/65536)),h=(G=h+t+65535)-65536*(t=Math.floor(G/65536)),l=(G=l+t+65535)-65536*(t=Math.floor(G/65536)),p=(G=p+t+65535)-65536*(t=Math.floor(G/65536)),d=(G=d+t+65535)-65536*(t=Math.floor(G/65536)),f=(G=f+t+65535)-65536*(t=Math.floor(G/65536)),m=(G=m+t+65535)-65536*(t=Math.floor(G/65536)),g=(G=g+t+65535)-65536*(t=Math.floor(G/65536)),v=(G=v+t+65535)-65536*(t=Math.floor(G/65536)),y=(G=y+t+65535)-65536*(t=Math.floor(G/65536)),e[0]=r+=t-1+37*(t-1),e[1]=a,e[2]=s,e[3]=n,e[4]=o,e[5]=c,e[6]=u,e[7]=h,e[8]=l,e[9]=p,e[10]=d,e[11]=f,e[12]=m,e[13]=g,e[14]=v,e[15]=y}function D(e,t){M(e,t,t)}function H(e,i){for(var r=t(),a=0;a<16;a++)r[a]=i[a];for(a=253;0<=a;a--)D(r,r),2!==a&&4!==a&&M(r,r,i);for(a=0;a<16;a++)e[a]=r[a]}function U(e,i,r){for(var a,s=new Uint8Array(32),n=new Float64Array(80),o=t(),u=t(),h=t(),l=t(),p=t(),d=t(),f=0;f<31;f++)s[f]=i[f];for(s[31]=127&i[31]|64,s[0]&=248,z(n,r),f=0;f<16;f++)u[f]=n[f],l[f]=o[f]=h[f]=0;for(o[0]=l[0]=1,f=254;0<=f;--f)P(o,u,a=s[f>>>3]>>>(7&f)&1),P(h,l,a),F(p,o,h),L(o,o,h),F(h,u,l),L(u,u,l),D(l,p),D(d,o),M(o,h,o),M(h,u,p),F(p,o,h),L(o,o,h),D(u,o),L(h,l,d),M(o,h,c),F(o,o,l),M(h,h,o),M(o,l,d),M(l,u,n),D(u,p),P(o,u,a),P(h,l,a);for(f=0;f<16;f++)n[f+16]=o[f],n[f+32]=h[f],n[f+48]=u[f],n[f+64]=l[f];r=n.subarray(32);var m=n.subarray(16);return H(r,r),M(m,m,r),T(e,m),0}function q(e,t){return U(e,t,s)}function V(e,t){return r(t,32),q(e,t)}function K(e,t,i){var r=new Uint8Array(32);return U(r,i,t),b(e,a,r,w)}E.prototype.blocks=function(e,t,i){for(var r,a,s,n,o,c,u,h,l,p,d,f=this.fin?0:2048,m=this.h[0],g=this.h[1],v=this.h[2],y=this.h[3],b=this.h[4],w=this.h[5],x=this.h[6],k=this.h[7],S=this.h[8],_=this.h[9],E=this.r[0],j=this.r[1],A=this.r[2],R=this.r[3],I=this.r[4],O=this.r[5],C=this.r[6],P=this.r[7],T=this.r[8],B=this.r[9];16<=i;)a=r=0,r=(a=(a=(a+=(m+=8191&(s=255&e[t+0]|(255&e[t+1])<<8))*E)+(g+=8191&(s>>>13|(s=255&e[t+2]|(255&e[t+3])<<8)<<3))*(5*B)+(v+=8191&(s>>>10|(s=255&e[t+4]|(255&e[t+5])<<8)<<6))*(5*T))+(y+=8191&(s>>>7|(s=255&e[t+6]|(255&e[t+7])<<8)<<9))*(5*P)+(b+=8191&(s>>>4|(s=255&e[t+8]|(255&e[t+9])<<8)<<12))*(5*C))>>>13,s=r+=(a=(a=(a=(8191&a)+(w+=s>>>1&8191)*(5*O))+(x+=8191&(s>>>14|(s=255&e[t+10]|(255&e[t+11])<<8)<<2))*(5*I)+(k+=8191&(s>>>11|(s=255&e[t+12]|(255&e[t+13])<<8)<<5))*(5*R))+(S+=8191&(s>>>8|(s=255&e[t+14]|(255&e[t+15])<<8)<<8))*(5*A)+(_+=s>>>5|f)*(5*j))>>>13,r=(s=(s=(s+=m*j)+g*E+v*(5*B))+y*(5*T)+b*(5*P))>>>13,n=r+=(s=(s=(s=(8191&s)+w*(5*C))+x*(5*O)+k*(5*I))+S*(5*R)+_*(5*A))>>>13,r=(n=(n=(n+=m*A)+g*j+v*E)+y*(5*B)+b*(5*T))>>>13,o=r+=(n=(n=(n=(8191&n)+w*(5*P))+x*(5*C)+k*(5*O))+S*(5*I)+_*(5*R))>>>13,r=(o=(o=(o+=m*R)+g*A+v*j)+y*E+b*(5*B))>>>13,c=r+=(o=(o=(o=(8191&o)+w*(5*T))+x*(5*P)+k*(5*C))+S*(5*O)+_*(5*I))>>>13,r=(c=(c=(c+=m*I)+g*R+v*A)+y*j+b*E)>>>13,u=r+=(c=(c=(c=(8191&c)+w*(5*B))+x*(5*T)+k*(5*P))+S*(5*C)+_*(5*O))>>>13,r=(u=(u=(u+=m*O)+g*I+v*R)+y*A+b*j)>>>13,h=r+=(u=(u=(u=(8191&u)+w*E)+x*(5*B)+k*(5*T))+S*(5*P)+_*(5*C))>>>13,r=(h=(h=(h+=m*C)+g*O+v*I)+y*R+b*A)>>>13,l=r+=(h=(h=(h=(8191&h)+w*j)+x*E+k*(5*B))+S*(5*T)+_*(5*P))>>>13,r=(l=(l=(l+=m*P)+g*C+v*O)+y*I+b*R)>>>13,p=r+=(l=(l=(l=(8191&l)+w*A)+x*j+k*E)+S*(5*B)+_*(5*T))>>>13,r=(p=(p=(p+=m*T)+g*P+v*C)+y*O+b*I)>>>13,d=r+=(p=(p=(p=(8191&p)+w*R)+x*A+k*j)+S*E+_*(5*B))>>>13,r=(d=(d=(d+=m*B)+g*T+v*P)+y*C+b*O)>>>13,m=a=8191&(r=(r=((r+=(d=(d=(d=(8191&d)+w*I)+x*R+k*A)+S*j+_*E)>>>13)<<2)+r|0)+(a&=8191)|0),g=s=(8191&s)+(r>>>=13),v=n&=8191,y=o&=8191,b=c&=8191,w=u&=8191,x=h&=8191,k=l&=8191,S=p&=8191,_=d&=8191,t+=16,i-=16;this.h[0]=m,this.h[1]=g,this.h[2]=v,this.h[3]=y,this.h[4]=b,this.h[5]=w,this.h[6]=x,this.h[7]=k,this.h[8]=S,this.h[9]=_},E.prototype.finish=function(e,t){var i,r,a,s,n=new Uint16Array(10);if(this.leftover){for(s=this.leftover,this.buffer[s++]=1;s<16;s++)this.buffer[s]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(i=this.h[1]>>>13,this.h[1]&=8191,s=2;s<10;s++)this.h[s]+=i,i=this.h[s]>>>13,this.h[s]&=8191;for(this.h[0]+=5*i,i=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=i,i=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=i,n[0]=this.h[0]+5,i=n[0]>>>13,n[0]&=8191,s=1;s<10;s++)n[s]=this.h[s]+i,i=n[s]>>>13,n[s]&=8191;for(n[9]-=8192,r=(1^i)-1,s=0;s<10;s++)n[s]&=r;for(r=~r,s=0;s<10;s++)this.h[s]=this.h[s]&r|n[s];for(this.h[0]=65535&(this.h[0]|this.h[1]<<13),this.h[1]=65535&(this.h[1]>>>3|this.h[2]<<10),this.h[2]=65535&(this.h[2]>>>6|this.h[3]<<7),this.h[3]=65535&(this.h[3]>>>9|this.h[4]<<4),this.h[4]=65535&(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14),this.h[5]=65535&(this.h[6]>>>2|this.h[7]<<11),this.h[6]=65535&(this.h[7]>>>5|this.h[8]<<8),this.h[7]=65535&(this.h[8]>>>8|this.h[9]<<5),a=this.h[0]+this.pad[0],this.h[0]=65535&a,s=1;s<8;s++)a=(this.h[s]+this.pad[s]|0)+(a>>>16)|0,this.h[s]=65535&a;e[t+0]=this.h[0]>>>0&255,e[t+1]=this.h[0]>>>8&255,e[t+2]=this.h[1]>>>0&255,e[t+3]=this.h[1]>>>8&255,e[t+4]=this.h[2]>>>0&255,e[t+5]=this.h[2]>>>8&255,e[t+6]=this.h[3]>>>0&255,e[t+7]=this.h[3]>>>8&255,e[t+8]=this.h[4]>>>0&255,e[t+9]=this.h[4]>>>8&255,e[t+10]=this.h[5]>>>0&255,e[t+11]=this.h[5]>>>8&255,e[t+12]=this.h[6]>>>0&255,e[t+13]=this.h[6]>>>8&255,e[t+14]=this.h[7]>>>0&255,e[t+15]=this.h[7]>>>8&255},E.prototype.update=function(e,t,i){var r,a;if(this.leftover){for(i<(a=16-this.leftover)&&(a=i),r=0;r<a;r++)this.buffer[this.leftover+r]=e[t+r];if(i-=a,t+=a,this.leftover+=a,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(16<=i&&(this.blocks(e,t,a=i-i%16),t+=a,i-=a),i){for(r=0;r<i;r++)this.buffer[this.leftover+r]=e[t+r];this.leftover+=i}};var W=R,$=I,Y=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function G(e,t,i,r){for(var a,s,n,o,c,u,h,l,p,d,f,m,g,v,y,b,w,x,k,S,_,E,j,A,R,I,O=new Int32Array(16),C=new Int32Array(16),P=e[0],T=e[1],B=e[2],N=e[3],z=e[4],F=e[5],L=e[6],M=e[7],D=t[0],H=t[1],U=t[2],q=t[3],V=t[4],K=t[5],W=t[6],$=t[7],G=0;128<=r;){for(k=0;k<16;k++)O[k]=i[(S=8*k+G)+0]<<24|i[S+1]<<16|i[S+2]<<8|i[S+3],C[k]=i[S+4]<<24|i[S+5]<<16|i[S+6]<<8|i[S+7];for(k=0;k<80;k++)if(a=P,s=T,n=B,o=N,p=D,d=H,f=U,m=q,j=65535&(E=$),A=E>>>16,R=65535&(_=M),I=_>>>16,A+=(E=((g=V)>>>14|(c=z)<<18)^(V>>>18|z<<14)^(z>>>9|V<<23))>>>16,I+=(_=(z>>>14|V<<18)^(z>>>18|V<<14)^(V>>>9|z<<23))>>>16,j=j+(65535&E)+(65535&(E=V&(v=K)^~V&(y=W))),A+=E>>>16,R=R+(65535&_)+(65535&(_=z&(u=F)^~z&(h=L))),I+=_>>>16,j+=65535&(E=Y[2*k+1]),A+=E>>>16,I+=(_=Y[2*k])>>>16,R=(R+=65535&_)+(65535&(_=O[k%16]))+((A=A+((E=C[k%16])>>>16)+((j+=65535&E)>>>16))>>>16),j=65535&(E=x=65535&j|A<<16),A=E>>>16,R=65535&(_=w=65535&R|(I=I+(_>>>16)+(R>>>16))<<16),I=_>>>16,j+=65535&(E=(D>>>28|P<<4)^(P>>>2|D<<30)^(P>>>7|D<<25)),I+=(_=(P>>>28|D<<4)^(D>>>2|P<<30)^(D>>>7|P<<25))>>>16,l=65535&(R=(R+=65535&_)+(65535&(_=P&T^P&B^T&B))+((A=(A+=E>>>16)+((E=D&H^D&U^H&U)>>>16)+((j+=65535&E)>>>16))>>>16))|(I=I+(_>>>16)+(R>>>16))<<16,b=65535&j|A<<16,j=65535&(E=m),I=(_=o)>>>16,T=a,B=s,N=n,z=65535&(R=(R=65535&_)+(65535&(_=w))+((A=(A=E>>>16)+((E=x)>>>16)+((j+=65535&E)>>>16))>>>16))|(I=I+(_>>>16)+(R>>>16))<<16,F=c,L=u,M=h,P=l,H=p,U=d,q=f,V=65535&j|A<<16,K=g,W=v,$=y,D=b,k%16==15)for(S=0;S<16;S++)_=O[S],j=65535&(E=C[S]),A=E>>>16,R=65535&_,I=_>>>16,_=O[(S+9)%16],j+=65535&(E=C[(S+9)%16]),A+=E>>>16,R+=65535&_,I+=_>>>16,w=O[(S+1)%16],j+=65535&(E=((x=C[(S+1)%16])>>>1|w<<31)^(x>>>8|w<<24)^(x>>>7|w<<25)),A+=E>>>16,R+=65535&(_=(w>>>1|x<<31)^(w>>>8|x<<24)^w>>>7),I=(I+=_>>>16)+((_=((w=O[(S+14)%16])>>>19|(x=C[(S+14)%16])<<13)^(x>>>29|w<<3)^w>>>6)>>>16)+((R=R+(65535&_)+((A=A+((E=(x>>>19|w<<13)^(w>>>29|x<<3)^(x>>>6|w<<26))>>>16)+((j+=65535&E)>>>16))>>>16))>>>16),O[S]=65535&R|I<<16,C[S]=65535&j|A<<16;j=65535&(E=D),R=65535&(_=P),I=(I=_>>>16)+((_=e[0])>>>16)+((R=R+(65535&_)+((A=(A=E>>>16)+((E=t[0])>>>16)+((j+=65535&E)>>>16))>>>16))>>>16),e[0]=P=65535&R|I<<16,t[0]=D=65535&j|A<<16,j=65535&(E=H),R=65535&(_=T),I=(I=_>>>16)+((_=e[1])>>>16)+((R=R+(65535&_)+((A=(A=E>>>16)+((E=t[1])>>>16)+((j+=65535&E)>>>16))>>>16))>>>16),e[1]=T=65535&R|I<<16,t[1]=H=65535&j|A<<16,j=65535&(E=U),R=65535&(_=B),I=(I=_>>>16)+((_=e[2])>>>16)+((R=R+(65535&_)+((A=(A=E>>>16)+((E=t[2])>>>16)+((j+=65535&E)>>>16))>>>16))>>>16),e[2]=B=65535&R|I<<16,t[2]=U=65535&j|A<<16,j=65535&(E=q),R=65535&(_=N),I=(I=_>>>16)+((_=e[3])>>>16)+((R=R+(65535&_)+((A=(A=E>>>16)+((E=t[3])>>>16)+((j+=65535&E)>>>16))>>>16))>>>16),e[3]=N=65535&R|I<<16,t[3]=q=65535&j|A<<16,j=65535&(E=V),R=65535&(_=z),I=(I=_>>>16)+((_=e[4])>>>16)+((R=R+(65535&_)+((A=(A=E>>>16)+((E=t[4])>>>16)+((j+=65535&E)>>>16))>>>16))>>>16),e[4]=z=65535&R|I<<16,t[4]=V=65535&j|A<<16,j=65535&(E=K),R=65535&(_=F),I=(I=_>>>16)+((_=e[5])>>>16)+((R=R+(65535&_)+((A=(A=E>>>16)+((E=t[5])>>>16)+((j+=65535&E)>>>16))>>>16))>>>16),e[5]=F=65535&R|I<<16,t[5]=K=65535&j|A<<16,j=65535&(E=W),R=65535&(_=L),I=(I=_>>>16)+((_=e[6])>>>16)+((R=R+(65535&_)+((A=(A=E>>>16)+((E=t[6])>>>16)+((j+=65535&E)>>>16))>>>16))>>>16),e[6]=L=65535&R|I<<16,t[6]=W=65535&j|A<<16,j=65535&(E=$),R=65535&(_=M),I=(I=_>>>16)+((_=e[7])>>>16)+((R=R+(65535&_)+((A=(A=E>>>16)+((E=t[7])>>>16)+((j+=65535&E)>>>16))>>>16))>>>16),e[7]=M=65535&R|I<<16,t[7]=$=65535&j|A<<16,G+=128,r-=128}}function X(e,t,i){var r,a=new Int32Array(8),s=new Int32Array(8),n=new Uint8Array(256),o=i;for(a[0]=1779033703,a[1]=3144134277,a[2]=1013904242,a[3]=2773480762,a[4]=1359893119,a[5]=2600822924,a[6]=528734635,a[7]=1541459225,s[0]=4089235720,s[1]=2227873595,s[2]=4271175723,s[3]=1595750129,s[4]=2917565137,s[5]=725511199,s[6]=4215389547,s[7]=327033209,G(a,s,t,i),i%=128,r=0;r<i;r++)n[r]=t[o-i+r];for(n[i]=128,n[(i=256-128*(i<112?1:0))-9]=0,f(n,i-8,o/536870912|0,o<<3),G(a,s,n,i),r=0;r<8;r++)f(e,8*r,a[r],s[r]);return 0}function J(e,i){var r=t(),a=t(),s=t(),n=t(),o=t(),c=t(),u=t(),l=t(),p=t();L(r,e[1],e[0]),L(p,i[1],i[0]),M(r,r,p),F(a,e[0],e[1]),F(p,i[0],i[1]),M(a,a,p),M(s,e[3],i[3]),M(s,s,h),M(n,e[2],i[2]),F(n,n,n),L(o,a,r),L(c,n,s),F(u,n,s),F(l,a,r),M(e[0],o,c),M(e[1],l,u),M(e[2],u,c),M(e[3],o,l)}function Q(e,t,i){for(var r=0;r<4;r++)P(e[r],t[r],i)}function Z(e,i){var r=t(),a=t(),s=t();H(s,i[2]),M(r,i[0],s),M(a,i[1],s),T(e,a),e[31]^=N(r)<<7}function ee(e,t,i){var r,a;for(O(e[0],n),O(e[1],o),O(e[2],o),O(e[3],n),a=255;0<=a;--a)Q(e,t,r=i[a/8|0]>>(7&a)&1),J(t,e),J(e,e),Q(e,t,r)}function te(e,i){var r=[t(),t(),t(),t()];O(r[0],l),O(r[1],p),O(r[2],o),M(r[3],l,p),ee(e,r,i)}function ie(e,i,a){var s,n=new Uint8Array(64),o=[t(),t(),t(),t()];for(a||r(i,32),X(n,i,32),n[0]&=248,n[31]&=127,n[31]|=64,te(o,n),Z(e,o),s=0;s<32;s++)i[s+32]=e[s];return 0}var re,ae=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function se(e,t){for(var i,r,a,s=63;32<=s;--s){for(i=0,r=s-32,a=s-12;r<a;++r)t[r]+=i-16*t[s]*ae[r-(s-32)],i=t[r]+128>>8,t[r]-=256*i;t[r]+=i,t[s]=0}for(r=i=0;r<32;r++)t[r]+=i-(t[31]>>4)*ae[r],i=t[r]>>8,t[r]&=255;for(r=0;r<32;r++)t[r]-=i*ae[r];for(s=0;s<32;s++)t[s+1]+=t[s]>>8,e[s]=255&t[s]}function ne(e){for(var t=new Float64Array(64),i=0;i<64;i++)t[i]=e[i];for(i=0;i<64;i++)e[i]=0;se(e,t)}function oe(e,i,r,a){for(var s,n=new Uint8Array(64),o=new Uint8Array(64),c=new Uint8Array(64),u=new Float64Array(64),h=[t(),t(),t(),t()],l=(X(n,a,32),n[0]&=248,n[31]&=127,n[31]|=64,r+64),p=0;p<r;p++)e[64+p]=i[p];for(p=0;p<32;p++)e[32+p]=n[32+p];for(X(c,e.subarray(32),r+32),ne(c),te(h,c),Z(e,h),p=32;p<64;p++)e[p]=a[p];for(X(o,e,r+64),ne(o),p=0;p<64;p++)u[p]=0;for(p=0;p<32;p++)u[p]=c[p];for(p=0;p<32;p++)for(s=0;s<32;s++)u[p+s]+=o[p]*n[s];return se(e.subarray(32),u),l}function ce(e,i,r,a){var s,c=new Uint8Array(32),h=new Uint8Array(64),l=[t(),t(),t(),t()],p=[t(),t(),t(),t()];if(r<64)return-1;if(function(e,i){for(var r=t(),a=t(),s=t(),c=t(),h=t(),l=t(),p=t(),f=(O(e[2],o),z(e[1],i),D(s,e[1]),M(c,s,u),L(s,s,e[2]),F(c,e[2],c),D(h,c),D(l,h),M(p,l,h),M(r,p,s),M(r,r,c),r),m=r,g=t(),v=0;v<16;v++)g[v]=m[v];for(v=250;0<=v;v--)D(g,g),1!==v&&M(g,g,m);for(v=0;v<16;v++)f[v]=g[v];if(M(r,r,s),M(r,r,c),M(r,r,c),M(e[0],r,c),D(a,e[0]),M(a,a,c),B(a,s)&&M(e[0],e[0],d),D(a,e[0]),M(a,a,c),B(a,s))return 1;N(e[0])===i[31]>>7&&L(e[0],n,e[0]),M(e[3],e[0],e[1])}(p,a))return-1;for(s=0;s<r;s++)e[s]=i[s];for(s=0;s<32;s++)e[s+32]=a[s];if(X(h,e,r),ne(h),ee(l,p,h),te(p,i.subarray(32)),J(l,p),Z(c,l),r-=64,v(i,0,c,0)){for(s=0;s<r;s++)e[s]=0;return-1}for(s=0;s<r;s++)e[s]=i[s+64];return r}function ue(e,t){if(32!==e.length)throw new Error("bad key size");if(24!==t.length)throw new Error("bad nonce size")}function he(){for(var e,t=0;t<arguments.length;t++)if("[object Uint8Array]"!==(e=Object.prototype.toString.call(arguments[t])))throw new TypeError("unexpected type "+e+", use Uint8Array")}function le(e){for(var t=0;t<e.length;t++)e[t]=0}e.lowlevel={crypto_core_hsalsa20:b,crypto_stream_xor:_,crypto_stream:S,crypto_stream_salsa20_xor:x,crypto_stream_salsa20:k,crypto_onetimeauth:j,crypto_onetimeauth_verify:A,crypto_verify_16:g,crypto_verify_32:v,crypto_secretbox:R,crypto_secretbox_open:I,crypto_scalarmult:U,crypto_scalarmult_base:q,crypto_box_beforenm:K,crypto_box_afternm:W,crypto_box:function(e,t,i,r,a,s){var n=new Uint8Array(32);return K(n,a,s),W(e,t,i,r,n)},crypto_box_open:function(e,t,i,r,a,s){var n=new Uint8Array(32);return K(n,a,s),$(e,t,i,r,n)},crypto_box_keypair:V,crypto_hash:X,crypto_sign:oe,crypto_sign_keypair:ie,crypto_sign_open:ce,crypto_secretbox_KEYBYTES:32,crypto_secretbox_NONCEBYTES:24,crypto_secretbox_ZEROBYTES:32,crypto_secretbox_BOXZEROBYTES:16,crypto_scalarmult_BYTES:32,crypto_scalarmult_SCALARBYTES:32,crypto_box_PUBLICKEYBYTES:32,crypto_box_SECRETKEYBYTES:32,crypto_box_BEFORENMBYTES:32,crypto_box_NONCEBYTES:24,crypto_box_ZEROBYTES:32,crypto_box_BOXZEROBYTES:16,crypto_sign_BYTES:64,crypto_sign_PUBLICKEYBYTES:32,crypto_sign_SECRETKEYBYTES:64,crypto_sign_SEEDBYTES:32,crypto_hash_BYTES:64},e.util||(e.util={},e.util.decodeUTF8=e.util.encodeUTF8=e.util.encodeBase64=e.util.decodeBase64=function(){throw new Error("nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js")}),e.randomBytes=function(e){var t=new Uint8Array(e);return r(t,e),t},e.secretbox=function(e,t,i){he(e,t,i),ue(i,t);for(var r=new Uint8Array(32+e.length),a=new Uint8Array(r.length),s=0;s<e.length;s++)r[s+32]=e[s];return R(a,r,r.length,t,i),a.subarray(16)},e.secretbox.open=function(e,t,i){he(e,t,i),ue(i,t);for(var r=new Uint8Array(16+e.length),a=new Uint8Array(r.length),s=0;s<e.length;s++)r[s+16]=e[s];return!(r.length<32)&&0===I(a,r,r.length,t,i)&&a.subarray(32)},e.secretbox.keyLength=32,e.secretbox.nonceLength=24,e.secretbox.overheadLength=16,e.scalarMult=function(e,t){if(he(e,t),32!==e.length)throw new Error("bad n size");if(32!==t.length)throw new Error("bad p size");var i=new Uint8Array(32);return U(i,e,t),i},e.scalarMult.base=function(e){if(he(e),32!==e.length)throw new Error("bad n size");var t=new Uint8Array(32);return q(t,e),t},e.scalarMult.scalarLength=32,e.scalarMult.groupElementLength=32,e.box=function(t,i,r,a){return r=e.box.before(r,a),e.secretbox(t,i,r)},e.box.before=function(e,t){he(e,t);var i=t;if(32!==e.length)throw new Error("bad public key size");if(32!==i.length)throw new Error("bad secret key size");return K(i=new Uint8Array(32),e,t),i},e.box.after=e.secretbox,e.box.open=function(t,i,r,a){return r=e.box.before(r,a),e.secretbox.open(t,i,r)},e.box.open.after=e.secretbox.open,e.box.keyPair=function(){var e=new Uint8Array(32),t=new Uint8Array(32);return V(e,t),{publicKey:e,secretKey:t}},e.box.keyPair.fromSecretKey=function(e){if(he(e),32!==e.length)throw new Error("bad secret key size");var t=new Uint8Array(32);return q(t,e),{publicKey:t,secretKey:new Uint8Array(e)}},e.box.publicKeyLength=32,e.box.secretKeyLength=32,e.box.sharedKeyLength=32,e.box.nonceLength=24,e.box.overheadLength=e.secretbox.overheadLength,e.sign=function(e,t){if(he(e,t),64!==t.length)throw new Error("bad secret key size");var i=new Uint8Array(64+e.length);return oe(i,e,e.length,t),i},e.sign.open=function(e,t){if(2!==arguments.length)throw new Error("nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?");if(he(e,t),32!==t.length)throw new Error("bad public key size");var i=new Uint8Array(e.length);if((e=ce(i,e,e.length,t))<0)return null;for(var r=new Uint8Array(e),a=0;a<r.length;a++)r[a]=i[a];return r},e.sign.detached=function(t,i){for(var r=e.sign(t,i),a=new Uint8Array(64),s=0;s<a.length;s++)a[s]=r[s];return a},e.sign.detached.verify=function(e,t,i){if(he(e,t,i),64!==t.length)throw new Error("bad signature size");if(32!==i.length)throw new Error("bad public key size");for(var r=new Uint8Array(64+e.length),a=new Uint8Array(64+e.length),s=0;s<64;s++)r[s]=t[s];for(s=0;s<e.length;s++)r[s+64]=e[s];return 0<=ce(a,r,r.length,i)},e.sign.keyPair=function(){var e=new Uint8Array(32),t=new Uint8Array(64);return ie(e,t),{publicKey:e,secretKey:t}},e.sign.keyPair.fromSecretKey=function(e){if(he(e),64!==e.length)throw new Error("bad secret key size");for(var t=new Uint8Array(32),i=0;i<t.length;i++)t[i]=e[32+i];return{publicKey:t,secretKey:new Uint8Array(e)}},e.sign.keyPair.fromSeed=function(e){if(he(e),32!==e.length)throw new Error("bad seed size");for(var t=new Uint8Array(32),i=new Uint8Array(64),r=0;r<32;r++)i[r]=e[r];return ie(t,i,!0),{publicKey:t,secretKey:i}},e.sign.publicKeyLength=32,e.sign.secretKeyLength=64,e.sign.seedLength=32,e.sign.signatureLength=64,e.hash=function(e){he(e);var t=new Uint8Array(64);return X(t,e,e.length),t},e.hash.hashLength=64,e.verify=function(e,t){return he(e,t),0!==e.length&&0!==t.length&&e.length===t.length&&0===m(e,0,t,0,e.length)},e.setPRNG=function(e){r=e},(re="undefined"!=typeof self?self.crypto||self.msCrypto:null)&&re.getRandomValues?e.setPRNG((function(e,t){for(var i=new Uint8Array(t),r=0;r<t;r+=65536)re.getRandomValues(i.subarray(r,r+Math.min(t-r,65536)));for(r=0;r<t;r++)e[r]=i[r];le(i)})):(re=i(8))&&re.randomBytes&&e.setPRNG((function(e,t){for(var i=re.randomBytes(t),r=0;r<t;r++)e[r]=i[r];le(i)}))}(e.exports||(self.nacl=self.nacl||{}))},function(e,t,i){e.exports={read:function(e,t){return h.read(e,t,"pkcs8")},readPkcs8:function(e,t,i){i.peek()===a.Ber.Integer&&(r.strictEqual(t,"private","unexpected Integer at start of public key"),i.readString(a.Ber.Integer,!0)),i.readSequence();var n=i.offset+i.length,h=i.readOID();switch(h){case"1.2.840.113549.1.1.1":return i._offset=n,("public"===t?function(e){e.readSequence(a.Ber.BitString),e.readByte(),e.readSequence();var t=l(e,"modulus"),i=l(e,"exponent");e={type:"rsa",source:e.originalInput,parts:[{name:"e",data:i},{name:"n",data:t}]};return new c(e)}:function(e){e.readSequence(a.Ber.OctetString),e.readSequence();var t=l(e,"version"),i=(t=(r.equal(t[0],0,"unknown RSA private key version"),l(e,"modulus")),l(e,"public exponent")),s=l(e,"private exponent"),n=l(e,"prime1"),o=l(e,"prime2"),c=l(e,"exponent1"),h=l(e,"exponent2");e=l(e,"iqmp");return new u({type:"rsa",parts:[{name:"n",data:t},{name:"e",data:i},{name:"d",data:s},{name:"iqmp",data:e},{name:"p",data:n},{name:"q",data:o},{name:"dmodp",data:c},{name:"dmodq",data:h}]})})(i);case"1.2.840.10040.4.1":return("public"===t?function(e){e.readSequence();var t=l(e,"p"),i=l(e,"q"),r=l(e,"g");e.readSequence(a.Ber.BitString),e.readByte(),e=l(e,"y");return new c({type:"dsa",parts:[{name:"p",data:t},{name:"q",data:i},{name:"g",data:r},{name:"y",data:e}]})}:function(e){e.readSequence();var t=l(e,"p"),i=l(e,"q"),r=l(e,"g"),s=(e=(e.readSequence(a.Ber.OctetString),l(e,"x")),o.calculateDSAPublic(r,t,e));return new u({type:"dsa",parts:[{name:"p",data:t},{name:"q",data:i},{name:"g",data:r},{name:"y",data:s},{name:"x",data:e}]})})(i);case"1.2.840.10045.2.1":return("public"===t?function(e){var t=p(e);r.string(t,"a known elliptic curve"),e=e.readString(a.Ber.BitString,!0),e=o.ecNormalize(e),t={type:"ecdsa",parts:[{name:"curve",data:s.from(t)},{name:"Q",data:e}]};return new c(t)}:function(e){var t,i=p(e),n=(r.string(i,"a known elliptic curve"),e.readSequence(a.Ber.OctetString),e.readSequence(),l(e,"version"));r.equal(n[0],1,"unknown version of ECDSA key"),n=e.readString(a.Ber.OctetString,!0);return 160==e.peek()&&(e.readSequence(160),e._offset+=e.length),161==e.peek()&&(e.readSequence(161),t=e.readString(a.Ber.BitString,!0),t=o.ecNormalize(t)),void 0===t&&(t=(e=o.publicFromPrivateECDSA(i,n)).part.Q.data),e={type:"ecdsa",parts:[{name:"curve",data:s.from(i)},{name:"Q",data:t},{name:"d",data:n}]},new u(e)})(i);case"1.3.101.112":return("public"===t?function(e){return 0===e.peek()&&e.readByte(),e=o.readBitString(e),e={type:"ed25519",parts:[{name:"A",data:o.zeroPadToLength(e,32)}]},new c(e)}:function(e){0===e.peek()&&e.readByte(),e.readSequence(a.Ber.OctetString);var t,i=e.readString(a.Ber.OctetString,!0);return i=o.zeroPadToLength(i,32),t=e.peek()===a.Ber.BitString?(t=o.readBitString(e),o.zeroPadToLength(t,32)):o.calculateED25519Public(i),e={type:"ed25519",parts:[{name:"A",data:o.zeroPadToLength(t,32)},{name:"k",data:o.zeroPadToLength(i,32)}]},new u(e)})(i);case"1.3.101.110":return("public"===t?function(e){return e=o.readBitString(e),e={type:"curve25519",parts:[{name:"A",data:o.zeroPadToLength(e,32)}]},new c(e)}:function(e){0===e.peek()&&e.readByte(),e.readSequence(a.Ber.OctetString);e=e.readString(a.Ber.OctetString,!0);var t=(e=o.zeroPadToLength(e,32),o.calculateX25519Public(e));t={type:"curve25519",parts:[{name:"A",data:o.zeroPadToLength(t,32)},{name:"k",data:o.zeroPadToLength(e,32)}]};return new u(t)})(i);default:throw new Error("Unknown key type OID "+h)}},write:function(e,t){return h.write(e,t,"pkcs8")},writePkcs8:d,pkcs8ToBuffer:function(e){var t=new a.BerWriter;return d(t,e),t.buffer},readECDSACurve:p,writeECDSACurve:f};var r=i(10),a=i(58),s=i(12).Buffer,n=i(30),o=i(25),c=i(23),u=i(24),h=i(65);function l(e,t){return r.strictEqual(e.peek(),a.Ber.Integer,t+" is not an Integer"),o.mpNormalize(e.readString(a.Ber.Integer,!0))}function p(e){var t;if(e.peek()===a.Ber.OID){for(var i=e.readOID(),c=Object.keys(n.curves),u=0;u<c.length;++u)if(d=c[u],(f=n.curves[d]).pkcs8oid===i){t=d;break}}else{e.readSequence();var h=e.readString(a.Ber.Integer,!0),l=(r.strictEqual(h[0],1,"ECDSA key not version 1"),{}),p=(h=(e.readSequence(),e.readOID()),h=(r.strictEqual(h,"1.2.840.10045.1.1","ECDSA key is not from a prime-field"),l.p=o.mpNormalize(e.readString(a.Ber.Integer,!0))),l.size=8*h.length-o.countZeros(h),e.readSequence(),l.a=o.mpNormalize(e.readString(a.Ber.OctetString,!0)),l.b=o.mpNormalize(e.readString(a.Ber.OctetString,!0)),e.peek()===a.Ber.BitString&&(l.s=e.readString(a.Ber.BitString,!0)),l.G=e.readString(a.Ber.OctetString,!0),r.strictEqual(l.G[0],4,"uncompressed G is required"),l.n=o.mpNormalize(e.readString(a.Ber.Integer,!0)),l.h=o.mpNormalize(e.readString(a.Ber.Integer,!0)),r.strictEqual(l.h[0],1,"a cofactor=1 curve is required"),c=Object.keys(n.curves),Object.keys(l));for(u=0;u<c.length;++u){for(var d=c[u],f=n.curves[d],m=!0,g=0;g<p.length;++g){var v=p[g];if(void 0!==f[v])if("object"==typeof f[v]&&void 0!==f[v].equals){if(!f[v].equals(l[v])){m=!1;break}}else if(s.isBuffer(f[v])){if(f[v].toString("binary")!==l[v].toString("binary")){m=!1;break}}else if(f[v]!==l[v]){m=!1;break}}if(m){t=d;break}}}return t}function d(e,t){var i,r,n,c,h;switch(e.startSequence(),u.isPrivateKey(t)&&(i=s.from([0]),e.writeBuffer(i,a.Ber.Integer)),e.startSequence(),t.type){case"rsa":if(e.writeOID("1.2.840.113549.1.1.1"),u.isPrivateKey(t)){var l=t,p=e,d=(p.writeNull(),p.endSequence(),p.startSequence(a.Ber.OctetString),p.startSequence(),s.from([0]));p.writeBuffer(d,a.Ber.Integer),p.writeBuffer(l.part.n.data,a.Ber.Integer),p.writeBuffer(l.part.e.data,a.Ber.Integer),p.writeBuffer(l.part.d.data,a.Ber.Integer),p.writeBuffer(l.part.p.data,a.Ber.Integer),p.writeBuffer(l.part.q.data,a.Ber.Integer),l.part.dmodp&&l.part.dmodq||o.addRSAMissing(l),p.writeBuffer(l.part.dmodp.data,a.Ber.Integer),p.writeBuffer(l.part.dmodq.data,a.Ber.Integer),p.writeBuffer(l.part.iqmp.data,a.Ber.Integer),p.endSequence(),p.endSequence()}else d=t,(l=e).writeNull(),l.endSequence(),l.startSequence(a.Ber.BitString),l.writeByte(0),l.startSequence(),l.writeBuffer(d.part.n.data,a.Ber.Integer),l.writeBuffer(d.part.e.data,a.Ber.Integer),l.endSequence(),l.endSequence();break;case"dsa":e.writeOID("1.2.840.10040.4.1"),(u.isPrivateKey(t)?(p=t,(h=e).startSequence(),h.writeBuffer(p.part.p.data,a.Ber.Integer),h.writeBuffer(p.part.q.data,a.Ber.Integer),h.writeBuffer(p.part.g.data,a.Ber.Integer),h.endSequence(),h.endSequence(),h.startSequence(a.Ber.OctetString),h.writeBuffer(p.part.x.data,a.Ber.Integer),h):(h=t,(c=e).startSequence(),c.writeBuffer(h.part.p.data,a.Ber.Integer),c.writeBuffer(h.part.q.data,a.Ber.Integer),c.writeBuffer(h.part.g.data,a.Ber.Integer),c.endSequence(),c.endSequence(),c.startSequence(a.Ber.BitString),c.writeByte(0),c.writeBuffer(h.part.y.data,a.Ber.Integer),c)).endSequence();break;case"ecdsa":if(e.writeOID("1.2.840.10045.2.1"),u.isPrivateKey(t))f(c=t,g=e),g.endSequence(),g.startSequence(a.Ber.OctetString),g.startSequence(),m=s.from([1]),g.writeBuffer(m,a.Ber.Integer),g.writeBuffer(c.part.d.data,a.Ber.OctetString),g.startSequence(161),m=o.ecNormalize(c.part.Q.data,!0),g.writeBuffer(m,a.Ber.BitString),g.endSequence(),g.endSequence(),g.endSequence();else{var m=t,g=e;f(m,g),g.endSequence(),m=o.ecNormalize(m.part.Q.data,!0),g.writeBuffer(m,a.Ber.BitString)}break;case"ed25519":if(e.writeOID("1.3.101.112"),u.isPrivateKey(t))throw new Error("Ed25519 private keys in pkcs8 format are not supported");r=t,(n=e).endSequence(),o.writeBitString(n,r.part.A.data);break;default:throw new Error("Unsupported key type: "+t.type)}e.endSequence()}function f(e,t){var i;(e=n.curves[e.curve]).pkcs8oid?t.writeOID(e.pkcs8oid):(t.startSequence(),i=s.from([1]),t.writeBuffer(i,a.Ber.Integer),t.startSequence(),t.writeOID("1.2.840.10045.1.1"),t.writeBuffer(e.p,a.Ber.Integer),t.endSequence(),t.startSequence(),0===(i=e.p)[0]&&(i=i.slice(1)),t.writeBuffer(i,a.Ber.OctetString),t.writeBuffer(e.b,a.Ber.OctetString),t.writeBuffer(e.s,a.Ber.BitString),t.endSequence(),t.writeBuffer(e.G,a.Ber.OctetString),t.writeBuffer(e.n,a.Ber.Integer),i=(i=e.h)||s.from([1]),t.writeBuffer(i,a.Ber.Integer),t.endSequence())}},function(e,t,i){e.exports=m;var r=i(10),a=i(12).Buffer,s=i(30),n=i(8),o=i(101),c=(e=(i(57),i(51)),i(9),i(25)),u=i(23),h=i(24),l=i(106),p={},d=(p.openssh=i(470),p.x509=i(278),p.pem=i(471),e.CertificateParseError),f=e.InvalidAlgorithmError;function m(e){r.object(e,"options"),r.arrayOfObject(e.subjects,"options.subjects"),c.assertCompatible(e.subjects[0],l,[1,0],"options.subjects"),c.assertCompatible(e.subjectKey,u,[1,0],"options.subjectKey"),c.assertCompatible(e.issuer,l,[1,0],"options.issuer"),void 0!==e.issuerKey&&c.assertCompatible(e.issuerKey,u,[1,0],"options.issuerKey"),r.object(e.signatures,"options.signatures"),r.buffer(e.serial,"options.serial"),r.date(e.validFrom,"options.validFrom"),r.date(e.validUntil,"optons.validUntil"),r.optionalArrayOfString(e.purposes,"options.purposes"),this._hashCache={},this.subjects=e.subjects,this.issuer=e.issuer,this.subjectKey=e.subjectKey,this.issuerKey=e.issuerKey,this.signatures=e.signatures,this.serial=e.serial,this.validFrom=e.validFrom,this.validUntil=e.validUntil,this.purposes=e.purposes}m.formats=p,m.prototype.toBuffer=function(e,t){return r.string(e=void 0===e?"x509":e,"format"),r.object(p[e],"formats[format]"),r.optionalObject(t,"options"),p[e].write(this,t)},m.prototype.toString=function(e,t){return this.toBuffer(e=void 0===e?"pem":e,t).toString()},m.prototype.fingerprint=function(e){return r.string(e=void 0===e?"sha256":e,"algorithm"),e={type:"certificate",hash:this.hash(e),algorithm:e},new o(e)},m.prototype.hash=function(e){if(r.string(e,"algorithm"),e=e.toLowerCase(),void 0===s.hashAlgs[e])throw new f(e);var t;return this._hashCache[e]||(t=n.createHash(e).update(this.toBuffer("x509")).digest(),this._hashCache[e]=t)},m.prototype.isExpired=function(e){return!((e=void 0===e?new Date:e).getTime()>=this.validFrom.getTime()&&e.getTime()<this.validUntil.getTime())},m.prototype.isSignedBy=function(e){return c.assertCompatible(e,m,[1,0],"issuer"),!(!this.issuer.equals(e.subjects[0])||this.issuer.purposes&&0<this.issuer.purposes.length&&-1===this.issuer.purposes.indexOf("ca"))&&this.isSignedByKey(e.subjectKey)},m.prototype.getExtension=function(e){return r.string(e,"keyOrOid"),this.getExtensions().filter((function(t){return"x509"===t.format?t.oid===e:"openssh"===t.format&&t.name===e}))[0]},m.prototype.getExtensions=function(){var e,t=[];return(e=((e=this.signatures.x509)&&e.extras&&e.extras.exts&&e.extras.exts.forEach((function(e){e.format="x509",t.push(e)})),this.signatures.openssh))&&e.exts&&e.exts.forEach((function(e){e.format="openssh",t.push(e)})),t},m.prototype.isSignedByKey=function(e){var t;return c.assertCompatible(e,u,[1,2],"issuerKey"),void 0!==this.issuerKey?this.issuerKey.fingerprint("sha512").matches(e):(t=Object.keys(this.signatures)[0],(t=p[t].verify(this,e))&&(this.issuerKey=e),t)},m.prototype.signWith=function(e){c.assertCompatible(e,h,[1,2],"key");for(var t=Object.keys(p),i=!1,r=0;r<t.length;++r)"pem"!==t[r]&&!0===p[t[r]].sign(this,e)&&(i=!0);if(!i)throw new Error("Failed to sign the certificate for any available certificate formats")},m.createSelfSigned=function(e,t,i){e=Array.isArray(e)?e:[e];var s,n=(r.arrayOfObject(e),e.forEach((function(e){c.assertCompatible(e,l,[1,0],"subject")})),c.assertCompatible(t,h,[1,2],"private key"),r.optionalObject(i,"options"),r.optionalObject((i=void 0===i?{}:i).validFrom,"options.validFrom"),r.optionalObject(i.validUntil,"options.validUntil"),i.validFrom),o=i.validUntil,u=(void 0===n&&(n=new Date),void 0===o&&(r.optionalNumber(i.lifetime,"options.lifetime"),void 0===(u=i.lifetime)&&(u=31536e4),(o=new Date).setTime(o.getTime()+1e3*u)),r.optionalBuffer(i.serial,"options.serial"),i.serial),p=(-1===(i=void 0===(i=(void 0===u&&(u=a.from("0000000000000001","hex")),i.purposes))?[]:i).indexOf("signature")&&i.push("signature"),-1===i.indexOf("ca")&&i.push("ca"),-1===i.indexOf("crl")&&i.push("crl"),i.length<=3&&(s=e.filter((function(e){return"host"===e.type})),p=e.filter((function(e){return"user"===e.type})),0<s.length&&-1===i.indexOf("serverAuth")&&i.push("serverAuth"),0<p.length&&-1===i.indexOf("clientAuth")&&i.push("clientAuth"),0<p.length||0<s.length)&&(-1===i.indexOf("keyAgreement")&&i.push("keyAgreement"),"rsa"===t.type)&&-1===i.indexOf("encryption")&&i.push("encryption"),new m({subjects:e,issuer:e[0],subjectKey:t.toPublic(),issuerKey:t.toPublic(),signatures:{},serial:u,validFrom:n,validUntil:o,purposes:i}));return p.signWith(t),p},m.create=function(e,t,i,s,n){e=Array.isArray(e)?e:[e];var o=(r.arrayOfObject(e),e.forEach((function(e){c.assertCompatible(e,l,[1,0],"subject")})),c.assertCompatible(t,u,[1,0],"key"),h.isPrivateKey(t)&&(t=t.toPublic()),c.assertCompatible(i,l,[1,0],"issuer"),c.assertCompatible(s,h,[1,2],"issuer key"),r.optionalObject(n,"options"),r.optionalObject((n=void 0===n?{}:n).validFrom,"options.validFrom"),r.optionalObject(n.validUntil,"options.validUntil"),n.validFrom),p=n.validUntil,d=(void 0===o&&(o=new Date),void 0===p&&(r.optionalNumber(n.lifetime,"options.lifetime"),void 0===(d=n.lifetime)&&(d=31536e4),(p=new Date).setTime(p.getTime()+1e3*d)),r.optionalBuffer(n.serial,"options.serial"),n.serial),f=(void 0===d&&(d=a.from("0000000000000001","hex")),n.purposes),g=(n=(-1===(f=void 0===f?[]:f).indexOf("signature")&&f.push("signature"),!0===n.ca&&(-1===f.indexOf("ca")&&f.push("ca"),-1===f.indexOf("crl"))&&f.push("crl"),e.filter((function(e){return"host"===e.type}))),e.filter((function(e){return"user"===e.type})));return(g=(0<n.length&&-1===f.indexOf("serverAuth")&&f.push("serverAuth"),0<g.length&&-1===f.indexOf("clientAuth")&&f.push("clientAuth"),(0<g.length||0<n.length)&&(-1===f.indexOf("keyAgreement")&&f.push("keyAgreement"),"rsa"===t.type)&&-1===f.indexOf("encryption")&&f.push("encryption"),new m({subjects:e,issuer:i,subjectKey:t,issuerKey:s.toPublic(),signatures:{},serial:d,validFrom:o,validUntil:p,purposes:f}))).signWith(s),g},m.parse=function(e,t,i){"string"!=typeof e&&r.buffer(e,"data"),r.string(t=void 0===t?"auto":t,"format"),r.optionalObject(i="string"==typeof i?{filename:i}:i,"options"),r.optionalString((i=void 0===i?{}:i).filename,"options.filename"),void 0===i.filename&&(i.filename="(unnamed)"),r.object(p[t],"formats[format]");try{return p[t].read(e,i)}catch(e){throw new d(i.filename,t,e)}},m.isCertificate=function(e,t){return c.isCompatible(e,m,t)},m.prototype._sshpkApiVersion=[1,1],m._oldVersionDetect=function(e){return[1,0]}},function(e,t,i){e.exports=h;var r=i(10),a=(i(30),i(8),i(101),i(57),i(51),i(9),i(25)),s=i(58),n=i(12).Buffer,o=/^([*]|[a-z0-9][a-z0-9\-]{0,62})(?:\.([*]|[a-z0-9][a-z0-9\-]{0,62}))*$/i,c={cn:"2.5.4.3",o:"2.5.4.10",ou:"2.5.4.11",l:"2.5.4.7",s:"2.5.4.8",c:"2.5.4.6",sn:"2.5.4.4",postalCode:"2.5.4.17",serialNumber:"2.5.4.5",street:"2.5.4.9",x500UniqueIdentifier:"2.5.4.45",role:"2.5.4.72",telephoneNumber:"2.5.4.20",description:"2.5.4.13",dc:"0.9.2342.19200300.100.1.25",uid:"0.9.2342.19200300.100.1.1",mail:"0.9.2342.19200300.100.1.3",title:"2.5.4.12",gn:"2.5.4.42",initials:"2.5.4.43",pseudonym:"2.5.4.65",emailAddress:"1.2.840.113549.1.9.1"},u={};function h(e){var t=this;if(r.object(e,"options"),r.arrayOfObject(e.components,"options.components"),this.components=e.components,this.componentLookup={},this.components.forEach((function(e){e.name&&!e.oid&&(e.oid=c[e.name]),e.oid&&!e.name&&(e.name=u[e.oid]),void 0===t.componentLookup[e.name]&&(t.componentLookup[e.name]=[]),t.componentLookup[e.name].push(e)})),this.componentLookup.cn&&0<this.componentLookup.cn.length&&(this.cn=this.componentLookup.cn[0].value),r.optionalString(e.type,"options.type"),void 0===e.type)1===this.components.length&&this.componentLookup.cn&&1===this.componentLookup.cn.length&&this.componentLookup.cn[0].value.match(o)?(this.type="host",this.hostname=this.componentLookup.cn[0].value):this.componentLookup.dc&&this.components.length===this.componentLookup.dc.length?(this.type="host",this.hostname=this.componentLookup.dc.map((function(e){return e.value})).join(".")):this.componentLookup.uid&&this.components.length===this.componentLookup.uid.length?(this.type="user",this.uid=this.componentLookup.uid[0].value):this.componentLookup.cn&&1===this.componentLookup.cn.length&&this.componentLookup.cn[0].value.match(o)?(this.type="host",this.hostname=this.componentLookup.cn[0].value):this.componentLookup.uid&&1===this.componentLookup.uid.length?(this.type="user",this.uid=this.componentLookup.uid[0].value):this.componentLookup.mail&&1===this.componentLookup.mail.length?(this.type="email",this.email=this.componentLookup.mail[0].value):this.componentLookup.cn&&1===this.componentLookup.cn.length?(this.type="user",this.uid=this.componentLookup.cn[0].value):this.type="unknown";else if(this.type=e.type,"host"===this.type)this.hostname=e.hostname;else if("user"===this.type)this.uid=e.uid;else{if("email"!==this.type)throw new Error("Unknown type "+this.type);this.email=e.email}}Object.keys(c).forEach((function(e){u[c[e]]=e})),h.prototype.toString=function(){return this.components.map((function(e){return e.name.toUpperCase().replace(/=/g,"\\=")+"="+e.value.replace(/,/g,"\\,")})).join(", ")},h.prototype.get=function(e,t){r.string(e,"name");var i=this.componentLookup[e];if(void 0!==i&&0!==i.length){if(!t&&1<i.length)throw new Error("Multiple values for attribute "+e);return t?i.map((function(e){return e.value})):i[0].value}},h.prototype.toArray=function(e){return this.components.map((function(e){return{name:e.name,value:e.value}}))};var l=/[^a-zA-Z0-9 '(),+.\/:=?-]/,p=/[^\x00-\x7f]/;h.prototype.toAsn1=function(e,t){e.startSequence(t),this.components.forEach((function(t){var i;e.startSequence(s.Ber.Constructor|s.Ber.Set),e.startSequence(),e.writeOID(t.oid),t.asn1type===s.Ber.Utf8String||t.value.match(p)?(i=n.from(t.value,"utf8"),e.writeBuffer(i,s.Ber.Utf8String)):t.asn1type===s.Ber.IA5String||t.value.match(l)?e.writeString(t.value,s.Ber.IA5String):(i=s.Ber.PrintableString,void 0!==t.asn1type&&(i=t.asn1type),e.writeString(t.value,i)),e.endSequence(),e.endSequence()})),e.endSequence()},h.prototype.equals=function(e){if(!h.isIdentity(e,[1,0]))return!1;if(e.components.length!==this.components.length)return!1;for(var t=0;t<this.components.length;++t){if(this.components[t].oid!==e.components[t].oid)return!1;if(!function(e,t){if("**"===e||"**"===t)return 1;var i=e.split("."),r=t.split(".");if(i.length===r.length){for(var a=0;a<i.length;++a)if("*"!==i[a]&&"*"!==r[a]&&i[a]!==r[a])return;return 1}}(this.components[t].value,e.components[t].value))return!1}return!0},h.forHost=function(e){return r.string(e,"hostname"),new h({type:"host",hostname:e,components:[{name:"cn",value:e}]})},h.forUser=function(e){return r.string(e,"uid"),new h({type:"user",uid:e,components:[{name:"uid",value:e}]})},h.forEmail=function(e){return r.string(e,"email"),new h({type:"email",email:e,components:[{name:"mail",value:e}]})},h.parseDN=function(e){r.string(e,"dn");for(var t,i=[""],a=0,s=e;0<s.length;){if(null!==(t=/^,/.exec(s)))i[++a]="";else if(null!==(t=/^\\,/.exec(s)))i[a]+=",";else{if(null===(t=/^\\./.exec(s))&&null===(t=/^[^\\,]+/.exec(s)))throw new Error("Failed to parse DN");i[a]+=t[0]}s=s.slice(t[0].length)}return new h({components:i.map((function(e){for(var t=(e=e.trim()).indexOf("=");0<t&&"\\"===e.charAt(t-1);)t=e.indexOf("=",t+1);if(-1===t)throw new Error("Failed to parse DN");return{name:e.slice(0,t).toLowerCase().replace(/\\=/g,"="),value:e.slice(t+1)}}))})},h.fromArray=function(e){return r.arrayOfObject(e,"components"),e.forEach((function(e){if(r.object(e,"component"),r.string(e.name,"component.name"),!n.isBuffer(e.value)&&"string"!=typeof e.value)throw new Error("Invalid component value")})),new h({components:e})},h.parseAsn1=function(e,t){for(var i=[],r=(e.readSequence(t),e.offset+e.length);e.offset<r;){e.readSequence(s.Ber.Constructor|s.Ber.Set);var a,n=e.offset+e.length,o=(e.readSequence(),e.readOID()),c=e.peek();switch(c){case s.Ber.PrintableString:case s.Ber.IA5String:case s.Ber.OctetString:case s.Ber.T61String:a=e.readString(c);break;case s.Ber.Utf8String:a=(a=e.readString(c,!0)).toString("utf8");break;case s.Ber.CharacterString:case s.Ber.BMPString:a=(a=e.readString(c,!0)).toString("utf16le");break;default:throw new Error("Unknown asn1 type "+c)}i.push({oid:o,asn1type:c,value:a}),e._offset=n}return e._offset=r,new h({components:i})},h.isIdentity=function(e,t){return a.isCompatible(e,h,t)},h.prototype._sshpkApiVersion=[1,0],h._oldVersionDetect=function(e){return[1,0]}},function(e,t,i){"use strict";
|
|
238
|
+
*/const r=i(0),a=i(144),s=i(1),n=i(4),o=i(3),c=a.sum32,u=a.mul32,h=Buffer.alloc(0);class l{constructor(e,t,i,r){this.filter=h,this.size=0,this.n=0,this.tweak=0,this.update=l.flags.NONE,null!=e&&this.fromOptions(e,t,i,r)}fromOptions(e,t,i,a){r("number"==typeof e,"`size` must be a number."),r(0<e,"`size` must be greater than zero."),r(Number.isSafeInteger(e),"`size` must be an integer."),e-=e%8;var s=Buffer.allocUnsafe(e/8);return s.fill(0),null!=i&&-1!==i||(i=4294967296*Math.random()>>>0),"string"==typeof(a=null!=a&&-1!==a?a:l.flags.NONE)&&(a=l.flags[a.toUpperCase()],r(null!=a,"Unknown update flag.")),r(0<e,"`size` must be greater than zero."),r(0<t,"`n` must be greater than zero."),r(Number.isSafeInteger(t),"`n` must be an integer."),r("number"==typeof i,"`tweak` must be a number."),r(Number.isSafeInteger(i),"`tweak` must be an integer."),r(l.flagsByVal[a],"Unknown update flag."),this.filter=s,this.size=e,this.n=t,this.tweak=i,this.update=a,this}static fromOptions(e,t,i,r){return(new l).fromOptions(e,t,i,r)}hash(e,t){return a(e,c(u(t,4221880213),this.tweak))%this.size}reset(){this.filter.fill(0)}add(e,t){"string"==typeof e&&(e=Buffer.from(e,t));for(let t=0;t<this.n;t++){var i=this.hash(e,t);this.filter[i>>>3]|=1<<(7&i)}}test(e,t){"string"==typeof e&&(e=Buffer.from(e,t));for(let t=0;t<this.n;t++){var i=this.hash(e,t);if(0==(this.filter[i>>>3]&1<<(7&i)))return!1}return!0}added(e,t){let i=!1;"string"==typeof e&&(e=Buffer.from(e,t));for(let t=0;t<this.n;t++){var r=this.hash(e,t);i||0!=(this.filter[r>>>3]&1<<(7&r))||(i=!0),this.filter[r>>>3]|=1<<(7&r)}return i}static fromRate(e,t,i){return r("number"==typeof e,"`items` must be a number."),r(0<e,"`items` must be greater than zero."),r(Number.isSafeInteger(e),"`items` must be an integer."),r("number"==typeof t,"`rate` must be a number."),r(0<=t&&t<=1,"`rate` must be between 0.0 and 1.0."),t=-2.0813689810056077*e*Math.log(t)|0,t=Math.max(8,t),-1!==i&&r(t<=8*l.MAX_BLOOM_FILTER_SIZE,"Bloom filter size violates policy limits!"),e=Math.max(1,t/e*.6931471805599453|0),-1!==i&&r(e<=l.MAX_HASH_FUNCS,"Bloom filter size violates policy limits!"),new l(t,e,-1,i)}isWithinConstraints(){return!(this.size>8*l.MAX_BLOOM_FILTER_SIZE||this.n>l.MAX_HASH_FUNCS)}getSize(){return o.sizeVarBytes(this.filter)+13}toWriter(e){return e.writeVarBytes(this.filter),e.writeU32(this.n),e.writeU32(this.tweak),e.writeU32(this.size),e.writeU8(this.update),e}toRaw(){var e=this.getSize();return this.toWriter(new n(e)).render()}fromReader(e){return this.filter=e.readVarBytes(),this.n=e.readU32(),this.tweak=e.readU32(),this.size=e.readU32(),this.update=e.readU8(),r(null!=l.flagsByVal[this.update],"Unknown update flag."),this}fromRaw(e){return this.fromReader(new s(e))}static fromReader(e){return(new l).fromReader(e)}static fromRaw(e,t){return"string"==typeof e&&(e=Buffer.from(e,t)),(new l).fromRaw(e)}}l.MAX_BLOOM_FILTER_SIZE=36e3,l.MAX_HASH_FUNCS=50,l.flags={NONE:0,ALL:1,PUBKEY_ONLY:2},l.flagsByVal={0:"NONE",1:"ALL",2:"PUBKEY_ONLY"},e.exports=l},function(e,t,i){e.exports=d;var r=i(10),a=i(12).Buffer,s=i(30),n=i(8),o=(e=i(51),i(23)),c=i(24),u=i(105),h=i(25),l=e.FingerprintFormatError,p=e.InvalidAlgorithmError;function d(e){if(r.object(e,"options"),r.string(e.type,"options.type"),r.buffer(e.hash,"options.hash"),r.string(e.algorithm,"options.algorithm"),this.algorithm=e.algorithm.toLowerCase(),!0!==s.hashAlgs[this.algorithm])throw new p(this.algorithm);this.hash=e.hash,this.type=e.type,this.hashType=e.hashType}d.prototype.toString=function(e){switch(void 0===e&&(e="md5"===this.algorithm||"spki"===this.hashType?"hex":"base64"),r.string(e),e){case"hex":return"spki"===this.hashType?this.hash.toString("hex"):this.hash.toString("hex").replace(/(.{2})(?=.)/g,"$1:");case"base64":return"spki"===this.hashType?this.hash.toString("base64"):(t=this.algorithm,i=this.hash.toString("base64"),t.toUpperCase()+":"+i.replace(/=*$/,""));default:throw new l(void 0,e)}var t,i},d.prototype.matches=function(e){return r.object(e,"key or certificate"),"key"===this.type&&"ssh"!==this.hashType?(h.assertCompatible(e,o,[1,7],"key with spki"),c.isPrivateKey(e)&&h.assertCompatible(e,c,[1,6],"privatekey with spki support")):"key"===this.type?h.assertCompatible(e,o,[1,0],"key"):h.assertCompatible(e,u,[1,0],"certificate"),e=e.hash(this.algorithm,this.hashType),e=n.createHash(this.algorithm).update(e).digest("base64"),void 0===this.hash2&&(this.hash2=n.createHash(this.algorithm).update(this.hash).digest("base64")),this.hash2===e};var f=/^[A-Za-z0-9+\/=]+$/,m=/^[a-fA-F0-9]+$/;d.parse=function(e,t){r.string(e,"fingerprint"),Array.isArray(t)&&(o=t,t={}),r.optionalObject(t,"options"),void 0!==(t=void 0===t?{}:t).enAlgs&&(o=t.enAlgs),void 0!==t.algorithms&&(o=t.algorithms),r.optionalArrayOfString(o,"algorithms");var i,n,o,c="ssh",u=(void 0!==t.hashType&&(c=t.hashType),r.string(c,"options.hashType"),e.split(":"));if(2==u.length){if(i=u[0].toLowerCase(),!f.test(u[1]))throw new l(e);try{n=a.from(u[1],"base64")}catch(t){throw new l(e)}}else if(2<u.length){if(u=(u=(u=(i="md5")===u[0].toLowerCase()?u.slice(1):u).map((function(t){for(;t.length<2;)t="0"+t;if(2<t.length)throw new l(e);return t}))).join(""),!m.test(u)||u.length%2!=0)throw new l(e);try{n=a.from(u,"hex")}catch(t){throw new l(e)}}else{if(m.test(e))n=a.from(e,"hex");else{if(!f.test(e))throw new l(e);n=a.from(e,"base64")}switch(n.length){case 32:i="sha256";break;case 16:i="md5";break;case 20:i="sha1";break;case 64:i="sha512";break;default:throw new l(e)}void 0===t.hashType&&(c="spki")}if(void 0===i)throw new l(e);if(void 0===s.hashAlgs[i])throw new p(i);if(void 0!==o&&-1===(o=o.map((function(e){return e.toLowerCase()}))).indexOf(i))throw new p(i);return new d({algorithm:i,hash:n,type:t.type||"key",hashType:c})},d.isFingerprint=function(e,t){return h.isCompatible(e,d,t)},d.prototype._sshpkApiVersion=[1,2],d._oldVersionDetect=function(e){return r.func(e.toString),r.func(e.matches),[1,0]}},function(e,t,i){(function(){function t(e,t,i){null!=e&&("number"==typeof e?this.fromNumber(e,t,i):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}function i(){return new t(null)}for(var r=(r="undefined"!=typeof navigator)&&"Microsoft Internet Explorer"==navigator.appName?(t.prototype.am=function(e,t,i,r,a,s){for(var n=32767&t,o=t>>15;0<=--s;){var c=32767&this[e],u=this[e++]>>15,h=o*c+u*n;a=((c=n*c+((32767&h)<<15)+i[r]+(1073741823&a))>>>30)+(h>>>15)+o*u+(a>>>30),i[r++]=1073741823&c}return a},30):r&&"Netscape"!=navigator.appName?(t.prototype.am=function(e,t,i,r,a,s){for(;0<=--s;){var n=t*this[e++]+i[r]+a;a=Math.floor(n/67108864),i[r++]=67108863&n}return a},26):(t.prototype.am=function(e,t,i,r,a,s){for(var n=16383&t,o=t>>14;0<=--s;){var c=16383&this[e],u=this[e++]>>14,h=o*c+u*n;a=((c=n*c+((16383&h)<<14)+i[r]+a)>>28)+(h>>14)+o*u,i[r++]=268435455&c}return a},28),a=(t.prototype.DB=r,t.prototype.DM=(1<<r)-1,t.prototype.DV=1<<r,t.prototype.FV=Math.pow(2,52),t.prototype.F1=52-r,t.prototype.F2=2*r-52,"0123456789abcdefghijklmnopqrstuvwxyz"),s=new Array,n="0".charCodeAt(0),o=0;o<=9;++o)s[n++]=o;for(n="a".charCodeAt(0),o=10;o<36;++o)s[n++]=o;for(n="A".charCodeAt(0),o=10;o<36;++o)s[n++]=o;function c(e){return a.charAt(e)}function u(e,t){return null==(e=s[e.charCodeAt(t)])?-1:e}function h(e){var t=i();return t.fromInt(e),t}function l(e){var t,i=1;return 0!=(t=e>>>16)&&(e=t,i+=16),0!=(t=e>>8)&&(e=t,i+=8),0!=(t=e>>4)&&(e=t,i+=4),0!=(t=e>>2)&&(e=t,i+=2),0!=(t=e>>1)&&(e=t,i+=1),i}function p(e){this.m=e}function d(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}function f(e,t){return e&t}function m(e,t){return e|t}function g(e,t){return e^t}function v(e,t){return e&~t}function y(){}function b(e){return e}function w(e){this.r2=i(),this.q3=i(),t.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}p.prototype.convert=function(e){return e.s<0||0<=e.compareTo(this.m)?e.mod(this.m):e},p.prototype.revert=function(e){return e},p.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},p.prototype.mulTo=function(e,t,i){e.multiplyTo(t,i),this.reduce(i)},p.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},d.prototype.convert=function(e){var r=i();return e.abs().dlShiftTo(this.m.t,r),r.divRemTo(this.m,null,r),e.s<0&&0<r.compareTo(t.ZERO)&&this.m.subTo(r,r),r},d.prototype.revert=function(e){var t=i();return e.copyTo(t),this.reduce(t),t},d.prototype.reduce=function(e){for(;e.t<=this.mt2;)e[e.t++]=0;for(var t=0;t<this.m.t;++t){var i=32767&e[t],r=i*this.mpl+((i*this.mph+(e[t]>>15)*this.mpl&this.um)<<15)&e.DM;for(e[i=t+this.m.t]+=this.m.am(0,r,e,t,0,this.m.t);e[i]>=e.DV;)e[i]-=e.DV,e[++i]++}e.clamp(),e.drShiftTo(this.m.t,e),0<=e.compareTo(this.m)&&e.subTo(this.m,e)},d.prototype.mulTo=function(e,t,i){e.multiplyTo(t,i),this.reduce(i)},d.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},t.prototype.copyTo=function(e){for(var t=this.t-1;0<=t;--t)e[t]=this[t];e.t=this.t,e.s=this.s},t.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,0<e?this[0]=e:e<-1?this[0]=e+this.DV:this.t=0},t.prototype.fromString=function(e,i){var r;if(16==i)r=4;else if(8==i)r=3;else if(256==i)r=8;else if(2==i)r=1;else if(32==i)r=5;else{if(4!=i)return void this.fromRadix(e,i);r=2}this.t=0,this.s=0;for(var a=e.length,s=!1,n=0;0<=--a;){var o=8==r?255&e[a]:u(e,a);o<0?"-"==e.charAt(a)&&(s=!0):(s=!1,0==n?this[this.t++]=o:n+r>this.DB?(this[this.t-1]|=(o&(1<<this.DB-n)-1)<<n,this[this.t++]=o>>this.DB-n):this[this.t-1]|=o<<n,(n+=r)>=this.DB&&(n-=this.DB))}8==r&&0!=(128&e[0])&&(this.s=-1,0<n)&&(this[this.t-1]|=(1<<this.DB-n)-1<<n),this.clamp(),s&&t.ZERO.subTo(this,this)},t.prototype.clamp=function(){for(var e=this.s&this.DM;0<this.t&&this[this.t-1]==e;)--this.t},t.prototype.dlShiftTo=function(e,t){for(var i=this.t-1;0<=i;--i)t[i+e]=this[i];for(i=e-1;0<=i;--i)t[i]=0;t.t=this.t+e,t.s=this.s},t.prototype.drShiftTo=function(e,t){for(var i=e;i<this.t;++i)t[i-e]=this[i];t.t=Math.max(this.t-e,0),t.s=this.s},t.prototype.lShiftTo=function(e,t){for(var i=e%this.DB,r=this.DB-i,a=(1<<r)-1,s=Math.floor(e/this.DB),n=this.s<<i&this.DM,o=this.t-1;0<=o;--o)t[o+s+1]=this[o]>>r|n,n=(this[o]&a)<<i;for(o=s-1;0<=o;--o)t[o]=0;t[s]=n,t.t=this.t+s+1,t.s=this.s,t.clamp()},t.prototype.rShiftTo=function(e,t){t.s=this.s;var i=Math.floor(e/this.DB);if(i>=this.t)t.t=0;else{var r=e%this.DB,a=this.DB-r,s=(1<<r)-1;t[0]=this[i]>>r;for(var n=i+1;n<this.t;++n)t[n-i-1]|=(this[n]&s)<<a,t[n-i]=this[n]>>r;0<r&&(t[this.t-i-1]|=(this.s&s)<<a),t.t=this.t-i,t.clamp()}},t.prototype.subTo=function(e,t){for(var i=0,r=0,a=Math.min(e.t,this.t);i<a;)r+=this[i]-e[i],t[i++]=r&this.DM,r>>=this.DB;if(e.t<this.t){for(r-=e.s;i<this.t;)r+=this[i],t[i++]=r&this.DM,r>>=this.DB;r+=this.s}else{for(r+=this.s;i<e.t;)r-=e[i],t[i++]=r&this.DM,r>>=this.DB;r-=e.s}t.s=r<0?-1:0,r<-1?t[i++]=this.DV+r:0<r&&(t[i++]=r),t.t=i,t.clamp()},t.prototype.multiplyTo=function(e,i){var r=this.abs(),a=e.abs(),s=r.t;for(i.t=s+a.t;0<=--s;)i[s]=0;for(s=0;s<a.t;++s)i[s+r.t]=r.am(0,a[s],i,s,0,r.t);i.s=0,i.clamp(),this.s!=e.s&&t.ZERO.subTo(i,i)},t.prototype.squareTo=function(e){for(var t=this.abs(),i=e.t=2*t.t;0<=--i;)e[i]=0;for(i=0;i<t.t-1;++i){var r=t.am(i,t[i],e,2*i,0,1);(e[i+t.t]+=t.am(i+1,2*t[i],e,2*i+1,r,t.t-i-1))>=t.DV&&(e[i+t.t]-=t.DV,e[i+t.t+1]=1)}0<e.t&&(e[e.t-1]+=t.am(i,t[i],e,2*i,0,1)),e.s=0,e.clamp()},t.prototype.divRemTo=function(e,r,a){if(!((p=e.abs()).t<=0)){var s=this.abs();if(s.t<p.t)null!=r&&r.fromInt(0),null!=a&&this.copyTo(a);else{null==a&&(a=i());var n=i(),o=this.s,c=(e=e.s,this.DB-l(p[p.t-1])),u=(0<c?(p.lShiftTo(c,n),s.lShiftTo(c,a)):(p.copyTo(n),s.copyTo(a)),n.t),h=n[u-1];if(0!=h){var p=h*(1<<this.F1)+(1<u?n[u-2]>>this.F2:0),d=this.FV/p,f=(1<<this.F1)/p,m=1<<this.F2,g=a.t,v=g-u,y=null==r?i():r;for(n.dlShiftTo(v,y),0<=a.compareTo(y)&&(a[a.t++]=1,a.subTo(y,a)),t.ONE.dlShiftTo(u,y),y.subTo(n,n);n.t<u;)n[n.t++]=0;for(;0<=--v;){var b=a[--g]==h?this.DM:Math.floor(a[g]*d+(a[g-1]+m)*f);if((a[g]+=n.am(0,b,a,v,0,u))<b)for(n.dlShiftTo(v,y),a.subTo(y,a);a[g]<--b;)a.subTo(y,a)}null!=r&&(a.drShiftTo(u,r),o!=e)&&t.ZERO.subTo(r,r),a.t=u,a.clamp(),0<c&&a.rShiftTo(c,a),o<0&&t.ZERO.subTo(a,a)}}}},t.prototype.invDigit=function(){var e,t;return this.t<1||0==(1&(e=this[0]))?0:0<(t=(t=(t=(t=(t=3&e)*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)?this.DV-t:-t},t.prototype.isEven=function(){return 0==(0<this.t?1&this[0]:this.s)},t.prototype.exp=function(e,r){if(4294967295<e||e<1)return t.ONE;var a,s=i(),n=i(),o=r.convert(this),c=l(e)-1;for(o.copyTo(s);0<=--c;)r.sqrTo(s,n),0<(e&1<<c)?r.mulTo(n,o,s):(a=s,s=n,n=a);return r.revert(s)},t.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var i,r=(1<<t)-1,a=!1,s="",n=this.t,o=this.DB-n*this.DB%t;if(0<n--)for(o<this.DB&&0<(i=this[n]>>o)&&(a=!0,s=c(i));0<=n;)o<t?(i=(this[n]&(1<<o)-1)<<t-o,i|=this[--n]>>(o+=this.DB-t)):(i=this[n]>>(o-=t)&r,o<=0&&(o+=this.DB,--n)),(a=0<i||a)&&(s+=c(i));return a?s:"0"},t.prototype.negate=function(){var e=i();return t.ZERO.subTo(this,e),e},t.prototype.abs=function(){return this.s<0?this.negate():this},t.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var i=this.t;if(0!=(t=i-e.t))return this.s<0?-t:t;for(;0<=--i;)if(0!=(t=this[i]-e[i]))return t;return 0},t.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+l(this[this.t-1]^this.s&this.DM)},t.prototype.mod=function(e){var r=i();return this.abs().divRemTo(e,null,r),this.s<0&&0<r.compareTo(t.ZERO)&&e.subTo(r,r),r},t.prototype.modPowInt=function(e,t){return t=new(e<256||t.isEven()?p:d)(t),this.exp(e,t)},t.ZERO=h(0),t.ONE=h(1),y.prototype.convert=b,y.prototype.revert=b,y.prototype.mulTo=function(e,t,i){e.multiplyTo(t,i)},y.prototype.sqrTo=function(e,t){e.squareTo(t)},w.prototype.convert=function(e){var t;return e.s<0||e.t>2*this.m.t?e.mod(this.m):e.compareTo(this.m)<0?e:(t=i(),e.copyTo(t),this.reduce(t),t)},w.prototype.revert=function(e){return e},w.prototype.reduce=function(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);0<=e.compareTo(this.m);)e.subTo(this.m,e)},w.prototype.mulTo=function(e,t,i){e.multiplyTo(t,i),this.reduce(i)},w.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var x,k=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],S=(1<<26)/k[k.length-1];function _(){var e;e=(new Date).getTime(),E[j++]^=255&e,E[j++]^=e>>8&255,E[j++]^=e>>16&255,E[j++]^=e>>24&255,T<=j&&(j-=T)}if(t.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},t.prototype.toRadix=function(e){if(null==e&&(e=10),0==this.signum()||e<2||36<e)return"0";var t=this.chunkSize(e),r=Math.pow(e,t),a=h(r),s=i(),n=i(),o="";for(this.divRemTo(a,s,n);0<s.signum();)o=(r+n.intValue()).toString(e).substr(1)+o,s.divRemTo(a,s,n);return n.intValue().toString(e)+o},t.prototype.fromRadix=function(e,i){this.fromInt(0);for(var r=this.chunkSize(i=null==i?10:i),a=Math.pow(i,r),s=!1,n=0,o=0,c=0;c<e.length;++c){var h=u(e,c);h<0?"-"==e.charAt(c)&&0==this.signum()&&(s=!0):(o=i*o+h,++n>=r&&(this.dMultiply(a),this.dAddOffset(o,0),o=n=0))}0<n&&(this.dMultiply(Math.pow(i,n)),this.dAddOffset(o,0)),s&&t.ZERO.subTo(this,this)},t.prototype.fromNumber=function(e,i,r){if("number"==typeof i)if(e<2)this.fromInt(1);else for(this.fromNumber(e,r),this.testBit(e-1)||this.bitwiseTo(t.ONE.shiftLeft(e-1),m,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(i);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(t.ONE.shiftLeft(e-1),this);else{var a=7&e;(r=new Array).length=1+(e>>3),i.nextBytes(r),0<a?r[0]&=(1<<a)-1:r[0]=0,this.fromString(r,256)}},t.prototype.bitwiseTo=function(e,t,i){for(var r,a=Math.min(e.t,this.t),s=0;s<a;++s)i[s]=t(this[s],e[s]);if(e.t<this.t){for(r=e.s&this.DM,s=a;s<this.t;++s)i[s]=t(this[s],r);i.t=this.t}else{for(r=this.s&this.DM,s=a;s<e.t;++s)i[s]=t(r,e[s]);i.t=e.t}i.s=t(this.s,e.s),i.clamp()},t.prototype.changeBit=function(e,i){return e=t.ONE.shiftLeft(e),this.bitwiseTo(e,i,e),e},t.prototype.addTo=function(e,t){for(var i=0,r=0,a=Math.min(e.t,this.t);i<a;)r+=this[i]+e[i],t[i++]=r&this.DM,r>>=this.DB;if(e.t<this.t){for(r+=e.s;i<this.t;)r+=this[i],t[i++]=r&this.DM,r>>=this.DB;r+=this.s}else{for(r+=this.s;i<e.t;)r+=e[i],t[i++]=r&this.DM,r>>=this.DB;r+=e.s}t.s=r<0?-1:0,0<r?t[i++]=r:r<-1&&(t[i++]=this.DV+r),t.t=i,t.clamp()},t.prototype.dMultiply=function(e){this[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},t.prototype.dAddOffset=function(e,t){if(0!=e){for(;this.t<=t;)this[this.t++]=0;for(this[t]+=e;this[t]>=this.DV;)this[t]-=this.DV,++t>=this.t&&(this[this.t++]=0),++this[t]}},t.prototype.multiplyLowerTo=function(e,t,i){var r,a=Math.min(this.t+e.t,t);for(i.s=0,i.t=a;0<a;)i[--a]=0;for(r=i.t-this.t;a<r;++a)i[a+this.t]=this.am(0,e[a],i,a,0,this.t);for(r=Math.min(e.t,t);a<r;++a)this.am(0,e[a],i,a,0,t-a);i.clamp()},t.prototype.multiplyUpperTo=function(e,t,i){var r=i.t=this.t+e.t- --t;for(i.s=0;0<=--r;)i[r]=0;for(r=Math.max(t-this.t,0);r<e.t;++r)i[this.t+r-t]=this.am(t-r,e[r],i,0,0,this.t+r-t);i.clamp(),i.drShiftTo(1,i)},t.prototype.modInt=function(e){if(e<=0)return 0;var t=this.DV%e,i=this.s<0?e-1:0;if(0<this.t)if(0==t)i=this[0]%e;else for(var r=this.t-1;0<=r;--r)i=(t*i+this[r])%e;return i},t.prototype.millerRabin=function(e){var r=this.subtract(t.ONE),a=r.getLowestSetBit();if(a<=0)return!1;for(var s=r.shiftRight(a),n=(k.length<(e=e+1>>1)&&(e=k.length),i()),o=0;o<e;++o){n.fromInt(k[Math.floor(Math.random()*k.length)]);var c=n.modPow(s,this);if(0!=c.compareTo(t.ONE)&&0!=c.compareTo(r)){for(var u=1;u++<a&&0!=c.compareTo(r);)if(0==(c=c.modPowInt(2,this)).compareTo(t.ONE))return!1;if(0!=c.compareTo(r))return!1}}return!0},t.prototype.clone=function(){var e=i();return this.copyTo(e),e},t.prototype.intValue=function(){if(this.s<0){if(1==this.t)return this[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this[0];if(0==this.t)return 0}return(this[1]&(1<<32-this.DB)-1)<<this.DB|this[0]},t.prototype.byteValue=function(){return 0==this.t?this.s:this[0]<<24>>24},t.prototype.shortValue=function(){return 0==this.t?this.s:this[0]<<16>>16},t.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this[0]<=0?0:1},t.prototype.toByteArray=function(){var e,t=this.t,i=new Array,r=(i[0]=this.s,this.DB-t*this.DB%8),a=0;if(0<t--)for(r<this.DB&&(e=this[t]>>r)!=(this.s&this.DM)>>r&&(i[a++]=e|this.s<<this.DB-r);0<=t;)r<8?(e=(this[t]&(1<<r)-1)<<8-r,e|=this[--t]>>(r+=this.DB-8)):(e=this[t]>>(r-=8)&255,r<=0&&(r+=this.DB,--t)),0!=(128&e)&&(e|=-256),0==a&&(128&this.s)!=(128&e)&&++a,(0<a||e!=this.s)&&(i[a++]=e);return i},t.prototype.equals=function(e){return 0==this.compareTo(e)},t.prototype.min=function(e){return this.compareTo(e)<0?this:e},t.prototype.max=function(e){return 0<this.compareTo(e)?this:e},t.prototype.and=function(e){var t=i();return this.bitwiseTo(e,f,t),t},t.prototype.or=function(e){var t=i();return this.bitwiseTo(e,m,t),t},t.prototype.xor=function(e){var t=i();return this.bitwiseTo(e,g,t),t},t.prototype.andNot=function(e){var t=i();return this.bitwiseTo(e,v,t),t},t.prototype.not=function(){for(var e=i(),t=0;t<this.t;++t)e[t]=this.DM&~this[t];return e.t=this.t,e.s=~this.s,e},t.prototype.shiftLeft=function(e){var t=i();return e<0?this.rShiftTo(-e,t):this.lShiftTo(e,t),t},t.prototype.shiftRight=function(e){var t=i();return e<0?this.lShiftTo(-e,t):this.rShiftTo(e,t),t},t.prototype.getLowestSetBit=function(){for(var e,t,i=0;i<this.t;++i)if(0!=this[i])return i*this.DB+(t=void 0,0==(e=this[i])?-1:((t=0)==(65535&e)&&(e>>=16,t+=16),0==(255&e)&&(e>>=8,t+=8),0==(15&e)&&(e>>=4,t+=4),0==(3&e)&&(e>>=2,t+=2),0==(1&e)&&++t,t));return this.s<0?this.t*this.DB:-1},t.prototype.bitCount=function(){for(var e=0,t=this.s&this.DM,i=0;i<this.t;++i)e+=function(e){for(var t=0;0!=e;)e&=e-1,++t;return t}(this[i]^t);return e},t.prototype.testBit=function(e){var t=Math.floor(e/this.DB);return t>=this.t?0!=this.s:0!=(this[t]&1<<e%this.DB)},t.prototype.setBit=function(e){return this.changeBit(e,m)},t.prototype.clearBit=function(e){return this.changeBit(e,v)},t.prototype.flipBit=function(e){return this.changeBit(e,g)},t.prototype.add=function(e){var t=i();return this.addTo(e,t),t},t.prototype.subtract=function(e){var t=i();return this.subTo(e,t),t},t.prototype.multiply=function(e){var t=i();return this.multiplyTo(e,t),t},t.prototype.divide=function(e){var t=i();return this.divRemTo(e,t,null),t},t.prototype.remainder=function(e){var t=i();return this.divRemTo(e,null,t),t},t.prototype.divideAndRemainder=function(e){var t=i(),r=i();return this.divRemTo(e,t,r),new Array(t,r)},t.prototype.modPow=function(e,t){var r=e.bitLength(),a=h(1);if(r<=0)return a;var s=r<18?1:r<48?3:r<144?4:r<768?5:6,n=new(r<8?p:t.isEven()?w:d)(t),o=new Array,c=3,u=s-1,f=(1<<s)-1;if(o[1]=n.convert(this),1<s){var m=i();for(n.sqrTo(o[1],m);c<=f;)o[c]=i(),n.mulTo(m,o[c-2],o[c]),c+=2}var g,v,y=e.t-1,b=!0,x=i();for(r=l(e[y])-1;0<=y;){for(u<=r?g=e[y]>>r-u&f:(g=(e[y]&(1<<r+1)-1)<<u-r,0<y&&(g|=e[y-1]>>this.DB+r-u)),c=s;0==(1&g);)g>>=1,--c;if((r-=c)<0&&(r+=this.DB,--y),b)o[g].copyTo(a),b=!1;else{for(;1<c;)n.sqrTo(a,x),n.sqrTo(x,a),c-=2;0<c?n.sqrTo(a,x):(v=a,a=x,x=v),n.mulTo(x,o[g],a)}for(;0<=y&&0==(e[y]&1<<r);)n.sqrTo(a,x),v=a,a=x,x=v,--r<0&&(r=this.DB-1,--y)}return n.revert(a)},t.prototype.modInverse=function(e){var i=e.isEven();if(this.isEven()&&i||0==e.signum())return t.ZERO;for(var r=e.clone(),a=this.clone(),s=h(1),n=h(0),o=h(0),c=h(1);0!=r.signum();){for(;r.isEven();)r.rShiftTo(1,r),i?(s.isEven()&&n.isEven()||(s.addTo(this,s),n.subTo(e,n)),s.rShiftTo(1,s)):n.isEven()||n.subTo(e,n),n.rShiftTo(1,n);for(;a.isEven();)a.rShiftTo(1,a),i?(o.isEven()&&c.isEven()||(o.addTo(this,o),c.subTo(e,c)),o.rShiftTo(1,o)):c.isEven()||c.subTo(e,c),c.rShiftTo(1,c);0<=r.compareTo(a)?(r.subTo(a,r),i&&s.subTo(o,s),n.subTo(c,n)):(a.subTo(r,a),i&&o.subTo(s,o),c.subTo(n,c))}return 0!=a.compareTo(t.ONE)?t.ZERO:0<=c.compareTo(e)?c.subtract(e):c.signum()<0&&(c.addTo(e,c),c.signum()<0)?c.add(e):c},t.prototype.pow=function(e){return this.exp(e,new y)},t.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),i=e.s<0?e.negate():e.clone(),r=(t.compareTo(i)<0&&(e=t,t=i,i=e),t.getLowestSetBit());if((e=i.getLowestSetBit())<0)return t;for(0<(e=r<e?r:e)&&(t.rShiftTo(e,t),i.rShiftTo(e,i));0<t.signum();)0<(r=t.getLowestSetBit())&&t.rShiftTo(r,t),0<(r=i.getLowestSetBit())&&i.rShiftTo(r,i),0<=t.compareTo(i)?(t.subTo(i,t),t.rShiftTo(1,t)):(i.subTo(t,i),i.rShiftTo(1,i));return 0<e&&i.lShiftTo(e,i),i},t.prototype.isProbablePrime=function(e){var t,i=this.abs();if(1==i.t&&i[0]<=k[k.length-1]){for(t=0;t<k.length;++t)if(i[0]==k[t])return!0;return!1}if(i.isEven())return!1;for(t=1;t<k.length;){for(var r=k[t],a=t+1;a<k.length&&r<S;)r*=k[a++];for(r=i.modInt(r);t<a;)if(r%k[t++]==0)return!1}return i.millerRabin(e)},t.prototype.square=function(){var e=i();return this.squareTo(e),e},t.prototype.Barrett=w,null==E){var E=new Array,j=0;if("undefined"!=typeof window&&window.crypto)if(window.crypto.getRandomValues){var A=new Uint8Array(32);for(window.crypto.getRandomValues(A),I=0;I<32;++I)E[j++]=A[I]}else if("Netscape"==navigator.appName&&navigator.appVersion<"5")for(var R=window.crypto.random(32),I=0;I<R.length;++I)E[j++]=255&R.charCodeAt(I);for(;j<T;)I=Math.floor(65536*Math.random()),E[j++]=I>>>8,E[j++]=255&I;j=0,_()}function O(){if(null==x){for(_(),(x=new P).init(E),j=0;j<E.length;++j)E[j]=0;j=0}return x.next()}function C(){}function P(){this.i=0,this.j=0,this.S=new Array}C.prototype.nextBytes=function(e){for(var t=0;t<e.length;++t)e[t]=O()},P.prototype.init=function(e){for(var t,i,r=0;r<256;++r)this.S[r]=r;for(r=t=0;r<256;++r)t=t+this.S[r]+e[r%e.length]&255,i=this.S[r],this.S[r]=this.S[t],this.S[t]=i;this.i=0,this.j=0},P.prototype.next=function(){var e;return this.i=this.i+1&255,this.j=this.j+this.S[this.i]&255,e=this.S[this.i],this.S[this.i]=this.S[this.j],this.S[this.j]=e,this.S[e+this.S[this.i]&255]};var T=256;t.SecureRandom=C,e.exports=t.BigInteger=t}).call(this)},function(e,t,i){!function(e){"use strict";var t=function(e){var t,i=new Float64Array(16);if(e)for(t=0;t<e.length;t++)i[t]=e[t];return i},r=function(){throw new Error("no PRNG")},a=new Uint8Array(16),s=new Uint8Array(32),n=(s[0]=9,t()),o=t([1]),c=t([56129,1]),u=t([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),h=t([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),l=t([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),p=t([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),d=t([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function f(e,t,i,r){e[t]=i>>24&255,e[t+1]=i>>16&255,e[t+2]=i>>8&255,e[t+3]=255&i,e[t+4]=r>>24&255,e[t+5]=r>>16&255,e[t+6]=r>>8&255,e[t+7]=255&r}function m(e,t,i,r,a){for(var s=0,n=0;n<a;n++)s|=e[t+n]^i[r+n];return(1&s-1>>>8)-1}function g(e,t,i,r){return m(e,t,i,r,16)}function v(e,t,i,r){return m(e,t,i,r,32)}function y(e,t,i,r){for(var a,s=255&(r=r)[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,n=255&i[0]|(255&i[1])<<8|(255&i[2])<<16|(255&i[3])<<24,o=255&i[4]|(255&i[5])<<8|(255&i[6])<<16|(255&i[7])<<24,c=255&i[8]|(255&i[9])<<8|(255&i[10])<<16|(255&i[11])<<24,u=255&i[12]|(255&i[13])<<8|(255&i[14])<<16|(255&i[15])<<24,h=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,l=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,p=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,d=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,f=(t=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24),m=255&i[16]|(255&i[17])<<8|(255&i[18])<<16|(255&i[19])<<24,g=255&i[20]|(255&i[21])<<8|(255&i[22])<<16|(255&i[23])<<24,v=255&i[24]|(255&i[25])<<8|(255&i[26])<<16|(255&i[27])<<24,y=s,b=n,w=o,x=c,k=u,S=h,_=l,E=p,j=d,A=t,R=f,I=m,O=g,C=v,P=i=255&i[28]|(255&i[29])<<8|(255&i[30])<<16|(255&i[31])<<24,T=r=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,B=0;B<20;B+=2)y^=(a=(O^=(a=(j^=(a=(k^=(a=y+O|0)<<7|a>>>25)+y|0)<<9|a>>>23)+k|0)<<13|a>>>19)+j|0)<<18|a>>>14,S^=(a=(b^=(a=(C^=(a=(A^=(a=S+b|0)<<7|a>>>25)+S|0)<<9|a>>>23)+A|0)<<13|a>>>19)+C|0)<<18|a>>>14,R^=(a=(_^=(a=(w^=(a=(P^=(a=R+_|0)<<7|a>>>25)+R|0)<<9|a>>>23)+P|0)<<13|a>>>19)+w|0)<<18|a>>>14,T^=(a=(I^=(a=(E^=(a=(x^=(a=T+I|0)<<7|a>>>25)+T|0)<<9|a>>>23)+x|0)<<13|a>>>19)+E|0)<<18|a>>>14,y^=(a=(x^=(a=(w^=(a=(b^=(a=y+x|0)<<7|a>>>25)+y|0)<<9|a>>>23)+b|0)<<13|a>>>19)+w|0)<<18|a>>>14,S^=(a=(k^=(a=(E^=(a=(_^=(a=S+k|0)<<7|a>>>25)+S|0)<<9|a>>>23)+_|0)<<13|a>>>19)+E|0)<<18|a>>>14,R^=(a=(A^=(a=(j^=(a=(I^=(a=R+A|0)<<7|a>>>25)+R|0)<<9|a>>>23)+I|0)<<13|a>>>19)+j|0)<<18|a>>>14,T^=(a=(P^=(a=(C^=(a=(O^=(a=T+P|0)<<7|a>>>25)+T|0)<<9|a>>>23)+O|0)<<13|a>>>19)+C|0)<<18|a>>>14;b=b+n|0,w=w+o|0,x=x+c|0,k=k+u|0,S=S+h|0,_=_+l|0,E=E+p|0,j=j+d|0,A=A+t|0,R=R+f|0,I=I+m|0,O=O+g|0,C=C+v|0,P=P+i|0,T=T+r|0,e[0]=(y=y+s|0)>>>0&255,e[1]=y>>>8&255,e[2]=y>>>16&255,e[3]=y>>>24&255,e[4]=b>>>0&255,e[5]=b>>>8&255,e[6]=b>>>16&255,e[7]=b>>>24&255,e[8]=w>>>0&255,e[9]=w>>>8&255,e[10]=w>>>16&255,e[11]=w>>>24&255,e[12]=x>>>0&255,e[13]=x>>>8&255,e[14]=x>>>16&255,e[15]=x>>>24&255,e[16]=k>>>0&255,e[17]=k>>>8&255,e[18]=k>>>16&255,e[19]=k>>>24&255,e[20]=S>>>0&255,e[21]=S>>>8&255,e[22]=S>>>16&255,e[23]=S>>>24&255,e[24]=_>>>0&255,e[25]=_>>>8&255,e[26]=_>>>16&255,e[27]=_>>>24&255,e[28]=E>>>0&255,e[29]=E>>>8&255,e[30]=E>>>16&255,e[31]=E>>>24&255,e[32]=j>>>0&255,e[33]=j>>>8&255,e[34]=j>>>16&255,e[35]=j>>>24&255,e[36]=A>>>0&255,e[37]=A>>>8&255,e[38]=A>>>16&255,e[39]=A>>>24&255,e[40]=R>>>0&255,e[41]=R>>>8&255,e[42]=R>>>16&255,e[43]=R>>>24&255,e[44]=I>>>0&255,e[45]=I>>>8&255,e[46]=I>>>16&255,e[47]=I>>>24&255,e[48]=O>>>0&255,e[49]=O>>>8&255,e[50]=O>>>16&255,e[51]=O>>>24&255,e[52]=C>>>0&255,e[53]=C>>>8&255,e[54]=C>>>16&255,e[55]=C>>>24&255,e[56]=P>>>0&255,e[57]=P>>>8&255,e[58]=P>>>16&255,e[59]=P>>>24&255,e[60]=T>>>0&255,e[61]=T>>>8&255,e[62]=T>>>16&255,e[63]=T>>>24&255}function b(e,t,i,r){for(var a,s=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,n=255&i[0]|(255&i[1])<<8|(255&i[2])<<16|(255&i[3])<<24,o=255&i[4]|(255&i[5])<<8|(255&i[6])<<16|(255&i[7])<<24,c=255&i[8]|(255&i[9])<<8|(255&i[10])<<16|(255&i[11])<<24,u=255&i[12]|(255&i[13])<<8|(255&i[14])<<16|(255&i[15])<<24,h=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,l=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,p=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,d=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,f=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,m=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,g=255&i[16]|(255&i[17])<<8|(255&i[18])<<16|(255&i[19])<<24,v=255&i[20]|(255&i[21])<<8|(255&i[22])<<16|(255&i[23])<<24,y=255&i[24]|(255&i[25])<<8|(255&i[26])<<16|(255&i[27])<<24,b=255&i[28]|(255&i[29])<<8|(255&i[30])<<16|(255&i[31])<<24,w=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,x=0;x<20;x+=2)s^=(a=(v^=(a=(d^=(a=(u^=(a=s+v|0)<<7|a>>>25)+s|0)<<9|a>>>23)+u|0)<<13|a>>>19)+d|0)<<18|a>>>14,h^=(a=(n^=(a=(y^=(a=(f^=(a=h+n|0)<<7|a>>>25)+h|0)<<9|a>>>23)+f|0)<<13|a>>>19)+y|0)<<18|a>>>14,m^=(a=(l^=(a=(o^=(a=(b^=(a=m+l|0)<<7|a>>>25)+m|0)<<9|a>>>23)+b|0)<<13|a>>>19)+o|0)<<18|a>>>14,w^=(a=(g^=(a=(p^=(a=(c^=(a=w+g|0)<<7|a>>>25)+w|0)<<9|a>>>23)+c|0)<<13|a>>>19)+p|0)<<18|a>>>14,s^=(a=(c^=(a=(o^=(a=(n^=(a=s+c|0)<<7|a>>>25)+s|0)<<9|a>>>23)+n|0)<<13|a>>>19)+o|0)<<18|a>>>14,h^=(a=(u^=(a=(p^=(a=(l^=(a=h+u|0)<<7|a>>>25)+h|0)<<9|a>>>23)+l|0)<<13|a>>>19)+p|0)<<18|a>>>14,m^=(a=(f^=(a=(d^=(a=(g^=(a=m+f|0)<<7|a>>>25)+m|0)<<9|a>>>23)+g|0)<<13|a>>>19)+d|0)<<18|a>>>14,w^=(a=(b^=(a=(y^=(a=(v^=(a=w+b|0)<<7|a>>>25)+w|0)<<9|a>>>23)+v|0)<<13|a>>>19)+y|0)<<18|a>>>14;e[0]=s>>>0&255,e[1]=s>>>8&255,e[2]=s>>>16&255,e[3]=s>>>24&255,e[4]=h>>>0&255,e[5]=h>>>8&255,e[6]=h>>>16&255,e[7]=h>>>24&255,e[8]=m>>>0&255,e[9]=m>>>8&255,e[10]=m>>>16&255,e[11]=m>>>24&255,e[12]=w>>>0&255,e[13]=w>>>8&255,e[14]=w>>>16&255,e[15]=w>>>24&255,e[16]=l>>>0&255,e[17]=l>>>8&255,e[18]=l>>>16&255,e[19]=l>>>24&255,e[20]=p>>>0&255,e[21]=p>>>8&255,e[22]=p>>>16&255,e[23]=p>>>24&255,e[24]=d>>>0&255,e[25]=d>>>8&255,e[26]=d>>>16&255,e[27]=d>>>24&255,e[28]=f>>>0&255,e[29]=f>>>8&255,e[30]=f>>>16&255,e[31]=f>>>24&255}var w=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function x(e,t,i,r,a,s,n){for(var o,c=new Uint8Array(16),u=new Uint8Array(64),h=0;h<16;h++)c[h]=0;for(h=0;h<8;h++)c[h]=s[h];for(;64<=a;){for(y(u,c,n,w),h=0;h<64;h++)e[t+h]=i[r+h]^u[h];for(o=1,h=8;h<16;h++)o=o+(255&c[h])|0,c[h]=255&o,o>>>=8;a-=64,t+=64,r+=64}if(0<a)for(y(u,c,n,w),h=0;h<a;h++)e[t+h]=i[r+h]^u[h];return 0}function k(e,t,i,r,a){for(var s,n=new Uint8Array(16),o=new Uint8Array(64),c=0;c<16;c++)n[c]=0;for(c=0;c<8;c++)n[c]=r[c];for(;64<=i;){for(y(o,n,a,w),c=0;c<64;c++)e[t+c]=o[c];for(s=1,c=8;c<16;c++)s=s+(255&n[c])|0,n[c]=255&s,s>>>=8;i-=64,t+=64}if(0<i)for(y(o,n,a,w),c=0;c<i;c++)e[t+c]=o[c];return 0}function S(e,t,i,r,a){for(var s=new Uint8Array(32),n=(b(s,r,a,w),new Uint8Array(8)),o=0;o<8;o++)n[o]=r[o+16];return k(e,t,i,n,s)}function _(e,t,i,r,a,s,n){for(var o=new Uint8Array(32),c=(b(o,s,n,w),new Uint8Array(8)),u=0;u<8;u++)c[u]=s[u+16];return x(e,t,i,r,a,c,o)}var E=function(e){var t,i;this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,t=255&e[this.fin=0]|(255&e[1])<<8,this.r[0]=8191&t,i=255&e[2]|(255&e[3])<<8,this.r[1]=8191&(t>>>13|i<<3),t=255&e[4]|(255&e[5])<<8,this.r[2]=7939&(i>>>10|t<<6),i=255&e[6]|(255&e[7])<<8,this.r[3]=8191&(t>>>7|i<<9),t=255&e[8]|(255&e[9])<<8,this.r[4]=255&(i>>>4|t<<12),this.r[5]=t>>>1&8190,i=255&e[10]|(255&e[11])<<8,this.r[6]=8191&(t>>>14|i<<2),t=255&e[12]|(255&e[13])<<8,this.r[7]=8065&(i>>>11|t<<5),i=255&e[14]|(255&e[15])<<8,this.r[8]=8191&(t>>>8|i<<8),this.r[9]=i>>>5&127,this.pad[0]=255&e[16]|(255&e[17])<<8,this.pad[1]=255&e[18]|(255&e[19])<<8,this.pad[2]=255&e[20]|(255&e[21])<<8,this.pad[3]=255&e[22]|(255&e[23])<<8,this.pad[4]=255&e[24]|(255&e[25])<<8,this.pad[5]=255&e[26]|(255&e[27])<<8,this.pad[6]=255&e[28]|(255&e[29])<<8,this.pad[7]=255&e[30]|(255&e[31])<<8};function j(e,t,i,r,a,s){return(s=new E(s)).update(i,r,a),s.finish(e,t),0}function A(e,t,i,r,a,s){var n=new Uint8Array(16);return j(n,0,i,r,a,s),g(e,t,n,0)}function R(e,t,i,r,a){var s;if(i<32)return-1;for(_(e,0,t,0,i,r,a),j(e,16,e,32,i-32,e),s=0;s<16;s++)e[s]=0;return 0}function I(e,t,i,r,a){var s,n=new Uint8Array(32);if(i<32)return-1;if(S(n,0,32,r,a),0!==A(t,16,t,32,i-32,n))return-1;for(_(e,0,t,0,i,r,a),s=0;s<32;s++)e[s]=0;return 0}function O(e,t){for(var i=0;i<16;i++)e[i]=0|t[i]}function C(e){for(var t,i=1,r=0;r<16;r++)t=e[r]+i+65535,i=Math.floor(t/65536),e[r]=t-65536*i;e[0]+=i-1+37*(i-1)}function P(e,t,i){for(var r,a=~(i-1),s=0;s<16;s++)r=a&(e[s]^t[s]),e[s]^=r,t[s]^=r}function T(e,i){for(var r,a,s=t(),n=t(),o=0;o<16;o++)n[o]=i[o];for(C(n),C(n),C(n),r=0;r<2;r++){for(s[0]=n[0]-65517,o=1;o<15;o++)s[o]=n[o]-65535-(s[o-1]>>16&1),s[o-1]&=65535;s[15]=n[15]-32767-(s[14]>>16&1),a=s[15]>>16&1,s[14]&=65535,P(n,s,1-a)}for(o=0;o<16;o++)e[2*o]=255&n[o],e[2*o+1]=n[o]>>8}function B(e,t){var i=new Uint8Array(32),r=new Uint8Array(32);return T(i,e),T(r,t),v(i,0,r,0)}function N(e){var t=new Uint8Array(32);return T(t,e),1&t[0]}function z(e,t){for(var i=0;i<16;i++)e[i]=t[2*i]+(t[2*i+1]<<8);e[15]&=32767}function F(e,t,i){for(var r=0;r<16;r++)e[r]=t[r]+i[r]}function L(e,t,i){for(var r=0;r<16;r++)e[r]=t[r]-i[r]}function M(e,t,i){var r=0,a=0,s=0,n=0,o=0,c=0,u=0,h=0,l=0,p=0,d=0,f=0,m=0,g=0,v=0,y=0,b=0,w=0,x=0,k=0,S=0,_=0,E=0,j=0,A=0,R=0,I=0,O=0,C=0,P=0,T=0,B=i[0],N=i[1],z=i[2],F=i[3],L=i[4],M=i[5],D=i[6],H=i[7],U=i[8],q=i[9],V=i[10],K=i[11],W=i[12],$=i[13],Y=i[14],G=(i=i[15],t[0]);r+=G*B,s+=G*z,n+=G*F,o+=G*L,c+=G*M,u+=G*D,h+=G*H,l+=G*U,p+=G*q,d+=G*V,f+=G*K,m+=G*W,g+=G*$,v+=G*Y,y+=G*i,a=0+G*N+(G=t[1])*B,n+=G*z,o+=G*F,c+=G*L,u+=G*M,h+=G*D,l+=G*H,p+=G*U,d+=G*q,f+=G*V,m+=G*K,g+=G*W,v+=G*$,y+=G*Y,b+=G*i,s=s+G*N+(G=t[2])*B,o+=G*z,c+=G*F,u+=G*L,h+=G*M,l+=G*D,p+=G*H,d+=G*U,f+=G*q,m+=G*V,g+=G*K,v+=G*W,y+=G*$,b+=G*Y,w+=G*i,n=n+G*N+(G=t[3])*B,c+=G*z,u+=G*F,h+=G*L,l+=G*M,p+=G*D,d+=G*H,f+=G*U,m+=G*q,g+=G*V,v+=G*K,y+=G*W,b+=G*$,w+=G*Y,x+=G*i,o=o+G*N+(G=t[4])*B,u+=G*z,h+=G*F,l+=G*L,p+=G*M,d+=G*D,f+=G*H,m+=G*U,g+=G*q,v+=G*V,y+=G*K,b+=G*W,w+=G*$,x+=G*Y,k+=G*i,c=c+G*N+(G=t[5])*B,h+=G*z,l+=G*F,p+=G*L,d+=G*M,f+=G*D,m+=G*H,g+=G*U,v+=G*q,y+=G*V,b+=G*K,w+=G*W,x+=G*$,k+=G*Y,S+=G*i,u=u+G*N+(G=t[6])*B,l+=G*z,p+=G*F,d+=G*L,f+=G*M,m+=G*D,g+=G*H,v+=G*U,y+=G*q,b+=G*V,w+=G*K,x+=G*W,k+=G*$,S+=G*Y,_+=G*i,h=h+G*N+(G=t[7])*B,p+=G*z,d+=G*F,f+=G*L,m+=G*M,g+=G*D,v+=G*H,y+=G*U,b+=G*q,w+=G*V,x+=G*K,k+=G*W,S+=G*$,_+=G*Y,E+=G*i,l=l+G*N+(G=t[8])*B,d+=G*z,f+=G*F,m+=G*L,g+=G*M,v+=G*D,y+=G*H,b+=G*U,w+=G*q,x+=G*V,k+=G*K,S+=G*W,_+=G*$,E+=G*Y,j+=G*i,p=p+G*N+(G=t[9])*B,f+=G*z,m+=G*F,g+=G*L,v+=G*M,y+=G*D,b+=G*H,w+=G*U,x+=G*q,k+=G*V,S+=G*K,_+=G*W,E+=G*$,j+=G*Y,A+=G*i,d=d+G*N+(G=t[10])*B,m+=G*z,g+=G*F,v+=G*L,y+=G*M,b+=G*D,w+=G*H,x+=G*U,k+=G*q,S+=G*V,_+=G*K,E+=G*W,j+=G*$,A+=G*Y,R+=G*i,f=f+G*N+(G=t[11])*B,g+=G*z,v+=G*F,y+=G*L,b+=G*M,w+=G*D,x+=G*H,k+=G*U,S+=G*q,_+=G*V,E+=G*K,j+=G*W,A+=G*$,R+=G*Y,I+=G*i,m=m+G*N+(G=t[12])*B,v+=G*z,y+=G*F,b+=G*L,w+=G*M,x+=G*D,k+=G*H,S+=G*U,_+=G*q,E+=G*V,j+=G*K,A+=G*W,R+=G*$,I+=G*Y,O+=G*i,g=g+G*N+(G=t[13])*B,y+=G*z,b+=G*F,w+=G*L,x+=G*M,k+=G*D,S+=G*H,_+=G*U,E+=G*q,j+=G*V,A+=G*K,R+=G*W,I+=G*$,O+=G*Y,C+=G*i,v=v+G*N+(G=t[14])*B,b+=G*z,w+=G*F,x+=G*L,k+=G*M,S+=G*D,_+=G*H,E+=G*U,j+=G*q,A+=G*V,R+=G*K,I+=G*W,O+=G*$,C+=G*Y,P+=G*i,y=y+G*N+(G=t[15])*B,a+=38*(w+=G*z),s+=38*(x+=G*F),n+=38*(k+=G*L),o+=38*(S+=G*M),c+=38*(_+=G*D),u+=38*(E+=G*H),h+=38*(j+=G*U),l+=38*(A+=G*q),p+=38*(R+=G*V),d+=38*(I+=G*K),f+=38*(O+=G*W),m+=38*(C+=G*$),g+=38*(P+=G*Y),v+=38*(T+=G*i),r=(G=1+(r+=38*(b+=G*N))+65535)-65536*(t=Math.floor(G/65536)),a=(G=a+t+65535)-65536*(t=Math.floor(G/65536)),s=(G=s+t+65535)-65536*(t=Math.floor(G/65536)),n=(G=n+t+65535)-65536*(t=Math.floor(G/65536)),o=(G=o+t+65535)-65536*(t=Math.floor(G/65536)),c=(G=c+t+65535)-65536*(t=Math.floor(G/65536)),u=(G=u+t+65535)-65536*(t=Math.floor(G/65536)),h=(G=h+t+65535)-65536*(t=Math.floor(G/65536)),l=(G=l+t+65535)-65536*(t=Math.floor(G/65536)),p=(G=p+t+65535)-65536*(t=Math.floor(G/65536)),d=(G=d+t+65535)-65536*(t=Math.floor(G/65536)),f=(G=f+t+65535)-65536*(t=Math.floor(G/65536)),m=(G=m+t+65535)-65536*(t=Math.floor(G/65536)),g=(G=g+t+65535)-65536*(t=Math.floor(G/65536)),v=(G=v+t+65535)-65536*(t=Math.floor(G/65536)),y=(G=y+t+65535)-65536*(t=Math.floor(G/65536)),r=(G=1+(r+=t-1+37*(t-1))+65535)-65536*(t=Math.floor(G/65536)),a=(G=a+t+65535)-65536*(t=Math.floor(G/65536)),s=(G=s+t+65535)-65536*(t=Math.floor(G/65536)),n=(G=n+t+65535)-65536*(t=Math.floor(G/65536)),o=(G=o+t+65535)-65536*(t=Math.floor(G/65536)),c=(G=c+t+65535)-65536*(t=Math.floor(G/65536)),u=(G=u+t+65535)-65536*(t=Math.floor(G/65536)),h=(G=h+t+65535)-65536*(t=Math.floor(G/65536)),l=(G=l+t+65535)-65536*(t=Math.floor(G/65536)),p=(G=p+t+65535)-65536*(t=Math.floor(G/65536)),d=(G=d+t+65535)-65536*(t=Math.floor(G/65536)),f=(G=f+t+65535)-65536*(t=Math.floor(G/65536)),m=(G=m+t+65535)-65536*(t=Math.floor(G/65536)),g=(G=g+t+65535)-65536*(t=Math.floor(G/65536)),v=(G=v+t+65535)-65536*(t=Math.floor(G/65536)),y=(G=y+t+65535)-65536*(t=Math.floor(G/65536)),e[0]=r+=t-1+37*(t-1),e[1]=a,e[2]=s,e[3]=n,e[4]=o,e[5]=c,e[6]=u,e[7]=h,e[8]=l,e[9]=p,e[10]=d,e[11]=f,e[12]=m,e[13]=g,e[14]=v,e[15]=y}function D(e,t){M(e,t,t)}function H(e,i){for(var r=t(),a=0;a<16;a++)r[a]=i[a];for(a=253;0<=a;a--)D(r,r),2!==a&&4!==a&&M(r,r,i);for(a=0;a<16;a++)e[a]=r[a]}function U(e,i,r){for(var a,s=new Uint8Array(32),n=new Float64Array(80),o=t(),u=t(),h=t(),l=t(),p=t(),d=t(),f=0;f<31;f++)s[f]=i[f];for(s[31]=127&i[31]|64,s[0]&=248,z(n,r),f=0;f<16;f++)u[f]=n[f],l[f]=o[f]=h[f]=0;for(o[0]=l[0]=1,f=254;0<=f;--f)P(o,u,a=s[f>>>3]>>>(7&f)&1),P(h,l,a),F(p,o,h),L(o,o,h),F(h,u,l),L(u,u,l),D(l,p),D(d,o),M(o,h,o),M(h,u,p),F(p,o,h),L(o,o,h),D(u,o),L(h,l,d),M(o,h,c),F(o,o,l),M(h,h,o),M(o,l,d),M(l,u,n),D(u,p),P(o,u,a),P(h,l,a);for(f=0;f<16;f++)n[f+16]=o[f],n[f+32]=h[f],n[f+48]=u[f],n[f+64]=l[f];r=n.subarray(32);var m=n.subarray(16);return H(r,r),M(m,m,r),T(e,m),0}function q(e,t){return U(e,t,s)}function V(e,t){return r(t,32),q(e,t)}function K(e,t,i){var r=new Uint8Array(32);return U(r,i,t),b(e,a,r,w)}E.prototype.blocks=function(e,t,i){for(var r,a,s,n,o,c,u,h,l,p,d,f=this.fin?0:2048,m=this.h[0],g=this.h[1],v=this.h[2],y=this.h[3],b=this.h[4],w=this.h[5],x=this.h[6],k=this.h[7],S=this.h[8],_=this.h[9],E=this.r[0],j=this.r[1],A=this.r[2],R=this.r[3],I=this.r[4],O=this.r[5],C=this.r[6],P=this.r[7],T=this.r[8],B=this.r[9];16<=i;)a=r=0,r=(a=(a=(a+=(m+=8191&(s=255&e[t+0]|(255&e[t+1])<<8))*E)+(g+=8191&(s>>>13|(s=255&e[t+2]|(255&e[t+3])<<8)<<3))*(5*B)+(v+=8191&(s>>>10|(s=255&e[t+4]|(255&e[t+5])<<8)<<6))*(5*T))+(y+=8191&(s>>>7|(s=255&e[t+6]|(255&e[t+7])<<8)<<9))*(5*P)+(b+=8191&(s>>>4|(s=255&e[t+8]|(255&e[t+9])<<8)<<12))*(5*C))>>>13,s=r+=(a=(a=(a=(8191&a)+(w+=s>>>1&8191)*(5*O))+(x+=8191&(s>>>14|(s=255&e[t+10]|(255&e[t+11])<<8)<<2))*(5*I)+(k+=8191&(s>>>11|(s=255&e[t+12]|(255&e[t+13])<<8)<<5))*(5*R))+(S+=8191&(s>>>8|(s=255&e[t+14]|(255&e[t+15])<<8)<<8))*(5*A)+(_+=s>>>5|f)*(5*j))>>>13,r=(s=(s=(s+=m*j)+g*E+v*(5*B))+y*(5*T)+b*(5*P))>>>13,n=r+=(s=(s=(s=(8191&s)+w*(5*C))+x*(5*O)+k*(5*I))+S*(5*R)+_*(5*A))>>>13,r=(n=(n=(n+=m*A)+g*j+v*E)+y*(5*B)+b*(5*T))>>>13,o=r+=(n=(n=(n=(8191&n)+w*(5*P))+x*(5*C)+k*(5*O))+S*(5*I)+_*(5*R))>>>13,r=(o=(o=(o+=m*R)+g*A+v*j)+y*E+b*(5*B))>>>13,c=r+=(o=(o=(o=(8191&o)+w*(5*T))+x*(5*P)+k*(5*C))+S*(5*O)+_*(5*I))>>>13,r=(c=(c=(c+=m*I)+g*R+v*A)+y*j+b*E)>>>13,u=r+=(c=(c=(c=(8191&c)+w*(5*B))+x*(5*T)+k*(5*P))+S*(5*C)+_*(5*O))>>>13,r=(u=(u=(u+=m*O)+g*I+v*R)+y*A+b*j)>>>13,h=r+=(u=(u=(u=(8191&u)+w*E)+x*(5*B)+k*(5*T))+S*(5*P)+_*(5*C))>>>13,r=(h=(h=(h+=m*C)+g*O+v*I)+y*R+b*A)>>>13,l=r+=(h=(h=(h=(8191&h)+w*j)+x*E+k*(5*B))+S*(5*T)+_*(5*P))>>>13,r=(l=(l=(l+=m*P)+g*C+v*O)+y*I+b*R)>>>13,p=r+=(l=(l=(l=(8191&l)+w*A)+x*j+k*E)+S*(5*B)+_*(5*T))>>>13,r=(p=(p=(p+=m*T)+g*P+v*C)+y*O+b*I)>>>13,d=r+=(p=(p=(p=(8191&p)+w*R)+x*A+k*j)+S*E+_*(5*B))>>>13,r=(d=(d=(d+=m*B)+g*T+v*P)+y*C+b*O)>>>13,m=a=8191&(r=(r=((r+=(d=(d=(d=(8191&d)+w*I)+x*R+k*A)+S*j+_*E)>>>13)<<2)+r|0)+(a&=8191)|0),g=s=(8191&s)+(r>>>=13),v=n&=8191,y=o&=8191,b=c&=8191,w=u&=8191,x=h&=8191,k=l&=8191,S=p&=8191,_=d&=8191,t+=16,i-=16;this.h[0]=m,this.h[1]=g,this.h[2]=v,this.h[3]=y,this.h[4]=b,this.h[5]=w,this.h[6]=x,this.h[7]=k,this.h[8]=S,this.h[9]=_},E.prototype.finish=function(e,t){var i,r,a,s,n=new Uint16Array(10);if(this.leftover){for(s=this.leftover,this.buffer[s++]=1;s<16;s++)this.buffer[s]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(i=this.h[1]>>>13,this.h[1]&=8191,s=2;s<10;s++)this.h[s]+=i,i=this.h[s]>>>13,this.h[s]&=8191;for(this.h[0]+=5*i,i=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=i,i=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=i,n[0]=this.h[0]+5,i=n[0]>>>13,n[0]&=8191,s=1;s<10;s++)n[s]=this.h[s]+i,i=n[s]>>>13,n[s]&=8191;for(n[9]-=8192,r=(1^i)-1,s=0;s<10;s++)n[s]&=r;for(r=~r,s=0;s<10;s++)this.h[s]=this.h[s]&r|n[s];for(this.h[0]=65535&(this.h[0]|this.h[1]<<13),this.h[1]=65535&(this.h[1]>>>3|this.h[2]<<10),this.h[2]=65535&(this.h[2]>>>6|this.h[3]<<7),this.h[3]=65535&(this.h[3]>>>9|this.h[4]<<4),this.h[4]=65535&(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14),this.h[5]=65535&(this.h[6]>>>2|this.h[7]<<11),this.h[6]=65535&(this.h[7]>>>5|this.h[8]<<8),this.h[7]=65535&(this.h[8]>>>8|this.h[9]<<5),a=this.h[0]+this.pad[0],this.h[0]=65535&a,s=1;s<8;s++)a=(this.h[s]+this.pad[s]|0)+(a>>>16)|0,this.h[s]=65535&a;e[t+0]=this.h[0]>>>0&255,e[t+1]=this.h[0]>>>8&255,e[t+2]=this.h[1]>>>0&255,e[t+3]=this.h[1]>>>8&255,e[t+4]=this.h[2]>>>0&255,e[t+5]=this.h[2]>>>8&255,e[t+6]=this.h[3]>>>0&255,e[t+7]=this.h[3]>>>8&255,e[t+8]=this.h[4]>>>0&255,e[t+9]=this.h[4]>>>8&255,e[t+10]=this.h[5]>>>0&255,e[t+11]=this.h[5]>>>8&255,e[t+12]=this.h[6]>>>0&255,e[t+13]=this.h[6]>>>8&255,e[t+14]=this.h[7]>>>0&255,e[t+15]=this.h[7]>>>8&255},E.prototype.update=function(e,t,i){var r,a;if(this.leftover){for(i<(a=16-this.leftover)&&(a=i),r=0;r<a;r++)this.buffer[this.leftover+r]=e[t+r];if(i-=a,t+=a,this.leftover+=a,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(16<=i&&(this.blocks(e,t,a=i-i%16),t+=a,i-=a),i){for(r=0;r<i;r++)this.buffer[this.leftover+r]=e[t+r];this.leftover+=i}};var W=R,$=I,Y=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function G(e,t,i,r){for(var a,s,n,o,c,u,h,l,p,d,f,m,g,v,y,b,w,x,k,S,_,E,j,A,R,I,O=new Int32Array(16),C=new Int32Array(16),P=e[0],T=e[1],B=e[2],N=e[3],z=e[4],F=e[5],L=e[6],M=e[7],D=t[0],H=t[1],U=t[2],q=t[3],V=t[4],K=t[5],W=t[6],$=t[7],G=0;128<=r;){for(k=0;k<16;k++)O[k]=i[(S=8*k+G)+0]<<24|i[S+1]<<16|i[S+2]<<8|i[S+3],C[k]=i[S+4]<<24|i[S+5]<<16|i[S+6]<<8|i[S+7];for(k=0;k<80;k++)if(a=P,s=T,n=B,o=N,p=D,d=H,f=U,m=q,j=65535&(E=$),A=E>>>16,R=65535&(_=M),I=_>>>16,A+=(E=((g=V)>>>14|(c=z)<<18)^(V>>>18|z<<14)^(z>>>9|V<<23))>>>16,I+=(_=(z>>>14|V<<18)^(z>>>18|V<<14)^(V>>>9|z<<23))>>>16,j=j+(65535&E)+(65535&(E=V&(v=K)^~V&(y=W))),A+=E>>>16,R=R+(65535&_)+(65535&(_=z&(u=F)^~z&(h=L))),I+=_>>>16,j+=65535&(E=Y[2*k+1]),A+=E>>>16,I+=(_=Y[2*k])>>>16,R=(R+=65535&_)+(65535&(_=O[k%16]))+((A=A+((E=C[k%16])>>>16)+((j+=65535&E)>>>16))>>>16),j=65535&(E=x=65535&j|A<<16),A=E>>>16,R=65535&(_=w=65535&R|(I=I+(_>>>16)+(R>>>16))<<16),I=_>>>16,j+=65535&(E=(D>>>28|P<<4)^(P>>>2|D<<30)^(P>>>7|D<<25)),I+=(_=(P>>>28|D<<4)^(D>>>2|P<<30)^(D>>>7|P<<25))>>>16,l=65535&(R=(R+=65535&_)+(65535&(_=P&T^P&B^T&B))+((A=(A+=E>>>16)+((E=D&H^D&U^H&U)>>>16)+((j+=65535&E)>>>16))>>>16))|(I=I+(_>>>16)+(R>>>16))<<16,b=65535&j|A<<16,j=65535&(E=m),I=(_=o)>>>16,T=a,B=s,N=n,z=65535&(R=(R=65535&_)+(65535&(_=w))+((A=(A=E>>>16)+((E=x)>>>16)+((j+=65535&E)>>>16))>>>16))|(I=I+(_>>>16)+(R>>>16))<<16,F=c,L=u,M=h,P=l,H=p,U=d,q=f,V=65535&j|A<<16,K=g,W=v,$=y,D=b,k%16==15)for(S=0;S<16;S++)_=O[S],j=65535&(E=C[S]),A=E>>>16,R=65535&_,I=_>>>16,_=O[(S+9)%16],j+=65535&(E=C[(S+9)%16]),A+=E>>>16,R+=65535&_,I+=_>>>16,w=O[(S+1)%16],j+=65535&(E=((x=C[(S+1)%16])>>>1|w<<31)^(x>>>8|w<<24)^(x>>>7|w<<25)),A+=E>>>16,R+=65535&(_=(w>>>1|x<<31)^(w>>>8|x<<24)^w>>>7),I=(I+=_>>>16)+((_=((w=O[(S+14)%16])>>>19|(x=C[(S+14)%16])<<13)^(x>>>29|w<<3)^w>>>6)>>>16)+((R=R+(65535&_)+((A=A+((E=(x>>>19|w<<13)^(w>>>29|x<<3)^(x>>>6|w<<26))>>>16)+((j+=65535&E)>>>16))>>>16))>>>16),O[S]=65535&R|I<<16,C[S]=65535&j|A<<16;j=65535&(E=D),R=65535&(_=P),I=(I=_>>>16)+((_=e[0])>>>16)+((R=R+(65535&_)+((A=(A=E>>>16)+((E=t[0])>>>16)+((j+=65535&E)>>>16))>>>16))>>>16),e[0]=P=65535&R|I<<16,t[0]=D=65535&j|A<<16,j=65535&(E=H),R=65535&(_=T),I=(I=_>>>16)+((_=e[1])>>>16)+((R=R+(65535&_)+((A=(A=E>>>16)+((E=t[1])>>>16)+((j+=65535&E)>>>16))>>>16))>>>16),e[1]=T=65535&R|I<<16,t[1]=H=65535&j|A<<16,j=65535&(E=U),R=65535&(_=B),I=(I=_>>>16)+((_=e[2])>>>16)+((R=R+(65535&_)+((A=(A=E>>>16)+((E=t[2])>>>16)+((j+=65535&E)>>>16))>>>16))>>>16),e[2]=B=65535&R|I<<16,t[2]=U=65535&j|A<<16,j=65535&(E=q),R=65535&(_=N),I=(I=_>>>16)+((_=e[3])>>>16)+((R=R+(65535&_)+((A=(A=E>>>16)+((E=t[3])>>>16)+((j+=65535&E)>>>16))>>>16))>>>16),e[3]=N=65535&R|I<<16,t[3]=q=65535&j|A<<16,j=65535&(E=V),R=65535&(_=z),I=(I=_>>>16)+((_=e[4])>>>16)+((R=R+(65535&_)+((A=(A=E>>>16)+((E=t[4])>>>16)+((j+=65535&E)>>>16))>>>16))>>>16),e[4]=z=65535&R|I<<16,t[4]=V=65535&j|A<<16,j=65535&(E=K),R=65535&(_=F),I=(I=_>>>16)+((_=e[5])>>>16)+((R=R+(65535&_)+((A=(A=E>>>16)+((E=t[5])>>>16)+((j+=65535&E)>>>16))>>>16))>>>16),e[5]=F=65535&R|I<<16,t[5]=K=65535&j|A<<16,j=65535&(E=W),R=65535&(_=L),I=(I=_>>>16)+((_=e[6])>>>16)+((R=R+(65535&_)+((A=(A=E>>>16)+((E=t[6])>>>16)+((j+=65535&E)>>>16))>>>16))>>>16),e[6]=L=65535&R|I<<16,t[6]=W=65535&j|A<<16,j=65535&(E=$),R=65535&(_=M),I=(I=_>>>16)+((_=e[7])>>>16)+((R=R+(65535&_)+((A=(A=E>>>16)+((E=t[7])>>>16)+((j+=65535&E)>>>16))>>>16))>>>16),e[7]=M=65535&R|I<<16,t[7]=$=65535&j|A<<16,G+=128,r-=128}}function X(e,t,i){var r,a=new Int32Array(8),s=new Int32Array(8),n=new Uint8Array(256),o=i;for(a[0]=1779033703,a[1]=3144134277,a[2]=1013904242,a[3]=2773480762,a[4]=1359893119,a[5]=2600822924,a[6]=528734635,a[7]=1541459225,s[0]=4089235720,s[1]=2227873595,s[2]=4271175723,s[3]=1595750129,s[4]=2917565137,s[5]=725511199,s[6]=4215389547,s[7]=327033209,G(a,s,t,i),i%=128,r=0;r<i;r++)n[r]=t[o-i+r];for(n[i]=128,n[(i=256-128*(i<112?1:0))-9]=0,f(n,i-8,o/536870912|0,o<<3),G(a,s,n,i),r=0;r<8;r++)f(e,8*r,a[r],s[r]);return 0}function J(e,i){var r=t(),a=t(),s=t(),n=t(),o=t(),c=t(),u=t(),l=t(),p=t();L(r,e[1],e[0]),L(p,i[1],i[0]),M(r,r,p),F(a,e[0],e[1]),F(p,i[0],i[1]),M(a,a,p),M(s,e[3],i[3]),M(s,s,h),M(n,e[2],i[2]),F(n,n,n),L(o,a,r),L(c,n,s),F(u,n,s),F(l,a,r),M(e[0],o,c),M(e[1],l,u),M(e[2],u,c),M(e[3],o,l)}function Q(e,t,i){for(var r=0;r<4;r++)P(e[r],t[r],i)}function Z(e,i){var r=t(),a=t(),s=t();H(s,i[2]),M(r,i[0],s),M(a,i[1],s),T(e,a),e[31]^=N(r)<<7}function ee(e,t,i){var r,a;for(O(e[0],n),O(e[1],o),O(e[2],o),O(e[3],n),a=255;0<=a;--a)Q(e,t,r=i[a/8|0]>>(7&a)&1),J(t,e),J(e,e),Q(e,t,r)}function te(e,i){var r=[t(),t(),t(),t()];O(r[0],l),O(r[1],p),O(r[2],o),M(r[3],l,p),ee(e,r,i)}function ie(e,i,a){var s,n=new Uint8Array(64),o=[t(),t(),t(),t()];for(a||r(i,32),X(n,i,32),n[0]&=248,n[31]&=127,n[31]|=64,te(o,n),Z(e,o),s=0;s<32;s++)i[s+32]=e[s];return 0}var re,ae=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function se(e,t){for(var i,r,a,s=63;32<=s;--s){for(i=0,r=s-32,a=s-12;r<a;++r)t[r]+=i-16*t[s]*ae[r-(s-32)],i=t[r]+128>>8,t[r]-=256*i;t[r]+=i,t[s]=0}for(r=i=0;r<32;r++)t[r]+=i-(t[31]>>4)*ae[r],i=t[r]>>8,t[r]&=255;for(r=0;r<32;r++)t[r]-=i*ae[r];for(s=0;s<32;s++)t[s+1]+=t[s]>>8,e[s]=255&t[s]}function ne(e){for(var t=new Float64Array(64),i=0;i<64;i++)t[i]=e[i];for(i=0;i<64;i++)e[i]=0;se(e,t)}function oe(e,i,r,a){for(var s,n=new Uint8Array(64),o=new Uint8Array(64),c=new Uint8Array(64),u=new Float64Array(64),h=[t(),t(),t(),t()],l=(X(n,a,32),n[0]&=248,n[31]&=127,n[31]|=64,r+64),p=0;p<r;p++)e[64+p]=i[p];for(p=0;p<32;p++)e[32+p]=n[32+p];for(X(c,e.subarray(32),r+32),ne(c),te(h,c),Z(e,h),p=32;p<64;p++)e[p]=a[p];for(X(o,e,r+64),ne(o),p=0;p<64;p++)u[p]=0;for(p=0;p<32;p++)u[p]=c[p];for(p=0;p<32;p++)for(s=0;s<32;s++)u[p+s]+=o[p]*n[s];return se(e.subarray(32),u),l}function ce(e,i,r,a){var s,c=new Uint8Array(32),h=new Uint8Array(64),l=[t(),t(),t(),t()],p=[t(),t(),t(),t()];if(r<64)return-1;if(function(e,i){for(var r=t(),a=t(),s=t(),c=t(),h=t(),l=t(),p=t(),f=(O(e[2],o),z(e[1],i),D(s,e[1]),M(c,s,u),L(s,s,e[2]),F(c,e[2],c),D(h,c),D(l,h),M(p,l,h),M(r,p,s),M(r,r,c),r),m=r,g=t(),v=0;v<16;v++)g[v]=m[v];for(v=250;0<=v;v--)D(g,g),1!==v&&M(g,g,m);for(v=0;v<16;v++)f[v]=g[v];if(M(r,r,s),M(r,r,c),M(r,r,c),M(e[0],r,c),D(a,e[0]),M(a,a,c),B(a,s)&&M(e[0],e[0],d),D(a,e[0]),M(a,a,c),B(a,s))return 1;N(e[0])===i[31]>>7&&L(e[0],n,e[0]),M(e[3],e[0],e[1])}(p,a))return-1;for(s=0;s<r;s++)e[s]=i[s];for(s=0;s<32;s++)e[s+32]=a[s];if(X(h,e,r),ne(h),ee(l,p,h),te(p,i.subarray(32)),J(l,p),Z(c,l),r-=64,v(i,0,c,0)){for(s=0;s<r;s++)e[s]=0;return-1}for(s=0;s<r;s++)e[s]=i[s+64];return r}function ue(e,t){if(32!==e.length)throw new Error("bad key size");if(24!==t.length)throw new Error("bad nonce size")}function he(){for(var e,t=0;t<arguments.length;t++)if("[object Uint8Array]"!==(e=Object.prototype.toString.call(arguments[t])))throw new TypeError("unexpected type "+e+", use Uint8Array")}function le(e){for(var t=0;t<e.length;t++)e[t]=0}e.lowlevel={crypto_core_hsalsa20:b,crypto_stream_xor:_,crypto_stream:S,crypto_stream_salsa20_xor:x,crypto_stream_salsa20:k,crypto_onetimeauth:j,crypto_onetimeauth_verify:A,crypto_verify_16:g,crypto_verify_32:v,crypto_secretbox:R,crypto_secretbox_open:I,crypto_scalarmult:U,crypto_scalarmult_base:q,crypto_box_beforenm:K,crypto_box_afternm:W,crypto_box:function(e,t,i,r,a,s){var n=new Uint8Array(32);return K(n,a,s),W(e,t,i,r,n)},crypto_box_open:function(e,t,i,r,a,s){var n=new Uint8Array(32);return K(n,a,s),$(e,t,i,r,n)},crypto_box_keypair:V,crypto_hash:X,crypto_sign:oe,crypto_sign_keypair:ie,crypto_sign_open:ce,crypto_secretbox_KEYBYTES:32,crypto_secretbox_NONCEBYTES:24,crypto_secretbox_ZEROBYTES:32,crypto_secretbox_BOXZEROBYTES:16,crypto_scalarmult_BYTES:32,crypto_scalarmult_SCALARBYTES:32,crypto_box_PUBLICKEYBYTES:32,crypto_box_SECRETKEYBYTES:32,crypto_box_BEFORENMBYTES:32,crypto_box_NONCEBYTES:24,crypto_box_ZEROBYTES:32,crypto_box_BOXZEROBYTES:16,crypto_sign_BYTES:64,crypto_sign_PUBLICKEYBYTES:32,crypto_sign_SECRETKEYBYTES:64,crypto_sign_SEEDBYTES:32,crypto_hash_BYTES:64},e.util||(e.util={},e.util.decodeUTF8=e.util.encodeUTF8=e.util.encodeBase64=e.util.decodeBase64=function(){throw new Error("nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js")}),e.randomBytes=function(e){var t=new Uint8Array(e);return r(t,e),t},e.secretbox=function(e,t,i){he(e,t,i),ue(i,t);for(var r=new Uint8Array(32+e.length),a=new Uint8Array(r.length),s=0;s<e.length;s++)r[s+32]=e[s];return R(a,r,r.length,t,i),a.subarray(16)},e.secretbox.open=function(e,t,i){he(e,t,i),ue(i,t);for(var r=new Uint8Array(16+e.length),a=new Uint8Array(r.length),s=0;s<e.length;s++)r[s+16]=e[s];return!(r.length<32)&&0===I(a,r,r.length,t,i)&&a.subarray(32)},e.secretbox.keyLength=32,e.secretbox.nonceLength=24,e.secretbox.overheadLength=16,e.scalarMult=function(e,t){if(he(e,t),32!==e.length)throw new Error("bad n size");if(32!==t.length)throw new Error("bad p size");var i=new Uint8Array(32);return U(i,e,t),i},e.scalarMult.base=function(e){if(he(e),32!==e.length)throw new Error("bad n size");var t=new Uint8Array(32);return q(t,e),t},e.scalarMult.scalarLength=32,e.scalarMult.groupElementLength=32,e.box=function(t,i,r,a){return r=e.box.before(r,a),e.secretbox(t,i,r)},e.box.before=function(e,t){he(e,t);var i=t;if(32!==e.length)throw new Error("bad public key size");if(32!==i.length)throw new Error("bad secret key size");return K(i=new Uint8Array(32),e,t),i},e.box.after=e.secretbox,e.box.open=function(t,i,r,a){return r=e.box.before(r,a),e.secretbox.open(t,i,r)},e.box.open.after=e.secretbox.open,e.box.keyPair=function(){var e=new Uint8Array(32),t=new Uint8Array(32);return V(e,t),{publicKey:e,secretKey:t}},e.box.keyPair.fromSecretKey=function(e){if(he(e),32!==e.length)throw new Error("bad secret key size");var t=new Uint8Array(32);return q(t,e),{publicKey:t,secretKey:new Uint8Array(e)}},e.box.publicKeyLength=32,e.box.secretKeyLength=32,e.box.sharedKeyLength=32,e.box.nonceLength=24,e.box.overheadLength=e.secretbox.overheadLength,e.sign=function(e,t){if(he(e,t),64!==t.length)throw new Error("bad secret key size");var i=new Uint8Array(64+e.length);return oe(i,e,e.length,t),i},e.sign.open=function(e,t){if(2!==arguments.length)throw new Error("nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?");if(he(e,t),32!==t.length)throw new Error("bad public key size");var i=new Uint8Array(e.length);if((e=ce(i,e,e.length,t))<0)return null;for(var r=new Uint8Array(e),a=0;a<r.length;a++)r[a]=i[a];return r},e.sign.detached=function(t,i){for(var r=e.sign(t,i),a=new Uint8Array(64),s=0;s<a.length;s++)a[s]=r[s];return a},e.sign.detached.verify=function(e,t,i){if(he(e,t,i),64!==t.length)throw new Error("bad signature size");if(32!==i.length)throw new Error("bad public key size");for(var r=new Uint8Array(64+e.length),a=new Uint8Array(64+e.length),s=0;s<64;s++)r[s]=t[s];for(s=0;s<e.length;s++)r[s+64]=e[s];return 0<=ce(a,r,r.length,i)},e.sign.keyPair=function(){var e=new Uint8Array(32),t=new Uint8Array(64);return ie(e,t),{publicKey:e,secretKey:t}},e.sign.keyPair.fromSecretKey=function(e){if(he(e),64!==e.length)throw new Error("bad secret key size");for(var t=new Uint8Array(32),i=0;i<t.length;i++)t[i]=e[32+i];return{publicKey:t,secretKey:new Uint8Array(e)}},e.sign.keyPair.fromSeed=function(e){if(he(e),32!==e.length)throw new Error("bad seed size");for(var t=new Uint8Array(32),i=new Uint8Array(64),r=0;r<32;r++)i[r]=e[r];return ie(t,i,!0),{publicKey:t,secretKey:i}},e.sign.publicKeyLength=32,e.sign.secretKeyLength=64,e.sign.seedLength=32,e.sign.signatureLength=64,e.hash=function(e){he(e);var t=new Uint8Array(64);return X(t,e,e.length),t},e.hash.hashLength=64,e.verify=function(e,t){return he(e,t),0!==e.length&&0!==t.length&&e.length===t.length&&0===m(e,0,t,0,e.length)},e.setPRNG=function(e){r=e},(re="undefined"!=typeof self?self.crypto||self.msCrypto:null)&&re.getRandomValues?e.setPRNG((function(e,t){for(var i=new Uint8Array(t),r=0;r<t;r+=65536)re.getRandomValues(i.subarray(r,r+Math.min(t-r,65536)));for(r=0;r<t;r++)e[r]=i[r];le(i)})):(re=i(8))&&re.randomBytes&&e.setPRNG((function(e,t){for(var i=re.randomBytes(t),r=0;r<t;r++)e[r]=i[r];le(i)}))}(e.exports||(self.nacl=self.nacl||{}))},function(e,t,i){e.exports={read:function(e,t){return h.read(e,t,"pkcs8")},readPkcs8:function(e,t,i){i.peek()===a.Ber.Integer&&(r.strictEqual(t,"private","unexpected Integer at start of public key"),i.readString(a.Ber.Integer,!0)),i.readSequence();var n=i.offset+i.length,h=i.readOID();switch(h){case"1.2.840.113549.1.1.1":return i._offset=n,("public"===t?function(e){e.readSequence(a.Ber.BitString),e.readByte(),e.readSequence();var t=l(e,"modulus"),i=l(e,"exponent");e={type:"rsa",source:e.originalInput,parts:[{name:"e",data:i},{name:"n",data:t}]};return new c(e)}:function(e){e.readSequence(a.Ber.OctetString),e.readSequence();var t=l(e,"version"),i=(t=(r.equal(t[0],0,"unknown RSA private key version"),l(e,"modulus")),l(e,"public exponent")),s=l(e,"private exponent"),n=l(e,"prime1"),o=l(e,"prime2"),c=l(e,"exponent1"),h=l(e,"exponent2");e=l(e,"iqmp");return new u({type:"rsa",parts:[{name:"n",data:t},{name:"e",data:i},{name:"d",data:s},{name:"iqmp",data:e},{name:"p",data:n},{name:"q",data:o},{name:"dmodp",data:c},{name:"dmodq",data:h}]})})(i);case"1.2.840.10040.4.1":return("public"===t?function(e){e.readSequence();var t=l(e,"p"),i=l(e,"q"),r=l(e,"g");e.readSequence(a.Ber.BitString),e.readByte(),e=l(e,"y");return new c({type:"dsa",parts:[{name:"p",data:t},{name:"q",data:i},{name:"g",data:r},{name:"y",data:e}]})}:function(e){e.readSequence();var t=l(e,"p"),i=l(e,"q"),r=l(e,"g"),s=(e=(e.readSequence(a.Ber.OctetString),l(e,"x")),o.calculateDSAPublic(r,t,e));return new u({type:"dsa",parts:[{name:"p",data:t},{name:"q",data:i},{name:"g",data:r},{name:"y",data:s},{name:"x",data:e}]})})(i);case"1.2.840.10045.2.1":return("public"===t?function(e){var t=p(e);r.string(t,"a known elliptic curve"),e=e.readString(a.Ber.BitString,!0),e=o.ecNormalize(e),t={type:"ecdsa",parts:[{name:"curve",data:s.from(t)},{name:"Q",data:e}]};return new c(t)}:function(e){var t,i=p(e),n=(r.string(i,"a known elliptic curve"),e.readSequence(a.Ber.OctetString),e.readSequence(),l(e,"version"));r.equal(n[0],1,"unknown version of ECDSA key"),n=e.readString(a.Ber.OctetString,!0);return 160==e.peek()&&(e.readSequence(160),e._offset+=e.length),161==e.peek()&&(e.readSequence(161),t=e.readString(a.Ber.BitString,!0),t=o.ecNormalize(t)),void 0===t&&(t=(e=o.publicFromPrivateECDSA(i,n)).part.Q.data),e={type:"ecdsa",parts:[{name:"curve",data:s.from(i)},{name:"Q",data:t},{name:"d",data:n}]},new u(e)})(i);case"1.3.101.112":return("public"===t?function(e){return 0===e.peek()&&e.readByte(),e=o.readBitString(e),e={type:"ed25519",parts:[{name:"A",data:o.zeroPadToLength(e,32)}]},new c(e)}:function(e){0===e.peek()&&e.readByte(),e.readSequence(a.Ber.OctetString);var t,i=e.readString(a.Ber.OctetString,!0);return i=o.zeroPadToLength(i,32),t=e.peek()===a.Ber.BitString?(t=o.readBitString(e),o.zeroPadToLength(t,32)):o.calculateED25519Public(i),e={type:"ed25519",parts:[{name:"A",data:o.zeroPadToLength(t,32)},{name:"k",data:o.zeroPadToLength(i,32)}]},new u(e)})(i);case"1.3.101.110":return("public"===t?function(e){return e=o.readBitString(e),e={type:"curve25519",parts:[{name:"A",data:o.zeroPadToLength(e,32)}]},new c(e)}:function(e){0===e.peek()&&e.readByte(),e.readSequence(a.Ber.OctetString);e=e.readString(a.Ber.OctetString,!0);var t=(e=o.zeroPadToLength(e,32),o.calculateX25519Public(e));t={type:"curve25519",parts:[{name:"A",data:o.zeroPadToLength(t,32)},{name:"k",data:o.zeroPadToLength(e,32)}]};return new u(t)})(i);default:throw new Error("Unknown key type OID "+h)}},write:function(e,t){return h.write(e,t,"pkcs8")},writePkcs8:d,pkcs8ToBuffer:function(e){var t=new a.BerWriter;return d(t,e),t.buffer},readECDSACurve:p,writeECDSACurve:f};var r=i(10),a=i(58),s=i(12).Buffer,n=i(30),o=i(25),c=i(23),u=i(24),h=i(65);function l(e,t){return r.strictEqual(e.peek(),a.Ber.Integer,t+" is not an Integer"),o.mpNormalize(e.readString(a.Ber.Integer,!0))}function p(e){var t;if(e.peek()===a.Ber.OID){for(var i=e.readOID(),c=Object.keys(n.curves),u=0;u<c.length;++u)if(d=c[u],(f=n.curves[d]).pkcs8oid===i){t=d;break}}else{e.readSequence();var h=e.readString(a.Ber.Integer,!0),l=(r.strictEqual(h[0],1,"ECDSA key not version 1"),{}),p=(h=(e.readSequence(),e.readOID()),h=(r.strictEqual(h,"1.2.840.10045.1.1","ECDSA key is not from a prime-field"),l.p=o.mpNormalize(e.readString(a.Ber.Integer,!0))),l.size=8*h.length-o.countZeros(h),e.readSequence(),l.a=o.mpNormalize(e.readString(a.Ber.OctetString,!0)),l.b=o.mpNormalize(e.readString(a.Ber.OctetString,!0)),e.peek()===a.Ber.BitString&&(l.s=e.readString(a.Ber.BitString,!0)),l.G=e.readString(a.Ber.OctetString,!0),r.strictEqual(l.G[0],4,"uncompressed G is required"),l.n=o.mpNormalize(e.readString(a.Ber.Integer,!0)),l.h=o.mpNormalize(e.readString(a.Ber.Integer,!0)),r.strictEqual(l.h[0],1,"a cofactor=1 curve is required"),c=Object.keys(n.curves),Object.keys(l));for(u=0;u<c.length;++u){for(var d=c[u],f=n.curves[d],m=!0,g=0;g<p.length;++g){var v=p[g];if(void 0!==f[v])if("object"==typeof f[v]&&void 0!==f[v].equals){if(!f[v].equals(l[v])){m=!1;break}}else if(s.isBuffer(f[v])){if(f[v].toString("binary")!==l[v].toString("binary")){m=!1;break}}else if(f[v]!==l[v]){m=!1;break}}if(m){t=d;break}}}return t}function d(e,t){var i,r,n,c,h;switch(e.startSequence(),u.isPrivateKey(t)&&(i=s.from([0]),e.writeBuffer(i,a.Ber.Integer)),e.startSequence(),t.type){case"rsa":if(e.writeOID("1.2.840.113549.1.1.1"),u.isPrivateKey(t)){var l=t,p=e,d=(p.writeNull(),p.endSequence(),p.startSequence(a.Ber.OctetString),p.startSequence(),s.from([0]));p.writeBuffer(d,a.Ber.Integer),p.writeBuffer(l.part.n.data,a.Ber.Integer),p.writeBuffer(l.part.e.data,a.Ber.Integer),p.writeBuffer(l.part.d.data,a.Ber.Integer),p.writeBuffer(l.part.p.data,a.Ber.Integer),p.writeBuffer(l.part.q.data,a.Ber.Integer),l.part.dmodp&&l.part.dmodq||o.addRSAMissing(l),p.writeBuffer(l.part.dmodp.data,a.Ber.Integer),p.writeBuffer(l.part.dmodq.data,a.Ber.Integer),p.writeBuffer(l.part.iqmp.data,a.Ber.Integer),p.endSequence(),p.endSequence()}else d=t,(l=e).writeNull(),l.endSequence(),l.startSequence(a.Ber.BitString),l.writeByte(0),l.startSequence(),l.writeBuffer(d.part.n.data,a.Ber.Integer),l.writeBuffer(d.part.e.data,a.Ber.Integer),l.endSequence(),l.endSequence();break;case"dsa":e.writeOID("1.2.840.10040.4.1"),(u.isPrivateKey(t)?(p=t,(h=e).startSequence(),h.writeBuffer(p.part.p.data,a.Ber.Integer),h.writeBuffer(p.part.q.data,a.Ber.Integer),h.writeBuffer(p.part.g.data,a.Ber.Integer),h.endSequence(),h.endSequence(),h.startSequence(a.Ber.OctetString),h.writeBuffer(p.part.x.data,a.Ber.Integer),h):(h=t,(c=e).startSequence(),c.writeBuffer(h.part.p.data,a.Ber.Integer),c.writeBuffer(h.part.q.data,a.Ber.Integer),c.writeBuffer(h.part.g.data,a.Ber.Integer),c.endSequence(),c.endSequence(),c.startSequence(a.Ber.BitString),c.writeByte(0),c.writeBuffer(h.part.y.data,a.Ber.Integer),c)).endSequence();break;case"ecdsa":if(e.writeOID("1.2.840.10045.2.1"),u.isPrivateKey(t))f(c=t,g=e),g.endSequence(),g.startSequence(a.Ber.OctetString),g.startSequence(),m=s.from([1]),g.writeBuffer(m,a.Ber.Integer),g.writeBuffer(c.part.d.data,a.Ber.OctetString),g.startSequence(161),m=o.ecNormalize(c.part.Q.data,!0),g.writeBuffer(m,a.Ber.BitString),g.endSequence(),g.endSequence(),g.endSequence();else{var m=t,g=e;f(m,g),g.endSequence(),m=o.ecNormalize(m.part.Q.data,!0),g.writeBuffer(m,a.Ber.BitString)}break;case"ed25519":if(e.writeOID("1.3.101.112"),u.isPrivateKey(t))throw new Error("Ed25519 private keys in pkcs8 format are not supported");r=t,(n=e).endSequence(),o.writeBitString(n,r.part.A.data);break;default:throw new Error("Unsupported key type: "+t.type)}e.endSequence()}function f(e,t){var i;(e=n.curves[e.curve]).pkcs8oid?t.writeOID(e.pkcs8oid):(t.startSequence(),i=s.from([1]),t.writeBuffer(i,a.Ber.Integer),t.startSequence(),t.writeOID("1.2.840.10045.1.1"),t.writeBuffer(e.p,a.Ber.Integer),t.endSequence(),t.startSequence(),0===(i=e.p)[0]&&(i=i.slice(1)),t.writeBuffer(i,a.Ber.OctetString),t.writeBuffer(e.b,a.Ber.OctetString),t.writeBuffer(e.s,a.Ber.BitString),t.endSequence(),t.writeBuffer(e.G,a.Ber.OctetString),t.writeBuffer(e.n,a.Ber.Integer),i=(i=e.h)||s.from([1]),t.writeBuffer(i,a.Ber.Integer),t.endSequence())}},function(e,t,i){e.exports=m;var r=i(10),a=i(12).Buffer,s=i(30),n=i(8),o=i(101),c=(e=(i(57),i(51)),i(9),i(25)),u=i(23),h=i(24),l=i(106),p={},d=(p.openssh=i(470),p.x509=i(278),p.pem=i(471),e.CertificateParseError),f=e.InvalidAlgorithmError;function m(e){r.object(e,"options"),r.arrayOfObject(e.subjects,"options.subjects"),c.assertCompatible(e.subjects[0],l,[1,0],"options.subjects"),c.assertCompatible(e.subjectKey,u,[1,0],"options.subjectKey"),c.assertCompatible(e.issuer,l,[1,0],"options.issuer"),void 0!==e.issuerKey&&c.assertCompatible(e.issuerKey,u,[1,0],"options.issuerKey"),r.object(e.signatures,"options.signatures"),r.buffer(e.serial,"options.serial"),r.date(e.validFrom,"options.validFrom"),r.date(e.validUntil,"optons.validUntil"),r.optionalArrayOfString(e.purposes,"options.purposes"),this._hashCache={},this.subjects=e.subjects,this.issuer=e.issuer,this.subjectKey=e.subjectKey,this.issuerKey=e.issuerKey,this.signatures=e.signatures,this.serial=e.serial,this.validFrom=e.validFrom,this.validUntil=e.validUntil,this.purposes=e.purposes}m.formats=p,m.prototype.toBuffer=function(e,t){return r.string(e=void 0===e?"x509":e,"format"),r.object(p[e],"formats[format]"),r.optionalObject(t,"options"),p[e].write(this,t)},m.prototype.toString=function(e,t){return this.toBuffer(e=void 0===e?"pem":e,t).toString()},m.prototype.fingerprint=function(e){return r.string(e=void 0===e?"sha256":e,"algorithm"),e={type:"certificate",hash:this.hash(e),algorithm:e},new o(e)},m.prototype.hash=function(e){if(r.string(e,"algorithm"),e=e.toLowerCase(),void 0===s.hashAlgs[e])throw new f(e);var t;return this._hashCache[e]||(t=n.createHash(e).update(this.toBuffer("x509")).digest(),this._hashCache[e]=t)},m.prototype.isExpired=function(e){return!((e=void 0===e?new Date:e).getTime()>=this.validFrom.getTime()&&e.getTime()<this.validUntil.getTime())},m.prototype.isSignedBy=function(e){return c.assertCompatible(e,m,[1,0],"issuer"),!(!this.issuer.equals(e.subjects[0])||this.issuer.purposes&&0<this.issuer.purposes.length&&-1===this.issuer.purposes.indexOf("ca"))&&this.isSignedByKey(e.subjectKey)},m.prototype.getExtension=function(e){return r.string(e,"keyOrOid"),this.getExtensions().filter((function(t){return"x509"===t.format?t.oid===e:"openssh"===t.format&&t.name===e}))[0]},m.prototype.getExtensions=function(){var e,t=[];return(e=((e=this.signatures.x509)&&e.extras&&e.extras.exts&&e.extras.exts.forEach((function(e){e.format="x509",t.push(e)})),this.signatures.openssh))&&e.exts&&e.exts.forEach((function(e){e.format="openssh",t.push(e)})),t},m.prototype.isSignedByKey=function(e){var t;return c.assertCompatible(e,u,[1,2],"issuerKey"),void 0!==this.issuerKey?this.issuerKey.fingerprint("sha512").matches(e):(t=Object.keys(this.signatures)[0],(t=p[t].verify(this,e))&&(this.issuerKey=e),t)},m.prototype.signWith=function(e){c.assertCompatible(e,h,[1,2],"key");for(var t=Object.keys(p),i=!1,r=0;r<t.length;++r)"pem"!==t[r]&&!0===p[t[r]].sign(this,e)&&(i=!0);if(!i)throw new Error("Failed to sign the certificate for any available certificate formats")},m.createSelfSigned=function(e,t,i){e=Array.isArray(e)?e:[e];var s,n=(r.arrayOfObject(e),e.forEach((function(e){c.assertCompatible(e,l,[1,0],"subject")})),c.assertCompatible(t,h,[1,2],"private key"),r.optionalObject(i,"options"),r.optionalObject((i=void 0===i?{}:i).validFrom,"options.validFrom"),r.optionalObject(i.validUntil,"options.validUntil"),i.validFrom),o=i.validUntil,u=(void 0===n&&(n=new Date),void 0===o&&(r.optionalNumber(i.lifetime,"options.lifetime"),void 0===(u=i.lifetime)&&(u=31536e4),(o=new Date).setTime(o.getTime()+1e3*u)),r.optionalBuffer(i.serial,"options.serial"),i.serial),p=(-1===(i=void 0===(i=(void 0===u&&(u=a.from("0000000000000001","hex")),i.purposes))?[]:i).indexOf("signature")&&i.push("signature"),-1===i.indexOf("ca")&&i.push("ca"),-1===i.indexOf("crl")&&i.push("crl"),i.length<=3&&(s=e.filter((function(e){return"host"===e.type})),p=e.filter((function(e){return"user"===e.type})),0<s.length&&-1===i.indexOf("serverAuth")&&i.push("serverAuth"),0<p.length&&-1===i.indexOf("clientAuth")&&i.push("clientAuth"),0<p.length||0<s.length)&&(-1===i.indexOf("keyAgreement")&&i.push("keyAgreement"),"rsa"===t.type)&&-1===i.indexOf("encryption")&&i.push("encryption"),new m({subjects:e,issuer:e[0],subjectKey:t.toPublic(),issuerKey:t.toPublic(),signatures:{},serial:u,validFrom:n,validUntil:o,purposes:i}));return p.signWith(t),p},m.create=function(e,t,i,s,n){e=Array.isArray(e)?e:[e];var o=(r.arrayOfObject(e),e.forEach((function(e){c.assertCompatible(e,l,[1,0],"subject")})),c.assertCompatible(t,u,[1,0],"key"),h.isPrivateKey(t)&&(t=t.toPublic()),c.assertCompatible(i,l,[1,0],"issuer"),c.assertCompatible(s,h,[1,2],"issuer key"),r.optionalObject(n,"options"),r.optionalObject((n=void 0===n?{}:n).validFrom,"options.validFrom"),r.optionalObject(n.validUntil,"options.validUntil"),n.validFrom),p=n.validUntil,d=(void 0===o&&(o=new Date),void 0===p&&(r.optionalNumber(n.lifetime,"options.lifetime"),void 0===(d=n.lifetime)&&(d=31536e4),(p=new Date).setTime(p.getTime()+1e3*d)),r.optionalBuffer(n.serial,"options.serial"),n.serial),f=(void 0===d&&(d=a.from("0000000000000001","hex")),n.purposes),g=(n=(-1===(f=void 0===f?[]:f).indexOf("signature")&&f.push("signature"),!0===n.ca&&(-1===f.indexOf("ca")&&f.push("ca"),-1===f.indexOf("crl"))&&f.push("crl"),e.filter((function(e){return"host"===e.type}))),e.filter((function(e){return"user"===e.type})));return(g=(0<n.length&&-1===f.indexOf("serverAuth")&&f.push("serverAuth"),0<g.length&&-1===f.indexOf("clientAuth")&&f.push("clientAuth"),(0<g.length||0<n.length)&&(-1===f.indexOf("keyAgreement")&&f.push("keyAgreement"),"rsa"===t.type)&&-1===f.indexOf("encryption")&&f.push("encryption"),new m({subjects:e,issuer:i,subjectKey:t,issuerKey:s.toPublic(),signatures:{},serial:d,validFrom:o,validUntil:p,purposes:f}))).signWith(s),g},m.parse=function(e,t,i){"string"!=typeof e&&r.buffer(e,"data"),r.string(t=void 0===t?"auto":t,"format"),r.optionalObject(i="string"==typeof i?{filename:i}:i,"options"),r.optionalString((i=void 0===i?{}:i).filename,"options.filename"),void 0===i.filename&&(i.filename="(unnamed)"),r.object(p[t],"formats[format]");try{return p[t].read(e,i)}catch(e){throw new d(i.filename,t,e)}},m.isCertificate=function(e,t){return c.isCompatible(e,m,t)},m.prototype._sshpkApiVersion=[1,1],m._oldVersionDetect=function(e){return[1,0]}},function(e,t,i){e.exports=h;var r=i(10),a=(i(30),i(8),i(101),i(57),i(51),i(9),i(25)),s=i(58),n=i(12).Buffer,o=/^([*]|[a-z0-9][a-z0-9\-]{0,62})(?:\.([*]|[a-z0-9][a-z0-9\-]{0,62}))*$/i,c={cn:"2.5.4.3",o:"2.5.4.10",ou:"2.5.4.11",l:"2.5.4.7",s:"2.5.4.8",c:"2.5.4.6",sn:"2.5.4.4",postalCode:"2.5.4.17",serialNumber:"2.5.4.5",street:"2.5.4.9",x500UniqueIdentifier:"2.5.4.45",role:"2.5.4.72",telephoneNumber:"2.5.4.20",description:"2.5.4.13",dc:"0.9.2342.19200300.100.1.25",uid:"0.9.2342.19200300.100.1.1",mail:"0.9.2342.19200300.100.1.3",title:"2.5.4.12",gn:"2.5.4.42",initials:"2.5.4.43",pseudonym:"2.5.4.65",emailAddress:"1.2.840.113549.1.9.1"},u={};function h(e){var t=this;if(r.object(e,"options"),r.arrayOfObject(e.components,"options.components"),this.components=e.components,this.componentLookup={},this.components.forEach((function(e){e.name&&!e.oid&&(e.oid=c[e.name]),e.oid&&!e.name&&(e.name=u[e.oid]),void 0===t.componentLookup[e.name]&&(t.componentLookup[e.name]=[]),t.componentLookup[e.name].push(e)})),this.componentLookup.cn&&0<this.componentLookup.cn.length&&(this.cn=this.componentLookup.cn[0].value),r.optionalString(e.type,"options.type"),void 0===e.type)1===this.components.length&&this.componentLookup.cn&&1===this.componentLookup.cn.length&&this.componentLookup.cn[0].value.match(o)?(this.type="host",this.hostname=this.componentLookup.cn[0].value):this.componentLookup.dc&&this.components.length===this.componentLookup.dc.length?(this.type="host",this.hostname=this.componentLookup.dc.map((function(e){return e.value})).join(".")):this.componentLookup.uid&&this.components.length===this.componentLookup.uid.length?(this.type="user",this.uid=this.componentLookup.uid[0].value):this.componentLookup.cn&&1===this.componentLookup.cn.length&&this.componentLookup.cn[0].value.match(o)?(this.type="host",this.hostname=this.componentLookup.cn[0].value):this.componentLookup.uid&&1===this.componentLookup.uid.length?(this.type="user",this.uid=this.componentLookup.uid[0].value):this.componentLookup.mail&&1===this.componentLookup.mail.length?(this.type="email",this.email=this.componentLookup.mail[0].value):this.componentLookup.cn&&1===this.componentLookup.cn.length?(this.type="user",this.uid=this.componentLookup.cn[0].value):this.type="unknown";else if(this.type=e.type,"host"===this.type)this.hostname=e.hostname;else if("user"===this.type)this.uid=e.uid;else{if("email"!==this.type)throw new Error("Unknown type "+this.type);this.email=e.email}}Object.keys(c).forEach((function(e){u[c[e]]=e})),h.prototype.toString=function(){return this.components.map((function(e){return e.name.toUpperCase().replace(/=/g,"\\=")+"="+e.value.replace(/,/g,"\\,")})).join(", ")},h.prototype.get=function(e,t){r.string(e,"name");var i=this.componentLookup[e];if(void 0!==i&&0!==i.length){if(!t&&1<i.length)throw new Error("Multiple values for attribute "+e);return t?i.map((function(e){return e.value})):i[0].value}},h.prototype.toArray=function(e){return this.components.map((function(e){return{name:e.name,value:e.value}}))};var l=/[^a-zA-Z0-9 '(),+.\/:=?-]/,p=/[^\x00-\x7f]/;h.prototype.toAsn1=function(e,t){e.startSequence(t),this.components.forEach((function(t){var i;e.startSequence(s.Ber.Constructor|s.Ber.Set),e.startSequence(),e.writeOID(t.oid),t.asn1type===s.Ber.Utf8String||t.value.match(p)?(i=n.from(t.value,"utf8"),e.writeBuffer(i,s.Ber.Utf8String)):t.asn1type===s.Ber.IA5String||t.value.match(l)?e.writeString(t.value,s.Ber.IA5String):(i=s.Ber.PrintableString,void 0!==t.asn1type&&(i=t.asn1type),e.writeString(t.value,i)),e.endSequence(),e.endSequence()})),e.endSequence()},h.prototype.equals=function(e){if(!h.isIdentity(e,[1,0]))return!1;if(e.components.length!==this.components.length)return!1;for(var t=0;t<this.components.length;++t){if(this.components[t].oid!==e.components[t].oid)return!1;if(!function(e,t){if("**"===e||"**"===t)return 1;var i=e.split("."),r=t.split(".");if(i.length===r.length){for(var a=0;a<i.length;++a)if("*"!==i[a]&&"*"!==r[a]&&i[a]!==r[a])return;return 1}}(this.components[t].value,e.components[t].value))return!1}return!0},h.forHost=function(e){return r.string(e,"hostname"),new h({type:"host",hostname:e,components:[{name:"cn",value:e}]})},h.forUser=function(e){return r.string(e,"uid"),new h({type:"user",uid:e,components:[{name:"uid",value:e}]})},h.forEmail=function(e){return r.string(e,"email"),new h({type:"email",email:e,components:[{name:"mail",value:e}]})},h.parseDN=function(e){r.string(e,"dn");for(var t,i=[""],a=0,s=e;0<s.length;){if(null!==(t=/^,/.exec(s)))i[++a]="";else if(null!==(t=/^\\,/.exec(s)))i[a]+=",";else{if(null===(t=/^\\./.exec(s))&&null===(t=/^[^\\,]+/.exec(s)))throw new Error("Failed to parse DN");i[a]+=t[0]}s=s.slice(t[0].length)}return new h({components:i.map((function(e){for(var t=(e=e.trim()).indexOf("=");0<t&&"\\"===e.charAt(t-1);)t=e.indexOf("=",t+1);if(-1===t)throw new Error("Failed to parse DN");return{name:e.slice(0,t).toLowerCase().replace(/\\=/g,"="),value:e.slice(t+1)}}))})},h.fromArray=function(e){return r.arrayOfObject(e,"components"),e.forEach((function(e){if(r.object(e,"component"),r.string(e.name,"component.name"),!n.isBuffer(e.value)&&"string"!=typeof e.value)throw new Error("Invalid component value")})),new h({components:e})},h.parseAsn1=function(e,t){for(var i=[],r=(e.readSequence(t),e.offset+e.length);e.offset<r;){e.readSequence(s.Ber.Constructor|s.Ber.Set);var a,n=e.offset+e.length,o=(e.readSequence(),e.readOID()),c=e.peek();switch(c){case s.Ber.PrintableString:case s.Ber.IA5String:case s.Ber.OctetString:case s.Ber.T61String:a=e.readString(c);break;case s.Ber.Utf8String:a=(a=e.readString(c,!0)).toString("utf8");break;case s.Ber.CharacterString:case s.Ber.BMPString:a=(a=e.readString(c,!0)).toString("utf16le");break;default:throw new Error("Unknown asn1 type "+c)}i.push({oid:o,asn1type:c,value:a}),e._offset=n}return e._offset=r,new h({components:i})},h.isIdentity=function(e,t){return a.isCompatible(e,h,t)},h.prototype._sshpkApiVersion=[1,0],h._oldVersionDetect=function(e){return[1,0]}},function(e,t,i){"use strict";
|
|
239
239
|
/*!
|
|
240
240
|
* utils/index.js - utils for vallnet
|
|
241
241
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
242
242
|
* https://github.com/bookmansoft/gamegold
|
|
243
|
-
*/t.ASN1=i(324),t.AsyncObject=i(71),t.base32=i(226),t.base58=i(69),t.bech32=i(237),t.Bloom=i(100),t.co=i(36),t.encoding=i(3),t.enforce=i(579),t.fs=i(59),t.GCSFilter=i(580),t.Heap=i(306),t.Int64=i(110),t.IP=i(55),t.List=i(149),t.Lock=i(35),t.LRU=i(63),t.MappedLock=i(198),t.murmur3=i(
|
|
243
|
+
*/t.ASN1=i(324),t.AsyncObject=i(71),t.base32=i(226),t.base58=i(69),t.bech32=i(237),t.Bloom=i(100),t.co=i(36),t.encoding=i(3),t.enforce=i(579),t.fs=i(59),t.GCSFilter=i(580),t.Heap=i(306),t.Int64=i(110),t.IP=i(55),t.List=i(149),t.Lock=i(35),t.LRU=i(63),t.MappedLock=i(198),t.murmur3=i(144),t.nfkd=i(303),t.PEM=i(223),t.ProtoWriter=i(161),t.ProtoReader=i(160),t.RBT=i(257),t.BufferReader=i(1),t.RollingFilter=i(227),t.StaticWriter=i(4),t.util=i(2),t.Validator=i(80),t.BufferWriter=i(22);var{verifyData:r,signObj:a,verifyObj:s,generateKey:n}=i(72),r=(t.verifyData=r,t.signObj=a,t.verifyObj=s,t.generateKey=n,i(140)).sortWithSeq;t.sortWithSeq=r},function(e,t,i){"use strict";
|
|
244
244
|
/*!
|
|
245
245
|
* mempool.js - mempool for vallnet
|
|
246
246
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -273,7 +273,7 @@ let r=[];[i(558),i(559),i(560),i(561),i(562),i(563),i(564),i(565),i(566),i(567),
|
|
|
273
273
|
* selector.js
|
|
274
274
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
275
275
|
*/
|
|
276
|
-
const r=i(19).opcodes;function a(e){let t=null;return new(0,(a.list[e.type]||a.list[r.OP_INVALIDOPCODE]).path)(e)}i(52),(a.list={})[r.OP_PROPCREATE]={name:"propcreate",path:i(189),desc:"道具创建"},a.list[r.OP_ATTACH]={name:"attach",path:i(190),desc:"附言输出(可消费)"},a.list[r.OP_PROPEXCHANGE]={name:"propexchange",path:i(191),desc:"道具交易"},a.list[r.OP_HTLCSUGGEST]={name:"htlcsuggest",path:i(
|
|
276
|
+
const r=i(19).opcodes;function a(e){let t=null;return new(0,(a.list[e.type]||a.list[r.OP_INVALIDOPCODE]).path)(e)}i(52),(a.list={})[r.OP_PROPCREATE]={name:"propcreate",path:i(189),desc:"道具创建"},a.list[r.OP_ATTACH]={name:"attach",path:i(190),desc:"附言输出(可消费)"},a.list[r.OP_PROPEXCHANGE]={name:"propexchange",path:i(191),desc:"道具交易"},a.list[r.OP_HTLCSUGGEST]={name:"htlcsuggest",path:i(135),desc:"HTLC提议"},a.list[r.OP_HTLCASSENT]={name:"htlcassent",path:i(136),desc:"HTLC应答"},a.list[r.OP_COMMENT]={name:"comment",path:i(137),desc:"附言输出"},a.list[r.OP_INVALIDOPCODE]={name:"default",path:i(52),desc:""},e.exports=a},function(e,t,i){"use strict";
|
|
277
277
|
/*!
|
|
278
278
|
* general.js - bitcoin constants for vallnet
|
|
279
279
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -282,7 +282,7 @@ const r=i(19).opcodes;function a(e){let t=null;return new(0,(a.list[e.type]||a.l
|
|
|
282
282
|
/*!
|
|
283
283
|
* wallet.js - wallet object for vallnet
|
|
284
284
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
285
|
-
*/const r=i(0);var a=i(16);const s=i(15),n=i(2),o=i(3),c=i(35),u=i(198),h=i(141).sortWithSeq,l=i(6),p=i(94),d=i(1),f=i(4),m=i(69),g=i(334);i(218);const v=i(109),y=i(73),b=i(13),w=i(68),x=i(17),k=i(219),S=i(156),_=i(28),E=i(157),j=i(337),A=i(63),R=i(26),I=i(29),O=i(7),C=i(310),P=i(38),T=S.Mnemonic,{opcodes:B,hashType:N}=i(19),z=i(165),F=i(77),L=i(78),M=i(142),D=i(46),H=i(20),U=i(42),q=i(54),{NotifyMsg:V,ContractStatus:K,ContractType:W,PropStatus:$}=i(5),Y=i(37).VerifyError,G=i(153).ErItem,X=i(154).ErAbolishItem,J=i(228).EnchancementItem,Q=i(67),Z=i(59),ee=i(83),te=i(85).txdb,ie=i(31);class re extends a{constructor(e,t){super(),r(e,"DB required."),this.db=e,this.network=e.network,this.logger=e.logger,this.readLock=new u,this.writeLock=new c,this.sendLock=new c,this.indexCache=new A(1e4),this.accountCache=new A(1e4),this.pathCache=new A(1e5),this.current=null,this.wid=0,this.id=null,this.initialized=!1,this.watchOnly=!1,this.accountDepth=0,this.token=o.ZERO_HASH,this.tokenDepth=0,this.master=new j,this.txdb=new g(this),this.account=null,t&&this.fromOptions(t)}fromOptions(e){let t,i,a=e.master;return a?("string"==typeof a&&(a=S.PrivateKey.fromBase58(a,this.network)),r(S.isPrivate(a),"Must create wallet with hd private key.")):(i=new T(e.mnemonic),a=S.fromMnemonic(i,this.network)),r(a.network===this.network,"Network mismatch for master key."),this.master.fromKey(a,i),null!=e.wid&&(r(n.isU32(e.wid)),this.wid=e.wid),e.id&&(r(y.isName(e.id),"Bad wallet ID."),t=e.id),null!=e.initialized&&(r("boolean"==typeof e.initialized),this.initialized=e.initialized),null!=e.watchOnly&&(r("boolean"==typeof e.watchOnly),this.watchOnly=e.watchOnly),null!=e.accountDepth&&(r(n.isU32(e.accountDepth)),this.accountDepth=e.accountDepth),e.token&&(r(Buffer.isBuffer(e.token)),r(32===e.token.length),this.token=e.token),t=t||this.getID(),this.id=t,this}static fromOptions(e,t){return new re(e).fromOptions(t)}async init(e){var t=e.passphrase;r(!this.initialized),this.initialized=!0,t&&await this.master.encrypt(t),e=await this._createAccount(e,t);r(e),this.account=e,this.logger.info("Wallet initialized (%s).",this.id),await this.txdb.open()}async open(){r(this.initialized);var e=await this.getAccount(0);if(!e)throw new Error("Default account not found.");this.account=e,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(e,t,i){var r={alliancename:e,nodeid:t};return e?(r.alliancePrivateKey=l.hash256(Buffer.concat([Buffer.from(e),this.master.key.privateKey])),i?(r.prv=Buffer.alloc(0),r.pub=Buffer.from(i,"hex"),r.awardAddress=b.fromWitnessPubkeyhash(l.hash160(r.pub),this.network.type).toString(this.network.type),r.mnemonic=new T):(i=l.hash256(Buffer.concat([Buffer.from(e+"-"+t),this.master.key.privateKey])),r.mnemonic=new T({entropy:i,language:this.master.mnemonic.language,passphrase:this.master.mnemonic.passphrase}),r.prv=l.hash256(Buffer.from(r.mnemonic.toSeed().toString("hex"))),r.pub=R.publicKeyCreate(r.prv,!0),e=j.fromKey(S.fromMnemonic(r.mnemonic),this.network.type).key.deriveAccount(44,0).derive(9).derive(1),r.awardAddress=b.fromWitnessPubkeyhash(l.hash160(e.publicKey),this.network.type).toString(this.network.type))):(r.mnemonic=T.fromOptions(this.master.mnemonic),r.prv=l.hash256(Buffer.from(r.mnemonic.toSeed().toString("hex"))),r.pub=R.publicKeyCreate(r.prv,!0),r.awardAddress=b.fromWitnessPubkeyhash(l.hash160(r.pub),this.network.type).toString(this.network.type)),r.address=b.fromWitnessPubkeyhash(l.hash160(r.pub),this.network.type).toString(),r}async destroy(){var e=await this.writeLock.lock(),t=await this.sendLock.lock();try{this.db.unregister(this),await this.master.destroy(),this.readLock.destroy(),this.writeLock.destroy(),this.sendLock.destroy()}finally{t(),e()}}async addSharedKey(e,t){var i=await this.writeLock.lock();try{return await this._addSharedKey(e,t)}finally{i()}}async _addSharedKey(e,t){if(t||(t=e,e=null),!(e=await this.getAccount(e=null==e?0:e)))throw new Error("Account not found.");let i;this.start();try{i=await e.addSharedKey(t)}catch(e){throw this.drop(),e}return await this.commit(),i}async removeSharedKey(e,t){var i=await this.writeLock.lock();try{return await this._removeSharedKey(e,t)}finally{i()}}async _removeSharedKey(e,t){if(t||(t=e,e=null),!(e=await this.getAccount(e=null==e?0:e)))throw new Error("Account not found.");let i;this.start();try{i=await e.removeSharedKey(t)}catch(e){throw this.drop(),e}return await this.commit(),i}async setPassphrase(e,t){e&&await this.decrypt(e),t&&await this.encrypt(t)}async encrypt(e){var t=await this.writeLock.lock();try{return await this._encrypt(e)}finally{t()}}async _encrypt(e){e=await this.master.encrypt(e,!0),this.start();try{await this.db.encryptKeys(this,e)}catch(t){throw p(e),this.drop(),t}p(e),this.save(),await this.commit()}async decrypt(e){var t=await this.writeLock.lock();try{return await this._decrypt(e)}finally{t()}}async _decrypt(e){e=await this.master.decrypt(e,!0),this.start();try{await this.db.decryptKeys(this,e)}catch(t){throw p(e),this.drop(),t}p(e),this.save(),await this.commit()}async rename(e){var t=await this.writeLock.lock();try{return await this.db.rename(this,e)}finally{t()}}async writeBalanceLog(e){var t=await this.writeLock.lock();try{return await this.db.writeBalanceLog(this,e)}finally{t()}}async renameAccount(e,t){var i=await this.writeLock.lock();try{return await this._renameAccount(e,t)}finally{i()}}async _renameAccount(e,t){if(!y.isName(t))throw new Error("Bad account name.");var i=await this.getAccount(e);if(!i)throw new Error("Account not found.");if(0===i.accountIndex)throw new Error("Cannot rename default account.");if(await this.hasAccount(t))throw new Error("Account name not available.");e=i.name,this.start(),this.db.renameAccount(i,t),await this.commit(),this.indexCache.remove(e),e=this.pathCache.values();for(const r of e)r.account===i.accountIndex&&(r.name=t)}async lock(){var e=await this.writeLock.lock(),t=await this.sendLock.lock();try{await this.master.lock()}finally{t(),e()}}unlock(e,t){return this.master.unlock(e,t)}getID(){r(this.master.key,"Cannot derive id.");var e,t=this.master.key.derive(44);(e=new f(37)).writeBytes(t.publicKey),e.writeU32(this.network.magic),t=l.hash160(e.render());return(e=new f(27)).writeU8(3),e.writeU8(190),e.writeU8(4),e.writeBytes(t),e.writeChecksum(),m.encode(e.render())}async createAccount(e,t){var i=await this.writeLock.lock();try{return await this._createAccount(e,t)}finally{i()}}async _createAccount(e,t){let i,a,s=e.name,o=(s=s||this.accountDepth.toString(10),0);if(0!=this.accountDepth&&(o=n.hashInt(s)),await this.hasAccountIndex(o))throw new Error("Account Index Conflict.");if(await this.hasAccount(s))throw new Error("Account already exists.");if(await this.unlock(t),this.watchOnly&&e.accountKey){if("string"==typeof(i=e.accountKey)&&(i=S.PublicKey.fromBase58(i,this.network)),!S.isPublic(i))throw new Error("Must add HD public keys to watch only wallet.");r(i.network===this.network,"Network mismatch for watch only key.")}else r(this.master.key),i=(i=this.master.key.deriveAccount(44,o)).toPublic();t={wid:this.wid,id:this.id,name:0===this.accountDepth?"default":s,witness:e.witness,watchOnly:this.watchOnly,accountKey:i,accountIndex:o,type:e.type,m:e.m,n:e.n,keys:e.keys},this.start();try{(a=E.fromOptions(this.db,t)).wallet=this,await a.init()}catch(e){throw this.drop(),e}return this.logger.info("Created account %s/%s/%d.",a.id,a.name,a.accountIndex),this.accountDepth++,this.save(),await this.commit(),a}async ensureAccount(e,t){var i=e.name;return(i=await this.getAccount(i))||this.createAccount(e,t)}getAccounts(){return this.db.getAccounts(this.wid)}getAccountMap(){return this.db.getAccountMap(this.wid)}getAddressHashes(e){return null!=e?this.getAccountHashes(e):this.db.getWalletHashes(this.wid)}async getAccountHashes(e){return e=await this.ensureIndex(e,!0),this.db.getAccountHashes(this.wid,e)}async getAccount(e){if(this.account&&(null==e||"default"===e||"number"==typeof e&&0===e||"string"==typeof e&&0===e.length))return this.account;if(-1===(e=await this.getAccountIndex(e)))return null;var t=await this.readLock.lock(e);try{return await this._getAccount(e)}finally{t()}}async _getAccount(e){var t=this.accountCache.get(e);return t||((t=await this.db.getAccount(this.wid,e))?(t.wallet=this,t.wid=this.wid,t.id=this.id,t.watchOnly=this.watchOnly,await t.open(),this.accountCache.set(e,t),t):null)}async getAccountIndex(e){var t;return null==e?-1:"number"==typeof e?e:null!=(t=this.indexCache.get(e))?t:-1===(t=await this.db.getAccountIndex(this.wid,e))?-1:(this.indexCache.set(e,t),t)}async getAccountName(e){var t;return"string"==typeof e?e:(t=this.accountCache.get(e))?t.name:this.db.getAccountName(this.wid,e)}async hasAccount(e){return-1!==(e=await this.getAccountIndex(e))&&(!!this.accountCache.has(e)||this.db.hasAccount(this.wid,e))}async hasAccountIndex(e){return!!this.accountCache.has(e)||this.db.hasAccount(this.wid,e)}createReceive(e,t=0,i=null){return this.createKey(e,0,t,i)}createChange(e){return this.createKey(e,1)}createNested(e){return this.createKey(e,2)}async createKey(e,t,i=0,r=null){var a=await this.writeLock.lock();try{return await this._createKey(e,t,i,r)}finally{a()}}async _createKey(e,t,i=0,r=null){if(null==t&&(t=e,e=null),!(e=await this.getAccount(e=e||0)))throw new Error("Account not found.");let a;this.start();try{a=await e.createKey(t,i,r)}catch(e){throw this.drop(),e}return await this.commit(),a}async deriveKey(e,t,i,r=null){let a=null;var s=await this.writeLock.lock();try{this.start(),a=await this._deriveKey(e,t,i,r),await this.commit()}catch(e){throw this.drop(),e}finally{s()}return a}async _deriveKey(e,t,i=0,r=null){if(null==t&&(t=e,e=null),e=e||0,e=parseInt(e),e=await this.getAccount(e))return t=await e.deriveKey(t,i,r),await e.saveKey(t),t;throw new Error("Account not found.")}save(){return this.db.save(this)}async saveAccount(e){var t=await this.writeLock.lock();try{this.start(),e._save(),await this.commit(),0==e.accountIndex&&(this.account=e)}finally{t()}}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(e){return e=b.getHash(e,"hex"),null!=await this.getPath(e)}async ownedAddress(e){return!!await this.getKey(e)}async getPath(e){return(e=await this.readPath(e))?(e.name=await this.getAccountName(e.account),r(e.name),this.pathCache.set(e.hash,e),e):null}async readPath(e){e=b.getHash(e,"hex");var t=this.pathCache.get(e);return t||((t=await this.db.getPath(this.wid,e))?(t.id=this.id,t):null)}async hasPath(e){return e=b.getHash(e,"hex"),!!this.pathCache.has(e)||this.db.hasPath(this.wid,e)}async getPaths(e){if(null!=e)return this.getAccountPaths(e);var t=[];for(const e of await this.db.getWalletPaths(this.wid))e.id=this.id,e.name=await this.getAccountName(e.account),r(e.name),this.pathCache.set(e.hash,e),t.push(e);return t}async getAccountPaths(e){var t=await this.ensureIndex(e,!0),i=await this.getAccountHashes(t),a=await this.getAccountName(e),s=(r(a),[]);for(const e of i){var n=await this.readPath(e);r(n),r(n.account===t),n.name=a,this.pathCache.set(n.hash,n),s.push(n)}return s}async importKey(e,t,i){var r=await this.writeLock.lock();try{return await this._importKey(e,t,i)}finally{r()}}async _importKey(e,t,i){if(e&&"object"==typeof e&&(i=t,t=e,e=null),null==e&&(e=0),r(t.network===this.network,"Network mismatch for key."),this.watchOnly){if(t.privateKey)throw new Error("Cannot import privkey into watch-only wallet.")}else if(!t.privateKey)throw new Error("Cannot import pubkey into non watch-only wallet.");var a=t.getHash("hex");if(await this.getPath(a))throw new Error("Key already exists.");if(!(a=await this.getAccount(e)))throw new Error("Account not found.");if(a.type!==E.types.PUBKEYHASH)throw new Error("Cannot import into non-pkh account.");await this.unlock(i),e=k.fromRing(a,t).toPath(),this.master.encrypted&&(e.data=this.master.encipher(e.data,e.hash),r(e.data),e.encrypted=!0),this.start();try{await a.savePath(e)}catch(e){throw this.drop(),e}await this.commit()}async importAddress(e,t){var i=await this.writeLock.lock();try{return await this._importAddress(e,t)}finally{i()}}async _importAddress(e,t){if(t||(t=e,e=null),null==e&&(e=0),t.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(t))throw new Error("Address already exists.");if(!(e=await this.getAccount(e)))throw new Error("Account not found.");if(e.type!==E.types.PUBKEYHASH)throw new Error("Cannot import into non-pkh account.");t=v.fromAddress(e,t),this.start();try{await e.savePath(t)}catch(e){throw this.drop(),e}await this.commit()}async fund(e,t){var i=await this.writeLock.lock();try{return await this._fund(e,t)}finally{i()}}async _fund(e,t){if(t=t||{},!this.initialized)throw new Error("Wallet is not initialized.");if(this.watchOnly)throw new Error("Cannot fund from watch-only wallet.");let i;if(null!=t.account){if(!(i=await this.getAccount(t.account)))throw new Error("Account not found.")}else i=this.account;if(!i.initialized)throw new Error("Account is not initialized.");let a,s=t.rate;return null==s&&(s=await this.db.estimateFee(t.blocks)),a=t.smart?await this.getSmartCoins(i.name):(a=await this.getCoins(i.name),this.txdb.filterConserved(a)),await e.fund(a,{allowPreInput:t.allowPreInput,noChange:t.noChange,selection:t.selection,round:t.round,depth:t.depth,hardFee:t.hardFee,subtractFee:t.subtractFee,subtractIndex:t.subtractIndex,changeAddress:i.change.getAddress(),height:this.db.curHeight,rate:s,maxFee:t.maxFee,estimate:e=>this.estimateSize(e),network:this.network}),!t.allowInfiniteFee&&t.noChange&&r(e.getFee()<=C.MAX_FEE,"TX exceeds MAX_FEE."),a}async getAccountByAddress(e){return e=b.getHash(e,"hex"),(e=await this.getPath(e))?this.getAccount(e.account):null}async estimateSize(e){var t=O.WITNESS_SCALE_FACTOR,i=b.fromScript(e);if(!i)return-1;var r=await this.getAccountByAddress(i);if(!r)return-1;let a=0;if(e.isScripthash()&&r.witness)switch(r.type){case E.types.PUBKEYHASH:a=4*(a+23);break;case E.types.MULTISIG:a=4*(a+35)}switch(r.type){case E.types.PUBKEYHASH:a=a+74+34;break;case E.types.MULTISIG:a=(a=(a=(a=(a+=1)+74*r.m)+3+1)+34*r.n)+1+1}return r.witness?a=((a+=1)+t-1)/t|0:a+=o.sizeVarint(a),a}async createTX(e){var t=e.outputs,i=new w;r(Array.isArray(t),"Outputs must be an array."),r(0<t.length,"No outputs available."),e.comment&&("object"==typeof e.comment&&(e.comment=JSON.stringify(e.comment)),i.outputs.push(_.fromScript(x.createScript(Buffer.from(e.comment),x.types.NULLDATA),0)));for(const e of t){var a=new _(e),s=a.getAddress();if(a.isDust())throw new Error("Output is dust.");if(0<a.value){if(!s)throw new Error("Cannot send to unknown address.");if(s.isNull())throw new Error("Cannot send to null address.")}i.outputs.push(a)}let n=null;if(e.inputs)for(const t of e.inputs){var o=await this.getTX(t.hash);o&&(o=q.fromTX(o.tx,t.index,-1,0))&&(n=o.getAddress(),e.allowPreInput=!0,i.addCoin(o))}else await this.fund(i,e);if(n&&((t=new _).value=i.getFee()-C.MIN_FEE,t.script.fromAddress(n),i.outputs.push(t),i.changeIndex=i.outputs.length-1),!1!==e.sort&&i.sortMembers(),null!=e.locktime&&i.setLocktime(e.locktime),r(i.isSane(),"TX failed sanity check."),r(i.verifyInputs(this.db.curHeight+1),"TX failed context check."),0===await this.template(i))throw new Error("Templating failed.");return i}async send(e,t){var i=await this.sendLock.lock();try{return await this._send(e,t)}finally{i()}}async _send(e,t){return t&&(e.account=t),t=await this.createTX(e,!0),await this.sign(t),this.sendMTX(t,{sendafter:e.sendafter})}async sendMTX(e,t={}){if(!e.isSigned())throw new Error("TX could not be fully signed.");var i=e.toTX();if(i.getSigopsCost(e.view)>I.MAX_TX_SIGOPS_COST)throw new Error("TX exceeds policy sigops.");if(i.getWeight()>I.MAX_TX_WEIGHT)throw new Error("TX exceeds policy weight.");return t.sendafter||(this.logger.debug("Sending wallet tx (%s): %s",this.id,i.txid()),await this.db.addTX(i),await this.db.send(i)),i}async resend(){var e=await this.getPending(),t=(0<e.length&&this.logger.info("Rebroadcasting %d transactions.",e.length),[]);for(const i of e)t.push(i.tx);for(const e of h(t))await this.db.send(e);return t}async deriveInputs(e){r(e.mutable);var t=[];for(const r of await this.getInputPaths(e)){var i=await this.getAccount(r.account);i&&(i=i.derivePath(r,this.master))&&t.push(i)}return t}async getKey(e){try{var t,i=b.getHash(e,"hex",this.network.type),r=await this.getPath(i);return r&&(t=await this.getAccount(r.account))?t.derivePath(r,this.master):null}catch{return null}}async exportToFile(e){if(!Z.unsupported){var t=await this.db.getTip(),i=n.date();let o="",c=[n.fmt("# Wallet Dump created by %s %s",ee.protocol,ee.version),n.fmt("# * Created on %s",i),n.fmt("# * Best block at time of backup was %d (%s).",t.height,n.revHex(t.hash)),n.fmt("# * File: %s",e.file),""];var r,a;t=n.fmt("W %s wid= %s",this.toRaw().toString("base64"),this.wid),t=(c.push(t),await this.getAccounts());for(const e of t){var s=await this.getAccount(e);s=n.fmt("C %s name= %s index= %d",s.toRaw().toString("base64"),s.name,s.accountIndex);c.push(s)}for(const t of await this.getAddressHashes())this.watchOnly?(r=b.fromWitnessPubkeyhash(Buffer.from(t,"hex"),this.network.type).toString(),r=n.fmt("A %s %s label= account= %s branch= %s index= %s addr= %s","S",i,0,-1,-1,r),c.push(r)):(r=await this.getPrivateKey(t))&&(a=r.getAddress("string"),a=n.fmt("A %s %s label= account= %s branch= %s index= %s addr= %s",r.toSecret(),i,r.account,r.branch,r.index,a),c.push(a),e.fragment)&&1e5<c.length&&(o=c.join("\n"),await Z.writeFile(e.file.split(".").reduce((e,t)=>(e?e+="."+t:e=t+"-1",e),""),o,"utf8"),c=[]);c.push(""),c.push("# End of dump"),c.push(""),o=c.join("\n"),await Z.writeFile(e.file,o,"utf8")}}async getPrivateKey(e,t){if(e=b.getHash(e,"hex"),!(e=await this.getPath(e)))return null;var i=await this.getAccount(e.account);return i?(await this.unlock(t),(t=i.derivePath(e,this.master)).privateKey?t:null):null}async getInputPaths(e){if(r(e.mutable),!e.hasCoins())throw new Error("Not all coins available.");var t=[];for(const r of e.getInputHashes("hex")){var i=await this.getPath(r);i&&t.push(i)}return t}async getOutputPaths(e){var t=[];for(const r of e.getOutputHashes("hex")){var i=await this.getPath(r);i&&t.push(i)}return t}async setLookahead(e,t){var i=await this.writeLock.lock();try{return this._setLookahead(e,t)}finally{i()}}async _setLookahead(e,t){if(null==t&&(t=e,e=null),!(e=await this.getAccount(e=null==e?0:e)))throw new Error("Account not found.");this.start();try{await e.setLookahead(t)}catch(e){throw this.drop(),e}await this.commit()}async syncOutputDepth(e){var t=new Map;for(const r of e.outputs){var i=r.path;i&&-1!==i.index&&(t.has(i.account)||t.set(i.account,[]),t.get(i.account).push(i))}var a,s,n=[];for([a,s]of t){let e=-1,t=-1,i=-1;for(const r of s)switch(r.branch){case 0:r.index>e&&(e=r.index);break;case 1:r.index>t&&(t=r.index);break;case 2:r.index>i&&(i=r.index)}e+=2,t+=2,i+=2;var o=await this.getAccount(a);(o=(r(o),await o.syncDepth(e,t,i)))&&n.push(o)}return n}async getRedeem(e){"string"==typeof e&&(e=Buffer.from(e,"hex"));var t=await this.getKey(e.toString("hex"));return t?t.getRedeem(e):null}async template(e){var t=await this.deriveInputs(e);return e.sign(t)}async onSaleList(e,t){return(await(await this.getPropList()).predict(async(e,i)=>!!i.bid&&await this.belongToAccount(t,i.bid.address))).where([["pst",$.Sale]]).paginate(10,e).records()}async mySaleList(e,t){return(await(await this.getPropList()).predict(async(e,i)=>this.belongToAccount(t,i.current.address))).where([["pst",$.Sale]]).paginate(10,e).records()}async getPropList(){const e=await this.db.loadVpList();var t=[];for(let i=0;i<e.length;i++){let r=e[i];t.push((async()=>{await this.getPrivateKey(r.current.address)&&(e[i]=[r.pid,r])})())}return await Promise.all(t),new ie(e)}async propCreate(e,t){var i,a=new w;for(i of e){var s=await this.ensureCp(i.cid,!0);!s||i.cid==this.network.genesisId||(i.gold=(0|i.gold)>>>0,i.gold<O.MINPROPVALUE)||(i.pid||(i.pid=M()),i.oid||(i.oid=i.pid),a.propCreate(s.current.address,i),i.index=a.outputs.length-1)}if(0<a.outputs.length){t?await this.fund(a,{account:t}):await this.fund(a),await this.sign(a);var n,o=a.commit();for(n of(await this.db.addTX(o[0]),await this.db.send(o[0]),r(o[0].verify(o[1],x.flags.STANDARD_VERIFY_FLAGS)),e))n.hash=o[0].hash("hex"),n.txid=o[0].txid();return o}return[]}async attach(e,t){var i,a=new w;for(i of e)a.attach(i.address,i.value,i.data);if(0<a.outputs.length){t?await this.fund(a,{account:t}):await this.fund(a),await this.sign(a);var s,n=a.commit();for(s of(await this.db.addTX(n[0]),await this.db.send(n[0]),r(n[0].verify(n[1],x.flags.STANDARD_VERIFY_FLAGS)),e))s.hash=n[0].hash("hex"),s.txid=n[0].txid();return n}return[]}async sendSecret(e,t,i){let r=this.db.$contacts.get(e);if(!r||!r.sender){var a=(await this.createReceive(i)).getAddress("string");if(e==a)throw new F(L.errors.TYPE_ERROR,"Forbid Sending to Self Address.");r=await this.db.ensureContact({contact:e,messenger:a,wallet:this,account:i})}if(r)return r.send(t);throw new F(L.errors.TYPE_ERROR,"Invalid Address.")}async commNotify(e){r(!!e),r(!!e.dst),r(!!e.content);var t=new w,i=e.src||this.getReceive().toString(),a=(i=new V(W.notify,M(),this.db.curHeight,{src:i,content:e.content}),_.fromScript(x.createScript(i.toRaw(),x.types.NULLDATA),0));t.outputs.push(a),a={address:e.dst,locktime:O.BLOCK_DAY,locktype:"csb",value:.1*O.COIN},t.outputs.push(new _(a)),e.account?await this.fund(t,{account:e.account,noChange:!0,allowInfiniteFee:!0}):await this.fund(t,{noChange:!0,allowInfiniteFee:!0}),await this.sign(t),a=t.commit();return r(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(a[0]),this.logger.debug("Sending tx on wallet(%s): %s",this.id,a[0].txid()),await this.db.send(a[0]),i.hash=a[0].hash("hex"),i.height=-1,i}async cpRegister(e,t,i,a){if(r(!!t&&"object"==typeof t),!await this.db.client.execute("canExecute",[{confirm:!1,cid:t.cid,name:t.name,oper:W.cpRegister}]))throw new F(L.errors.TYPE_ERROR,"Invalid CP Register Info.");const s=new w;e||(n=await this.createReceive(i),e=n.getAddress());var n=await this.getKey(e);if(!n)throw new F(L.errors.TYPE_ERROR,"Invalid CP Register Address, Not along to this wallet.");if(t.pubAddress=e.toString(),t.pubKey=n.getPublicKey("hex"),t.signMethod="secp256k1",n=await this.createAllianceInfo(),t.register=n.pub.toString("hex"),s.cpRegister(e,O.registerFee,t),n=async()=>{i?await this.fund(s,{account:i}):await this.fund(s),await this.sign(s);var a=s.commit();return r(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(a[0]),await this.db.send(a[0]),t.txid=a[0].txid(),t.addr=e.toString(),a},!a)return n();n()}getSCAddress(e){return e=Q.fromMnemonic(T.fromOptions(O.SmartContractMnemonic),this.network).deriveAccount(44,e).derive(9).derive(1),b.fromWitnessPubkeyhash(l.hash160(e.publicKey),this.network)}async cpChange(e,t){var i=await this.ensureCp(e.cid);if(i.cid==this.network.genesisId||"ATHENA"==i.name)throw new F(L.errors.TYPE_ERROR,"Invalid cp name.");var a=await this.getTX(i.current.hash);if(!a)throw new F(L.errors.TYPE_ERROR,"Do not have permission to change this info.");if(a=a.tx,!await this.belongToAccount(t,a.outputs[0].getAddress()))throw new F(L.errors.TYPE_ERROR,"Invalid account info.");if(e.newName){if(!await this.db.client.execute("canExecute",[{confirm:!1,cid:i.cid,name:e.newName,oper:W.cpChange}]))throw new F(L.errors.TYPE_ERROR,"Invalid CP Change Info.")}else e.newName=i.name;return e.addr||(e.addr=b.fromString(i.current.address)),i=w.cpChange(a,e),t?await this.fund(i,{allowPreInput:!0,account:t}):await this.fund(i,{allowPreInput:!0}),await this.sign(i),a=i.commit(),await this.db.send(a[0]),r(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),e.txid=a[0].txid(),a}async propExchangeList(e,t,i=!1){var a,s,n,o=new w,c=[];for([a,s,n]of e){var u,h=null;if(h=await this.getTX(a.hash)){if(h=h.tx,u=a.index,h&&h.outputs&&!(h.outputs.length<=u)){if(i){if(!await this.ownedAddress(h.outputs[u].getAddress())){this.logger.error("not owned prop:",a.hash,a.index);continue}}else if(!await this.belongToAccount(t,h.outputs[u].getAddress())){this.logger.error("not owned prop:",a.hash,a.index);continue}var l=h.outputs[u].getReturnData();l&&(o.propExchange(h,u,s),l.index=o.outputs.length-1,l.addr=s.toString(),c.push(l))}}else this.logger.error("tx not find:",a.hash,n)}return t?await this.fund(o,{allowPreInput:!0,account:t}):await this.fund(o,{allowPreInput:!0}),await this.sign(o),e=o.commit(),await this.db.addTX(e[0]),await this.db.send(e[0]),r(e[0].verify(e[1],x.flags.STANDARD_VERIFY_FLAGS)),e.push(c),e}async propDonate(e,t){var i=e.index;if(!(e=await this.getTX(e.hash))||!e.tx||!e.tx.outputs||e.tx.outputs.length<=i)throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");if(!await this.belongToAccount(t,e.tx.outputs[i].getAddress()))throw new F(L.errors.TYPE_ERROR,"Props that do not belong to you.");if(!(t=e.tx.outputs[i].getReturnData()))throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");if(t.cid&&t.cid==this.network.genesisId)throw new Y(e.tx,"invalid","Special props that can not to donate",100);var r=new w;return(e=(r.addInputFromTx(e.tx,i),r.addOutput(x.createScript(Buffer.from(JSON.stringify({value:e.tx.outputs[i].value,cid:t.cid,pid:t.pid,oid:t.oid,gaddr:this.getAddress().toString(this.network)})),x.types.NULLDATA),0),await this.sign(r,null,N.NONE|N.ANYONECANPAY),r.commit())).push(t),e}async propReceive(e,t){var i=(e=w.fromTX(e,1)).inputs[0].prevout,r=e.outputs[0].getReturnData();e.view.addOutput({hash:e.inputs[0].prevout.hash,index:e.inputs[0].prevout.index},new _({value:r.value})),e.outputs.pop();let a=this.getAddress().toString(this.network);t&&(s={cid:r.cid,uid:t},a=(s=await this.tokenCreate(s,t)).data.addr),e.outputs.push(_.fromScript(a,r.value,{oper:W.propExchange,pid:r.pid,cid:r.cid,oid:r.oid,prev:{hash:i.hash,index:i.index}})),t?await this.fund(e,{allowPreInput:!0,account:t}):await this.fund(e,{allowPreInput:!0}),await this.sign(e,null,N.ALL,[0]);var s=e.commit();return await this.db.send(s[0]),r.simAddr=a,[s[0],null,r]}async belongToAccount(e,t){return!!t&&!(!(t=await this.getAccountByAddress(t))||e&&t.name!==e)}async propExchange(e,t,i){let a=null,s=0;var n;return Array.isArray(e)?(a=e[0],s=e[1]):(n=await this.getTX(e.hash))&&(a=n.tx,s=e.index),!a||!a.outputs||a.outputs.length<=s?(this.logger.error("Invalid tx info."),null):await this.ownedAddress(a.outputs[s].getAddress())?(n=a.outputs[s].getReturnData())?(e=(new w).propExchange(a,s,t),n.index=e.outputs.length-1,i?await this.fund(e,{allowPreInput:!0,account:i}):await this.fund(e,{allowPreInput:!0}),await this.sign(e),t=e.commit(),await this.db.addTX(t[0]),await this.db.send(t[0]),r(t[0].verify(t[1],x.flags.STANDARD_VERIFY_FLAGS)),t.push(n),t):(this.logger.error("Invalid tx info."),null):(this.logger.error("Invalid user."),null)}async propFound(e,t,i){if(e=await this.getTX(e),r(e),!(e=e.tx))throw new F(L.errors.TYPE_ERROR,"Invalid hex string.");var a=e.outputs[t],s=a.getReturnData();if(!s||s.oper!==W.propExchange&&s.oper!==W.propCreate)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");if(s.cid==this.network.genesisId)throw new Y(block,"invalid","prop found supertoken",100);var n=new w;n.addInputFromTx(e,t),e=_.fromScript(a.getAddress(),a.value),n.outputs.push(e),i?await this.fund(n,{allowPreInput:!0,subtractFee:!0,account:i}):await this.fund(n,{allowPreInput:!0,subtractFee:!0}),await this.sign(n),t=n.commit();return await this.db.send(t[0]),r(t[0].verify(t[1],x.flags.STANDARD_VERIFY_FLAGS)),t.push(s),t}async propSale(e,t,i,a){let s=await this.getTX(e);if(!s)throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");if(s.getDepth(this.db.curHeight)<=0)throw new F(L.errors.TYPE_ERROR,"No enough confirmations.");if(!(s=s.tx))throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");var n=s.outputs[t].getReturnData([x.opcodes.OP_PROPEXCHANGE,x.opcodes.OP_PROPCREATE]);if(!n)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");if(!await this.ownedAddress(s.outputs[t].getAddress()))throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");var o=await this.getCoin(e,t);if(!o||-1===o.height)throw new F(L.errors.WALLET_INSUFFICIENT_FUNDS,"Invalid coin.");if(await this.txdb.isSpent(e,t))throw new F(L.errors.WALLET_INSUFFICIENT_FUNDS,"Invalid coin.");if(i<=s.outputs[t].value)throw new F(L.errors.TYPE_ERROR,"Invalid fixed price.");if(n.cid==this.network.genesisId)throw new Y(s,"invalid","prop not for sale",100);return e=(o=new w).addInputFromTx(s,t),t={oper:W.propSale,pid:n.pid,prev:{hash:e.prevout.hash,index:e.prevout.index},fixed:i,period:this.db.curHeight+O.BLOCK_DAY},n=_.fromScript(x.createScript(Buffer.from(JSON.stringify(t)),x.types.NULLDATA),0),o.outputs.push(n),await this.sign(o,null,N.SINGLE|N.ANYONECANPAY),e=o.commit(),r(e[0].verify(e[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.send(e[0]),e}async propBuy(e,t,i){if(!(e=this.db.propList.get(e))||e.pst!=$.Sale||!e.bid||!e.bid.raw)throw new F(L.errors.INVALID_PARAMS,"Invalid Tx Hash.");var r=H.fromRaw(Buffer.from(e.bid.raw,"hex")),a=(await this.createReceive(i)).getAddress(),s=e.gold;if(t<s)throw new Error("wrong price");if(1<r.outputs.length&&t<r.outputs[1].value)throw new Error("low bid price than before");var n=w.fromTX(r,1);if(!n.outputs[0].getReturnType(B.OP_RETURN))throw new Error("not a sale order");return await this.remove(r.hash("hex")),n.view.addOutput({hash:n.inputs[0].prevout.hash,index:n.inputs[0].prevout.index},new _({value:e.gold})),t=new _({address:e.current.address,value:t}),n.outputs.push(t),t={oper:W.propExchange,pid:e.pid,cid:e.cid,oid:e.oid,prev:{hash:n.inputs[0].prevout.hash,index:n.inputs[0].prevout.index}},a=_.fromScript(a,s,t),n.outputs.push(a),i?await this.fund(n,{allowPreInput:!0,account:i}):await this.fund(n,{allowPreInput:!0}),await this.sign(n,null,N.ALL,[0]),s=n.commit(),e.owned||this.db.client.watchOutpoint((new D).fromOptions(r.inputs[0].prevout)),await this.db.send(s[0]),s}async getTXByAmount(e,t){let i=null;var r;for(r of await this.getCoins(t))if(!(r.height<=0)&&r.value==e){i=r;break}return i&&(t=await this.getTX(i.hash))?[t.tx,i.index,i.height]:[]}async contractCreate(e,t,i,a,s){if(this.db.transactionList.query(e,a)!=K.None)throw new F(L.errors.TYPE_ERROR,"Contract with the same address finded.");if(0!=parseInt(t%1e3,10))throw new F(L.errors.TYPE_ERROR,"Contract source should an integer multiple of 1000.");if(!await U.checkSum(this.network,e,a))throw new F(L.errors.TYPE_ERROR,"Create contract with an invalid Address or a Address with old transations.");let n=!1,[o,c,u]=await this.getTXByAmount(t,s);if(!o){n=!0;var h=new w;let e="";e=(s?await this.createReceive(s):this).getAddress(),h.outputs.push(_.fromScript(e,t)),s?await this.fund(h,{allowPreInput:!0,account:s}):await this.fund(h,{allowPreInput:!0}),await this.sign(h),h=h.commit(),r(h[0].verify(h[1],x.flags.STANDARD_VERIFY_FLAGS)),o=h[0],c=0,u=-1}(h=new w).addInputFromTx(o,c,u);let l="";l=(s?await this.createReceive(s):this).getAddress();var p=await this.getKey(l);e={oper:W.contractCreate,type:e,addr:a,src:t,dst:i,srcact:s,alice:p.getPublicKey("hex"),period:this.db.curHeight+O.TRANSACTION_PERIOD},a=_.fromScript(x.createScript(Buffer.from(JSON.stringify(e)),x.types.NULLDATA),0),h.outputs.push(a),await this.sign(h,null,N.SINGLE|N.ANYONECANPAY),t=h.commit();return n&&await this.db.send(o),await this.db.send(t[0]),t}async contractPromise(e,t){if(!(e=this.db.transactionList.get(e))||e.transStatus!=K.CreatedOnMem)throw new F(L.errors.INVALID_PARAMS,"Invalid Tx id.");if(!(e=H.fromRaw(Buffer.from(e.raw,"hex"))))throw new F(L.errors.TYPE_ERROR,"Invalid Tx id.");var i=U.parseContract(e);if(!i||i.oper!==W.contractCreate)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");var r=w.fromTX(e,1);if(!r.outputs[0].getReturnType(B.OP_RETURN))throw new Error("not a valid contract");r.view.addOutput({hash:r.inputs[0].prevout.hash,index:r.inputs[0].prevout.index},new _({value:i.src}));let a="";a=(t?await this.createReceive(t):this).getAddress();var s=await this.getKey(a);e={oper:W.contractPromise,prevhash:e.hash("hex"),type:i.type,addr:i.addr,dst:i.dst,srcact:i.srcact,dstact:t,bob:s.getPublicKey("hex"),period:i.period},t=new x([z.fromSymbol("promise"),z.fromData(Buffer.from(JSON.stringify(e))),z.fromSymbol("drop"),z.fromSymbol("greaterthan"),z.fromSymbol("drop"),z.fromSymbol("if"),z.fromData(l.hash160(Buffer.from(e.bob,"hex"))),z.fromSymbol("else"),z.fromData(l.hash160(Buffer.from(i.alice,"hex"))),z.fromSymbol("endif"),z.fromSymbol("checksig")]),r.outputs.push(_.fromScript(t,i.src)),await this.remove(e.prevhash),await this.sign(r,null,N.ALL,[0]),s=r.commit();return await this.db.send(s[0]),e.current={hash:s[0].hash("hex"),index:0},e.raw=s[0].toRaw().toString("hex"),e.transStatus=K.Promised,this.db.transactionList.saveContract(e,!0),s}async contractExecute(e,t){if(!(e=this.db.transactionList.get(e))||e.transStatus!=K.Confirmed&&e.transStatus!=K.Expired)throw new F(L.errors.INVALID_PARAMS,"Invalid Tx id.");if(!(e=H.fromRaw(Buffer.from(e.raw,"hex"))))throw new F(L.errors.TYPE_ERROR,"Invalid Tx id.");t=t||1;var i=U.parseContract(e);if(!i||i.oper!==W.contractPromise)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");var a=e.outputs[1].getReturnData();if(!a||a.oper!==W.contractPromise)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");r.strictEqual(i.addr,a.addr),r.strictEqual(i.type,a.type),r.strictEqual(i.dst,a.dst),r.strictEqual(i.period,a.period),r.strictEqual(i.srcact,a.srcact),r.strictEqual(i.dstact,a.dstact);var s=this.db.transactionList.query(i.type,i.addr);if(s!=K.Confirmed&&s!=K.Expired)throw new F(L.errors.TYPE_ERROR,"Contract Promise not Check yet.");if(s==K.Expired&&1!=t||s==K.Confirmed&&2!=t)throw new F(L.errors.TYPE_ERROR,"Invalid Executor.");let n=i.srcact,o=(2==t&&(n=i.dstact),"");o=(n?await this.createReceive(n):this).getAddress();var c=new w,u=(c.addInputFromTx(e,1),{oper:W.contractExecute,type:i.type,addr:i.addr,master:t});u=_.fromScript(x.createScript(Buffer.from(JSON.stringify(u)),x.types.NULLDATA),0),c.outputs.push(u),u=_.fromScript(o,e.outputs[1].value),c.outputs.push(u),e=1==t?await P.fromPublic(Buffer.from(i.ori.alice,"hex")):await P.fromPublic(Buffer.from(a.bob,"hex")),u=await this.getKey(e.getAddress()),await c.signAsync(u,x.hashType.ALL,this.db.workers),t=c.commit();return r(t[0].verify(t[1],x.flags.STANDARD_VERIFY_FLAGS,s)),await this.db.send(t[0]),t}async htlcDeal(e,t){var i=await this.getTX(e.hash);let r=null;if(t){if(!(t=await this.getAccount(t)))throw new F(L.errors.TYPE_ERROR,"Invalid Account.");r=t.getReceive().toString()}else r=this.getReceive().toString();t=new w;var a=(new x).pushOp(B.OP_1);e.suggest&&a.pushData(Buffer.from(e.sa,"hex")),t.addInput({prevout:{hash:e.hash,index:e.index},script:a}),t.addOutput(r,i.tx.outputs[e.index].value-1e4),t.view.addOutput({hash:e.hash,index:e.index},new _(i.tx.outputs[e.index])),await this.sign(t,null,N.ALL),a=t.commit();return await this.db.send(a[0]),a}async htlcCancel(e,t){let i=null;var r=await this.getTX(e.hash);if(!(i=r?r.tx.outputs[e.index]:i))throw new F(L.errors.TYPE_ERROR,"Invalid Input.");let a=null;if(t){if(!(r=await this.getAccount(t)))throw new F(L.errors.TYPE_ERROR,"Invalid Account.");a=r.getReceive().toString()}else a=this.getReceive().toString();return t=new w,r=(new x).pushOp(B.OP_0),e.suggest&&r.pushData(Buffer.from(e.sa,"hex")),t.addInput({prevout:{hash:e.hash,index:e.index},script:r}),e.suggest?t.setSequence(0,2*O.HTLC_CANCEL_PERIOD,!1):t.setSequence(0,O.HTLC_CANCEL_PERIOD,!1),t.addOutput(a,i.value-1e4),t.view.addOutput({hash:e.hash,index:e.index},new _(i)),r=await this.getKey(e.master),await t.signAsync(r,x.hashType.ALL,this.db.workers),e=t.commit(),await this.db.send(e[0]),e}async sendContracts(e,t,i){var r,a=new w;for(r of e)a.outputs.push(i.create(r));return t?await this.fund(a,{account:t}):await this.fund(a),await this.sign(a),e=a.commit(),await this.db.addTX(e[0]),await this.db.send(e[0]),e}async tokenCreate(e,t="",i){r(e&&"object"==typeof e,"Token data should be a object"),r(e.cid,"Token data should has a cid property"),r(e.uid,"Token data should has a uid property"),e.time=!0,await this.ensureAccount({name:t,witness:!0});let a=null;if(i){if(!await this.belongToAccount(t,i))throw new F(L.errors.TYPE_ERROR,`tokenCreate address error: addr:${i} is not belongs to account:`+t);a=await this.getKey(i)}else a=await this.createReceive(t,n.hashInt(e.cid),this.master);return a.signData(e)}async sign(e,t,i=x.hashType.ALL,r){if(this.watchOnly)throw new Error("Cannot sign from a watch-only wallet.");return await this.unlock(t),t=await this.deriveInputs(e),e.signAsync(t,i,this.db.workers,r)}getCoinView(e){return this.txdb.getCoinView(e)}getSpentView(e){return this.txdb.getSpentView(e)}toDetails(e){return this.txdb.toDetails(e)}getDetails(e){return this.txdb.getDetails(e)}async getCoin(e,t){return this.txdb.getCoin(e,t)}async getCredit(e,t){return this.txdb.getCredit(e,t)}async getStatusOfSC(e){return this.txdb.getStatusOfSC(e)}async setStatusOfSC(e,t){var i=await this.writeLock.lock();try{this.txdb.start();try{await this.txdb._setStatusOfSC(e,t),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}}finally{i()}}getLockedCoins(){return this.txdb.lockedCoins.values}getTX(e){return this.txdb.getTX(e)}getBlocks(){return this.txdb.getBlocks()}getBlock(e){return this.txdb.getBlock(e)}async add(e,t,i){var r=await this.writeLock.lock();try{return await this._add(e,t,i)}finally{r()}}async _add(e,t,i){let r,a;this.txdb.start();try{(r=await this.txdb._add(e,t,i))&&(a=await this.syncOutputDepth(r)),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}return a&&0<a.length&&(this.db.emit("address",this.id,a),this.emit("address",a)),r}async resetBalance(){var e=await this.writeLock.lock();try{this.txdb.start();try{this.txdb.pending.unconfirmed=0,this.txdb.pending.confirmed=0;for(const e of await this.getAccounts()){var t=await this.getBalance(e);this.txdb.pending.unconfirmed+=t.unconfirmed,this.txdb.pending.confirmed+=t.confirmed}this.txdb.put(te.R,this.txdb.pending.commit()),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}}finally{e()}return this.txdb.state.toBalance()}async unconfirm(e){var t=await this.writeLock.lock();try{return await this.txdb.unconfirm(e)}finally{t()}}async remove(e){var t=await this.writeLock.lock();try{return await this.txdb.remove(e)}finally{t()}}async zap(e,t){var i=await this.writeLock.lock();try{return await this._zap(e,t)}finally{i()}}async _zap(e,t){return e=await this.ensureIndex(e),this.txdb.zap(e,t)}async abandon(e){var t=await this.writeLock.lock();try{return await this._abandon(e)}finally{t()}}_abandon(e){return this.txdb.abandon(e)}conserveCoin(e){return this.txdb.conserveCoin(e)}unConserveCoin(e){return this.txdb.unConserveCoin(e)}isConserved(e){return this.txdb.isConserved(e)}getConserved(){return this.txdb.getConserved()}async getHistory(e){return e=await this.ensureIndex(e),this.txdb.getHistory(e)}async getCoins(e){return e=await this.ensureIndex(e),this.txdb.getCoins(e)}async getCredits(e){return e=await this.ensureIndex(e),this.txdb.getCredits(e)}async getSmartCoins(e){var t=[];for(const r of await this.getCredits(e)){var i=r.coin;r.spent||this.txdb.isConserved(i)||-1===i.height&&!r.own||t.push(i)}return t}async getPending(e){return e=await this.ensureIndex(e),this.txdb.getPending(e)}async getBalance(e){return e=await this.ensureIndex(e),this.txdb.getBalance(e)}async queryBalanceLog(e,t=0){return(e=await this.ensureIndex(e))?this.db.queryBalanceLog(this.wid,e,t):[]}async getRange(e,t){return e&&"object"==typeof e&&(t=e,e=null),e=await this.ensureIndex(e),this.txdb.getRange(e,t)}async getLast(e,t){return e=await this.ensureIndex(e),this.txdb.getLast(e,t)}async ensureIndex(e,t){if(null==e){if(t)throw new Error("No account provided.");return null}if(-1===(t=await this.getAccountIndex(e)))throw new Error("Account not found.");return t}getAddress(e){return this.account.getAddress(e)}getReceive(e){return this.account.getReceive(e)}getChange(e){return this.account.getChange(e)}getNested(e){return this.account.getNested(e)}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(e){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(e),account:this.account.toJSON(!0)}}getSize(){var e=0;return(e+=50)+o.sizeVarString(this.id,"ascii")+o.sizeVarlen(this.master.getSize())}toRaw(){var e=this.getSize();return(e=new f(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(e){e=new d(e);var t=s.fromMagic(e.readU32());return 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()),r(t===this.db.network,"Wallet network mismatch."),this}static fromRaw(e,t){return new re(e).fromRaw(t)}static isWallet(e){return e instanceof re}async issueCreate(e,t,i){var r=new G(e),a=((a=(r.source.subjectName||(r.source.subjectName=r.erid),P.fromPrivate(Buffer.from(e.key,"hex"),!0,this.network))).witness=!0,r.sign(a,!0,this.network),r.toOptions(!0));return i?this.send({outputs:[{address:e.address,value:1e4}],comment:a},t):(r=await this.send({outputs:[{address:e.address,value:1e4}],comment:a},t),a.txid=r.txid()),a}async caAbolish(e,t,i){var r=P.fromPrivate(Buffer.from(e.key,"hex"),!0,this.network),a=(r.witness=!0,await this.db.client.execute("ca.byId",[e.erid]));if(!a)throw new F(L.errors.TYPE_ERROR,"ca.abolish: Invalid erid.");if(a.source.cid!=e.cid)throw new F(L.errors.TYPE_ERROR,"ca.abolish: Invalid cid.");if(a.source.uid!=e.uid)throw new F(L.errors.TYPE_ERROR,"ca.abolish: Invalid uid.");var s=a.signature;if(a.sign(r,!0,this.network),a.witness!=e.witness||a.signature!=s)throw new F(L.errors.TYPE_ERROR,"ca.abolish: You have no permission to abolish this witness.");return(a=new X(e)).sign(r),s=a.toOptions(!0),i?this.send({outputs:[{address:e.address,value:1e4}],comment:s},t):await this.send({outputs:[{address:e.address,value:1e4}],comment:s},t),s}async enchanceCp(e,t){var i=((e=new J(e)).oper="enchanceCp",await this.ensureCp(e.to)),r=await this.ensureCp(e.from);if(!(r=await this.getKey(r.pubAddress)))throw new F(L.errors.TYPE_ERROR,"Invalid cid, Not along to this wallet.");return e.sign(r),r=e.toOptions(!0),[await this.send({outputs:[{address:i.pubAddress,value:1e4}],comment:r},t),r]}async ensureCp(e,t=!1){if(await this.db.flushCP([e]),(e=this.db.cpList.getItem(e))||t)return e;throw new F(L.errors.TYPE_ERROR,"Invalid cid, cannot find cp.")}}e.exports=re},function(e,t,i){"use strict";
|
|
285
|
+
*/const r=i(0);var a=i(16);const s=i(15),n=i(2),o=i(3),c=i(35),u=i(198),h=i(140).sortWithSeq,l=i(6),p=i(94),d=i(1),f=i(4),m=i(69),g=i(334);i(218);const v=i(109),y=i(73),b=i(13),w=i(68),x=i(17),k=i(219),S=i(156),_=i(28),E=i(157),j=i(337),A=i(63),R=i(26),I=i(29),O=i(7),C=i(310),P=i(38),T=S.Mnemonic,{opcodes:B,hashType:N}=i(19),z=i(165),F=i(77),L=i(78),M=i(141),D=i(46),H=i(20),U=i(42),q=i(54),{NotifyMsg:V,ContractStatus:K,ContractType:W,PropStatus:$}=i(5),Y=i(37).VerifyError,G=i(153).ErItem,X=i(154).ErAbolishItem,J=i(228).EnchancementItem,Q=i(67),Z=i(59),ee=i(83),te=i(85).txdb,ie=i(31);class re extends a{constructor(e,t){super(),r(e,"DB required."),this.db=e,this.network=e.network,this.logger=e.logger,this.readLock=new u,this.writeLock=new c,this.sendLock=new c,this.indexCache=new A(1e4),this.accountCache=new A(1e4),this.pathCache=new A(1e5),this.current=null,this.wid=0,this.id=null,this.initialized=!1,this.watchOnly=!1,this.accountDepth=0,this.token=o.ZERO_HASH,this.tokenDepth=0,this.master=new j,this.txdb=new g(this),this.account=null,t&&this.fromOptions(t)}fromOptions(e){let t,i,a=e.master;return a?("string"==typeof a&&(a=S.PrivateKey.fromBase58(a,this.network)),r(S.isPrivate(a),"Must create wallet with hd private key.")):(i=new T(e.mnemonic),a=S.fromMnemonic(i,this.network)),r(a.network===this.network,"Network mismatch for master key."),this.master.fromKey(a,i),null!=e.wid&&(r(n.isU32(e.wid)),this.wid=e.wid),e.id&&(r(y.isName(e.id),"Bad wallet ID."),t=e.id),null!=e.initialized&&(r("boolean"==typeof e.initialized),this.initialized=e.initialized),null!=e.watchOnly&&(r("boolean"==typeof e.watchOnly),this.watchOnly=e.watchOnly),null!=e.accountDepth&&(r(n.isU32(e.accountDepth)),this.accountDepth=e.accountDepth),e.token&&(r(Buffer.isBuffer(e.token)),r(32===e.token.length),this.token=e.token),t=t||this.getID(),this.id=t,this}static fromOptions(e,t){return new re(e).fromOptions(t)}async init(e){var t=e.passphrase;r(!this.initialized),this.initialized=!0,t&&await this.master.encrypt(t),e=await this._createAccount(e,t);r(e),this.account=e,this.logger.info("Wallet initialized (%s).",this.id),await this.txdb.open()}async open(){r(this.initialized);var e=await this.getAccount(0);if(!e)throw new Error("Default account not found.");this.account=e,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(e,t,i){var r={alliancename:e,nodeid:t};return e?(r.alliancePrivateKey=l.hash256(Buffer.concat([Buffer.from(e),this.master.key.privateKey])),i?(r.prv=Buffer.alloc(0),r.pub=Buffer.from(i,"hex"),r.awardAddress=b.fromWitnessPubkeyhash(l.hash160(r.pub),this.network.type).toString(this.network.type),r.mnemonic=new T):(i=l.hash256(Buffer.concat([Buffer.from(e+"-"+t),this.master.key.privateKey])),r.mnemonic=new T({entropy:i,language:this.master.mnemonic.language,passphrase:this.master.mnemonic.passphrase}),r.prv=l.hash256(Buffer.from(r.mnemonic.toSeed().toString("hex"))),r.pub=R.publicKeyCreate(r.prv,!0),e=j.fromKey(S.fromMnemonic(r.mnemonic),this.network.type).key.deriveAccount(44,0).derive(9).derive(1),r.awardAddress=b.fromWitnessPubkeyhash(l.hash160(e.publicKey),this.network.type).toString(this.network.type))):(r.mnemonic=T.fromOptions(this.master.mnemonic),r.prv=l.hash256(Buffer.from(r.mnemonic.toSeed().toString("hex"))),r.pub=R.publicKeyCreate(r.prv,!0),r.awardAddress=b.fromWitnessPubkeyhash(l.hash160(r.pub),this.network.type).toString(this.network.type)),r.address=b.fromWitnessPubkeyhash(l.hash160(r.pub),this.network.type).toString(),r}async destroy(){var e=await this.writeLock.lock(),t=await this.sendLock.lock();try{this.db.unregister(this),await this.master.destroy(),this.readLock.destroy(),this.writeLock.destroy(),this.sendLock.destroy()}finally{t(),e()}}async addSharedKey(e,t){var i=await this.writeLock.lock();try{return await this._addSharedKey(e,t)}finally{i()}}async _addSharedKey(e,t){if(t||(t=e,e=null),!(e=await this.getAccount(e=null==e?0:e)))throw new Error("Account not found.");let i;this.start();try{i=await e.addSharedKey(t)}catch(e){throw this.drop(),e}return await this.commit(),i}async removeSharedKey(e,t){var i=await this.writeLock.lock();try{return await this._removeSharedKey(e,t)}finally{i()}}async _removeSharedKey(e,t){if(t||(t=e,e=null),!(e=await this.getAccount(e=null==e?0:e)))throw new Error("Account not found.");let i;this.start();try{i=await e.removeSharedKey(t)}catch(e){throw this.drop(),e}return await this.commit(),i}async setPassphrase(e,t){e&&await this.decrypt(e),t&&await this.encrypt(t)}async encrypt(e){var t=await this.writeLock.lock();try{return await this._encrypt(e)}finally{t()}}async _encrypt(e){e=await this.master.encrypt(e,!0),this.start();try{await this.db.encryptKeys(this,e)}catch(t){throw p(e),this.drop(),t}p(e),this.save(),await this.commit()}async decrypt(e){var t=await this.writeLock.lock();try{return await this._decrypt(e)}finally{t()}}async _decrypt(e){e=await this.master.decrypt(e,!0),this.start();try{await this.db.decryptKeys(this,e)}catch(t){throw p(e),this.drop(),t}p(e),this.save(),await this.commit()}async rename(e){var t=await this.writeLock.lock();try{return await this.db.rename(this,e)}finally{t()}}async writeBalanceLog(e){var t=await this.writeLock.lock();try{return await this.db.writeBalanceLog(this,e)}finally{t()}}async renameAccount(e,t){var i=await this.writeLock.lock();try{return await this._renameAccount(e,t)}finally{i()}}async _renameAccount(e,t){if(!y.isName(t))throw new Error("Bad account name.");var i=await this.getAccount(e);if(!i)throw new Error("Account not found.");if(0===i.accountIndex)throw new Error("Cannot rename default account.");if(await this.hasAccount(t))throw new Error("Account name not available.");e=i.name,this.start(),this.db.renameAccount(i,t),await this.commit(),this.indexCache.remove(e),e=this.pathCache.values();for(const r of e)r.account===i.accountIndex&&(r.name=t)}async lock(){var e=await this.writeLock.lock(),t=await this.sendLock.lock();try{await this.master.lock()}finally{t(),e()}}unlock(e,t){return this.master.unlock(e,t)}getID(){r(this.master.key,"Cannot derive id.");var e,t=this.master.key.derive(44);(e=new f(37)).writeBytes(t.publicKey),e.writeU32(this.network.magic),t=l.hash160(e.render());return(e=new f(27)).writeU8(3),e.writeU8(190),e.writeU8(4),e.writeBytes(t),e.writeChecksum(),m.encode(e.render())}async createAccount(e,t){var i=await this.writeLock.lock();try{return await this._createAccount(e,t)}finally{i()}}async _createAccount(e,t){let i,a,s=e.name,o=(s=s||this.accountDepth.toString(10),0);if(0!=this.accountDepth&&(o=n.hashInt(s)),await this.hasAccountIndex(o))throw new Error("Account Index Conflict.");if(await this.hasAccount(s))throw new Error("Account already exists.");if(await this.unlock(t),this.watchOnly&&e.accountKey){if("string"==typeof(i=e.accountKey)&&(i=S.PublicKey.fromBase58(i,this.network)),!S.isPublic(i))throw new Error("Must add HD public keys to watch only wallet.");r(i.network===this.network,"Network mismatch for watch only key.")}else r(this.master.key),i=(i=this.master.key.deriveAccount(44,o)).toPublic();t={wid:this.wid,id:this.id,name:0===this.accountDepth?"default":s,witness:e.witness,watchOnly:this.watchOnly,accountKey:i,accountIndex:o,type:e.type,m:e.m,n:e.n,keys:e.keys},this.start();try{(a=E.fromOptions(this.db,t)).wallet=this,await a.init()}catch(e){throw this.drop(),e}return this.logger.info("Created account %s/%s/%d.",a.id,a.name,a.accountIndex),this.accountDepth++,this.save(),await this.commit(),a}async ensureAccount(e,t){var i=e.name;return(i=await this.getAccount(i))||this.createAccount(e,t)}getAccounts(){return this.db.getAccounts(this.wid)}getAccountMap(){return this.db.getAccountMap(this.wid)}getAddressHashes(e){return null!=e?this.getAccountHashes(e):this.db.getWalletHashes(this.wid)}async getAccountHashes(e){return e=await this.ensureIndex(e,!0),this.db.getAccountHashes(this.wid,e)}async getAccount(e){if(this.account&&(null==e||"default"===e||"number"==typeof e&&0===e||"string"==typeof e&&0===e.length))return this.account;if(-1===(e=await this.getAccountIndex(e)))return null;var t=await this.readLock.lock(e);try{return await this._getAccount(e)}finally{t()}}async _getAccount(e){var t=this.accountCache.get(e);return t||((t=await this.db.getAccount(this.wid,e))?(t.wallet=this,t.wid=this.wid,t.id=this.id,t.watchOnly=this.watchOnly,await t.open(),this.accountCache.set(e,t),t):null)}async getAccountIndex(e){var t;return null==e?-1:"number"==typeof e?e:null!=(t=this.indexCache.get(e))?t:-1===(t=await this.db.getAccountIndex(this.wid,e))?-1:(this.indexCache.set(e,t),t)}async getAccountName(e){var t;return"string"==typeof e?e:(t=this.accountCache.get(e))?t.name:this.db.getAccountName(this.wid,e)}async hasAccount(e){return-1!==(e=await this.getAccountIndex(e))&&(!!this.accountCache.has(e)||this.db.hasAccount(this.wid,e))}async hasAccountIndex(e){return!!this.accountCache.has(e)||this.db.hasAccount(this.wid,e)}createReceive(e,t=0,i=null){return this.createKey(e,0,t,i)}createChange(e){return this.createKey(e,1)}createNested(e){return this.createKey(e,2)}async createKey(e,t,i=0,r=null){var a=await this.writeLock.lock();try{return await this._createKey(e,t,i,r)}finally{a()}}async _createKey(e,t,i=0,r=null){if(null==t&&(t=e,e=null),!(e=await this.getAccount(e=e||0)))throw new Error("Account not found.");let a;this.start();try{a=await e.createKey(t,i,r)}catch(e){throw this.drop(),e}return await this.commit(),a}async deriveKey(e,t,i,r=null){let a=null;var s=await this.writeLock.lock();try{this.start(),a=await this._deriveKey(e,t,i,r),await this.commit()}catch(e){throw this.drop(),e}finally{s()}return a}async _deriveKey(e,t,i=0,r=null){if(null==t&&(t=e,e=null),e=e||0,e=parseInt(e),e=await this.getAccount(e))return t=await e.deriveKey(t,i,r),await e.saveKey(t),t;throw new Error("Account not found.")}save(){return this.db.save(this)}async saveAccount(e){var t=await this.writeLock.lock();try{this.start(),e._save(),await this.commit(),0==e.accountIndex&&(this.account=e)}finally{t()}}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(e){return e=b.getHash(e,"hex"),null!=await this.getPath(e)}async ownedAddress(e){return!!await this.getKey(e)}async getPath(e){return(e=await this.readPath(e))?(e.name=await this.getAccountName(e.account),r(e.name),this.pathCache.set(e.hash,e),e):null}async readPath(e){e=b.getHash(e,"hex");var t=this.pathCache.get(e);return t||((t=await this.db.getPath(this.wid,e))?(t.id=this.id,t):null)}async hasPath(e){return e=b.getHash(e,"hex"),!!this.pathCache.has(e)||this.db.hasPath(this.wid,e)}async getPaths(e){if(null!=e)return this.getAccountPaths(e);var t=[];for(const e of await this.db.getWalletPaths(this.wid))e.id=this.id,e.name=await this.getAccountName(e.account),r(e.name),this.pathCache.set(e.hash,e),t.push(e);return t}async getAccountPaths(e){var t=await this.ensureIndex(e,!0),i=await this.getAccountHashes(t),a=await this.getAccountName(e),s=(r(a),[]);for(const e of i){var n=await this.readPath(e);r(n),r(n.account===t),n.name=a,this.pathCache.set(n.hash,n),s.push(n)}return s}async importKey(e,t,i){var r=await this.writeLock.lock();try{return await this._importKey(e,t,i)}finally{r()}}async _importKey(e,t,i){if(e&&"object"==typeof e&&(i=t,t=e,e=null),null==e&&(e=0),r(t.network===this.network,"Network mismatch for key."),this.watchOnly){if(t.privateKey)throw new Error("Cannot import privkey into watch-only wallet.")}else if(!t.privateKey)throw new Error("Cannot import pubkey into non watch-only wallet.");var a=t.getHash("hex");if(await this.getPath(a))throw new Error("Key already exists.");if(!(a=await this.getAccount(e)))throw new Error("Account not found.");if(a.type!==E.types.PUBKEYHASH)throw new Error("Cannot import into non-pkh account.");await this.unlock(i),e=k.fromRing(a,t).toPath(),this.master.encrypted&&(e.data=this.master.encipher(e.data,e.hash),r(e.data),e.encrypted=!0),this.start();try{await a.savePath(e)}catch(e){throw this.drop(),e}await this.commit()}async importAddress(e,t){var i=await this.writeLock.lock();try{return await this._importAddress(e,t)}finally{i()}}async _importAddress(e,t){if(t||(t=e,e=null),null==e&&(e=0),t.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(t))throw new Error("Address already exists.");if(!(e=await this.getAccount(e)))throw new Error("Account not found.");if(e.type!==E.types.PUBKEYHASH)throw new Error("Cannot import into non-pkh account.");t=v.fromAddress(e,t),this.start();try{await e.savePath(t)}catch(e){throw this.drop(),e}await this.commit()}async fund(e,t){var i=await this.writeLock.lock();try{return await this._fund(e,t)}finally{i()}}async _fund(e,t){if(t=t||{},!this.initialized)throw new Error("Wallet is not initialized.");if(this.watchOnly)throw new Error("Cannot fund from watch-only wallet.");let i;if(null!=t.account){if(!(i=await this.getAccount(t.account)))throw new Error("Account not found.")}else i=this.account;if(!i.initialized)throw new Error("Account is not initialized.");let a,s=t.rate;return null==s&&(s=await this.db.estimateFee(t.blocks)),a=t.smart?await this.getSmartCoins(i.name):(a=await this.getCoins(i.name),this.txdb.filterConserved(a)),await e.fund(a,{allowPreInput:t.allowPreInput,noChange:t.noChange,selection:t.selection,round:t.round,depth:t.depth,hardFee:t.hardFee,subtractFee:t.subtractFee,subtractIndex:t.subtractIndex,changeAddress:i.change.getAddress(),height:this.db.curHeight,rate:s,maxFee:t.maxFee,estimate:e=>this.estimateSize(e),network:this.network}),!t.allowInfiniteFee&&t.noChange&&r(e.getFee()<=C.MAX_FEE,"TX exceeds MAX_FEE."),a}async getAccountByAddress(e){return e=b.getHash(e,"hex"),(e=await this.getPath(e))?this.getAccount(e.account):null}async estimateSize(e){var t=O.WITNESS_SCALE_FACTOR,i=b.fromScript(e);if(!i)return-1;var r=await this.getAccountByAddress(i);if(!r)return-1;let a=0;if(e.isScripthash()&&r.witness)switch(r.type){case E.types.PUBKEYHASH:a=4*(a+23);break;case E.types.MULTISIG:a=4*(a+35)}switch(r.type){case E.types.PUBKEYHASH:a=a+74+34;break;case E.types.MULTISIG:a=(a=(a=(a=(a+=1)+74*r.m)+3+1)+34*r.n)+1+1}return r.witness?a=((a+=1)+t-1)/t|0:a+=o.sizeVarint(a),a}async createTX(e){var t=e.outputs,i=new w;r(Array.isArray(t),"Outputs must be an array."),r(0<t.length,"No outputs available."),e.comment&&("object"==typeof e.comment&&(e.comment=JSON.stringify(e.comment)),i.outputs.push(_.fromScript(x.createScript(Buffer.from(e.comment),x.types.NULLDATA),0)));for(const e of t){var a=new _(e),s=a.getAddress();if(a.isDust())throw new Error("Output is dust.");if(0<a.value){if(!s)throw new Error("Cannot send to unknown address.");if(s.isNull())throw new Error("Cannot send to null address.")}i.outputs.push(a)}let n=null;if(e.inputs)for(const t of e.inputs){var o=await this.getTX(t.hash);o&&(o=q.fromTX(o.tx,t.index,-1,0))&&(n=o.getAddress(),e.allowPreInput=!0,i.addCoin(o))}else await this.fund(i,e);if(n&&((t=new _).value=i.getFee()-C.MIN_FEE,t.script.fromAddress(n),i.outputs.push(t),i.changeIndex=i.outputs.length-1),!1!==e.sort&&i.sortMembers(),null!=e.locktime&&i.setLocktime(e.locktime),r(i.isSane(),"TX failed sanity check."),r(i.verifyInputs(this.db.curHeight+1),"TX failed context check."),0===await this.template(i))throw new Error("Templating failed.");return i}async send(e,t){var i=await this.sendLock.lock();try{return await this._send(e,t)}finally{i()}}async _send(e,t){return t&&(e.account=t),t=await this.createTX(e,!0),await this.sign(t),this.sendMTX(t,{sendafter:e.sendafter})}async sendMTX(e,t={}){if(!e.isSigned())throw new Error("TX could not be fully signed.");var i=e.toTX();if(i.getSigopsCost(e.view)>I.MAX_TX_SIGOPS_COST)throw new Error("TX exceeds policy sigops.");if(i.getWeight()>I.MAX_TX_WEIGHT)throw new Error("TX exceeds policy weight.");return t.sendafter||(this.logger.debug("Sending wallet tx (%s): %s",this.id,i.txid()),await this.db.addTX(i),await this.db.send(i)),i}async resend(){var e=await this.getPending(),t=(0<e.length&&this.logger.info("Rebroadcasting %d transactions.",e.length),[]);for(const i of e)t.push(i.tx);for(const e of h(t))await this.db.send(e);return t}async deriveInputs(e){r(e.mutable);var t=[];for(const r of await this.getInputPaths(e)){var i=await this.getAccount(r.account);i&&(i=i.derivePath(r,this.master))&&t.push(i)}return t}async getKey(e){try{var t,i=b.getHash(e,"hex",this.network.type),r=await this.getPath(i);return r&&(t=await this.getAccount(r.account))?t.derivePath(r,this.master):null}catch{return null}}async exportToFile(e){if(!Z.unsupported){var t=await this.db.getTip(),i=n.date();let o="",c=[n.fmt("# Wallet Dump created by %s %s",ee.protocol,ee.version),n.fmt("# * Created on %s",i),n.fmt("# * Best block at time of backup was %d (%s).",t.height,n.revHex(t.hash)),n.fmt("# * File: %s",e.file),""];var r,a;t=n.fmt("W %s wid= %s",this.toRaw().toString("base64"),this.wid),t=(c.push(t),await this.getAccounts());for(const e of t){var s=await this.getAccount(e);s=n.fmt("C %s name= %s index= %d",s.toRaw().toString("base64"),s.name,s.accountIndex);c.push(s)}for(const t of await this.getAddressHashes())this.watchOnly?(r=b.fromWitnessPubkeyhash(Buffer.from(t,"hex"),this.network.type).toString(),r=n.fmt("A %s %s label= account= %s branch= %s index= %s addr= %s","S",i,0,-1,-1,r),c.push(r)):(r=await this.getPrivateKey(t))&&(a=r.getAddress("string"),a=n.fmt("A %s %s label= account= %s branch= %s index= %s addr= %s",r.toSecret(),i,r.account,r.branch,r.index,a),c.push(a),e.fragment)&&1e5<c.length&&(o=c.join("\n"),await Z.writeFile(e.file.split(".").reduce((e,t)=>(e?e+="."+t:e=t+"-1",e),""),o,"utf8"),c=[]);c.push(""),c.push("# End of dump"),c.push(""),o=c.join("\n"),await Z.writeFile(e.file,o,"utf8")}}async getPrivateKey(e,t){if(e=b.getHash(e,"hex"),!(e=await this.getPath(e)))return null;var i=await this.getAccount(e.account);return i?(await this.unlock(t),(t=i.derivePath(e,this.master)).privateKey?t:null):null}async getInputPaths(e){if(r(e.mutable),!e.hasCoins())throw new Error("Not all coins available.");var t=[];for(const r of e.getInputHashes("hex")){var i=await this.getPath(r);i&&t.push(i)}return t}async getOutputPaths(e){var t=[];for(const r of e.getOutputHashes("hex")){var i=await this.getPath(r);i&&t.push(i)}return t}async setLookahead(e,t){var i=await this.writeLock.lock();try{return this._setLookahead(e,t)}finally{i()}}async _setLookahead(e,t){if(null==t&&(t=e,e=null),!(e=await this.getAccount(e=null==e?0:e)))throw new Error("Account not found.");this.start();try{await e.setLookahead(t)}catch(e){throw this.drop(),e}await this.commit()}async syncOutputDepth(e){var t=new Map;for(const r of e.outputs){var i=r.path;i&&-1!==i.index&&(t.has(i.account)||t.set(i.account,[]),t.get(i.account).push(i))}var a,s,n=[];for([a,s]of t){let e=-1,t=-1,i=-1;for(const r of s)switch(r.branch){case 0:r.index>e&&(e=r.index);break;case 1:r.index>t&&(t=r.index);break;case 2:r.index>i&&(i=r.index)}e+=2,t+=2,i+=2;var o=await this.getAccount(a);(o=(r(o),await o.syncDepth(e,t,i)))&&n.push(o)}return n}async getRedeem(e){"string"==typeof e&&(e=Buffer.from(e,"hex"));var t=await this.getKey(e.toString("hex"));return t?t.getRedeem(e):null}async template(e){var t=await this.deriveInputs(e);return e.sign(t)}async onSaleList(e,t){return(await(await this.getPropList()).predict(async(e,i)=>!!i.bid&&await this.belongToAccount(t,i.bid.address))).where([["pst",$.Sale]]).paginate(10,e).records()}async mySaleList(e,t){return(await(await this.getPropList()).predict(async(e,i)=>this.belongToAccount(t,i.current.address))).where([["pst",$.Sale]]).paginate(10,e).records()}async getPropList(){const e=await this.db.loadVpList();var t=[];for(let i=0;i<e.length;i++){let r=e[i];t.push((async()=>{await this.getPrivateKey(r.current.address)&&(e[i]=[r.pid,r])})())}return await Promise.all(t),new ie(e)}async propCreate(e,t){var i,a=new w;for(i of e){var s=await this.ensureCp(i.cid,!0);!s||i.cid==this.network.genesisId||(i.gold=(0|i.gold)>>>0,i.gold<O.MINPROPVALUE)||(i.pid||(i.pid=M()),i.oid||(i.oid=i.pid),a.propCreate(s.current.address,i),i.index=a.outputs.length-1)}if(0<a.outputs.length){t?await this.fund(a,{account:t}):await this.fund(a),await this.sign(a);var n,o=a.commit();for(n of(await this.db.addTX(o[0]),await this.db.send(o[0]),r(o[0].verify(o[1],x.flags.STANDARD_VERIFY_FLAGS)),e))n.hash=o[0].hash("hex"),n.txid=o[0].txid();return o}return[]}async attach(e,t){var i,a=new w;for(i of e)a.attach(i.address,i.value,i.data);if(0<a.outputs.length){t?await this.fund(a,{account:t}):await this.fund(a),await this.sign(a);var s,n=a.commit();for(s of(await this.db.addTX(n[0]),await this.db.send(n[0]),r(n[0].verify(n[1],x.flags.STANDARD_VERIFY_FLAGS)),e))s.hash=n[0].hash("hex"),s.txid=n[0].txid();return n}return[]}async sendSecret(e,t,i){let r=this.db.$contacts.get(e);if(!r||!r.sender){var a=(await this.createReceive(i)).getAddress("string");if(e==a)throw new F(L.errors.TYPE_ERROR,"Forbid Sending to Self Address.");r=await this.db.ensureContact({contact:e,messenger:a,wallet:this,account:i})}if(r)return r.send(t);throw new F(L.errors.TYPE_ERROR,"Invalid Address.")}async commNotify(e){r(!!e),r(!!e.dst),r(!!e.content);var t=new w,i=e.src||this.getReceive().toString(),a=(i=new V(W.notify,M(),this.db.curHeight,{src:i,content:e.content}),_.fromScript(x.createScript(i.toRaw(),x.types.NULLDATA),0));t.outputs.push(a),a={address:e.dst,locktime:O.BLOCK_DAY,locktype:"csb",value:.1*O.COIN},t.outputs.push(new _(a)),e.account?await this.fund(t,{account:e.account,noChange:!0,allowInfiniteFee:!0}):await this.fund(t,{noChange:!0,allowInfiniteFee:!0}),await this.sign(t),a=t.commit();return r(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(a[0]),this.logger.debug("Sending tx on wallet(%s): %s",this.id,a[0].txid()),await this.db.send(a[0]),i.hash=a[0].hash("hex"),i.height=-1,i}async cpRegister(e,t,i,a){if(r(!!t&&"object"==typeof t),!await this.db.client.execute("canExecute",[{confirm:!1,cid:t.cid,name:t.name,oper:W.cpRegister}]))throw new F(L.errors.TYPE_ERROR,"Invalid CP Register Info.");const s=new w;e||(n=await this.createReceive(i),e=n.getAddress());var n=await this.getKey(e);if(!n)throw new F(L.errors.TYPE_ERROR,"Invalid CP Register Address, Not along to this wallet.");if(t.pubAddress=e.toString(),t.pubKey=n.getPublicKey("hex"),t.signMethod="secp256k1",n=await this.createAllianceInfo(),t.register=n.pub.toString("hex"),s.cpRegister(e,O.registerFee,t),n=async()=>{i?await this.fund(s,{account:i}):await this.fund(s),await this.sign(s);var a=s.commit();return r(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(a[0]),await this.db.send(a[0]),t.txid=a[0].txid(),t.addr=e.toString(),a},!a)return n();n()}getSCAddress(e){return e=Q.fromMnemonic(T.fromOptions(O.SmartContractMnemonic),this.network).deriveAccount(44,e).derive(9).derive(1),b.fromWitnessPubkeyhash(l.hash160(e.publicKey),this.network)}async cpChange(e,t){var i=await this.ensureCp(e.cid);if(i.cid==this.network.genesisId||"ATHENA"==i.name)throw new F(L.errors.TYPE_ERROR,"Invalid cp name.");var a=await this.getTX(i.current.hash);if(!a)throw new F(L.errors.TYPE_ERROR,"Do not have permission to change this info.");if(a=a.tx,!await this.belongToAccount(t,a.outputs[0].getAddress()))throw new F(L.errors.TYPE_ERROR,"Invalid account info.");if(e.newName){if(!await this.db.client.execute("canExecute",[{confirm:!1,cid:i.cid,name:e.newName,oper:W.cpChange}]))throw new F(L.errors.TYPE_ERROR,"Invalid CP Change Info.")}else e.newName=i.name;return e.addr||(e.addr=b.fromString(i.current.address)),i=w.cpChange(a,e),t?await this.fund(i,{allowPreInput:!0,account:t}):await this.fund(i,{allowPreInput:!0}),await this.sign(i),a=i.commit(),await this.db.send(a[0]),r(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),e.txid=a[0].txid(),a}async propExchangeList(e,t,i=!1){var a,s,n,o=new w,c=[];for([a,s,n]of e){var u,h=null;if(h=await this.getTX(a.hash)){if(h=h.tx,u=a.index,h&&h.outputs&&!(h.outputs.length<=u)){if(i){if(!await this.ownedAddress(h.outputs[u].getAddress())){this.logger.error("not owned prop:",a.hash,a.index);continue}}else if(!await this.belongToAccount(t,h.outputs[u].getAddress())){this.logger.error("not owned prop:",a.hash,a.index);continue}var l=h.outputs[u].getReturnData();l&&(o.propExchange(h,u,s),l.index=o.outputs.length-1,l.addr=s.toString(),c.push(l))}}else this.logger.error("tx not find:",a.hash,n)}return t?await this.fund(o,{allowPreInput:!0,account:t}):await this.fund(o,{allowPreInput:!0}),await this.sign(o),e=o.commit(),await this.db.addTX(e[0]),await this.db.send(e[0]),r(e[0].verify(e[1],x.flags.STANDARD_VERIFY_FLAGS)),e.push(c),e}async propDonate(e,t){var i=e.index;if(!(e=await this.getTX(e.hash))||!e.tx||!e.tx.outputs||e.tx.outputs.length<=i)throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");if(!await this.belongToAccount(t,e.tx.outputs[i].getAddress()))throw new F(L.errors.TYPE_ERROR,"Props that do not belong to you.");if(!(t=e.tx.outputs[i].getReturnData()))throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");if(t.cid&&t.cid==this.network.genesisId)throw new Y(e.tx,"invalid","Special props that can not to donate",100);var r=new w;return(e=(r.addInputFromTx(e.tx,i),r.addOutput(x.createScript(Buffer.from(JSON.stringify({value:e.tx.outputs[i].value,cid:t.cid,pid:t.pid,oid:t.oid,gaddr:this.getAddress().toString(this.network)})),x.types.NULLDATA),0),await this.sign(r,null,N.NONE|N.ANYONECANPAY),r.commit())).push(t),e}async propReceive(e,t){var i=(e=w.fromTX(e,1)).inputs[0].prevout,r=e.outputs[0].getReturnData();e.view.addOutput({hash:e.inputs[0].prevout.hash,index:e.inputs[0].prevout.index},new _({value:r.value})),e.outputs.pop();let a=this.getAddress().toString(this.network);t&&(s={cid:r.cid,uid:t},a=(s=await this.tokenCreate(s,t)).data.addr),e.outputs.push(_.fromScript(a,r.value,{oper:W.propExchange,pid:r.pid,cid:r.cid,oid:r.oid,prev:{hash:i.hash,index:i.index}})),t?await this.fund(e,{allowPreInput:!0,account:t}):await this.fund(e,{allowPreInput:!0}),await this.sign(e,null,N.ALL,[0]);var s=e.commit();return await this.db.send(s[0]),r.simAddr=a,[s[0],null,r]}async belongToAccount(e,t){return!!t&&!(!(t=await this.getAccountByAddress(t))||e&&t.name!==e)}async propExchange(e,t,i){let a=null,s=0;var n;return Array.isArray(e)?(a=e[0],s=e[1]):(n=await this.getTX(e.hash))&&(a=n.tx,s=e.index),!a||!a.outputs||a.outputs.length<=s?(this.logger.error("Invalid tx info."),null):await this.ownedAddress(a.outputs[s].getAddress())?(n=a.outputs[s].getReturnData())?(e=(new w).propExchange(a,s,t),n.index=e.outputs.length-1,i?await this.fund(e,{allowPreInput:!0,account:i}):await this.fund(e,{allowPreInput:!0}),await this.sign(e),t=e.commit(),await this.db.addTX(t[0]),await this.db.send(t[0]),r(t[0].verify(t[1],x.flags.STANDARD_VERIFY_FLAGS)),t.push(n),t):(this.logger.error("Invalid tx info."),null):(this.logger.error("Invalid user."),null)}async propFound(e,t,i){if(e=await this.getTX(e),r(e),!(e=e.tx))throw new F(L.errors.TYPE_ERROR,"Invalid hex string.");var a=e.outputs[t],s=a.getReturnData();if(!s||s.oper!==W.propExchange&&s.oper!==W.propCreate)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");if(s.cid==this.network.genesisId)throw new Y(block,"invalid","prop found supertoken",100);var n=new w;n.addInputFromTx(e,t),e=_.fromScript(a.getAddress(),a.value),n.outputs.push(e),i?await this.fund(n,{allowPreInput:!0,subtractFee:!0,account:i}):await this.fund(n,{allowPreInput:!0,subtractFee:!0}),await this.sign(n),t=n.commit();return await this.db.send(t[0]),r(t[0].verify(t[1],x.flags.STANDARD_VERIFY_FLAGS)),t.push(s),t}async propSale(e,t,i,a){let s=await this.getTX(e);if(!s)throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");if(s.getDepth(this.db.curHeight)<=0)throw new F(L.errors.TYPE_ERROR,"No enough confirmations.");if(!(s=s.tx))throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");var n=s.outputs[t].getReturnData([x.opcodes.OP_PROPEXCHANGE,x.opcodes.OP_PROPCREATE]);if(!n)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");if(!await this.ownedAddress(s.outputs[t].getAddress()))throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");var o=await this.getCoin(e,t);if(!o||-1===o.height)throw new F(L.errors.WALLET_INSUFFICIENT_FUNDS,"Invalid coin.");if(await this.txdb.isSpent(e,t))throw new F(L.errors.WALLET_INSUFFICIENT_FUNDS,"Invalid coin.");if(i<=s.outputs[t].value)throw new F(L.errors.TYPE_ERROR,"Invalid fixed price.");if(n.cid==this.network.genesisId)throw new Y(s,"invalid","prop not for sale",100);return e=(o=new w).addInputFromTx(s,t),t={oper:W.propSale,pid:n.pid,prev:{hash:e.prevout.hash,index:e.prevout.index},fixed:i,period:this.db.curHeight+O.BLOCK_DAY},n=_.fromScript(x.createScript(Buffer.from(JSON.stringify(t)),x.types.NULLDATA),0),o.outputs.push(n),await this.sign(o,null,N.SINGLE|N.ANYONECANPAY),e=o.commit(),r(e[0].verify(e[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.send(e[0]),e}async propBuy(e,t,i){let r=null;try{(a=await this.db.client.execute("getPropById",[e]))&&(r=a[0])}catch(e){console.log("remote get prop by id",e.message)}if(!(r=r||this.db.propList.get(e))||r.pst!=$.Sale||!r.bid||!r.bid.raw)throw new F(L.errors.INVALID_PARAMS,"Invalid Tx Hash.");var a=H.fromRaw(Buffer.from(r.bid.raw,"hex")),s=(e=(await this.createReceive(i)).getAddress(),r.gold);if(t<s)throw new Error("wrong price");if(1<a.outputs.length&&t<a.outputs[1].value)throw new Error("low bid price than before");var n=w.fromTX(a,1);if(!n.outputs[0].getReturnType(B.OP_RETURN))throw new Error("not a sale order");return await this.remove(a.hash("hex")),n.view.addOutput({hash:n.inputs[0].prevout.hash,index:n.inputs[0].prevout.index},new _({value:r.gold})),t=new _({address:r.current.address,value:t}),n.addOutput(t),t={oper:W.propExchange,pid:r.pid,cid:r.cid,oid:r.oid,prev:{hash:n.inputs[0].prevout.hash,index:n.inputs[0].prevout.index}},e=_.fromScript(e,s,t),n.outputs.push(e),i?await this.fund(n,{allowPreInput:!0,account:i}):await this.fund(n,{allowPreInput:!0}),await this.sign(n,null,N.ALL,[0]),s=n.commit(),r.owned||this.db.client.watchOutpoint((new D).fromOptions(a.inputs[0].prevout)),await this.db.send(s[0]),s}async getTXByAmount(e,t){let i=null;var r;for(r of await this.getCoins(t))if(!(r.height<=0)&&r.value==e){i=r;break}return i&&(t=await this.getTX(i.hash))?[t.tx,i.index,i.height]:[]}async contractCreate(e,t,i,a,s){if(this.db.transactionList.query(e,a)!=K.None)throw new F(L.errors.TYPE_ERROR,"Contract with the same address finded.");if(0!=parseInt(t%1e3,10))throw new F(L.errors.TYPE_ERROR,"Contract source should an integer multiple of 1000.");if(!await U.checkSum(this.network,e,a))throw new F(L.errors.TYPE_ERROR,"Create contract with an invalid Address or a Address with old transations.");let n=!1,[o,c,u]=await this.getTXByAmount(t,s);if(!o){n=!0;var h=new w;let e="";e=(s?await this.createReceive(s):this).getAddress(),h.outputs.push(_.fromScript(e,t)),s?await this.fund(h,{allowPreInput:!0,account:s}):await this.fund(h,{allowPreInput:!0}),await this.sign(h),h=h.commit(),r(h[0].verify(h[1],x.flags.STANDARD_VERIFY_FLAGS)),o=h[0],c=0,u=-1}(h=new w).addInputFromTx(o,c,u);let l="";l=(s?await this.createReceive(s):this).getAddress();var p=await this.getKey(l);e={oper:W.contractCreate,type:e,addr:a,src:t,dst:i,srcact:s,alice:p.getPublicKey("hex"),period:this.db.curHeight+O.TRANSACTION_PERIOD},a=_.fromScript(x.createScript(Buffer.from(JSON.stringify(e)),x.types.NULLDATA),0),h.outputs.push(a),await this.sign(h,null,N.SINGLE|N.ANYONECANPAY),t=h.commit();return n&&await this.db.send(o),await this.db.send(t[0]),t}async contractPromise(e,t){if(!(e=this.db.transactionList.get(e))||e.transStatus!=K.CreatedOnMem)throw new F(L.errors.INVALID_PARAMS,"Invalid Tx id.");if(!(e=H.fromRaw(Buffer.from(e.raw,"hex"))))throw new F(L.errors.TYPE_ERROR,"Invalid Tx id.");var i=U.parseContract(e);if(!i||i.oper!==W.contractCreate)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");var r=w.fromTX(e,1);if(!r.outputs[0].getReturnType(B.OP_RETURN))throw new Error("not a valid contract");r.view.addOutput({hash:r.inputs[0].prevout.hash,index:r.inputs[0].prevout.index},new _({value:i.src}));let a="";a=(t?await this.createReceive(t):this).getAddress();var s=await this.getKey(a);e={oper:W.contractPromise,prevhash:e.hash("hex"),type:i.type,addr:i.addr,dst:i.dst,srcact:i.srcact,dstact:t,bob:s.getPublicKey("hex"),period:i.period},t=new x([z.fromSymbol("promise"),z.fromData(Buffer.from(JSON.stringify(e))),z.fromSymbol("drop"),z.fromSymbol("greaterthan"),z.fromSymbol("drop"),z.fromSymbol("if"),z.fromData(l.hash160(Buffer.from(e.bob,"hex"))),z.fromSymbol("else"),z.fromData(l.hash160(Buffer.from(i.alice,"hex"))),z.fromSymbol("endif"),z.fromSymbol("checksig")]),r.outputs.push(_.fromScript(t,i.src)),await this.remove(e.prevhash),await this.sign(r,null,N.ALL,[0]),s=r.commit();return await this.db.send(s[0]),e.current={hash:s[0].hash("hex"),index:0},e.raw=s[0].toRaw().toString("hex"),e.transStatus=K.Promised,this.db.transactionList.saveContract(e,!0),s}async contractExecute(e,t){if(!(e=this.db.transactionList.get(e))||e.transStatus!=K.Confirmed&&e.transStatus!=K.Expired)throw new F(L.errors.INVALID_PARAMS,"Invalid Tx id.");if(!(e=H.fromRaw(Buffer.from(e.raw,"hex"))))throw new F(L.errors.TYPE_ERROR,"Invalid Tx id.");t=t||1;var i=U.parseContract(e);if(!i||i.oper!==W.contractPromise)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");var a=e.outputs[1].getReturnData();if(!a||a.oper!==W.contractPromise)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");r.strictEqual(i.addr,a.addr),r.strictEqual(i.type,a.type),r.strictEqual(i.dst,a.dst),r.strictEqual(i.period,a.period),r.strictEqual(i.srcact,a.srcact),r.strictEqual(i.dstact,a.dstact);var s=this.db.transactionList.query(i.type,i.addr);if(s!=K.Confirmed&&s!=K.Expired)throw new F(L.errors.TYPE_ERROR,"Contract Promise not Check yet.");if(s==K.Expired&&1!=t||s==K.Confirmed&&2!=t)throw new F(L.errors.TYPE_ERROR,"Invalid Executor.");let n=i.srcact,o=(2==t&&(n=i.dstact),"");o=(n?await this.createReceive(n):this).getAddress();var c=new w,u=(c.addInputFromTx(e,1),{oper:W.contractExecute,type:i.type,addr:i.addr,master:t});u=_.fromScript(x.createScript(Buffer.from(JSON.stringify(u)),x.types.NULLDATA),0),c.outputs.push(u),u=_.fromScript(o,e.outputs[1].value),c.outputs.push(u),e=1==t?await P.fromPublic(Buffer.from(i.ori.alice,"hex")):await P.fromPublic(Buffer.from(a.bob,"hex")),u=await this.getKey(e.getAddress()),await c.signAsync(u,x.hashType.ALL,this.db.workers),t=c.commit();return r(t[0].verify(t[1],x.flags.STANDARD_VERIFY_FLAGS,s)),await this.db.send(t[0]),t}async htlcDeal(e,t){var i=await this.getTX(e.hash);let r=null;if(t){if(!(t=await this.getAccount(t)))throw new F(L.errors.TYPE_ERROR,"Invalid Account.");r=t.getReceive().toString()}else r=this.getReceive().toString();t=new w;var a=(new x).pushOp(B.OP_1);e.suggest&&a.pushData(Buffer.from(e.sa,"hex")),t.addInput({prevout:{hash:e.hash,index:e.index},script:a}),t.addOutput(r,i.tx.outputs[e.index].value-1e4),t.view.addOutput({hash:e.hash,index:e.index},new _(i.tx.outputs[e.index])),await this.sign(t,null,N.ALL),a=t.commit();return await this.db.send(a[0]),a}async htlcCancel(e,t){let i=null;var r=await this.getTX(e.hash);if(!(i=r?r.tx.outputs[e.index]:i))throw new F(L.errors.TYPE_ERROR,"Invalid Input.");let a=null;if(t){if(!(r=await this.getAccount(t)))throw new F(L.errors.TYPE_ERROR,"Invalid Account.");a=r.getReceive().toString()}else a=this.getReceive().toString();return t=new w,r=(new x).pushOp(B.OP_0),e.suggest&&r.pushData(Buffer.from(e.sa,"hex")),t.addInput({prevout:{hash:e.hash,index:e.index},script:r}),e.suggest?t.setSequence(0,2*O.HTLC_CANCEL_PERIOD,!1):t.setSequence(0,O.HTLC_CANCEL_PERIOD,!1),t.addOutput(a,i.value-1e4),t.view.addOutput({hash:e.hash,index:e.index},new _(i)),r=await this.getKey(e.master),await t.signAsync(r,x.hashType.ALL,this.db.workers),e=t.commit(),await this.db.send(e[0]),e}async sendContracts(e,t,i){var r,a=new w;for(r of e)a.outputs.push(i.create(r));return t?await this.fund(a,{account:t}):await this.fund(a),await this.sign(a),e=a.commit(),await this.db.addTX(e[0]),await this.db.send(e[0]),e}async tokenCreate(e,t="",i){r(e&&"object"==typeof e,"Token data should be a object"),r(e.cid,"Token data should has a cid property"),r(e.uid,"Token data should has a uid property"),e.time=!0,await this.ensureAccount({name:t,witness:!0});let a=null;if(i){if(!await this.belongToAccount(t,i))throw new F(L.errors.TYPE_ERROR,`tokenCreate address error: addr:${i} is not belongs to account:`+t);a=await this.getKey(i)}else a=await this.createReceive(t,n.hashInt(e.cid),this.master);return a.signData(e)}async sign(e,t,i=x.hashType.ALL,r){if(this.watchOnly)throw new Error("Cannot sign from a watch-only wallet.");return await this.unlock(t),t=await this.deriveInputs(e),e.signAsync(t,i,this.db.workers,r)}getCoinView(e){return this.txdb.getCoinView(e)}getSpentView(e){return this.txdb.getSpentView(e)}toDetails(e){return this.txdb.toDetails(e)}getDetails(e){return this.txdb.getDetails(e)}async getCoin(e,t){return this.txdb.getCoin(e,t)}async getCredit(e,t){return this.txdb.getCredit(e,t)}async getStatusOfSC(e){return this.txdb.getStatusOfSC(e)}async setStatusOfSC(e,t){var i=await this.writeLock.lock();try{this.txdb.start();try{await this.txdb._setStatusOfSC(e,t),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}}finally{i()}}getLockedCoins(){return this.txdb.lockedCoins.values}getTX(e){return this.txdb.getTX(e)}getBlocks(){return this.txdb.getBlocks()}getBlock(e){return this.txdb.getBlock(e)}async add(e,t,i){var r=await this.writeLock.lock();try{return await this._add(e,t,i)}finally{r()}}async _add(e,t,i){let r,a;this.txdb.start();try{(r=await this.txdb._add(e,t,i))&&(a=await this.syncOutputDepth(r)),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}return a&&0<a.length&&(this.db.emit("address",this.id,a),this.emit("address",a)),r}async resetBalance(){var e=await this.writeLock.lock();try{this.txdb.start();try{this.txdb.pending.unconfirmed=0,this.txdb.pending.confirmed=0;for(const e of await this.getAccounts()){var t=await this.getBalance(e);this.txdb.pending.unconfirmed+=t.unconfirmed,this.txdb.pending.confirmed+=t.confirmed}this.txdb.put(te.R,this.txdb.pending.commit()),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}}finally{e()}return this.txdb.state.toBalance()}async unconfirm(e){var t=await this.writeLock.lock();try{return await this.txdb.unconfirm(e)}finally{t()}}async remove(e){var t=await this.writeLock.lock();try{return await this.txdb.remove(e)}finally{t()}}async zap(e,t){var i=await this.writeLock.lock();try{return await this._zap(e,t)}finally{i()}}async _zap(e,t){return e=await this.ensureIndex(e),this.txdb.zap(e,t)}async abandon(e){var t=await this.writeLock.lock();try{return await this._abandon(e)}finally{t()}}_abandon(e){return this.txdb.abandon(e)}conserveCoin(e){return this.txdb.conserveCoin(e)}unConserveCoin(e){return this.txdb.unConserveCoin(e)}isConserved(e){return this.txdb.isConserved(e)}getConserved(){return this.txdb.getConserved()}async getHistory(e){return e=await this.ensureIndex(e),this.txdb.getHistory(e)}async getCoins(e){return e=await this.ensureIndex(e),this.txdb.getCoins(e)}async getCredits(e){return e=await this.ensureIndex(e),this.txdb.getCredits(e)}async getSmartCoins(e){var t=[];for(const r of await this.getCredits(e)){var i=r.coin;r.spent||this.txdb.isConserved(i)||-1===i.height&&!r.own||t.push(i)}return t}async getPending(e){return e=await this.ensureIndex(e),this.txdb.getPending(e)}async getBalance(e){return e=await this.ensureIndex(e),this.txdb.getBalance(e)}async queryBalanceLog(e,t=0){return(e=await this.ensureIndex(e))?this.db.queryBalanceLog(this.wid,e,t):[]}async getRange(e,t){return e&&"object"==typeof e&&(t=e,e=null),e=await this.ensureIndex(e),this.txdb.getRange(e,t)}async getLast(e,t){return e=await this.ensureIndex(e),this.txdb.getLast(e,t)}async ensureIndex(e,t){if(null==e){if(t)throw new Error("No account provided.");return null}if(-1===(t=await this.getAccountIndex(e)))throw new Error("Account not found.");return t}getAddress(e){return this.account.getAddress(e)}getReceive(e){return this.account.getReceive(e)}getChange(e){return this.account.getChange(e)}getNested(e){return this.account.getNested(e)}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(e){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(e),account:this.account.toJSON(!0)}}getSize(){var e=0;return(e+=50)+o.sizeVarString(this.id,"ascii")+o.sizeVarlen(this.master.getSize())}toRaw(){var e=this.getSize();return(e=new f(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(e){e=new d(e);var t=s.fromMagic(e.readU32());return 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()),r(t===this.db.network,"Wallet network mismatch."),this}static fromRaw(e,t){return new re(e).fromRaw(t)}static isWallet(e){return e instanceof re}async issueCreate(e,t,i){var r=new G(e),a=((a=(r.source.subjectName||(r.source.subjectName=r.erid),P.fromPrivate(Buffer.from(e.key,"hex"),!0,this.network))).witness=!0,r.sign(a,!0,this.network),r.toOptions(!0));return i?this.send({outputs:[{address:e.address,value:1e4}],comment:a},t):(r=await this.send({outputs:[{address:e.address,value:1e4}],comment:a},t),a.txid=r.txid()),a}async caAbolish(e,t,i){var r=P.fromPrivate(Buffer.from(e.key,"hex"),!0,this.network),a=(r.witness=!0,await this.db.client.execute("ca.byId",[e.erid]));if(!a)throw new F(L.errors.TYPE_ERROR,"ca.abolish: Invalid erid.");if(a.source.cid!=e.cid)throw new F(L.errors.TYPE_ERROR,"ca.abolish: Invalid cid.");if(a.source.uid!=e.uid)throw new F(L.errors.TYPE_ERROR,"ca.abolish: Invalid uid.");var s=a.signature;if(a.sign(r,!0,this.network),a.witness!=e.witness||a.signature!=s)throw new F(L.errors.TYPE_ERROR,"ca.abolish: You have no permission to abolish this witness.");return(a=new X(e)).sign(r),s=a.toOptions(!0),i?this.send({outputs:[{address:e.address,value:1e4}],comment:s},t):await this.send({outputs:[{address:e.address,value:1e4}],comment:s},t),s}async enchanceCp(e,t){var i=((e=new J(e)).oper="enchanceCp",await this.ensureCp(e.to)),r=await this.ensureCp(e.from);if(!(r=await this.getKey(r.pubAddress)))throw new F(L.errors.TYPE_ERROR,"Invalid cid, Not along to this wallet.");return e.sign(r),r=e.toOptions(!0),[await this.send({outputs:[{address:i.pubAddress,value:1e4}],comment:r},t),r]}async ensureCp(e,t=!1){if(await this.db.flushCP([e]),(e=this.db.cpList.getItem(e))||t)return e;throw new F(L.errors.TYPE_ERROR,"Invalid cid, cannot find cp.")}}e.exports=re},function(e,t,i){"use strict";
|
|
286
286
|
/*!
|
|
287
287
|
* BlockMeta.js - walletdb records
|
|
288
288
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -319,7 +319,7 @@ const r=i(19).opcodes;function a(e){let t=null;return new(0,(a.list[e.type]||a.l
|
|
|
319
319
|
* merkleblock.js - merkleblock object for vallnet
|
|
320
320
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
321
321
|
* https://github.com/bookmansoft/gamegold
|
|
322
|
-
*/const r=i(0),a=i(2),s=i(1),n=i(4),o=i(3),c=i(6),u=i(7);var h=i(115);const l=i(89),p=Buffer.from([0]);class d extends h{constructor(e){super(),this.txs=[],this.hashes=[],this.flags=p,this.totalTX=0,this._tree=null,e&&this.fromOptions(e)}fromOptions(e){if(this.parseOptions(e),r(e,"MerkleBlock data is required."),r(Array.isArray(e.hashes)),r(Buffer.isBuffer(e.flags)),r(a.isU32(e.totalTX)),e.hashes)for(var t of e.hashes)"string"==typeof t&&(t=Buffer.from(t,"hex")),r(Buffer.isBuffer(t)),this.hashes.push(t);return e.flags&&(r(Buffer.isBuffer(e.flags)),this.flags=e.flags),null!=e.totalTX&&(r(a.isU32(e.totalTX)),this.totalTX=e.totalTX),this}static fromOptions(e){return(new d).fromOptions(e)}refresh(e){if(this._refresh(),this._tree=null,e)for(const e of this.txs)e.refresh()}hasTX(e){return-1!==this.indexOf(e)}indexOf(e){return null==(e=this.getTree().map.get(e))?-1:e}verifyBody(){var[e]=this.checkBody();return e}checkBody(){return this.getTree().root!==this.merkleRoot?[!1,"bad-txnmrklroot",100]:[!0,"valid",0]}getTree(){if(!this._tree)try{this._tree=this.extractTree()}catch(e){this._tree=new f}return this._tree}extractTree(){const e=[],t=[],i=new Map,r=this.hashes,a=this.flags,s=this.totalTX;let n=0,h=0,l=!1,p=0;const d=e=>s+(1<<e)-1>>>e,m=(s,u)=>{if(n>=8*a.length)return l=!0,o.ZERO_HASH;var p,f=a[n/8|0]>>>n%8&1;if(n++,0===s||!f)return h>=r.length?(l=!0,o.ZERO_HASH):(p=r[h++],0===s&&f&&(f=p.toString("hex"),e.push(p),t.push(u),i.set(f,u)),p);let g;return f=m(s-1,2*u),2*u+1<d(s-1)?(g=m(s-1,2*u+1)).equals(f)&&(l=!0):g=f,c.root256(f,g)};if(0===s)throw new Error("Zero transactions.");if(s>(u.MAX_BLOCK_SIZE-81)/60)throw new Error("Too many transactions.");if(r.length>s)throw new Error("Too many hashes.");if(8*a.length<r.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(((n+7)/8|0)!==a.length)throw new Error("Too many flag bits.");if(h!==r.length)throw new Error("Incorrect number of hashes.");return new f(g,e,t,i)}getCoinbaseHeight(){return-1}inspect(){return this.format()}format(e,t){return{hash:this.rhash(),height:null!=t?t:-1,date:a.date(this.time),version:a.hex32(this.version),prevBlock:a.revHex(this.prevBlock),merkleRoot:a.revHex(this.merkleRoot),time:this.time,bits:this.bits,nonce:this.nonce,totalTX:this.totalTX,hashes:this.hashes.map(e=>e.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(e){this.writeHead(e),e.writeU32(this.totalTX),e.writeVarint(this.hashes.length);for(const t of this.hashes)e.writeHash(t);return e.writeVarBytes(this.flags),e}toRaw(){var e=this.getSize();return this.toWriter(new n(e)).render()}fromReader(e){this.readHead(e),this.totalTX=e.readU32();var t=e.readVarint();for(let i=0;i<t;i++)this.hashes.push(e.readHash());return this.flags=e.readVarBytes(),this}fromRaw(e){return this.fromReader(new s(e))}static fromReader(e){return(new d).fromReader(e)}static fromRaw(e,t){return"string"==typeof e&&(e=Buffer.from(e,t)),(new d).fromRaw(e)}toJSON(){return this.getJSON()}getJSON(e,t,i){return{hash:this.rhash(),height:i,version:this.version,prevBlock:a.revHex(this.prevBlock),merkleRoot:a.revHex(this.merkleRoot),time:this.time,bits:this.bits,nonce:this.nonce,totalTX:this.totalTX,hashes:this.hashes.map(e=>a.revHex(e.toString("hex"))),flags:this.flags.toString("hex")}}fromJSON(e){for(var t of(r(e,"MerkleBlock data is required."),r(Array.isArray(e.hashes)),r("string"==typeof e.flags),r(a.isU32(e.totalTX)),this.parseJSON(e),e.hashes))t=a.revHex(t),this.hashes.push(Buffer.from(t,"hex"));return this.flags=Buffer.from(e.flags,"hex"),this.totalTX=e.totalTX,this}static fromJSON(e){return(new d).fromJSON(e)}static fromBlock(e,t){var i=[];for(const r of e.txs)i.push(r.isWatched(t)?1:0);return d.fromMatches(e,i)}static fromHashes(e,t){var i,r=new Set;for(i of t)Buffer.isBuffer(i)&&(i=i.toString("hex")),r.add(i);var a=[];for(const t of e.txs){var s=t.hash("hex");a.push(r.has(s)?1:0)}return d.fromMatches(e,a)}static fromMatches(e,t){var i=[],r=[];const a=[],s=[],n=e.txs.length;let o=0;const u=e=>n+(1<<e)-1>>>e,h=(e,t,i)=>{if(0===e)return i[t];var r=h(e-1,2*t,i);let a;return a=2*t+1<u(e-1)?h(e-1,2*t+1,i):r,c.root256(r,a)},l=(e,t,i,r)=>{let o=0;for(let i=t<<e;i<t+1<<e&&i<n;i++)o|=r[i];a.push(o),0!==e&&o?(l(e-1,2*t,i,r),2*t+1<u(e-1)&&l(e-1,2*t+1,i,r)):s.push(h(e,t,i))};for(let a=0;a<e.txs.length;a++){var p=e.txs[a];t[a]&&i.push(p),r.push(p.hash())}for(;1<u(o);)o++;l(o,0,r,t);var f=Buffer.allocUnsafe((a.length+7)/8|0);f.fill(0);for(let e=0;e<a.length;e++)f[e/8|0]|=a[e]<<e%8;var m=new d;return m._hash=e._hash,m._hhash=e._hhash,m.version=e.version,m.prevBlock=e.prevBlock,m.merkleRoot=e.merkleRoot,m.time=e.time,m.bits=e.bits,m.nonce=e.nonce,m.totalTX=n,m.hashes=s,m.flags=f,m.txs=i,m}static isMerkleBlock(e){return e instanceof d}toHeaders(){return l.fromBlock(this)}}function f(e,t,i,r){this.root=e?e.toString("hex"):o.NULL_HASH,this.matches=t||[],this.indexes=i||[],this.map=r||new Map}e.exports=d},function(e,t,i){const r=i(5).PropStatus;i=i(31);class a extends i{constructor(e){super(),this.db=e||{getVp:async e=>this.get(e),setVp:e=>{this.set(e.pid,e)},delVp:e=>{this.delete(e)},loadVpList:()=>{},save:()=>{}},this.pending=[]}async loadHistory(){}setAccount(e,t,i){var r;e&&e.wid&&e.account&&(r=e.wid+"."+e.account,this.account.get(r))&&this.account.get(r).delete(e.pid),e.wid=t,e.account=i,t&&i&&(r=e.wid+"."+e.account,this.account.get(r)||this.account.set(r,new Map),this.account.get(r).set(e.pid,e))}delAccount(e){var t;e&&e.wid&&e.account&&(t=e.wid+"."+e.account,this.account.get(t))&&this.account.get(t).delete(e.pid)}async getVp(e){return this.get(e)||this.db.getVp(e)}async getVpByAddress(e){return this.db.getVpByAddress(e)}async getVpByOid(e){return this.db.getVpByOid(e)}async setVp(e,t){e=new s(e),this.set(e.pid,e),this.pending.push({oper:"set",data:{data:e,tx:t}})}async delVp(e){this.delete(e.pid),this.pending.push({oper:"unset",data:{data:e}})}async save(){for(var e=[];0<this.pending.length;){var t=this.pending.shift();switch(t.oper){case"set":e.push(this.db.setVp(t.data.data,t.data.tx));break;case"unset":e.push(this.db.delVp(t.data.data))}}await Promise.all(e)}}class s{constructor(e){this.fromOptions(e=e||{})}fromOptions(e){this.pid=e.pid,this.cid=e.cid||"",this.oid=e.oid||"",this.gold=e.gold,this.current=null,e.current&&(this.current={},this.current.hash=e.current.hash,this.current.index=e.current.index,this.current.address=e.current.address),this.height=e.height,this.pst=e.pst||r.Ready,this.wid=e.wid||0,this.account=e.account||"",this.bid=null,e.bid&&(this.bid={},this.bid.raw=e.bid.raw||"",this.bid.fixed=e.bid.fixed||0,this.bid.period=e.bid.period||0,this.bid.hash=e.bid.hash||"",this.bid.value=e.bid.value||0,this.bid.address=e.bid.address||"")}toRaw(){var e={};return e.pid=this.pid,e.cid=this.cid||"",e.oid=this.oid||"",e.gold=this.gold,this.current&&(e.current={},e.current.hash=this.current.hash,e.current.index=this.current.index,e.current.address=this.current.address),e.height=this.height,e.pst=this.pst||r.Ready,e.wid=this.wid||0,e.account=this.account||"",this.bid&&(e.bid={},e.bid.raw=this.bid.raw||"",e.bid.fixed=this.bid.fixed||0,e.bid.period=this.bid.period||0,e.bid.hash=this.bid.hash||"",e.bid.value=this.bid.value||0,e.bid.address=this.bid.address||""),Buffer.from(JSON.stringify(e),"utf-8")}fromRaw(e){return e=JSON.parse(e.toString("utf8")),this.fromOptions(e),this}static fromRaw(e){return(new s).fromRaw(e)}}a.vpItem=s,e.exports=a},function(e,t,i){var r=i(10),a=i(175),s=(i=i(9),{sha1:!0,sha256:!0,sha512:!0}),n={rsa:!0,dsa:!0,ecdsa:!0};function o(e,t){Error.captureStackTrace&&Error.captureStackTrace(this,t||o),this.message=e,this.name=t.name}function c(e){o.call(this,e,c)}i.inherits(o,Error),i.inherits(c,o),e.exports={HASH_ALGOS:s,PK_ALGOS:n,HttpSignatureError:o,InvalidAlgorithmError:c,validateAlgorithm:function(e){if(2!==(e=e.toLowerCase().split("-")).length)throw new c(e[0].toUpperCase()+" is not a valid algorithm");if("hmac"!==e[0]&&!n[e[0]])throw new c(e[0].toUpperCase()+" type keys are not supported");if(s[e[1]])return e;throw new c(e[1].toUpperCase()+" is not a supported hash algorithm")},sshKeyToPEM:function(e){return r.string(e,"ssh_key"),a.parseKey(e,"ssh").toString("pem")},fingerprint:function(e){return r.string(e,"ssh_key"),a.parseKey(e,"ssh").fingerprint("md5").toString("hex")},pemToRsaSSHKey:function(e,t){return r.equal("string",typeof e,"typeof pem"),(e=a.parseKey(e,"pem")).comment=t,e.toString("ssh")}}},function(e,t,i){var r=i(102).BigInteger,a=r.prototype.Barrett;function s(e,t){this.x=t,this.q=e}function n(e,t,i,a){this.curve=e,this.x=t,this.y=i,this.z=null==a?r.ONE:a,this.zinv=null}function o(e,t,i){this.q=e,this.a=this.fromBigInteger(t),this.b=this.fromBigInteger(i),this.infinity=new n(this,null,null),this.reducer=new a(this.q)}s.prototype.equals=function(e){return e==this||this.q.equals(e.q)&&this.x.equals(e.x)},s.prototype.toBigInteger=function(){return this.x},s.prototype.negate=function(){return new s(this.q,this.x.negate().mod(this.q))},s.prototype.add=function(e){return new s(this.q,this.x.add(e.toBigInteger()).mod(this.q))},s.prototype.subtract=function(e){return new s(this.q,this.x.subtract(e.toBigInteger()).mod(this.q))},s.prototype.multiply=function(e){return new s(this.q,this.x.multiply(e.toBigInteger()).mod(this.q))},s.prototype.square=function(){return new s(this.q,this.x.square().mod(this.q))},s.prototype.divide=function(e){return new s(this.q,this.x.multiply(e.toBigInteger().modInverse(this.q)).mod(this.q))},n.prototype.getX=function(){null==this.zinv&&(this.zinv=this.z.modInverse(this.curve.q));var e=this.x.toBigInteger().multiply(this.zinv);return this.curve.reduce(e),this.curve.fromBigInteger(e)},n.prototype.getY=function(){null==this.zinv&&(this.zinv=this.z.modInverse(this.curve.q));var e=this.y.toBigInteger().multiply(this.zinv);return this.curve.reduce(e),this.curve.fromBigInteger(e)},n.prototype.equals=function(e){return e==this||(this.isInfinity()?e.isInfinity():e.isInfinity()?this.isInfinity():!!e.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(e.z)).mod(this.curve.q).equals(r.ZERO)&&e.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(e.z)).mod(this.curve.q).equals(r.ZERO))},n.prototype.isInfinity=function(){return null==this.x&&null==this.y||this.z.equals(r.ZERO)&&!this.y.toBigInteger().equals(r.ZERO)},n.prototype.negate=function(){return new n(this.curve,this.x,this.y.negate(),this.z)},n.prototype.add=function(e){var t,i,a,s,o,c,u;return this.isInfinity()?e:e.isInfinity()?this:(t=e.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(e.z)).mod(this.curve.q),o=e.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(e.z)).mod(this.curve.q),r.ZERO.equals(o)?r.ZERO.equals(t)?this.twice():this.curve.getInfinity():(u=new r("3"),c=this.x.toBigInteger(),i=this.y.toBigInteger(),e.x.toBigInteger(),e.y.toBigInteger(),a=(s=o.square()).multiply(o),c=c.multiply(s),o=(s=t.square().multiply(this.z)).subtract(c.shiftLeft(1)).multiply(e.z).subtract(a).multiply(o).mod(this.curve.q),c=c.multiply(u).multiply(t).subtract(i.multiply(a)).subtract(s.multiply(t)).multiply(e.z).add(t.multiply(a)).mod(this.curve.q),u=a.multiply(this.z).multiply(e.z).mod(this.curve.q),new n(this.curve,this.curve.fromBigInteger(o),this.curve.fromBigInteger(c),u)))},n.prototype.twice=function(){var e,t,i,a,s,o;return this.isInfinity()?this:0==this.y.toBigInteger().signum()?this.curve.getInfinity():(s=new r("3"),o=this.x.toBigInteger(),t=(e=(t=this.y.toBigInteger()).multiply(this.z)).multiply(t).mod(this.curve.q),a=this.curve.a.toBigInteger(),i=o.square().multiply(s),a=(i=(i=r.ZERO.equals(a)?i:i.add(this.z.square().multiply(a))).mod(this.curve.q)).square().subtract(o.shiftLeft(3).multiply(t)).shiftLeft(1).multiply(e).mod(this.curve.q),s=i.multiply(s).multiply(o).subtract(t.shiftLeft(1)).shiftLeft(2).multiply(t).subtract(i.square().multiply(i)).mod(this.curve.q),o=e.square().multiply(e).shiftLeft(3).mod(this.curve.q),new n(this.curve,this.curve.fromBigInteger(a),this.curve.fromBigInteger(s),o))},n.prototype.multiply=function(e){if(this.isInfinity())return this;if(0==e.signum())return this.curve.getInfinity();for(var t=e,i=t.multiply(new r("3")),a=this.negate(),s=this,n=i.bitLength()-2;0<n;--n){s=s.twice();var o=i.testBit(n);o!=t.testBit(n)&&(s=s.add(o?this:a))}return s},n.prototype.multiplyTwo=function(e,t,i){for(var r=e.bitLength()>i.bitLength()?e.bitLength()-1:i.bitLength()-1,a=this.curve.getInfinity(),s=this.add(t);0<=r;)a=a.twice(),e.testBit(r)?a=i.testBit(r)?a.add(s):a.add(this):i.testBit(r)&&(a=a.add(t)),--r;return a},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(e){return e==this||this.q.equals(e.q)&&this.a.equals(e.a)&&this.b.equals(e.b)},o.prototype.getInfinity=function(){return this.infinity},o.prototype.fromBigInteger=function(e){return new s(this.q,e)},o.prototype.reduce=function(e){this.reducer.reduce(e)},o.prototype.encodePointHex=function(e){if(e.isInfinity())return"00";var t=e.getX().toBigInteger().toString(16),i=e.getY().toBigInteger().toString(16),r=this.getQ().toString(16).length;for(r%2!=0&&r++;t.length<r;)t="0"+t;for(;i.length<r;)i="0"+i;return"04"+t+i},o.prototype.decodePointHex=function(e){switch(parseInt(e.substr(0,2),16)){case 0:return this.infinity;case 2:c=!1;case 3:null==c&&(c=!0);var t=e.length-2,i=e.substr(2,t),a=this.fromBigInteger(new r(i,16)),s=a.multiply(a.square().add(this.getA())).add(this.getB()).sqrt();if(null==s)throw"Invalid point compression";var o=s.toBigInteger();return o.testBit(0)!=c&&(s=this.fromBigInteger(this.getQ().subtract(o))),new n(this,a,s);case 4:case 6:case 7:t=(e.length-2)/2,i=e.substr(2,t);var c=e.substr(t+2,t);return new n(this,this.fromBigInteger(new r(i,16)),this.fromBigInteger(new r(c,16)));default:return null}},o.prototype.encodeCompressedPointHex=function(e){if(e.isInfinity())return"00";var t=e.getX().toBigInteger().toString(16),i=this.getQ().toString(16).length;for(i%2!=0&&i++;t.length<i;)t="0"+t;return(e.getY().toBigInteger().isEven()?"02":"03")+t},s.prototype.getR=function(){var e;return null==this.r&&(this.r=null,128<(e=this.q.bitLength())&&-1==this.q.shiftRight(e-64).intValue())&&(this.r=r.ONE.shiftLeft(e).subtract(this.q)),this.r},s.prototype.modMult=function(e,t){return this.modReduce(e.multiply(t))},s.prototype.modReduce=function(e){if(null!=this.getR()){for(var t=q.bitLength();e.bitLength()>t+1;){var i=e.shiftRight(t),a=e.subtract(i.shiftLeft(t));e=(i=this.getR().equals(r.ONE)?i:i.multiply(this.getR())).add(a)}for(;0<=e.compareTo(q);)e=e.subtract(q)}else e=e.mod(q);return e},s.prototype.sqrt=function(){if(!this.q.testBit(0))throw"unsupported";var e;if(this.q.testBit(1))return(e=new s(this.q,this.x.modPow(this.q.shiftRight(2).add(r.ONE),this.q))).square().equals(this)?e:null;var t=this.q.subtract(r.ONE),i=t.shiftRight(1);if(this.x.modPow(i,this.q).equals(r.ONE)){var a,n=t.shiftRight(2).shiftLeft(1).add(r.ONE),o=this.x,c=modDouble(modDouble(o));do{for(;0<=(a=new r(this.q.bitLength(),new SecureRandom)).compareTo(this.q)||!a.multiply(a).subtract(c).modPow(i,this.q).equals(t););var u=(h=this.lucasSequence(a,o,n))[0],h=h[1];if(this.modMult(h,h).equals(c))return h=(h=h.testBit(0)?h.add(q):h).shiftRight(1),new s(q,h)}while(u.equals(r.ONE)||u.equals(t))}return null},s.prototype.lucasSequence=function(e,t,i){for(var a=i.bitLength(),s=i.getLowestSetBit(),n=r.ONE,o=r.TWO,c=e,u=r.ONE,h=r.ONE,l=a-1;s+1<=l;--l)u=this.modMult(u,h),i.testBit(l)?(h=this.modMult(u,t),n=this.modMult(n,c),o=this.modReduce(c.multiply(o).subtract(e.multiply(u))),c=this.modReduce(c.multiply(c).subtract(h.shiftLeft(1)))):(h=u,n=this.modReduce(n.multiply(o).subtract(u)),c=this.modReduce(c.multiply(o).subtract(e.multiply(u))),o=this.modReduce(o.multiply(o).subtract(u.shiftLeft(1))));for(u=this.modMult(u,h),h=this.modMult(u,t),n=this.modReduce(n.multiply(o).subtract(u)),o=this.modReduce(c.multiply(o).subtract(e.multiply(u))),u=this.modMult(u,h),l=1;l<=s;++l)n=this.modMult(n,o),o=this.modReduce(o.multiply(o).subtract(u.shiftLeft(1))),u=this.modMult(u,u);return[n,o]},e.exports={ECCurveFp:o,ECPointFp:n,ECFieldElementFp:s}},function(e,t,i){e.exports={read:function(e,t){return u.read(e,t)},readSSHPrivate:function(e,t,c){var u=(t=new l({buffer:t})).readCString(),f=(a.strictEqual(u,d,"bad magic string"),t.readString()),m=t.readString();u=t.readBuffer();if(1!==t.readInt())throw new Error("OpenSSH-format key file contains multiple keys: this is unsupported.");var g=t.readBuffer();if("public"===e)return a.ok(t.atEnd(),"excess bytes left after key"),h.read(g);var v=t.readBuffer(),y=(a.ok(t.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=y.readBuffer(),w=y.readInt(),x=n.opensshCipherInfo(f);if(void 0===r&&(r=i(276)),"string"==typeof c.passphrase&&(c.passphrase=s.from(c.passphrase,"utf-8")),!s.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!==r.pbkdf(k,k.length,b,b.length,S,S.length,w))throw new Error("bcrypt_pbkdf function returned failure, parameters invalid");k=(S=s.from(S)).slice(0,x.keySize),b=S.slice(x.keySize,x.keySize+x.blockSize);var _=o.createDecipheriv(x.opensslName,k,b);_.setAutoPadding(!1);var E,j=[];for(_.once("error",(function(e){if(-1!==e.toString().indexOf("bad decrypt"))throw new Error("Incorrect passphrase supplied, could not decrypt key");throw e})),_.write(v),_.end();null!==(E=_.read());)j.push(E);v=s.concat(j);break;default:throw new Error('OpenSSH-format key uses unknown KDF "'+m+'"')}if((e=(t=new l({buffer:v})).readInt())!==(g=t.readInt()))throw new Error("Incorrect passphrase supplied, could not decrypt key");return u={},e=h.readInternal(u,"private",t.remainder()),t.skip(u.consumed),g=t.readString(),e.comment=g,e},write:function(e,t){var u;u=c.isPrivateKey(e)?e.toPublic():e;var h,p,f="none",m="none",g=s.alloc(0),v={blockSize:8};if(void 0!==t&&void 0!==(h="string"==typeof(h=t.passphrase)?s.from(h,"utf-8"):h)&&(a.buffer(h,"options.passphrase"),a.optionalString(t.cipher,"options.cipher"),void 0===(f=t.cipher)&&(f="aes128-ctr"),v=n.opensshCipherInfo(f),m="bcrypt"),c.isPrivateKey(e)){p=new l({});t=o.randomBytes(4).readUInt32BE(0);for(var y=(p.writeInt(t),p.writeInt(t),p.write(e.toBuffer("rfc4253")),p.writeString(e.comment||""),1);p._offset%v.blockSize!=0;)p.writeChar(y++);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===r&&(r=i(276)),new Uint8Array(h)),x=(b=new Uint8Array(b),new Uint8Array(v.keySize+v.blockSize));if(0!==r.pbkdf(w,w.length,b,b.length,x,x.length,16))throw new Error("bcrypt_pbkdf function returned failure, parameters invalid");w=(x=s.from(x)).slice(0,v.keySize),b=x.slice(v.keySize,v.keySize+v.blockSize);var k=o.createCipheriv(v.opensslName,w,b);k.setAutoPadding(!1);var S,_=[];for(k.once("error",(function(e){throw e})),k.write(p),k.end();null!==(S=k.read());)_.push(S);p=s.concat(_);break;default:throw new Error("Unsupported kdf "+m)}var E=new l({});E.writeCString(d),E.writeString(f),E.writeString(m),E.writeBuffer(g),E.writeInt(1),E.writeBuffer(u.toBuffer("rfc4253")),p&&E.writeBuffer(p),E=E.toBuffer(),t=c.isPrivateKey(e)?"OPENSSH PRIVATE KEY":"OPENSSH PUBLIC KEY";var j=E.toString("base64"),A=(f=j.length+j.length/70+18+16+2*t.length+10,E=s.alloc(f),0);A+=E.write("-----BEGIN "+t+"-----\n",A);for(var R=0;R<j.length;){var I=R+70;I>j.length&&(I=j.length),A+=E.write(j.slice(R,I),A),E[A++]=10,R=I}return A+=E.write("-----END "+t+"-----\n",A),E.slice(0,A)}};var r,a=i(10),s=(i(58),i(12).Buffer),n=(i(30),i(25)),o=i(8),c=(i(23),i(24)),u=i(65),h=i(66),l=i(91),p=i(51),d="openssh-key-v1"},function(e,t,i){var r=i(52);const a=i(83),s=i(17),n=i(28),o=i(7),c=i(0),{Transform:u,ContractType:h,HtlcStatus:l,ContractEnvType:p}=i(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");e.exports=class extends r{async confirm(){var{env:e,output:t,hash:i,i:r,data:s,height:n}=this.options,o=t.getHashs("hex"),i={type:"suggest",src:a.protocol+"."+e.network.type,dst:s.dst,shash:i,sidx:r,sheight:n,pst:l.Sent,amount:t.value,rate:s.rate,ab:t.script.code[4].data.toString("hex"),aa:o[1],ba:o[0]};await e.setSuggest(i),e.mode==p.Block&&e.node.transmit("htlcsuggest.receive",i)}async unconfirm(){var{env:e,data:t}=this.options,t={shash:t.hash,sidx:t.index};await e.delHtlc(t)}async spent(e){var t=this.options.env,i=t.htlcList.get(""+e.prevout.hash+e.prevout.index);i&&(81==e.script.code[2].value?(i.pst=l.Finished,await t.setSuggest(i),t.mode==p.Block&&t.node.transmit("htlcsuggest.deal",i)):(i.pst=l.Cancel,await t.setSuggest(i),t.mode==p.Block&&t.node.transmit("htlcsuggest.cancel",i)))}async verify(){var{output:e,data:t}=this.options,i=(t={oper:h.htlcSuggest,rate:t.rate,dst:t.dst},e.getHashs("hex")),r=e.script.code[4].data.toString("hex"),t={contract:"0x"+Buffer.from(JSON.stringify(t)).toString("hex"),ab:"0x"+r.toString("hex"),aa:"0x"+i[1].toString("hex"),ba:"0x"+i[0].toString("hex"),period:2*o.HTLC_CANCEL_PERIOD};r=s.fromString(d.replace(t));return c(r.toString()===e.script.toString()),!0}static create(e){var t={oper:h.htlcSuggest,rate:e.rate,dst:e.dst};t={contract:"0x"+Buffer.from(JSON.stringify(t)).toString("hex"),ab:"0x"+e.ab.toString("hex"),aa:"0x"+e.aa.toString("hex"),ba:"0x"+e.ba.toString("hex"),period:2*o.HTLC_CANCEL_PERIOD},t=s.fromString(d.replace(t));return n.fromScript(t,e.amount)}}},function(e,t,i){var r=i(52);const a=i(83),s=i(17),n=i(28),o=i(7),{Transform:c,ContractType:u,HtlcStatus:h,ContractEnvType:l}=i(5),p=i(0),d=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");e.exports=class extends r{async confirm(){var{env:e,i:t,output:i,hash:r,height:s,data:n}=this.options,i=i.getHashs("hex"),r={src:n.src,dst:a.protocol+"."+e.network.type,shash:n.hash,sidx:n.index,ahash:r,aidx:t,aheight:s,pst:h.Assent,amount:n.value,rate:n.rate,ab:i[0],bb:i[1]};await e.setAssent(r),e.mode==l.Block&&e.node.transmit("htlcassent.receive",r)}async unconfirm(){var{env:e,data:t}=this.options,t={shash:t.hash,sidx:t.index};await e.delHtlc(t)}async spent(e){var t=this.options.env,i=t.htlcList.query([["ahash",e.prevout.hash],["aidx",e.prevout.index]]);i&&1===i.list.length&&i.list[0].pst===h.Assent&&(i=i.list[0],81==e.script.code[2].value?(i.secret=e.script.code[1].data.toString("hex"),i.pst=h.Deal,await t.setAssent(i),t.mode==l.Block&&t.node.transmit("htlcassent.deal",i)):(i.pst=h.Cancel,await t.setAssent(i),t.mode==l.Block&&t.node.transmit("htlcassent.cancel",i)))}async verify(){var{output:e,data:t}=this.options,i=(t={oper:u.htlcAssent,hash:t.hash,index:t.index},e.getHashs("hex")),t=s.fromString(d.replace({contract:"0x"+Buffer.from(JSON.stringify(t)).toString("hex"),ab:"0x"+i[0].toString("hex"),bb:"0x"+i[1].toString("hex"),period:o.HTLC_CANCEL_PERIOD}));return p(t.toString()===e.script.toString()),!0}static create(e){var t={oper:u.htlcAssent,hash:e.hash,index:e.index};t=s.fromString(d.replace({contract:"0x"+Buffer.from(JSON.stringify(t)).toString("hex"),ab:"0x"+e.ab.toString("hex"),bb:"0x"+e.bb.toString("hex"),period:o.HTLC_CANCEL_PERIOD}));return n.fromScript(t,e.amount)}}},function(e,t,i){var r=i(52);const a=i(17),s=i(28),n=i(0),{Transform:o,ContractType:c,ContractEnvType:u}=i(5),h=i(13),l=i(72).verifyData,p=new o("\n /*携带合约信息*/\n COMMENT var_contract DROP\n /*Bob确认时执行: 校验Bob签名*/\n DUP HASH160 var_bob EQUALVERIFY CHECKSIG\n");e.exports=class extends r{async insert(){var{env:e,output:t,hash:i,i:r,data:a}=this.options,t=h.fromWitnessPubkeyhash(t.getHash(),e.network).toString(),i={shash:i,sidx:r,alice:a.payload.addr,bob:t,body:a.payload.body};e.mode==u.Wallet&&await e.setComment(i)}async erase(){var{env:e,hash:t,i:i}=this.options,t={shash:t,sidx:i};e.mode==u.Wallet&&await e.delComment(t)}async verify(){var{output:e,data:t}=this.options,i=e.getHash();i=a.fromString(p.replace({contract:"0x"+Buffer.from(JSON.stringify(t)).toString("hex"),bob:"0x"+i.toString("hex")})),n(i.toString()===e.script.toString()),i=t.payload.sig;return delete(t=t.payload).sig,n.strictEqual(!0,l({data:t,sig:i})),!0}static create(e){var t={oper:c.comment,payload:e};t={contract:"0x"+Buffer.from(JSON.stringify(t)).toString("hex"),bob:"0x"+h.fromString(e.bob).hash.toString("hex")},t=a.fromString(p.replace(t));return s.fromScript(t,e.amount)}}},function(e,t,i){"use strict";
|
|
322
|
+
*/const r=i(0),a=i(2),s=i(1),n=i(4),o=i(3),c=i(6),u=i(7);var h=i(115);const l=i(89),p=Buffer.from([0]);class d extends h{constructor(e){super(),this.txs=[],this.hashes=[],this.flags=p,this.totalTX=0,this._tree=null,e&&this.fromOptions(e)}fromOptions(e){if(this.parseOptions(e),r(e,"MerkleBlock data is required."),r(Array.isArray(e.hashes)),r(Buffer.isBuffer(e.flags)),r(a.isU32(e.totalTX)),e.hashes)for(var t of e.hashes)"string"==typeof t&&(t=Buffer.from(t,"hex")),r(Buffer.isBuffer(t)),this.hashes.push(t);return e.flags&&(r(Buffer.isBuffer(e.flags)),this.flags=e.flags),null!=e.totalTX&&(r(a.isU32(e.totalTX)),this.totalTX=e.totalTX),this}static fromOptions(e){return(new d).fromOptions(e)}refresh(e){if(this._refresh(),this._tree=null,e)for(const e of this.txs)e.refresh()}hasTX(e){return-1!==this.indexOf(e)}indexOf(e){return null==(e=this.getTree().map.get(e))?-1:e}verifyBody(){var[e]=this.checkBody();return e}checkBody(){return this.getTree().root!==this.merkleRoot?[!1,"bad-txnmrklroot",100]:[!0,"valid",0]}getTree(){if(!this._tree)try{this._tree=this.extractTree()}catch(e){this._tree=new f}return this._tree}extractTree(){const e=[],t=[],i=new Map,r=this.hashes,a=this.flags,s=this.totalTX;let n=0,h=0,l=!1,p=0;const d=e=>s+(1<<e)-1>>>e,m=(s,u)=>{if(n>=8*a.length)return l=!0,o.ZERO_HASH;var p,f=a[n/8|0]>>>n%8&1;if(n++,0===s||!f)return h>=r.length?(l=!0,o.ZERO_HASH):(p=r[h++],0===s&&f&&(f=p.toString("hex"),e.push(p),t.push(u),i.set(f,u)),p);let g;return f=m(s-1,2*u),2*u+1<d(s-1)?(g=m(s-1,2*u+1)).equals(f)&&(l=!0):g=f,c.root256(f,g)};if(0===s)throw new Error("Zero transactions.");if(s>(u.MAX_BLOCK_SIZE-81)/60)throw new Error("Too many transactions.");if(r.length>s)throw new Error("Too many hashes.");if(8*a.length<r.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(((n+7)/8|0)!==a.length)throw new Error("Too many flag bits.");if(h!==r.length)throw new Error("Incorrect number of hashes.");return new f(g,e,t,i)}getCoinbaseHeight(){return-1}inspect(){return this.format()}format(e,t){return{hash:this.rhash(),height:null!=t?t:-1,date:a.date(this.time),version:a.hex32(this.version),prevBlock:a.revHex(this.prevBlock),merkleRoot:a.revHex(this.merkleRoot),time:this.time,bits:this.bits,nonce:this.nonce,totalTX:this.totalTX,hashes:this.hashes.map(e=>e.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(e){this.writeHead(e),e.writeU32(this.totalTX),e.writeVarint(this.hashes.length);for(const t of this.hashes)e.writeHash(t);return e.writeVarBytes(this.flags),e}toRaw(){var e=this.getSize();return this.toWriter(new n(e)).render()}fromReader(e){this.readHead(e),this.totalTX=e.readU32();var t=e.readVarint();for(let i=0;i<t;i++)this.hashes.push(e.readHash());return this.flags=e.readVarBytes(),this}fromRaw(e){return this.fromReader(new s(e))}static fromReader(e){return(new d).fromReader(e)}static fromRaw(e,t){return"string"==typeof e&&(e=Buffer.from(e,t)),(new d).fromRaw(e)}toJSON(){return this.getJSON()}getJSON(e,t,i){return{hash:this.rhash(),height:i,version:this.version,prevBlock:a.revHex(this.prevBlock),merkleRoot:a.revHex(this.merkleRoot),time:this.time,bits:this.bits,nonce:this.nonce,totalTX:this.totalTX,hashes:this.hashes.map(e=>a.revHex(e.toString("hex"))),flags:this.flags.toString("hex")}}fromJSON(e){for(var t of(r(e,"MerkleBlock data is required."),r(Array.isArray(e.hashes)),r("string"==typeof e.flags),r(a.isU32(e.totalTX)),this.parseJSON(e),e.hashes))t=a.revHex(t),this.hashes.push(Buffer.from(t,"hex"));return this.flags=Buffer.from(e.flags,"hex"),this.totalTX=e.totalTX,this}static fromJSON(e){return(new d).fromJSON(e)}static fromBlock(e,t){var i=[];for(const r of e.txs)i.push(r.isWatched(t)?1:0);return d.fromMatches(e,i)}static fromHashes(e,t){var i,r=new Set;for(i of t)Buffer.isBuffer(i)&&(i=i.toString("hex")),r.add(i);var a=[];for(const t of e.txs){var s=t.hash("hex");a.push(r.has(s)?1:0)}return d.fromMatches(e,a)}static fromMatches(e,t){var i=[],r=[];const a=[],s=[],n=e.txs.length;let o=0;const u=e=>n+(1<<e)-1>>>e,h=(e,t,i)=>{if(0===e)return i[t];var r=h(e-1,2*t,i);let a;return a=2*t+1<u(e-1)?h(e-1,2*t+1,i):r,c.root256(r,a)},l=(e,t,i,r)=>{let o=0;for(let i=t<<e;i<t+1<<e&&i<n;i++)o|=r[i];a.push(o),0!==e&&o?(l(e-1,2*t,i,r),2*t+1<u(e-1)&&l(e-1,2*t+1,i,r)):s.push(h(e,t,i))};for(let a=0;a<e.txs.length;a++){var p=e.txs[a];t[a]&&i.push(p),r.push(p.hash())}for(;1<u(o);)o++;l(o,0,r,t);var f=Buffer.allocUnsafe((a.length+7)/8|0);f.fill(0);for(let e=0;e<a.length;e++)f[e/8|0]|=a[e]<<e%8;var m=new d;return m._hash=e._hash,m._hhash=e._hhash,m.version=e.version,m.prevBlock=e.prevBlock,m.merkleRoot=e.merkleRoot,m.time=e.time,m.bits=e.bits,m.nonce=e.nonce,m.totalTX=n,m.hashes=s,m.flags=f,m.txs=i,m}static isMerkleBlock(e){return e instanceof d}toHeaders(){return l.fromBlock(this)}}function f(e,t,i,r){this.root=e?e.toString("hex"):o.NULL_HASH,this.matches=t||[],this.indexes=i||[],this.map=r||new Map}e.exports=d},function(e,t,i){var r=i(10),a=i(175),s=(i=i(9),{sha1:!0,sha256:!0,sha512:!0}),n={rsa:!0,dsa:!0,ecdsa:!0};function o(e,t){Error.captureStackTrace&&Error.captureStackTrace(this,t||o),this.message=e,this.name=t.name}function c(e){o.call(this,e,c)}i.inherits(o,Error),i.inherits(c,o),e.exports={HASH_ALGOS:s,PK_ALGOS:n,HttpSignatureError:o,InvalidAlgorithmError:c,validateAlgorithm:function(e){if(2!==(e=e.toLowerCase().split("-")).length)throw new c(e[0].toUpperCase()+" is not a valid algorithm");if("hmac"!==e[0]&&!n[e[0]])throw new c(e[0].toUpperCase()+" type keys are not supported");if(s[e[1]])return e;throw new c(e[1].toUpperCase()+" is not a supported hash algorithm")},sshKeyToPEM:function(e){return r.string(e,"ssh_key"),a.parseKey(e,"ssh").toString("pem")},fingerprint:function(e){return r.string(e,"ssh_key"),a.parseKey(e,"ssh").fingerprint("md5").toString("hex")},pemToRsaSSHKey:function(e,t){return r.equal("string",typeof e,"typeof pem"),(e=a.parseKey(e,"pem")).comment=t,e.toString("ssh")}}},function(e,t,i){var r=i(102).BigInteger,a=r.prototype.Barrett;function s(e,t){this.x=t,this.q=e}function n(e,t,i,a){this.curve=e,this.x=t,this.y=i,this.z=null==a?r.ONE:a,this.zinv=null}function o(e,t,i){this.q=e,this.a=this.fromBigInteger(t),this.b=this.fromBigInteger(i),this.infinity=new n(this,null,null),this.reducer=new a(this.q)}s.prototype.equals=function(e){return e==this||this.q.equals(e.q)&&this.x.equals(e.x)},s.prototype.toBigInteger=function(){return this.x},s.prototype.negate=function(){return new s(this.q,this.x.negate().mod(this.q))},s.prototype.add=function(e){return new s(this.q,this.x.add(e.toBigInteger()).mod(this.q))},s.prototype.subtract=function(e){return new s(this.q,this.x.subtract(e.toBigInteger()).mod(this.q))},s.prototype.multiply=function(e){return new s(this.q,this.x.multiply(e.toBigInteger()).mod(this.q))},s.prototype.square=function(){return new s(this.q,this.x.square().mod(this.q))},s.prototype.divide=function(e){return new s(this.q,this.x.multiply(e.toBigInteger().modInverse(this.q)).mod(this.q))},n.prototype.getX=function(){null==this.zinv&&(this.zinv=this.z.modInverse(this.curve.q));var e=this.x.toBigInteger().multiply(this.zinv);return this.curve.reduce(e),this.curve.fromBigInteger(e)},n.prototype.getY=function(){null==this.zinv&&(this.zinv=this.z.modInverse(this.curve.q));var e=this.y.toBigInteger().multiply(this.zinv);return this.curve.reduce(e),this.curve.fromBigInteger(e)},n.prototype.equals=function(e){return e==this||(this.isInfinity()?e.isInfinity():e.isInfinity()?this.isInfinity():!!e.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(e.z)).mod(this.curve.q).equals(r.ZERO)&&e.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(e.z)).mod(this.curve.q).equals(r.ZERO))},n.prototype.isInfinity=function(){return null==this.x&&null==this.y||this.z.equals(r.ZERO)&&!this.y.toBigInteger().equals(r.ZERO)},n.prototype.negate=function(){return new n(this.curve,this.x,this.y.negate(),this.z)},n.prototype.add=function(e){var t,i,a,s,o,c,u;return this.isInfinity()?e:e.isInfinity()?this:(t=e.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(e.z)).mod(this.curve.q),o=e.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(e.z)).mod(this.curve.q),r.ZERO.equals(o)?r.ZERO.equals(t)?this.twice():this.curve.getInfinity():(u=new r("3"),c=this.x.toBigInteger(),i=this.y.toBigInteger(),e.x.toBigInteger(),e.y.toBigInteger(),a=(s=o.square()).multiply(o),c=c.multiply(s),o=(s=t.square().multiply(this.z)).subtract(c.shiftLeft(1)).multiply(e.z).subtract(a).multiply(o).mod(this.curve.q),c=c.multiply(u).multiply(t).subtract(i.multiply(a)).subtract(s.multiply(t)).multiply(e.z).add(t.multiply(a)).mod(this.curve.q),u=a.multiply(this.z).multiply(e.z).mod(this.curve.q),new n(this.curve,this.curve.fromBigInteger(o),this.curve.fromBigInteger(c),u)))},n.prototype.twice=function(){var e,t,i,a,s,o;return this.isInfinity()?this:0==this.y.toBigInteger().signum()?this.curve.getInfinity():(s=new r("3"),o=this.x.toBigInteger(),t=(e=(t=this.y.toBigInteger()).multiply(this.z)).multiply(t).mod(this.curve.q),a=this.curve.a.toBigInteger(),i=o.square().multiply(s),a=(i=(i=r.ZERO.equals(a)?i:i.add(this.z.square().multiply(a))).mod(this.curve.q)).square().subtract(o.shiftLeft(3).multiply(t)).shiftLeft(1).multiply(e).mod(this.curve.q),s=i.multiply(s).multiply(o).subtract(t.shiftLeft(1)).shiftLeft(2).multiply(t).subtract(i.square().multiply(i)).mod(this.curve.q),o=e.square().multiply(e).shiftLeft(3).mod(this.curve.q),new n(this.curve,this.curve.fromBigInteger(a),this.curve.fromBigInteger(s),o))},n.prototype.multiply=function(e){if(this.isInfinity())return this;if(0==e.signum())return this.curve.getInfinity();for(var t=e,i=t.multiply(new r("3")),a=this.negate(),s=this,n=i.bitLength()-2;0<n;--n){s=s.twice();var o=i.testBit(n);o!=t.testBit(n)&&(s=s.add(o?this:a))}return s},n.prototype.multiplyTwo=function(e,t,i){for(var r=e.bitLength()>i.bitLength()?e.bitLength()-1:i.bitLength()-1,a=this.curve.getInfinity(),s=this.add(t);0<=r;)a=a.twice(),e.testBit(r)?a=i.testBit(r)?a.add(s):a.add(this):i.testBit(r)&&(a=a.add(t)),--r;return a},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(e){return e==this||this.q.equals(e.q)&&this.a.equals(e.a)&&this.b.equals(e.b)},o.prototype.getInfinity=function(){return this.infinity},o.prototype.fromBigInteger=function(e){return new s(this.q,e)},o.prototype.reduce=function(e){this.reducer.reduce(e)},o.prototype.encodePointHex=function(e){if(e.isInfinity())return"00";var t=e.getX().toBigInteger().toString(16),i=e.getY().toBigInteger().toString(16),r=this.getQ().toString(16).length;for(r%2!=0&&r++;t.length<r;)t="0"+t;for(;i.length<r;)i="0"+i;return"04"+t+i},o.prototype.decodePointHex=function(e){switch(parseInt(e.substr(0,2),16)){case 0:return this.infinity;case 2:c=!1;case 3:null==c&&(c=!0);var t=e.length-2,i=e.substr(2,t),a=this.fromBigInteger(new r(i,16)),s=a.multiply(a.square().add(this.getA())).add(this.getB()).sqrt();if(null==s)throw"Invalid point compression";var o=s.toBigInteger();return o.testBit(0)!=c&&(s=this.fromBigInteger(this.getQ().subtract(o))),new n(this,a,s);case 4:case 6:case 7:t=(e.length-2)/2,i=e.substr(2,t);var c=e.substr(t+2,t);return new n(this,this.fromBigInteger(new r(i,16)),this.fromBigInteger(new r(c,16)));default:return null}},o.prototype.encodeCompressedPointHex=function(e){if(e.isInfinity())return"00";var t=e.getX().toBigInteger().toString(16),i=this.getQ().toString(16).length;for(i%2!=0&&i++;t.length<i;)t="0"+t;return(e.getY().toBigInteger().isEven()?"02":"03")+t},s.prototype.getR=function(){var e;return null==this.r&&(this.r=null,128<(e=this.q.bitLength())&&-1==this.q.shiftRight(e-64).intValue())&&(this.r=r.ONE.shiftLeft(e).subtract(this.q)),this.r},s.prototype.modMult=function(e,t){return this.modReduce(e.multiply(t))},s.prototype.modReduce=function(e){if(null!=this.getR()){for(var t=q.bitLength();e.bitLength()>t+1;){var i=e.shiftRight(t),a=e.subtract(i.shiftLeft(t));e=(i=this.getR().equals(r.ONE)?i:i.multiply(this.getR())).add(a)}for(;0<=e.compareTo(q);)e=e.subtract(q)}else e=e.mod(q);return e},s.prototype.sqrt=function(){if(!this.q.testBit(0))throw"unsupported";var e;if(this.q.testBit(1))return(e=new s(this.q,this.x.modPow(this.q.shiftRight(2).add(r.ONE),this.q))).square().equals(this)?e:null;var t=this.q.subtract(r.ONE),i=t.shiftRight(1);if(this.x.modPow(i,this.q).equals(r.ONE)){var a,n=t.shiftRight(2).shiftLeft(1).add(r.ONE),o=this.x,c=modDouble(modDouble(o));do{for(;0<=(a=new r(this.q.bitLength(),new SecureRandom)).compareTo(this.q)||!a.multiply(a).subtract(c).modPow(i,this.q).equals(t););var u=(h=this.lucasSequence(a,o,n))[0],h=h[1];if(this.modMult(h,h).equals(c))return h=(h=h.testBit(0)?h.add(q):h).shiftRight(1),new s(q,h)}while(u.equals(r.ONE)||u.equals(t))}return null},s.prototype.lucasSequence=function(e,t,i){for(var a=i.bitLength(),s=i.getLowestSetBit(),n=r.ONE,o=r.TWO,c=e,u=r.ONE,h=r.ONE,l=a-1;s+1<=l;--l)u=this.modMult(u,h),i.testBit(l)?(h=this.modMult(u,t),n=this.modMult(n,c),o=this.modReduce(c.multiply(o).subtract(e.multiply(u))),c=this.modReduce(c.multiply(c).subtract(h.shiftLeft(1)))):(h=u,n=this.modReduce(n.multiply(o).subtract(u)),c=this.modReduce(c.multiply(o).subtract(e.multiply(u))),o=this.modReduce(o.multiply(o).subtract(u.shiftLeft(1))));for(u=this.modMult(u,h),h=this.modMult(u,t),n=this.modReduce(n.multiply(o).subtract(u)),o=this.modReduce(c.multiply(o).subtract(e.multiply(u))),u=this.modMult(u,h),l=1;l<=s;++l)n=this.modMult(n,o),o=this.modReduce(o.multiply(o).subtract(u.shiftLeft(1))),u=this.modMult(u,u);return[n,o]},e.exports={ECCurveFp:o,ECPointFp:n,ECFieldElementFp:s}},function(e,t,i){e.exports={read:function(e,t){return u.read(e,t)},readSSHPrivate:function(e,t,c){var u=(t=new l({buffer:t})).readCString(),f=(a.strictEqual(u,d,"bad magic string"),t.readString()),m=t.readString();u=t.readBuffer();if(1!==t.readInt())throw new Error("OpenSSH-format key file contains multiple keys: this is unsupported.");var g=t.readBuffer();if("public"===e)return a.ok(t.atEnd(),"excess bytes left after key"),h.read(g);var v=t.readBuffer(),y=(a.ok(t.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=y.readBuffer(),w=y.readInt(),x=n.opensshCipherInfo(f);if(void 0===r&&(r=i(276)),"string"==typeof c.passphrase&&(c.passphrase=s.from(c.passphrase,"utf-8")),!s.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!==r.pbkdf(k,k.length,b,b.length,S,S.length,w))throw new Error("bcrypt_pbkdf function returned failure, parameters invalid");k=(S=s.from(S)).slice(0,x.keySize),b=S.slice(x.keySize,x.keySize+x.blockSize);var _=o.createDecipheriv(x.opensslName,k,b);_.setAutoPadding(!1);var E,j=[];for(_.once("error",(function(e){if(-1!==e.toString().indexOf("bad decrypt"))throw new Error("Incorrect passphrase supplied, could not decrypt key");throw e})),_.write(v),_.end();null!==(E=_.read());)j.push(E);v=s.concat(j);break;default:throw new Error('OpenSSH-format key uses unknown KDF "'+m+'"')}if((e=(t=new l({buffer:v})).readInt())!==(g=t.readInt()))throw new Error("Incorrect passphrase supplied, could not decrypt key");return u={},e=h.readInternal(u,"private",t.remainder()),t.skip(u.consumed),g=t.readString(),e.comment=g,e},write:function(e,t){var u;u=c.isPrivateKey(e)?e.toPublic():e;var h,p,f="none",m="none",g=s.alloc(0),v={blockSize:8};if(void 0!==t&&void 0!==(h="string"==typeof(h=t.passphrase)?s.from(h,"utf-8"):h)&&(a.buffer(h,"options.passphrase"),a.optionalString(t.cipher,"options.cipher"),void 0===(f=t.cipher)&&(f="aes128-ctr"),v=n.opensshCipherInfo(f),m="bcrypt"),c.isPrivateKey(e)){p=new l({});t=o.randomBytes(4).readUInt32BE(0);for(var y=(p.writeInt(t),p.writeInt(t),p.write(e.toBuffer("rfc4253")),p.writeString(e.comment||""),1);p._offset%v.blockSize!=0;)p.writeChar(y++);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===r&&(r=i(276)),new Uint8Array(h)),x=(b=new Uint8Array(b),new Uint8Array(v.keySize+v.blockSize));if(0!==r.pbkdf(w,w.length,b,b.length,x,x.length,16))throw new Error("bcrypt_pbkdf function returned failure, parameters invalid");w=(x=s.from(x)).slice(0,v.keySize),b=x.slice(v.keySize,v.keySize+v.blockSize);var k=o.createCipheriv(v.opensslName,w,b);k.setAutoPadding(!1);var S,_=[];for(k.once("error",(function(e){throw e})),k.write(p),k.end();null!==(S=k.read());)_.push(S);p=s.concat(_);break;default:throw new Error("Unsupported kdf "+m)}var E=new l({});E.writeCString(d),E.writeString(f),E.writeString(m),E.writeBuffer(g),E.writeInt(1),E.writeBuffer(u.toBuffer("rfc4253")),p&&E.writeBuffer(p),E=E.toBuffer(),t=c.isPrivateKey(e)?"OPENSSH PRIVATE KEY":"OPENSSH PUBLIC KEY";var j=E.toString("base64"),A=(f=j.length+j.length/70+18+16+2*t.length+10,E=s.alloc(f),0);A+=E.write("-----BEGIN "+t+"-----\n",A);for(var R=0;R<j.length;){var I=R+70;I>j.length&&(I=j.length),A+=E.write(j.slice(R,I),A),E[A++]=10,R=I}return A+=E.write("-----END "+t+"-----\n",A),E.slice(0,A)}};var r,a=i(10),s=(i(58),i(12).Buffer),n=(i(30),i(25)),o=i(8),c=(i(23),i(24)),u=i(65),h=i(66),l=i(91),p=i(51),d="openssh-key-v1"},function(e,t,i){var r=i(52);const a=i(83),s=i(17),n=i(28),o=i(7),c=i(0),{Transform:u,ContractType:h,HtlcStatus:l,ContractEnvType:p}=i(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");e.exports=class extends r{async confirm(){var{env:e,output:t,hash:i,i:r,data:s,height:n}=this.options,o=t.getHashs("hex"),i={type:"suggest",src:a.protocol+"."+e.network.type,dst:s.dst,shash:i,sidx:r,sheight:n,pst:l.Sent,amount:t.value,rate:s.rate,ab:t.script.code[4].data.toString("hex"),aa:o[1],ba:o[0]};await e.setSuggest(i),e.mode==p.Block&&e.node.transmit("htlcsuggest.receive",i)}async unconfirm(){var{env:e,data:t}=this.options,t={shash:t.hash,sidx:t.index};await e.delHtlc(t)}async spent(e){var t=this.options.env,i=t.htlcList.get(""+e.prevout.hash+e.prevout.index);i&&(81==e.script.code[2].value?(i.pst=l.Finished,await t.setSuggest(i),t.mode==p.Block&&t.node.transmit("htlcsuggest.deal",i)):(i.pst=l.Cancel,await t.setSuggest(i),t.mode==p.Block&&t.node.transmit("htlcsuggest.cancel",i)))}async verify(){var{output:e,data:t}=this.options,i=(t={oper:h.htlcSuggest,rate:t.rate,dst:t.dst},e.getHashs("hex")),r=e.script.code[4].data.toString("hex"),t={contract:"0x"+Buffer.from(JSON.stringify(t)).toString("hex"),ab:"0x"+r.toString("hex"),aa:"0x"+i[1].toString("hex"),ba:"0x"+i[0].toString("hex"),period:2*o.HTLC_CANCEL_PERIOD};r=s.fromString(d.replace(t));return c(r.toString()===e.script.toString()),!0}static create(e){var t={oper:h.htlcSuggest,rate:e.rate,dst:e.dst};t={contract:"0x"+Buffer.from(JSON.stringify(t)).toString("hex"),ab:"0x"+e.ab.toString("hex"),aa:"0x"+e.aa.toString("hex"),ba:"0x"+e.ba.toString("hex"),period:2*o.HTLC_CANCEL_PERIOD},t=s.fromString(d.replace(t));return n.fromScript(t,e.amount)}}},function(e,t,i){var r=i(52);const a=i(83),s=i(17),n=i(28),o=i(7),{Transform:c,ContractType:u,HtlcStatus:h,ContractEnvType:l}=i(5),p=i(0),d=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");e.exports=class extends r{async confirm(){var{env:e,i:t,output:i,hash:r,height:s,data:n}=this.options,i=i.getHashs("hex"),r={src:n.src,dst:a.protocol+"."+e.network.type,shash:n.hash,sidx:n.index,ahash:r,aidx:t,aheight:s,pst:h.Assent,amount:n.value,rate:n.rate,ab:i[0],bb:i[1]};await e.setAssent(r),e.mode==l.Block&&e.node.transmit("htlcassent.receive",r)}async unconfirm(){var{env:e,data:t}=this.options,t={shash:t.hash,sidx:t.index};await e.delHtlc(t)}async spent(e){var t=this.options.env,i=t.htlcList.query([["ahash",e.prevout.hash],["aidx",e.prevout.index]]);i&&1===i.list.length&&i.list[0].pst===h.Assent&&(i=i.list[0],81==e.script.code[2].value?(i.secret=e.script.code[1].data.toString("hex"),i.pst=h.Deal,await t.setAssent(i),t.mode==l.Block&&t.node.transmit("htlcassent.deal",i)):(i.pst=h.Cancel,await t.setAssent(i),t.mode==l.Block&&t.node.transmit("htlcassent.cancel",i)))}async verify(){var{output:e,data:t}=this.options,i=(t={oper:u.htlcAssent,hash:t.hash,index:t.index},e.getHashs("hex")),t=s.fromString(d.replace({contract:"0x"+Buffer.from(JSON.stringify(t)).toString("hex"),ab:"0x"+i[0].toString("hex"),bb:"0x"+i[1].toString("hex"),period:o.HTLC_CANCEL_PERIOD}));return p(t.toString()===e.script.toString()),!0}static create(e){var t={oper:u.htlcAssent,hash:e.hash,index:e.index};t=s.fromString(d.replace({contract:"0x"+Buffer.from(JSON.stringify(t)).toString("hex"),ab:"0x"+e.ab.toString("hex"),bb:"0x"+e.bb.toString("hex"),period:o.HTLC_CANCEL_PERIOD}));return n.fromScript(t,e.amount)}}},function(e,t,i){var r=i(52);const a=i(17),s=i(28),n=i(0),{Transform:o,ContractType:c,ContractEnvType:u}=i(5),h=i(13),l=i(72).verifyData,p=new o("\n /*携带合约信息*/\n COMMENT var_contract DROP\n /*Bob确认时执行: 校验Bob签名*/\n DUP HASH160 var_bob EQUALVERIFY CHECKSIG\n");e.exports=class extends r{async insert(){var{env:e,output:t,hash:i,i:r,data:a}=this.options,t=h.fromWitnessPubkeyhash(t.getHash(),e.network).toString(),i={shash:i,sidx:r,alice:a.payload.addr,bob:t,body:a.payload.body};e.mode==u.Wallet&&await e.setComment(i)}async erase(){var{env:e,hash:t,i:i}=this.options,t={shash:t,sidx:i};e.mode==u.Wallet&&await e.delComment(t)}async verify(){var{output:e,data:t}=this.options,i=e.getHash();i=a.fromString(p.replace({contract:"0x"+Buffer.from(JSON.stringify(t)).toString("hex"),bob:"0x"+i.toString("hex")})),n(i.toString()===e.script.toString()),i=t.payload.sig;return delete(t=t.payload).sig,n.strictEqual(!0,l({data:t,sig:i})),!0}static create(e){var t={oper:c.comment,payload:e};t={contract:"0x"+Buffer.from(JSON.stringify(t)).toString("hex"),bob:"0x"+h.fromString(e.bob).hash.toString("hex")},t=a.fromString(p.replace(t));return s.fromScript(t,e.amount)}}},function(e,t,i){"use strict";
|
|
323
323
|
/*!
|
|
324
324
|
* netaddress.js - network address object for vallnet
|
|
325
325
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -354,7 +354,7 @@ const r=i(19).opcodes;function a(e){let t=null;return new(0,(a.list[e.type]||a.l
|
|
|
354
354
|
*/function r(e,t){var i=e.length-e.length%4;let r,o=t;for(let t=0;t<i;t+=4)r=a(r=e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t],3432918353),r=a(r=n(r,15),461845907),o=s(a(o=n(o^=r,13),5),3864292196);switch(r=0,3&e.length){case 3:r^=e[2+i]<<16;case 2:r^=e[1+i]<<8;case 1:r=a(r^=e[0+i],3432918353),r=a(r=n(r,15),461845907),o^=r}return o=a(o=(o^=e.length)^o>>>16,2246822507),o=a(o^=o>>>13,3266489909),(o^=o>>>16)<0&&(o+=4294967296),o}function a(e,t){var i=65535&e,r=65535&t,a=i*r;e=(e>>>16)*r+(t>>>16)*i&65535;let s=(e+=a>>>16)<<16|(a&=65535);return s<0&&(s+=4294967296),s}function s(e,t){let i=e+t&4294967295;return i<0&&(i+=4294967296),i}function n(e,t){return e<<t|e>>>32-t}(t=r=(i=i(56).binding)?i.murmur3:r).murmur3=r,t.mul32=a,t.sum32=s,t.rotl32=n,e.exports=t},function(e,t,i){"use strict";
|
|
355
355
|
/*!
|
|
356
356
|
* coinentry.js - coin entry object for vallnet
|
|
357
|
-
*/const r=i(0),a=i(28),s=i(1),n=i(4),o=i(3),c=i(323),u=i(54);e.exports=class e{constructor(){this.version=1,this.height=-1,this.time=0,this.coinbase=!1,this.output=new a,this.spent=!1,this.raw=null}toOutput(){return this.output}toCoin(e){var t=new u;return t.version=this.version,t.height=this.height,t.time=this.time,t.coinbase=this.coinbase,t.script=this.output.script,t.value=this.output.value,t.hash=e.hash,t.index=e.index,t}fromOutput(e){return this.output=e,this}static fromOutput(t){return(new e).fromOutput(t)}fromCoin(e){return this.version=e.version,this.height=e.height,this.time=e.time,this.coinbase=e.coinbase,this.output.script=e.script,this.output.value=e.value,this}static fromCoin(t){return(new e).fromCoin(t)}fromTX(e,t,i,a){return r("number"==typeof t),r("number"==typeof i),r("number"==typeof a),r(0<=t&&t<e.outputs.length),this.version=e.version,this.height=i,this.time=a,this.coinbase=e.isCoinbase(),this.output=e.outputs[t],this}static fromTX(t,i,r,a){return(new e).fromTX(t,i,r,a)}getSize(){return this.raw?this.raw.length:0+o.sizeVarint(this.version)+4+4+c.size(this.output)}toWriter(e){if(this.raw)e.writeBytes(this.raw);else{let t=this.height,i=0;this.coinbase&&(i|=1),-1===t&&(t=2147483647),i|=t<<1,e.writeVarint(this.version),i>>>=0,e.writeU32(i),e.writeU32(this.time),c.pack(this.output,e)}return e}toRaw(){var e;return this.raw||(e=this.getSize(),e=new n(e),this.toWriter(e),this.raw=e.render()),this.raw}fromReader(e){var t=e.readVarint(),i=e.readU32();let r=i>>>1;return 2147483647===r&&(r=-1),this.version=t,this.coinbase=0!=(1&i),this.height=r,this.time=e.readU32(),c.unpack(this.output,e),this}static fromReader(t){return(new e).fromReader(t)}fromRaw(e){return this.fromReader(new s(e)),this.raw=e,this}static fromRaw(t){return(new e).fromRaw(t)}}},function(e,t){e.exports=require("tls")},function(e,t,i){"use strict";
|
|
357
|
+
*/const r=i(0),a=i(28),s=i(1),n=i(4),o=i(3),c=i(323),u=i(54);e.exports=class e{constructor(){this.version=1,this.height=-1,this.time=0,this.coinbase=!1,this.output=new a,this.spent=!1,this.raw=null}toOutput(){return this.output}toCoin(e){var t=new u;return t.version=this.version,t.height=this.height,t.time=this.time,t.coinbase=this.coinbase,t.script=this.output.script,t.value=this.output.value,t.hash=e.hash,t.index=e.index,t}fromOutput(e){return this.output=e,this}static fromOutput(t){return(new e).fromOutput(t)}fromCoin(e){return this.version=e.version,this.height=e.height,this.time=e.time,this.coinbase=e.coinbase,this.output.script=e.script,this.output.value=e.value,this}static fromCoin(t){return(new e).fromCoin(t)}fromTX(e,t,i,a){return r("number"==typeof t),r("number"==typeof i),r("number"==typeof a),r(0<=t&&t<e.outputs.length),this.version=e.version,this.height=i,this.time=a,this.coinbase=e.isCoinbase(),this.output=e.outputs[t],this}static fromTX(t,i,r,a){return(new e).fromTX(t,i,r,a)}getSize(){return this.raw?this.raw.length:0+o.sizeVarint(this.version)+4+4+c.size(this.output)}toWriter(e){if(this.raw)e.writeBytes(this.raw);else{let t=this.height,i=0;this.coinbase&&(i|=1),-1===t&&(t=2147483647),i|=t<<1,e.writeVarint(this.version),i>>>=0,e.writeU32(i),e.writeU32(this.time),c.pack(this.output,e)}return e}toRaw(){var e;return this.raw||(e=this.getSize(),e=new n(e),this.toWriter(e),this.raw=e.render()),this.raw}fromReader(e){var t=e.readVarint(),i=e.readU32();let r=i>>>1;return 2147483647===r&&(r=-1),this.version=t,this.coinbase=0!=(1&i),this.height=r,this.time=e.readU32(),c.unpack(this.output,e),this}static fromReader(t){return(new e).fromReader(t)}fromRaw(e){return this.fromReader(new s(e)),this.raw=e,this}static fromRaw(t){return(new e).fromRaw(t)}}},function(e,t,i){const r=i(5).PropStatus;i=i(31);class a extends i{constructor(e){super(),this.db=e||{getVp:async e=>this.get(e),setVp:e=>{this.set(e.pid,e)},delVp:e=>{this.delete(e)},loadVpList:()=>{},save:()=>{}},this.pending=[]}async loadHistory(){}setAccount(e,t,i){var r;e&&e.wid&&e.account&&(r=e.wid+"."+e.account,this.account.get(r))&&this.account.get(r).delete(e.pid),e.wid=t,e.account=i,t&&i&&(r=e.wid+"."+e.account,this.account.get(r)||this.account.set(r,new Map),this.account.get(r).set(e.pid,e))}delAccount(e){var t;e&&e.wid&&e.account&&(t=e.wid+"."+e.account,this.account.get(t))&&this.account.get(t).delete(e.pid)}async getVp(e){return this.get(e)||this.db.getVp(e)}async getVpByAddress(e){return this.db.getVpByAddress(e)}async getVpByOid(e){return this.db.getVpByOid(e)}async setVp(e,t){e=new s(e),this.set(e.pid,e),this.pending.push({oper:"set",data:{data:e,tx:t}})}async delVp(e){this.delete(e.pid),this.pending.push({oper:"unset",data:{data:e}})}async save(){for(var e=[];0<this.pending.length;){var t=this.pending.shift();switch(t.oper){case"set":e.push(this.db.setVp(t.data.data,t.data.tx));break;case"unset":e.push(this.db.delVp(t.data.data))}}await Promise.all(e)}}class s{constructor(e){this.fromOptions(e=e||{})}fromOptions(e){this.pid=e.pid,this.cid=e.cid||"",this.oid=e.oid||"",this.gold=e.gold,this.current=null,e.current&&(this.current={},this.current.hash=e.current.hash,this.current.index=e.current.index,this.current.address=e.current.address),this.height=e.height,this.pst=e.pst||r.Ready,this.wid=e.wid||0,this.account=e.account||"",this.bid=null,e.bid&&(this.bid={},this.bid.raw=e.bid.raw||"",this.bid.fixed=e.bid.fixed||0,this.bid.period=e.bid.period||0,this.bid.hash=e.bid.hash||"",this.bid.value=e.bid.value||0,this.bid.address=e.bid.address||"")}toRaw(){var e={};return e.pid=this.pid,e.cid=this.cid||"",e.oid=this.oid||"",e.gold=this.gold,this.current&&(e.current={},e.current.hash=this.current.hash,e.current.index=this.current.index,e.current.address=this.current.address),e.height=this.height,e.pst=this.pst||r.Ready,e.wid=this.wid||0,e.account=this.account||"",this.bid&&(e.bid={},e.bid.raw=this.bid.raw||"",e.bid.fixed=this.bid.fixed||0,e.bid.period=this.bid.period||0,e.bid.hash=this.bid.hash||"",e.bid.value=this.bid.value||0,e.bid.address=this.bid.address||""),Buffer.from(JSON.stringify(e),"utf-8")}fromRaw(e){return e=JSON.parse(e.toString("utf8")),this.fromOptions(e),this}static fromRaw(e){return(new s).fromRaw(e)}}a.vpItem=s,e.exports=a},function(e,t){e.exports=require("tls")},function(e,t,i){"use strict";
|
|
358
358
|
/*!
|
|
359
359
|
* pbkdf2.js - pbkdf2 for vallnet
|
|
360
360
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -384,7 +384,7 @@ function r(e){let t=null;var i=r.list[e.contract.options.type];return i?new(t=i.
|
|
|
384
384
|
* hd.js - hd keys for vallnet
|
|
385
385
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
386
386
|
* https://github.com/bookmansoft/gamegold
|
|
387
|
-
*/const r=i(0);var a=i(
|
|
387
|
+
*/const r=i(0);var a=i(139),s=i(197),n=i(123);const o=i(67),c=i(304);i=i(301);const u=t;u.fromBase58=function(e,t){return(o.isBase58(e)?o:c).fromBase58(e,t)},u.generate=function(e){return o.generate(e)},u.fromSeed=function(e,t){return o.fromSeed(e,t)},u.fromMnemonic=function(e,t){return o.fromMnemonic(e,t)},u.fromJSON=function(e,t){return(e.xprivkey?o:c).fromJSON(e,t)},u.fromRaw=function(e,t){return(o.isRaw(e,t)?o:c).fromRaw(e,t)},u.from=function(e,t){if(r(e,"Options required."),u.isHD(e))return e;if(u.isBase58(e,t))return u.fromBase58(e,t);if(u.isRaw(e,t))return u.fromRaw(e,t);if(e&&"object"==typeof e)return u.fromMnemonic(e,t);throw new Error("Cannot create HD key from bad options.")},u.isBase58=function(e,t){return o.isBase58(e,t)||c.isBase58(e,t)},u.isRaw=function(e,t){return o.isRaw(e,t)||c.isRaw(e,t)},u.isHD=function(e){return o.isHDPrivateKey(e)||c.isHDPublicKey(e)},u.isPrivate=function(e){return o.isHDPrivateKey(e)},u.isPublic=function(e){return c.isHDPublicKey(e)},u.common=a,(u.HD=u).Mnemonic=s,u.MnemonicHelper=n,u.PrivateKey=o,u.PublicKey=c,u.wordlist=i},function(e,t,i){"use strict";
|
|
388
388
|
/*!
|
|
389
389
|
* account.js - account object for vallnet
|
|
390
390
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -392,7 +392,7 @@ function r(e){let t=null;var i=r.list[e.contract.options.type];return i?new(t=i.
|
|
|
392
392
|
/*!
|
|
393
393
|
* ccmp.js - constant-time compare for vallnet
|
|
394
394
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
395
|
-
*/const r=i(0);e.exports=function(e,t){if(r(Buffer.isBuffer(e)),r(Buffer.isBuffer(t)),0===t.length)return 0===e.length;let i=e.length^t.length;for(let r=0;r<e.length;r++)i|=e[r]^t[r%t.length];return 0===i}},function(e,t,i){let r=i(610);const a=i(
|
|
395
|
+
*/const r=i(0);e.exports=function(e,t){if(r(Buffer.isBuffer(e)),r(Buffer.isBuffer(t)),0===t.length)return 0===e.length;let i=e.length^t.length;for(let r=0;r<e.length;r++)i|=e[r]^t[r%t.length];return 0===i}},function(e,t,i){let r=i(610);const a=i(141);e.exports=class{constructor(e){this.parent=e,this.updateRecord={},this.inCheck=!1;let t=this;new r(5e3).tick(0,async()=>{try{0==this.inCheck&&(this.inCheck=!0,await t.checkTask.apply(t),this.inCheck=!1)}catch(e){console.error(e),this.inCheck=!1}})}addTask(e,t=3e4){"function"==typeof e&&(e={execute:e,id:a()}),this.updateRecord[e.id]||(e.$taskTime=new r(t),this.updateRecord[e.id]=e)}async checkTask(){try{let i=5;for(var e of Object.keys(this.updateRecord)){var t;0<i&&this.updateRecord[e].$taskTime.check()&&(i--,[t]=await this.updateRecord[e].execute(this.parent),t)&&Reflect.deleteProperty(this.updateRecord,e)}return Object.keys(this.updateRecord).length}catch(e){console.error(e)}}}},function(e,t,i){"use strict";
|
|
396
396
|
/*!
|
|
397
397
|
* protoreader.js - protobufs for vallnet
|
|
398
398
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -406,7 +406,7 @@ function r(e){let t=null;var i=r.list[e.contract.options.type];return i?new(t=i.
|
|
|
406
406
|
/*!
|
|
407
407
|
* opcode.js - opcode object for vallnet
|
|
408
408
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
409
|
-
*/const r=i(0),a=i(99),s=i(2),n=i(19),o=i(1),c=i(4),u=n.opcodes,h=[];let l=null;class p{constructor(e,t){this.value=e||0,this.data=t||null}isMinimal(){if(this.data){if(1===this.data.length){if(129===this.data[0])return!1;if(1<=this.data[0]&&this.data[0]<=16)return!1}if(this.data.length<=75)return this.value===this.data.length;if(this.data.length<=255)return this.value===u.OP_PUSHDATA1;if(this.data.length<=65535)return this.value===u.OP_PUSHDATA2;r(this.value===u.OP_PUSHDATA4)}return!0}isDisabled(){switch(this.value){case u.OP_CAT:case u.OP_SUBSTR:case u.OP_LEFT:case u.OP_RIGHT:case u.OP_INVERT:case u.OP_AND:case u.OP_OR:case u.OP_XOR:case u.OP_2MUL:case u.OP_2DIV:case u.OP_MUL:case u.OP_DIV:case u.OP_MOD:case u.OP_LSHIFT:case u.OP_RSHIFT:return!0}return!1}isBranch(){return this.value>=u.OP_IF&&this.value<=u.OP_ENDIF}equals(e){return r(p.isOpcode(e)),this.value===e.value&&(this.data?(r(e.data),this.data.equals(e.data)):(r(!e.data),!0))}toOp(){return this.value}toData(){return this.data}toLength(){return this.data?this.data.length:-1}toPush(){return this.value===u.OP_0?n.small[1]:this.value===u.OP_1NEGATE?n.small[0]:this.value>=u.OP_1&&this.value<=u.OP_16?n.small[this.value-80+1]:this.toData()}toString(e){var t=this.toPush();return t?t.toString(e||"utf8"):null}toSmall(){return this.value===u.OP_0?0:this.value>=u.OP_1&&this.value<=u.OP_16?this.value-80:-1}toNum(e,t){return this.value===u.OP_0?a.fromInt(0):this.value===u.OP_1NEGATE?a.fromInt(-1):this.value>=u.OP_1&&this.value<=u.OP_16?a.fromInt(this.value-80):this.data?a.decode(this.data,e,t):null}toInt(e,t){return(e=this.toNum(e,t))?e.getInt():-1}toBool(){var e=this.toSmall();return-1!==e&&1===e}toSymbol(){return-1===this.value?"OP_INVALIDOPCODE":n.opcodesByVal[this.value]||"0x"+s.hex8(this.value)}getSize(){if(!this.data)return 1;switch(this.value){case u.OP_PUSHDATA1:return 2+this.data.length;case u.OP_PUSHDATA2:return 3+this.data.length;case u.OP_PUSHDATA4:return 5+this.data.length;default:return 1+this.data.length}}toWriter(e){if(-1===this.value)throw new Error("Cannot reserialize a parse error.");if(this.data)switch(this.value){case u.OP_PUSHDATA1:e.writeU8(this.value),e.writeU8(this.data.length),e.writeBytes(this.data);break;case u.OP_PUSHDATA2:e.writeU8(this.value),e.writeU16(this.data.length),e.writeBytes(this.data);break;case u.OP_PUSHDATA4:e.writeU8(this.value),e.writeU32(this.data.length),e.writeBytes(this.data);break;default:r(this.value===this.data.length),e.writeU8(this.value),e.writeBytes(this.data)}else e.writeU8(this.value);return e}toRaw(){var e=this.getSize();return this.toWriter(new c(e)).render()}toFormat(){if(-1===this.value)return"0x01";if(this.data){if(this.data.length<=4){var e=this.toNum();if(this.equals(p.fromNum(e)))return e.toString(10)}const t=n.opcodesByVal[this.value];if(e=this.data.toString("hex"),!t)return`0x${s.hex8(this.value)} 0x`+e;let i=this.data.length.toString(16);if(i.length%2!=0&&(i="0"+i),i=s.revHex(i),this.data.length<=75)return`${t} 0x${i} 0x`+e;if(this.data.length<=255)return`${t} 0x4c 0x${i} 0x`+e;if(this.data.length<=65535)return`${t} 0x4d 0x${i} 0x`+e;if(this.data.length<=4294967295)return`${t} 0x4e 0x${i} 0x`+e}return n.opcodesByVal[this.value]||"0x"+s.hex8(this.value)}toASM(e){return-1===this.value?"[error]":this.data?n.toASM(this.data,e):n.opcodesByVal[this.value]||"OP_UNKNOWN"}static fromOp(e){return r("number"==typeof e),e=h[e],r(e,"Bad opcode."),e}static fromData(e){if(r(Buffer.isBuffer(e)),1===e.length){if(129===e[0])return p.fromOp(u.OP_1NEGATE);if(1<=e[0]&&e[0]<=16)return p.fromOp(e[0]+80)}return p.fromPush(e)}static fromPush(e){if(r(Buffer.isBuffer(e)),0===e.length)return p.fromOp(u.OP_0);if(e.length<=75)return new p(e.length,e);if(e.length<=255)return new p(u.OP_PUSHDATA1,e);if(e.length<=65535)return new p(u.OP_PUSHDATA2,e);if(e.length<=4294967295)return new p(u.OP_PUSHDATA4,e);throw new Error("Pushdata size too large.")}static fromString(e,t){return r("string"==typeof e),e=Buffer.from(e,t||"utf8"),p.fromData(e)}static fromSmall(e){return r(s.isU8(e)&&0<=e&&e<=16),p.fromOp(0===e?0:e+80)}static fromNum(e){return r(a.isScriptNum(e)),p.fromData(e.encode())}static fromInt(e){return r(s.isInt(e)),0===e?p.fromOp(u.OP_0):-1===e?p.fromOp(u.OP_1NEGATE):1<=e&&e<=16?p.fromOp(e+80):p.fromNum(a.fromNumber(e))}static fromBool(e){return r("boolean"==typeof e),p.fromSmall(e?1:0)}static fromSymbol(e){r("string"==typeof e),r(0<e.length),s.isUpperCase(e)||(e=e.toUpperCase()),s.startsWith(e,"OP_")||(e="OP_"+e);var t=n.opcodes[e];return null!=t||(r(s.startsWith(e,"OP_0X"),"Unknown opcode."),r(7===e.length,"Unknown opcode."),t=parseInt(e.substring(5),16),r(s.isU8(t),"Unknown opcode.")),p.fromOp(t)}static fromReader(e){var t,i=e.readU8(),r=h[i];if(r)return r;switch(i){case u.OP_PUSHDATA1:return e.left()<1?l:(t=e.readU8(),e.left()<t?(e.seek(e.left()),l):(t=e.readBytes(t),new p(i,t)));case u.OP_PUSHDATA2:return e.left()<2?(e.seek(e.left()),l):(t=e.readU16(),e.left()<t?(e.seek(e.left()),l):(t=e.readBytes(t),new p(i,t)));case u.OP_PUSHDATA4:return e.left()<4?(e.seek(e.left()),l):(t=e.readU32(),e.left()<t?(e.seek(e.left()),l):(t=e.readBytes(t),new p(i,t)));default:return e.left()<i?(e.seek(e.left()),l):(t=e.readBytes(i),new p(i,t))}}static fromRaw(e){return p.fromReader(new o(e))}static isOpcode(e){return e instanceof p}}l=Object.freeze(new p(-1));for(let e=0;e<=255;e++){var d;1<=e&&e<=78?h.push(null):(d=new p(e),h.push(Object.freeze(d)))}e.exports=p},function(e,t,i){const r=i(5).ContractStatus;e.exports=class extends class{constructor(e){this.period=e.period}run(e){var t=this.getResult();if(t&&Array.isArray(t)&&t.length<=10)for(var i of t)e.pushInt(i)}getResult(){return[]}}{constructor(e,t){super(e),this.type=e.type,this.addr=e.addr,this.dst=e.dst,this.status=t}getResult(){return this.status===r.Expired||this.status===r.Backed?[1,2]:this.status===r.Confirmed||this.status===r.Exchanged?[2,1]:[]}}},function(e,t,i){"use strict";const r=i(0),a=i(326),s=i(327);function n(e){var t=(i=n.getBackend(e)).backend,i=i.location;return new a(t,i,e)}n.getName=function(e){let t,i;switch(e=e||"memory"){case"ldb":case"leveldb":case"leveldown":t="leveldown",i="ldb";break;case"rdb":case"rocksdb":case"rocksdown":t="rocksdown",i="rdb";break;case"mdb":case"lmdb":t="lmdb",i="mdb";break;case"mem":case"memory":case"rbt":t="memory",i="mem";break;default:t=e,i="db"}return[t,i]},n.getBackend=function(e){var[t,i]=n.getName(e.db),a=s.get(t);let o=e.location;return"string"!=typeof o&&(r("memory"===t,"Location required."),o="memory"),{backend:a,location:o+"."+i}},e.exports=n},function(e,t,i){"use strict";t.AbstractLevelDOWN=i(403),t.AbstractIterator=i(254),t.AbstractChainedBatch=i(255)},function(e,t,i){"use strict";e.exports=process.nextTick},function(e,t,i){e.exports=i(408)(__dirname)},function(e,t){e.exports=function(e){return null!=e&&"object"==typeof e}},function(e,t,i){"use strict";function r(e){return"function"==typeof Array.isArray?Array.isArray(e):"[object Array]"===c.call(e)}function a(e){if(e&&"[object Object]"===c.call(e)){var t,i=o.call(e,"constructor"),r=e.constructor&&e.constructor.prototype&&o.call(e.constructor.prototype,"isPrototypeOf");if(!e.constructor||i||r){for(t in e);return void 0===t||o.call(e,t)}}}function s(e,t){u&&"__proto__"===t.name?u(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue}function n(e,t){if("__proto__"===t){if(!o.call(e,t))return;if(h)return h(e,t).value}return e[t]}var o=Object.prototype.hasOwnProperty,c=Object.prototype.toString,u=Object.defineProperty,h=Object.getOwnPropertyDescriptor;e.exports=function e(){var t,i,o,c,u,h=arguments[0],l=1,p=arguments.length,d=!1;for("boolean"==typeof h&&(d=h,h=arguments[1]||{},l=2),(null==h||"object"!=typeof h&&"function"!=typeof h)&&(h={});l<p;++l)if(null!=(t=arguments[l]))for(i in t)u=n(h,i),h!==(o=n(t,i))&&(d&&o&&(a(o)||(c=r(o)))?s(h,{name:i,newValue:e(d,u=c?(c=!1,u&&r(u)?u:[]):u&&a(u)?u:{},o)}):void 0!==o&&s(h,{name:i,newValue:o}));return h}},function(e,t,i){"use strict";var r=i(458),a=i(8),s=i(39).Buffer;i="undefined"==typeof setImmediate?process.nextTick:setImmediate;t.paramsHaveRequestBody=function(e){return e.body||e.requestBodyStream||e.json&&"boolean"!=typeof e.json||e.multipart},t.safeStringify=function(e,t){var i;try{i=JSON.stringify(e,t)}catch(a){i=r(e,t)}return i},t.md5=function(e){return a.createHash("md5").update(e).digest("hex")},t.isReadStream=function(e){return e.readable&&e.path&&e.mode},t.toBase64=function(e){return s.from(e||"","utf8").toString("base64")},t.copy=function(e){var t={};return Object.keys(e).forEach((function(i){t[i]=e[i]})),t},t.version=function(){var e=process.version.replace("v","").split(".");return{major:parseInt(e[0],10),minor:parseInt(e[1],10),patch:parseInt(e[2],10)}},t.defer=i},function(e,t){e.exports=require("zlib")},function(e,t,i){var r=i(23),a=i(101),s=i(57),n=i(24),o=i(105),c=i(106);i=i(51);e.exports={Key:r,parseKey:r.parse,Fingerprint:a,parseFingerprint:a.parse,Signature:s,parseSignature:s.parse,PrivateKey:n,parsePrivateKey:n.parse,generatePrivateKey:n.generate,Certificate:o,parseCertificate:o.parse,createSelfSignedCertificate:o.createSelfSigned,createCertificate:o.create,Identity:c,identityFromDN:c.parseDN,identityForHost:c.forHost,identityForUser:c.forUser,identityForEmail:c.forEmail,identityFromArray:c.fromArray,FingerprintFormatError:i.FingerprintFormatError,InvalidAlgorithmError:i.InvalidAlgorithmError,KeyParseError:i.KeyParseError,SignatureParseError:i.SignatureParseError,KeyEncryptedError:i.KeyEncryptedError,CertificateParseError:i.CertificateParseError}},function(e,t){e.exports={newInvalidAsn1Error:function(e){var t=new Error;return t.name="InvalidAsn1Error",t.message=e||"",t}}},function(e,t){e.exports={EOC:0,Boolean:1,Integer:2,BitString:3,OctetString:4,Null:5,OID:6,ObjectDescriptor:7,External:8,Real:9,Enumeration:10,PDV:11,Utf8String:12,RelativeOID:13,Sequence:16,Set:17,NumericString:18,PrintableString:19,T61String:20,VideotexString:21,IA5String:22,UTCTime:23,GeneralizedTime:24,GraphicString:25,VisibleString:26,GeneralString:28,UniversalString:29,CharacterString:30,BMPString:31,Constructor:32,Context:128}},function(e,t,i){e.exports={DiffieHellman:f,generateECDSA:function(e){var t,i,r,n=[];return l?(t={nistp256:"prime256v1",nistp384:"secp384r1",nistp521:"secp521r1"}[e],(t=a.createECDH(t)).generateKeys(),n.push({name:"curve",data:s.from(e)}),n.push({name:"Q",data:t.getPublicKey()}),n.push({name:"d",data:t.getPrivateKey()})):(r=(t=new m(e)).getN(),i=Math.ceil((r.bitLength()+64)/8),i=new d(a.randomBytes(i)),r=r.subtract(d.ONE),i=i.mod(r).add(d.ONE),r=t.getG().multiply(i),i=s.from(i.toByteArray()),r=s.from(t.getCurve().encodePointHex(r),"hex"),n.push({name:"curve",data:s.from(e)}),n.push({name:"Q",data:r}),n.push({name:"d",data:i})),new h({type:"ecdsa",curve:e,parts:n})},generateED25519:function(){var e=c.sign.keyPair(),t=s.from(e.secretKey),i=(e=s.from(e.publicKey),r.strictEqual(t.length,64),r.strictEqual(e.length,32),[]);return i.push({name:"A",data:e}),i.push({name:"k",data:t.slice(0,32)}),new h({type:"ed25519",parts:i})}};var r=i(10),a=i(8),s=i(12).Buffer,n=i(30),o=i(25),c=i(103),u=i(23),h=i(24),l=void 0!==a.createECDH,p=(i(468),i(134)),d=i(102).BigInteger;function f(e){if(o.assertCompatible(e,u,[1,4],"key"),this._isPriv=h.isPrivateKey(e,[1,3]),this._algo=e.type,this._curve=e.curve,"dsa"===(this._key=e).type){if(!l)throw new Error("Due to bugs in the node 0.10 crypto API, node 0.12.x or later is required to use DH");this._dh=a.createDiffieHellman(e.part.p.data,void 0,e.part.g.data,void 0),this._p=e.part.p,this._g=e.part.g,this._isPriv&&this._dh.setPrivateKey(e.part.x.data),this._dh.setPublicKey(e.part.y.data)}else if("ecdsa"===e.type){var t;l?(t={nistp256:"prime256v1",nistp384:"secp384r1",nistp521:"secp521r1"}[e.curve],this._dh=a.createECDH(t),"object"!=typeof this._dh||"function"!=typeof this._dh.setPrivateKey?(l=!1,f.call(this,e)):(this._isPriv&&this._dh.setPrivateKey(e.part.d.data),this._dh.setPublicKey(e.part.Q.data))):(this._ecParams=new m(this._curve),this._isPriv&&(this._priv=new v(this._ecParams,e.part.d.data)))}else{if("curve25519"!==e.type)throw new Error("DH not supported for "+e.type+" keys");this._isPriv&&(o.assertCompatible(e,h,[1,5],"key"),this._priv=e.part.k.data)}}function m(e){e=n.curves[e];var t=(r.object(e),new d(e.p)),i=new d(e.a),a=new d(e.b),s=new d(e.n),o=d.ONE;i=(t=new p.ECCurveFp(t,i,a)).decodePointHex(e.G.toString("hex"));this.curve=t,this.g=i,this.n=s,this.h=o}function g(e,t){this._params=e,0===t[0]&&(t=t.slice(1)),this._pub=e.getCurve().decodePointHex(t.toString("hex"))}function v(e,t){this._params=e,this._priv=new d(o.mpNormalize(t))}f.prototype.getPublicKey=function(){return this._isPriv?this._key.toPublic():this._key},f.prototype.getKey=f.prototype.getPrivateKey=function(){return this._isPriv?this._key:void 0},f.prototype._keyCheck=function(e,t){if(r.object(e,"key"),t||o.assertCompatible(e,h,[1,3],"key"),o.assertCompatible(e,u,[1,4],"key"),e.type!==this._algo)throw new Error("A "+e.type+" key cannot be used in "+this._algo+" Diffie-Hellman");if(e.curve!==this._curve)throw new Error("A key from the "+e.curve+" curve cannot be used with a "+this._curve+" Diffie-Hellman");"dsa"===e.type&&(r.deepEqual(e.part.p,this._p,"DSA key prime does not match"),r.deepEqual(e.part.g,this._g,"DSA key generator does not match"))},f.prototype.setPrivateKey=f.prototype.setKey=function(e){var t;this._keyCheck(e),"dsa"===e.type?(this._dh.setPrivateKey(e.part.x.data),this._dh.setPublicKey(e.part.y.data)):"ecdsa"===e.type?l?(this._dh.setPrivateKey(e.part.d.data),this._dh.setPublicKey(e.part.Q.data)):this._priv=new v(this._ecParams,e.part.d.data):"curve25519"===e.type&&(t=e.part.k,e.part.k||(t=e.part.r),this._priv=t.data,0===this._priv[0]&&(this._priv=this._priv.slice(1)),this._priv=this._priv.slice(0,32)),this._key=e,this._isPriv=!0},f.prototype.computeSecret=function(e){if(this._keyCheck(e,!0),!this._isPriv)throw new Error("DH exchange has not been initialized with a private key yet");var t;if("dsa"===this._algo)return this._dh.computeSecret(e.part.y.data);if("ecdsa"===this._algo)return l?this._dh.computeSecret(e.part.Q.data):(t=new g(this._ecParams,e.part.Q.data),this._priv.deriveSharedSecret(t));if("curve25519"!==this._algo)throw new Error("Invalid algorithm: "+this._algo);for(t=e.part.A.data;0===t[0]&&32<t.length;)t=t.slice(1);return e=this._priv,r.strictEqual(t.length,32),r.strictEqual(e.length,32),e=c.box.before(new Uint8Array(t),new Uint8Array(e)),s.from(e)},f.prototype.generateKeys=f.prototype.generateKey=function(){var e,t,i,n=[];if("dsa"===this._algo)return this._dh.generateKeys(),n.push({name:"p",data:this._p.data}),n.push({name:"q",data:this._key.part.q.data}),n.push({name:"g",data:this._g.data}),n.push({name:"y",data:this._dh.getPublicKey()}),n.push({name:"x",data:this._dh.getPrivateKey()}),this._key=new h({type:"dsa",parts:n}),this._isPriv=!0,this._key;if("ecdsa"===this._algo)return l?(this._dh.generateKeys(),n.push({name:"curve",data:s.from(this._curve)}),n.push({name:"Q",data:this._dh.getPublicKey()}),n.push({name:"d",data:this._dh.getPrivateKey()})):(t=this._ecParams.getN(),e=new d(a.randomBytes(t.bitLength())),t=t.subtract(d.ONE),e=e.mod(t).add(d.ONE),t=this._ecParams.getG().multiply(e),e=s.from(e.toByteArray()),t=s.from(this._ecParams.getCurve().encodePointHex(t),"hex"),this._priv=new v(this._ecParams,e),n.push({name:"curve",data:s.from(this._curve)}),n.push({name:"Q",data:t}),n.push({name:"d",data:e})),this._key=new h({type:"ecdsa",curve:this._curve,parts:n}),this._isPriv=!0,this._key;if("curve25519"===this._algo)return i=c.box.keyPair(),e=s.from(i.secretKey),t=s.from(i.publicKey),e=s.concat([e,t]),r.strictEqual(e.length,64),r.strictEqual(t.length,32),n.push({name:"A",data:t}),n.push({name:"k",data:e}),this._key=new h({type:"curve25519",parts:n}),this._isPriv=!0,this._key;throw new Error("Invalid algorithm: "+this._algo)},m.prototype.getCurve=function(){return this.curve},m.prototype.getG=function(){return this.g},m.prototype.getN=function(){return this.n},m.prototype.getH=function(){return this.h},v.prototype.deriveSharedSecret=function(e){return r.ok(e instanceof g),e=e._pub.multiply(this._priv),s.from(e.getX().toBigInteger().toByteArray())}},function(e,t,i){e.exports={read:function(e,t){return h.read(e,t,"pkcs1")},readPkcs1:function(e,t,i){switch(e){case"RSA":if("public"===t)return function(e){var t=p(e,"modulus");e=p(e,"exponent");return new c({type:"rsa",parts:[{name:"e",data:e},{name:"n",data:t}]})}(i);if("private"===t)return function(e){var t=p(e,"version"),i=(t=(r.strictEqual(t[0],0),p(e,"modulus")),p(e,"public exponent")),a=p(e,"private exponent"),s=p(e,"prime1"),n=p(e,"prime2"),o=p(e,"exponent1"),c=p(e,"exponent2");e=p(e,"iqmp");return new u({type:"rsa",parts:[{name:"n",data:t},{name:"e",data:i},{name:"d",data:a},{name:"iqmp",data:e},{name:"p",data:s},{name:"q",data:n},{name:"dmodp",data:o},{name:"dmodq",data:c}]})}(i);throw new Error("Unknown key type: "+t);case"DSA":if("public"===t)return function(e){var t=p(e,"y"),i=p(e,"p"),r=p(e,"q");e=p(e,"g");return new c({type:"dsa",parts:[{name:"y",data:t},{name:"p",data:i},{name:"q",data:r},{name:"g",data:e}]})}(i);if("private"===t)return function(e){var t=p(e,"version"),i=(t=(r.strictEqual(t.readUInt8(0),0),p(e,"p")),p(e,"q")),a=p(e,"g"),s=p(e,"y");e=p(e,"x");return new u({type:"dsa",parts:[{name:"p",data:t},{name:"q",data:i},{name:"g",data:a},{name:"y",data:s},{name:"x",data:e}]})}(i);throw new Error("Unknown key type: "+t);case"EC":case"ECDSA":if("private"===t)return function(e){var t=p(e,"version"),i=(t=(r.strictEqual(t.readUInt8(0),1),e.readString(a.Ber.OctetString,!0)),e.readSequence(160),l(e));r.string(i,"a known elliptic curve"),e.readSequence(161),e=e.readString(a.Ber.BitString,!0),e=o.ecNormalize(e),i={type:"ecdsa",parts:[{name:"curve",data:s.from(i)},{name:"Q",data:e},{name:"d",data:t}]};return new u(i)}(i);if("public"===t)return function(e){e.readSequence();for(var t,i=e.readOID(),u=(r.strictEqual(i,"1.2.840.10045.2.1","must be ecPublicKey"),e.readOID()),h=Object.keys(n.curves),l=0;l<h.length;++l){var p=h[l];if(n.curves[p].pkcs8oid===u){t=p;break}}return r.string(t,"a known ECDSA named curve"),i=e.readString(a.Ber.BitString,!0),i=o.ecNormalize(i),e={type:"ecdsa",parts:[{name:"curve",data:s.from(t)},{name:"Q",data:i}]},new c(e)}(i);throw new Error("Unknown key type: "+t);case"EDDSA":case"EdDSA":if("private"===t)return function(e){var t=p(e,"version"),i=(t=(r.strictEqual(t.readUInt8(0),1),e.readString(a.Ber.OctetString,!0)),e.readSequence(160),e.readOID());r.strictEqual(i,"1.3.101.112","the ed25519 curve identifier"),e.readSequence(161),i=o.readBitString(e),e={type:"ed25519",parts:[{name:"A",data:o.zeroPadToLength(i,32)},{name:"k",data:t}]};return new u(e)}(i);throw new Error(t+" keys not supported with EdDSA");default:throw new Error("Unknown key algo: "+e)}},write:function(e,t){return h.write(e,t,"pkcs1")},writePkcs1:function(e,t){switch(e.startSequence(),t.type){case"rsa":(u.isPrivateKey(t)?function(e,t){var i=s.from([0]);e.writeBuffer(i,a.Ber.Integer),e.writeBuffer(t.part.n.data,a.Ber.Integer),e.writeBuffer(t.part.e.data,a.Ber.Integer),e.writeBuffer(t.part.d.data,a.Ber.Integer),e.writeBuffer(t.part.p.data,a.Ber.Integer),e.writeBuffer(t.part.q.data,a.Ber.Integer),t.part.dmodp&&t.part.dmodq||o.addRSAMissing(t),e.writeBuffer(t.part.dmodp.data,a.Ber.Integer),e.writeBuffer(t.part.dmodq.data,a.Ber.Integer),e.writeBuffer(t.part.iqmp.data,a.Ber.Integer)}:function(e,t){e.writeBuffer(t.part.n.data,a.Ber.Integer),e.writeBuffer(t.part.e.data,a.Ber.Integer)})(e,t);break;case"dsa":(u.isPrivateKey(t)?function(e,t){var i=s.from([0]);e.writeBuffer(i,a.Ber.Integer),e.writeBuffer(t.part.p.data,a.Ber.Integer),e.writeBuffer(t.part.q.data,a.Ber.Integer),e.writeBuffer(t.part.g.data,a.Ber.Integer),e.writeBuffer(t.part.y.data,a.Ber.Integer),e.writeBuffer(t.part.x.data,a.Ber.Integer)}:function(e,t){e.writeBuffer(t.part.y.data,a.Ber.Integer),e.writeBuffer(t.part.p.data,a.Ber.Integer),e.writeBuffer(t.part.q.data,a.Ber.Integer),e.writeBuffer(t.part.g.data,a.Ber.Integer)})(e,t);break;case"ecdsa":(u.isPrivateKey(t)?function(e,t){var i=s.from([1]);e.writeBuffer(i,a.Ber.Integer),e.writeBuffer(t.part.d.data,a.Ber.OctetString),e.startSequence(160),i=t.part.curve.data.toString(),i=n.curves[i].pkcs8oid,r.string(i,"a known ECDSA named curve"),e.writeOID(i),e.endSequence(),e.startSequence(161),i=o.ecNormalize(t.part.Q.data,!0);e.writeBuffer(i,a.Ber.BitString),e.endSequence()}:function(e,t){e.startSequence(),e.writeOID("1.2.840.10045.2.1");var i=t.part.curve.data.toString();i=n.curves[i].pkcs8oid,r.string(i,"a known ECDSA named curve"),e.writeOID(i),e.endSequence(),i=o.ecNormalize(t.part.Q.data,!0);e.writeBuffer(i,a.Ber.BitString)})(e,t);break;case"ed25519":u.isPrivateKey(t)?function(e,t){var i=s.from([1]);e.writeBuffer(i,a.Ber.Integer),e.writeBuffer(t.part.k.data,a.Ber.OctetString),e.startSequence(160),e.writeOID("1.3.101.112"),e.endSequence(),e.startSequence(161),o.writeBitString(e,t.part.A.data),e.endSequence()}(e,t):function(){throw new Error("Public keys are not supported for EdDSA PKCS#1")}();break;default:throw new Error("Unknown key algo: "+t.type)}e.endSequence()}};var r=i(10),a=i(58),s=i(12).Buffer,n=i(30),o=i(25),c=i(23),u=i(24),h=i(65),l=i(104).readECDSACurve;function p(e,t){return r.strictEqual(e.peek(),a.Ber.Integer,t+" is not an Integer"),o.mpNormalize(e.readString(a.Ber.Integer,!0))}},function(e,t,i){e.exports={read:function(e,t){"string"!=typeof e&&(r.buffer(e,"buf"),e=e.toString("ascii"));var i=e.split("\n");if(i[0].match(/^Private-key-format\: v1/)){e=i[1].split(" ");var c=parseInt(e[1],10);e=e[2];if(u[c])return function(e,t){if(u[e].match(/^RSA-/))return function(e){var t={};e.forEach((function(e){"Modulus:"===e.split(" ")[0]?t.n=h(e):"PublicExponent:"===e.split(" ")[0]?t.e=h(e):"PrivateExponent:"===e.split(" ")[0]?t.d=h(e):"Prime1:"===e.split(" ")[0]?t.p=h(e):"Prime2:"===e.split(" ")[0]?t.q=h(e):"Exponent1:"===e.split(" ")[0]?t.dmodp=h(e):"Exponent2:"===e.split(" ")[0]?t.dmodq=h(e):"Coefficient:"===e.split(" ")[0]&&(t.iqmp=h(e))})),e={type:"rsa",parts:[{name:"e",data:o.mpNormalize(t.e)},{name:"n",data:o.mpNormalize(t.n)},{name:"d",data:o.mpNormalize(t.d)},{name:"p",data:o.mpNormalize(t.p)},{name:"q",data:o.mpNormalize(t.q)},{name:"dmodp",data:o.mpNormalize(t.dmodp)},{name:"dmodq",data:o.mpNormalize(t.dmodq)},{name:"iqmp",data:o.mpNormalize(t.iqmp)}]};return new n(e)}(t);if("ECDSA-P384-SHA384"!==u[e]&&"ECDSA-P256-SHA256"!==u[e])throw new Error("Unsupported algorithm: "+u[e]);t=a.from(t[0].split(" ")[1],"base64");var i="nistp384",r=384;return"ECDSA-P256-SHA256"===u[e]&&(i="nistp256",r=256),e=o.publicFromPrivateECDSA(i,t).part.Q.data,r={type:"ecdsa",curve:i,size:r,parts:[{name:"curve",data:a.from(i)},{name:"d",data:t},{name:"Q",data:e}]},new n(r)}(c,i.slice(2));throw new Error("Unsupported algorithm: "+e)}for(var l=0;i[l].match(/^\;/);)l++;if(!i[l].match(/\. IN KEY /)&&!i[l].match(/\. IN DNSKEY /)||0!==i[l+1].length)throw new Error("Cannot parse dnssec key");return function(e){e=e.split(" ");var t=parseInt(e[5],10);if(!u[t])throw new Error("Unsupported algorithm: "+t);if(e=e.slice(6,e.length).join(),e=a.from(e,"base64"),u[t].match(/^RSA-/)){if(3!=(r=e.readUInt8(0))&&1!=r)throw new Error("Cannot parse dnssec key: unsupported exponent length");var i=e.slice(1,r+1),r=(i=o.mpNormalize(i),e.slice(1+r)),n=(r=o.mpNormalize(r),{type:"rsa",parts:[]});return n.parts.push({name:"e",data:i}),n.parts.push({name:"n",data:r}),new s(n)}if("ECDSA-P384-SHA384"!==u[t]&&"ECDSA-P256-SHA256"!==u[t])throw new Error("Unsupported algorithm: "+u[t]);return i="nistp384",r=384,u[t].match(/^ECDSA-P256-SHA256/)&&(i="nistp256",r=256),n={type:"ecdsa",curve:i,size:r,parts:[{name:"curve",data:a.from(i)},{name:"Q",data:o.ecNormalize(e)}]},new s(n)}(i[l])},write:function(e,t){if(n.isPrivateKey(e)){if("rsa"===e.type)return function(e,t){e.part.dmodp&&e.part.dmodq||o.addRSAMissing(e);var i="";i=(i+="Private-key-format: v1.3\n")+"Algorithm: "+function(e){if(e&&e.hashAlgo&&"sha1"!==e.hashAlgo){if("sha256"===e.hashAlgo)return"8 (RSASHA256)";if("sha512"===e.hashAlgo)return"10 (RSASHA512)";throw new Error("Unknown or unsupported hash: "+e.hashAlgo)}return"5 (RSASHA1)"}(t)+"\n",t=o.mpDenormalize(e.part.n.data),i+="Modulus: "+t.toString("base64")+"\n",t=o.mpDenormalize(e.part.e.data),i+="PublicExponent: "+t.toString("base64")+"\n",t=o.mpDenormalize(e.part.d.data),i+="PrivateExponent: "+t.toString("base64")+"\n",t=o.mpDenormalize(e.part.p.data),i+="Prime1: "+t.toString("base64")+"\n",t=o.mpDenormalize(e.part.q.data),i+="Prime2: "+t.toString("base64")+"\n",t=o.mpDenormalize(e.part.dmodp.data),i+="Exponent1: "+t.toString("base64")+"\n",t=o.mpDenormalize(e.part.dmodq.data),i+="Exponent2: "+t.toString("base64")+"\n",t=o.mpDenormalize(e.part.iqmp.data),i+="Coefficient: "+t.toString("base64")+"\n",e=new Date;return i=(i=(i+="Created: "+l(e)+"\n")+"Publish: "+l(e)+"\n")+"Activate: "+l(e)+"\n",a.from(i,"ascii")}(e,t);if("ecdsa"===e.type)return function(e){var t="";if(t+="Private-key-format: v1.3\n","nistp256"===e.curve)t+="Algorithm: 13 (ECDSAP256SHA256)\n";else{if("nistp384"!==e.curve)throw new Error("Unsupported curve");t+="Algorithm: 14 (ECDSAP384SHA384)\n"}return t+="PrivateKey: "+(e=e.part.d.data.toString("base64"))+"\n",t=(t=(t+="Created: "+l(e=new Date)+"\n")+"Publish: "+l(e)+"\n")+"Activate: "+l(e)+"\n",a.from(t,"ascii")}(e);throw new Error("Unsupported algorithm: "+e.type)}throw s.isKey(e)?new Error('Format "dnssec" only supports writing private keys'):new Error("key is not a Key or PrivateKey")}};var r=i(10),a=i(12).Buffer,s=i(23),n=i(24),o=i(25),c=(i(91),i(178),{"rsa-sha1":5,"rsa-sha256":8,"rsa-sha512":10,"ecdsa-p256-sha256":13,"ecdsa-p384-sha384":14}),u={};function h(e){return a.from(e.split(" ")[1],"base64")}function l(e){var t=e.getFullYear()+""+(e.getMonth()+1)+e.getUTCDate();return(t+=""+e.getUTCHours()+e.getUTCMinutes())+e.getUTCSeconds()}Object.keys(c).forEach((function(e){u[c[e]]=e.toUpperCase()}))},function(e,t,i){e.exports={read:function(e,t){for(var i,n,p=e.toString("ascii").split(/[\r\n]+/),d=!1,f=0;f<p.length;)if((i=l(p[f++]))&&(n={"putty-user-key-file-2":2,"putty-user-key-file-3":3}[i[0].toLowerCase()])){d=!0;break}if(!d)throw new Error("No PuTTY format first line found");e=i[1];var m=(i=l(p[f++]),r.equal(i[0].toLowerCase(),"encryption"),i[1]),g=(i=l(p[f++]),r.equal(i[0].toLowerCase(),"comment"),i[1]),v=(i=l(p[f++]),r.equal(i[0].toLowerCase(),"public-lines"),parseInt(i[1],10));if(!isFinite(v)||v<0||v>p.length)throw new Error("Invalid public-lines count");var y,b=a.from(p.slice(f,f+v).join(""),"base64"),w=s.algToKeyType(e);if((b=s.read(b)).type!==w)throw new Error("Outer key algorithm mismatch");if(p[f+=v]){if(i=l(p[f++]),r.equal(i[0].toLowerCase(),"private-lines"),v=parseInt(i[1],10),!isFinite(v)||v<0||v>p.length)throw new Error("Invalid private-lines count");if(v=a.from(p.slice(f,f+v).join(""),"base64"),"none"!==m&&3===n)throw new Error("Encrypted keys arenot supported for PuTTY format version 3");if("aes256-cbc"===m){if(!t.passphrase)throw new h.KeyEncryptedError(t.filename,"PEM");m=a.alloc(16,0),(t=c.createDecipheriv("aes-256-cbc",function(e){var t=c.createHash("sha1").update(a.concat([a.from([0,0,0,0]),a.from(e)])).digest();e=c.createHash("sha1").update(a.concat([a.from([0,0,0,1]),a.from(e)])).digest();return a.concat([t,e]).slice(0,32)}(t.passphrase),m)).setAutoPadding(!1),v=a.concat([t.update(v),t.final()])}if((b=new u(b)).type!==w)throw new Error("Outer key algorithm mismatch");if(m=new o({buffer:v}),"ssh-dss"===e)y=[{name:"x",data:m.readBuffer()}];else if("ssh-rsa"===e)y=[{name:"d",data:m.readBuffer()},{name:"p",data:m.readBuffer()},{name:"q",data:m.readBuffer()},{name:"iqmp",data:m.readBuffer()}];else if(e.match(/^ecdsa-sha2-nistp/))y=[{name:"d",data:m.readBuffer()}];else{if("ssh-ed25519"!==e)throw new Error("Unsupported PPK key type: "+e);y=[{name:"k",data:m.readBuffer()}]}b=new u({type:b.type,parts:b.parts.concat(y)})}return b.comment=g,b},write:function(e,t){var i,o;if(r.object(e),n.isKey(e))return i=s.keyTypeToAlg(e),o=s.write(e),e=e.comment||"",(o=function(e){for(var t=[],i=0;i<e.length;)t.push(e.slice(i,i+64)),i+=64;return t}(o.toString("base64"))).unshift("Public-Lines: "+o.length),o.unshift("Comment: "+e),o.unshift("Encryption: none"),o.unshift("PuTTY-User-Key-File-2: "+i),a.from(o.join("\n")+"\n");throw new Error("Must be a public key")}};var r=i(10),a=i(12).Buffer,s=i(66),n=i(23),o=i(91),c=i(8),u=i(24),h=i(51);function l(e){var t=e.indexOf(":");if(-1===t)return null;var i=e.slice(0,t);for(++t;" "===e[t];)++t;return[i,e.slice(t)]}},function(e,t){function i(e){this.dict=e||{}}i.prototype.set=function(e,t,i){var r,a;if("object"!=typeof e)return void 0===i&&(i=!0),r=this.has(e),!i&&r?this.dict[r]=this.dict[r]+","+t:this.dict[r||e]=t,r;for(a in e)this.set(a,e[a],t)},i.prototype.has=function(e){for(var t=Object.keys(this.dict),i=(e=e.toLowerCase(),0);i<t.length;i++)if(t[i].toLowerCase()===e)return t[i];return!1},i.prototype.get=function(e){e=e.toLowerCase();var t,i,r=this.dict;return Object.keys(r).forEach((function(a){i=a.toLowerCase(),e===i&&(t=r[a])})),t},i.prototype.swap=function(e){var t=this.has(e);if(t!==e){if(!t)throw new Error('There is no header than matches "'+e+'"');this.dict[e]=this.dict[t],delete this.dict[t]}},i.prototype.del=function(e){var t=this.has(e);return delete this.dict[t||e]},e.exports=function(e){return new i(e)},e.exports.httpify=function(e,t){var r=new i(t);return e.setHeader=function(e,t,i){if(void 0!==t)return r.set(e,t,i)},e.hasHeader=function(e){return r.has(e)},e.getHeader=function(e){return r.get(e)},e.removeHeader=function(e){return r.del(e)},e.headers=r.dict,r}},function(e,t,i){"use strict";var r=i(496),a=i(184),s=i(92),n=i(291),o=i(498);function c(e,t,i){var r,a,s,o=this._refs[i];if("string"==typeof o){if(!this._refs[o])return c.call(this,e,t,o);o=this._refs[o]}return(o=o||this._schemas[i])instanceof n?d(o.schema,this._opts.inlineRefs)?o.schema:o.validate||this._compile(o):((o=u.call(this,t,i))&&(r=o.schema,t=o.root,s=o.baseId),r instanceof n?a=r.validate||e.call(this,r.schema,t,void 0,s):void 0!==r&&(a=d(r,this._opts.inlineRefs)?r:e.call(this,r,t,void 0,s)),a)}function u(e,t){var i=r.parse(t),a=m(i),s=f(this._getId(e.schema));if(0===Object.keys(e.schema).length||a!==s){a=v(a);var o=this._refs[a];if("string"==typeof o)return function(e,t,i){var r,a;if(t=u.call(this,e,t))return r=t.schema,a=t.baseId,e=t.root,(t=this._getId(r))&&(a=y(a,t)),l.call(this,i,a,r,e)}.call(this,e,o,i);if(o instanceof n)o.validate||this._compile(o);else{if(!((o=this._schemas[a])instanceof n))return;if(o.validate||this._compile(o),a==v(t))return{schema:o,root:e,baseId:s}}if(!(e=o).schema)return;s=f(this._getId(e.schema))}return l.call(this,i,s,e.schema,e)}(e.exports=c).normalizeId=v,c.fullPath=f,c.url=y,c.ids=function(e){var t=v(this._getId(e)),i={"":t},n={"":f(t,!1)},c={},u=this;return o(e,{allKeys:!0},(function(e,t,o,h,l,p,d){if(""!==t){var f=u._getId(e),m=i[h];h=n[h]+"/"+l;if(void 0!==d&&(h+="/"+("number"==typeof d?d:s.escapeFragment(d))),"string"==typeof f)if(f=m=v(m?r.resolve(m,f):f),(l="string"==typeof(l=u._refs[f])?u._refs[l]:l)&&l.schema){if(!a(e,l.schema))throw new Error('id "'+f+'" resolves to more than one schema')}else if(f!=v(h))if("#"==f[0]){if(c[f]&&!a(e,c[f]))throw new Error('id "'+f+'" resolves to more than one schema');c[f]=e}else u._refs[f]=h;i[t]=m,n[t]=h}})),c},c.inlineRef=d,c.schema=u;var h=s.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function l(e,t,i,r){if(e.fragment=e.fragment||"","/"==e.fragment.slice(0,1)){for(var a=e.fragment.split("/"),n=1;n<a.length;n++){var o=a[n];if(o){if(void 0===(i=i[o=s.unescapeFragment(o)]))break;h[o]||((o=this._getId(i))&&(t=y(t,o)),i.$ref&&(o=y(t,i.$ref),o=u.call(this,r,o))&&(i=o.schema,r=o.root,t=o.baseId))}}return void 0!==i&&i!==r.schema?{schema:i,root:r,baseId:t}:void 0}}var p=s.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function d(e,t){return!1!==t&&(void 0===t||!0===t?function e(t){var i;if(Array.isArray(t)){for(var r=0;r<t.length;r++)if("object"==typeof(i=t[r])&&!e(i))return!1}else for(var a in t){if("$ref"==a)return!1;if("object"==typeof(i=t[a])&&!e(i))return!1}return!0}(e):t?function e(t){var i,r=0;if(Array.isArray(t)){for(var a=0;a<t.length;a++)if("object"==typeof(i=t[a])&&(r+=e(i)),r==1/0)return 1/0}else for(var s in t){if("$ref"==s)return 1/0;if(p[s])r++;else if("object"==typeof(i=t[s])&&(r+=e(i)+1),r==1/0)return 1/0}return r}(e)<=t:void 0)}function f(e,t){return!1!==t&&(e=v(e)),m(r.parse(e))}function m(e){return r.serialize(e).split("#")[0]+"#"}var g=/#\/?$/;function v(e){return e?e.replace(g,""):""}function y(e,t){return t=v(t),r.resolve(e,t)}},function(e,t,i){"use strict";e.exports=function e(t,i){if(t===i)return!0;if(t&&i&&"object"==typeof t&&"object"==typeof i){if(t.constructor!==i.constructor)return!1;var r,a,s;if(Array.isArray(t)){if((r=t.length)!=i.length)return!1;for(a=r;0!=a--;)if(!e(t[a],i[a]))return!1}else{if(t.constructor===RegExp)return t.source===i.source&&t.flags===i.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===i.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===i.toString();if((r=(s=Object.keys(t)).length)!==Object.keys(i).length)return!1;for(a=r;0!=a--;)if(!Object.prototype.hasOwnProperty.call(i,s[a]))return!1;for(a=r;0!=a--;){var n=s[a];if(!e(t[n],i[n]))return!1}}return!0}return t!=t&&i!=i}},function(e,t,i){"use strict";var r=i(183);function a(e,t,i){this.message=i||a.message(e,t),this.missingRef=r.url(e,t),this.missingSchema=r.normalizeId(r.fullPath(this.missingRef))}function s(e){return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e}e.exports={Validation:s((function(e){this.message="validation failed",this.errors=e,this.ajv=this.validation=!0})),MissingRef:s(a)},a.message=function(e,t){return"can't resolve reference "+t+" from id "+e}},function(e,t,i){var r=i(299),a=i(300);e.exports=function(e,t,i){var s=t&&i||0,n=("string"==typeof e&&(t="binary"===e?new Array(16):null,e=null),(e=e||{}).random||(e.rng||r)());if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t)for(var o=0;o<16;++o)t[s+o]=n[o];return t||a(n)}},function(e,t,i){
|
|
409
|
+
*/const r=i(0),a=i(99),s=i(2),n=i(19),o=i(1),c=i(4),u=n.opcodes,h=[];let l=null;class p{constructor(e,t){this.value=e||0,this.data=t||null}isMinimal(){if(this.data){if(1===this.data.length){if(129===this.data[0])return!1;if(1<=this.data[0]&&this.data[0]<=16)return!1}if(this.data.length<=75)return this.value===this.data.length;if(this.data.length<=255)return this.value===u.OP_PUSHDATA1;if(this.data.length<=65535)return this.value===u.OP_PUSHDATA2;r(this.value===u.OP_PUSHDATA4)}return!0}isDisabled(){switch(this.value){case u.OP_CAT:case u.OP_SUBSTR:case u.OP_LEFT:case u.OP_RIGHT:case u.OP_INVERT:case u.OP_AND:case u.OP_OR:case u.OP_XOR:case u.OP_2MUL:case u.OP_2DIV:case u.OP_MUL:case u.OP_DIV:case u.OP_MOD:case u.OP_LSHIFT:case u.OP_RSHIFT:return!0}return!1}isBranch(){return this.value>=u.OP_IF&&this.value<=u.OP_ENDIF}equals(e){return r(p.isOpcode(e)),this.value===e.value&&(this.data?(r(e.data),this.data.equals(e.data)):(r(!e.data),!0))}toOp(){return this.value}toData(){return this.data}toLength(){return this.data?this.data.length:-1}toPush(){return this.value===u.OP_0?n.small[1]:this.value===u.OP_1NEGATE?n.small[0]:this.value>=u.OP_1&&this.value<=u.OP_16?n.small[this.value-80+1]:this.toData()}toString(e){var t=this.toPush();return t?t.toString(e||"utf8"):null}toSmall(){return this.value===u.OP_0?0:this.value>=u.OP_1&&this.value<=u.OP_16?this.value-80:-1}toNum(e,t){return this.value===u.OP_0?a.fromInt(0):this.value===u.OP_1NEGATE?a.fromInt(-1):this.value>=u.OP_1&&this.value<=u.OP_16?a.fromInt(this.value-80):this.data?a.decode(this.data,e,t):null}toInt(e,t){return(e=this.toNum(e,t))?e.getInt():-1}toBool(){var e=this.toSmall();return-1!==e&&1===e}toSymbol(){return-1===this.value?"OP_INVALIDOPCODE":n.opcodesByVal[this.value]||"0x"+s.hex8(this.value)}getSize(){if(!this.data)return 1;switch(this.value){case u.OP_PUSHDATA1:return 2+this.data.length;case u.OP_PUSHDATA2:return 3+this.data.length;case u.OP_PUSHDATA4:return 5+this.data.length;default:return 1+this.data.length}}toWriter(e){if(-1===this.value)throw new Error("Cannot reserialize a parse error.");if(this.data)switch(this.value){case u.OP_PUSHDATA1:e.writeU8(this.value),e.writeU8(this.data.length),e.writeBytes(this.data);break;case u.OP_PUSHDATA2:e.writeU8(this.value),e.writeU16(this.data.length),e.writeBytes(this.data);break;case u.OP_PUSHDATA4:e.writeU8(this.value),e.writeU32(this.data.length),e.writeBytes(this.data);break;default:r(this.value===this.data.length),e.writeU8(this.value),e.writeBytes(this.data)}else e.writeU8(this.value);return e}toRaw(){var e=this.getSize();return this.toWriter(new c(e)).render()}toFormat(){if(-1===this.value)return"0x01";if(this.data){if(this.data.length<=4){var e=this.toNum();if(this.equals(p.fromNum(e)))return e.toString(10)}const t=n.opcodesByVal[this.value];if(e=this.data.toString("hex"),!t)return`0x${s.hex8(this.value)} 0x`+e;let i=this.data.length.toString(16);if(i.length%2!=0&&(i="0"+i),i=s.revHex(i),this.data.length<=75)return`${t} 0x${i} 0x`+e;if(this.data.length<=255)return`${t} 0x4c 0x${i} 0x`+e;if(this.data.length<=65535)return`${t} 0x4d 0x${i} 0x`+e;if(this.data.length<=4294967295)return`${t} 0x4e 0x${i} 0x`+e}return n.opcodesByVal[this.value]||"0x"+s.hex8(this.value)}toASM(e){return-1===this.value?"[error]":this.data?n.toASM(this.data,e):n.opcodesByVal[this.value]||"OP_UNKNOWN"}static fromOp(e){return r("number"==typeof e),e=h[e],r(e,"Bad opcode."),e}static fromData(e){if(r(Buffer.isBuffer(e)),1===e.length){if(129===e[0])return p.fromOp(u.OP_1NEGATE);if(1<=e[0]&&e[0]<=16)return p.fromOp(e[0]+80)}return p.fromPush(e)}static fromPush(e){if(r(Buffer.isBuffer(e)),0===e.length)return p.fromOp(u.OP_0);if(e.length<=75)return new p(e.length,e);if(e.length<=255)return new p(u.OP_PUSHDATA1,e);if(e.length<=65535)return new p(u.OP_PUSHDATA2,e);if(e.length<=4294967295)return new p(u.OP_PUSHDATA4,e);throw new Error("Pushdata size too large.")}static fromString(e,t){return r("string"==typeof e),e=Buffer.from(e,t||"utf8"),p.fromData(e)}static fromSmall(e){return r(s.isU8(e)&&0<=e&&e<=16),p.fromOp(0===e?0:e+80)}static fromNum(e){return r(a.isScriptNum(e)),p.fromData(e.encode())}static fromInt(e){return r(s.isInt(e)),0===e?p.fromOp(u.OP_0):-1===e?p.fromOp(u.OP_1NEGATE):1<=e&&e<=16?p.fromOp(e+80):p.fromNum(a.fromNumber(e))}static fromBool(e){return r("boolean"==typeof e),p.fromSmall(e?1:0)}static fromSymbol(e){r("string"==typeof e),r(0<e.length),s.isUpperCase(e)||(e=e.toUpperCase()),s.startsWith(e,"OP_")||(e="OP_"+e);var t=n.opcodes[e];return null!=t||(r(s.startsWith(e,"OP_0X"),"Unknown opcode."),r(7===e.length,"Unknown opcode."),t=parseInt(e.substring(5),16),r(s.isU8(t),"Unknown opcode.")),p.fromOp(t)}static fromReader(e){var t,i=e.readU8(),r=h[i];if(r)return r;switch(i){case u.OP_PUSHDATA1:return e.left()<1?l:(t=e.readU8(),e.left()<t?(e.seek(e.left()),l):(t=e.readBytes(t),new p(i,t)));case u.OP_PUSHDATA2:return e.left()<2?(e.seek(e.left()),l):(t=e.readU16(),e.left()<t?(e.seek(e.left()),l):(t=e.readBytes(t),new p(i,t)));case u.OP_PUSHDATA4:return e.left()<4?(e.seek(e.left()),l):(t=e.readU32(),e.left()<t?(e.seek(e.left()),l):(t=e.readBytes(t),new p(i,t)));default:return e.left()<i?(e.seek(e.left()),l):(t=e.readBytes(i),new p(i,t))}}static fromRaw(e){return p.fromReader(new o(e))}static isOpcode(e){return e instanceof p}}l=Object.freeze(new p(-1));for(let e=0;e<=255;e++){var d;1<=e&&e<=78?h.push(null):(d=new p(e),h.push(Object.freeze(d)))}e.exports=p},function(e,t,i){const r=i(5).ContractStatus;e.exports=class extends class{constructor(e){this.period=e.period}run(e){var t=this.getResult();if(t&&Array.isArray(t)&&t.length<=10)for(var i of t)e.pushInt(i)}getResult(){return[]}}{constructor(e,t){super(e),this.type=e.type,this.addr=e.addr,this.dst=e.dst,this.status=t}getResult(){return this.status===r.Expired||this.status===r.Backed?[1,2]:this.status===r.Confirmed||this.status===r.Exchanged?[2,1]:[]}}},function(e,t,i){"use strict";const r=i(0),a=i(326),s=i(327);function n(e){var t=(i=n.getBackend(e)).backend,i=i.location;return new a(t,i,e)}n.getName=function(e){let t,i;switch(e=e||"memory"){case"ldb":case"leveldb":case"leveldown":t="leveldown",i="ldb";break;case"rdb":case"rocksdb":case"rocksdown":t="rocksdown",i="rdb";break;case"mdb":case"lmdb":t="lmdb",i="mdb";break;case"mem":case"memory":case"rbt":t="memory",i="mem";break;default:t=e,i="db"}return[t,i]},n.getBackend=function(e){var[t,i]=n.getName(e.db),a=s.get(t);let o=e.location;return"string"!=typeof o&&(r("memory"===t,"Location required."),o="memory"),{backend:a,location:o+"."+i}},e.exports=n},function(e,t,i){"use strict";t.AbstractLevelDOWN=i(403),t.AbstractIterator=i(254),t.AbstractChainedBatch=i(255)},function(e,t,i){"use strict";e.exports=process.nextTick},function(e,t,i){e.exports=i(408)(__dirname)},function(e,t){e.exports=function(e){return null!=e&&"object"==typeof e}},function(e,t,i){"use strict";function r(e){return"function"==typeof Array.isArray?Array.isArray(e):"[object Array]"===c.call(e)}function a(e){if(e&&"[object Object]"===c.call(e)){var t,i=o.call(e,"constructor"),r=e.constructor&&e.constructor.prototype&&o.call(e.constructor.prototype,"isPrototypeOf");if(!e.constructor||i||r){for(t in e);return void 0===t||o.call(e,t)}}}function s(e,t){u&&"__proto__"===t.name?u(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue}function n(e,t){if("__proto__"===t){if(!o.call(e,t))return;if(h)return h(e,t).value}return e[t]}var o=Object.prototype.hasOwnProperty,c=Object.prototype.toString,u=Object.defineProperty,h=Object.getOwnPropertyDescriptor;e.exports=function e(){var t,i,o,c,u,h=arguments[0],l=1,p=arguments.length,d=!1;for("boolean"==typeof h&&(d=h,h=arguments[1]||{},l=2),(null==h||"object"!=typeof h&&"function"!=typeof h)&&(h={});l<p;++l)if(null!=(t=arguments[l]))for(i in t)u=n(h,i),h!==(o=n(t,i))&&(d&&o&&(a(o)||(c=r(o)))?s(h,{name:i,newValue:e(d,u=c?(c=!1,u&&r(u)?u:[]):u&&a(u)?u:{},o)}):void 0!==o&&s(h,{name:i,newValue:o}));return h}},function(e,t,i){"use strict";var r=i(458),a=i(8),s=i(39).Buffer;i="undefined"==typeof setImmediate?process.nextTick:setImmediate;t.paramsHaveRequestBody=function(e){return e.body||e.requestBodyStream||e.json&&"boolean"!=typeof e.json||e.multipart},t.safeStringify=function(e,t){var i;try{i=JSON.stringify(e,t)}catch(a){i=r(e,t)}return i},t.md5=function(e){return a.createHash("md5").update(e).digest("hex")},t.isReadStream=function(e){return e.readable&&e.path&&e.mode},t.toBase64=function(e){return s.from(e||"","utf8").toString("base64")},t.copy=function(e){var t={};return Object.keys(e).forEach((function(i){t[i]=e[i]})),t},t.version=function(){var e=process.version.replace("v","").split(".");return{major:parseInt(e[0],10),minor:parseInt(e[1],10),patch:parseInt(e[2],10)}},t.defer=i},function(e,t){e.exports=require("zlib")},function(e,t,i){var r=i(23),a=i(101),s=i(57),n=i(24),o=i(105),c=i(106);i=i(51);e.exports={Key:r,parseKey:r.parse,Fingerprint:a,parseFingerprint:a.parse,Signature:s,parseSignature:s.parse,PrivateKey:n,parsePrivateKey:n.parse,generatePrivateKey:n.generate,Certificate:o,parseCertificate:o.parse,createSelfSignedCertificate:o.createSelfSigned,createCertificate:o.create,Identity:c,identityFromDN:c.parseDN,identityForHost:c.forHost,identityForUser:c.forUser,identityForEmail:c.forEmail,identityFromArray:c.fromArray,FingerprintFormatError:i.FingerprintFormatError,InvalidAlgorithmError:i.InvalidAlgorithmError,KeyParseError:i.KeyParseError,SignatureParseError:i.SignatureParseError,KeyEncryptedError:i.KeyEncryptedError,CertificateParseError:i.CertificateParseError}},function(e,t){e.exports={newInvalidAsn1Error:function(e){var t=new Error;return t.name="InvalidAsn1Error",t.message=e||"",t}}},function(e,t){e.exports={EOC:0,Boolean:1,Integer:2,BitString:3,OctetString:4,Null:5,OID:6,ObjectDescriptor:7,External:8,Real:9,Enumeration:10,PDV:11,Utf8String:12,RelativeOID:13,Sequence:16,Set:17,NumericString:18,PrintableString:19,T61String:20,VideotexString:21,IA5String:22,UTCTime:23,GeneralizedTime:24,GraphicString:25,VisibleString:26,GeneralString:28,UniversalString:29,CharacterString:30,BMPString:31,Constructor:32,Context:128}},function(e,t,i){e.exports={DiffieHellman:f,generateECDSA:function(e){var t,i,r,n=[];return l?(t={nistp256:"prime256v1",nistp384:"secp384r1",nistp521:"secp521r1"}[e],(t=a.createECDH(t)).generateKeys(),n.push({name:"curve",data:s.from(e)}),n.push({name:"Q",data:t.getPublicKey()}),n.push({name:"d",data:t.getPrivateKey()})):(r=(t=new m(e)).getN(),i=Math.ceil((r.bitLength()+64)/8),i=new d(a.randomBytes(i)),r=r.subtract(d.ONE),i=i.mod(r).add(d.ONE),r=t.getG().multiply(i),i=s.from(i.toByteArray()),r=s.from(t.getCurve().encodePointHex(r),"hex"),n.push({name:"curve",data:s.from(e)}),n.push({name:"Q",data:r}),n.push({name:"d",data:i})),new h({type:"ecdsa",curve:e,parts:n})},generateED25519:function(){var e=c.sign.keyPair(),t=s.from(e.secretKey),i=(e=s.from(e.publicKey),r.strictEqual(t.length,64),r.strictEqual(e.length,32),[]);return i.push({name:"A",data:e}),i.push({name:"k",data:t.slice(0,32)}),new h({type:"ed25519",parts:i})}};var r=i(10),a=i(8),s=i(12).Buffer,n=i(30),o=i(25),c=i(103),u=i(23),h=i(24),l=void 0!==a.createECDH,p=(i(468),i(133)),d=i(102).BigInteger;function f(e){if(o.assertCompatible(e,u,[1,4],"key"),this._isPriv=h.isPrivateKey(e,[1,3]),this._algo=e.type,this._curve=e.curve,"dsa"===(this._key=e).type){if(!l)throw new Error("Due to bugs in the node 0.10 crypto API, node 0.12.x or later is required to use DH");this._dh=a.createDiffieHellman(e.part.p.data,void 0,e.part.g.data,void 0),this._p=e.part.p,this._g=e.part.g,this._isPriv&&this._dh.setPrivateKey(e.part.x.data),this._dh.setPublicKey(e.part.y.data)}else if("ecdsa"===e.type){var t;l?(t={nistp256:"prime256v1",nistp384:"secp384r1",nistp521:"secp521r1"}[e.curve],this._dh=a.createECDH(t),"object"!=typeof this._dh||"function"!=typeof this._dh.setPrivateKey?(l=!1,f.call(this,e)):(this._isPriv&&this._dh.setPrivateKey(e.part.d.data),this._dh.setPublicKey(e.part.Q.data))):(this._ecParams=new m(this._curve),this._isPriv&&(this._priv=new v(this._ecParams,e.part.d.data)))}else{if("curve25519"!==e.type)throw new Error("DH not supported for "+e.type+" keys");this._isPriv&&(o.assertCompatible(e,h,[1,5],"key"),this._priv=e.part.k.data)}}function m(e){e=n.curves[e];var t=(r.object(e),new d(e.p)),i=new d(e.a),a=new d(e.b),s=new d(e.n),o=d.ONE;i=(t=new p.ECCurveFp(t,i,a)).decodePointHex(e.G.toString("hex"));this.curve=t,this.g=i,this.n=s,this.h=o}function g(e,t){this._params=e,0===t[0]&&(t=t.slice(1)),this._pub=e.getCurve().decodePointHex(t.toString("hex"))}function v(e,t){this._params=e,this._priv=new d(o.mpNormalize(t))}f.prototype.getPublicKey=function(){return this._isPriv?this._key.toPublic():this._key},f.prototype.getKey=f.prototype.getPrivateKey=function(){return this._isPriv?this._key:void 0},f.prototype._keyCheck=function(e,t){if(r.object(e,"key"),t||o.assertCompatible(e,h,[1,3],"key"),o.assertCompatible(e,u,[1,4],"key"),e.type!==this._algo)throw new Error("A "+e.type+" key cannot be used in "+this._algo+" Diffie-Hellman");if(e.curve!==this._curve)throw new Error("A key from the "+e.curve+" curve cannot be used with a "+this._curve+" Diffie-Hellman");"dsa"===e.type&&(r.deepEqual(e.part.p,this._p,"DSA key prime does not match"),r.deepEqual(e.part.g,this._g,"DSA key generator does not match"))},f.prototype.setPrivateKey=f.prototype.setKey=function(e){var t;this._keyCheck(e),"dsa"===e.type?(this._dh.setPrivateKey(e.part.x.data),this._dh.setPublicKey(e.part.y.data)):"ecdsa"===e.type?l?(this._dh.setPrivateKey(e.part.d.data),this._dh.setPublicKey(e.part.Q.data)):this._priv=new v(this._ecParams,e.part.d.data):"curve25519"===e.type&&(t=e.part.k,e.part.k||(t=e.part.r),this._priv=t.data,0===this._priv[0]&&(this._priv=this._priv.slice(1)),this._priv=this._priv.slice(0,32)),this._key=e,this._isPriv=!0},f.prototype.computeSecret=function(e){if(this._keyCheck(e,!0),!this._isPriv)throw new Error("DH exchange has not been initialized with a private key yet");var t;if("dsa"===this._algo)return this._dh.computeSecret(e.part.y.data);if("ecdsa"===this._algo)return l?this._dh.computeSecret(e.part.Q.data):(t=new g(this._ecParams,e.part.Q.data),this._priv.deriveSharedSecret(t));if("curve25519"!==this._algo)throw new Error("Invalid algorithm: "+this._algo);for(t=e.part.A.data;0===t[0]&&32<t.length;)t=t.slice(1);return e=this._priv,r.strictEqual(t.length,32),r.strictEqual(e.length,32),e=c.box.before(new Uint8Array(t),new Uint8Array(e)),s.from(e)},f.prototype.generateKeys=f.prototype.generateKey=function(){var e,t,i,n=[];if("dsa"===this._algo)return this._dh.generateKeys(),n.push({name:"p",data:this._p.data}),n.push({name:"q",data:this._key.part.q.data}),n.push({name:"g",data:this._g.data}),n.push({name:"y",data:this._dh.getPublicKey()}),n.push({name:"x",data:this._dh.getPrivateKey()}),this._key=new h({type:"dsa",parts:n}),this._isPriv=!0,this._key;if("ecdsa"===this._algo)return l?(this._dh.generateKeys(),n.push({name:"curve",data:s.from(this._curve)}),n.push({name:"Q",data:this._dh.getPublicKey()}),n.push({name:"d",data:this._dh.getPrivateKey()})):(t=this._ecParams.getN(),e=new d(a.randomBytes(t.bitLength())),t=t.subtract(d.ONE),e=e.mod(t).add(d.ONE),t=this._ecParams.getG().multiply(e),e=s.from(e.toByteArray()),t=s.from(this._ecParams.getCurve().encodePointHex(t),"hex"),this._priv=new v(this._ecParams,e),n.push({name:"curve",data:s.from(this._curve)}),n.push({name:"Q",data:t}),n.push({name:"d",data:e})),this._key=new h({type:"ecdsa",curve:this._curve,parts:n}),this._isPriv=!0,this._key;if("curve25519"===this._algo)return i=c.box.keyPair(),e=s.from(i.secretKey),t=s.from(i.publicKey),e=s.concat([e,t]),r.strictEqual(e.length,64),r.strictEqual(t.length,32),n.push({name:"A",data:t}),n.push({name:"k",data:e}),this._key=new h({type:"curve25519",parts:n}),this._isPriv=!0,this._key;throw new Error("Invalid algorithm: "+this._algo)},m.prototype.getCurve=function(){return this.curve},m.prototype.getG=function(){return this.g},m.prototype.getN=function(){return this.n},m.prototype.getH=function(){return this.h},v.prototype.deriveSharedSecret=function(e){return r.ok(e instanceof g),e=e._pub.multiply(this._priv),s.from(e.getX().toBigInteger().toByteArray())}},function(e,t,i){e.exports={read:function(e,t){return h.read(e,t,"pkcs1")},readPkcs1:function(e,t,i){switch(e){case"RSA":if("public"===t)return function(e){var t=p(e,"modulus");e=p(e,"exponent");return new c({type:"rsa",parts:[{name:"e",data:e},{name:"n",data:t}]})}(i);if("private"===t)return function(e){var t=p(e,"version"),i=(t=(r.strictEqual(t[0],0),p(e,"modulus")),p(e,"public exponent")),a=p(e,"private exponent"),s=p(e,"prime1"),n=p(e,"prime2"),o=p(e,"exponent1"),c=p(e,"exponent2");e=p(e,"iqmp");return new u({type:"rsa",parts:[{name:"n",data:t},{name:"e",data:i},{name:"d",data:a},{name:"iqmp",data:e},{name:"p",data:s},{name:"q",data:n},{name:"dmodp",data:o},{name:"dmodq",data:c}]})}(i);throw new Error("Unknown key type: "+t);case"DSA":if("public"===t)return function(e){var t=p(e,"y"),i=p(e,"p"),r=p(e,"q");e=p(e,"g");return new c({type:"dsa",parts:[{name:"y",data:t},{name:"p",data:i},{name:"q",data:r},{name:"g",data:e}]})}(i);if("private"===t)return function(e){var t=p(e,"version"),i=(t=(r.strictEqual(t.readUInt8(0),0),p(e,"p")),p(e,"q")),a=p(e,"g"),s=p(e,"y");e=p(e,"x");return new u({type:"dsa",parts:[{name:"p",data:t},{name:"q",data:i},{name:"g",data:a},{name:"y",data:s},{name:"x",data:e}]})}(i);throw new Error("Unknown key type: "+t);case"EC":case"ECDSA":if("private"===t)return function(e){var t=p(e,"version"),i=(t=(r.strictEqual(t.readUInt8(0),1),e.readString(a.Ber.OctetString,!0)),e.readSequence(160),l(e));r.string(i,"a known elliptic curve"),e.readSequence(161),e=e.readString(a.Ber.BitString,!0),e=o.ecNormalize(e),i={type:"ecdsa",parts:[{name:"curve",data:s.from(i)},{name:"Q",data:e},{name:"d",data:t}]};return new u(i)}(i);if("public"===t)return function(e){e.readSequence();for(var t,i=e.readOID(),u=(r.strictEqual(i,"1.2.840.10045.2.1","must be ecPublicKey"),e.readOID()),h=Object.keys(n.curves),l=0;l<h.length;++l){var p=h[l];if(n.curves[p].pkcs8oid===u){t=p;break}}return r.string(t,"a known ECDSA named curve"),i=e.readString(a.Ber.BitString,!0),i=o.ecNormalize(i),e={type:"ecdsa",parts:[{name:"curve",data:s.from(t)},{name:"Q",data:i}]},new c(e)}(i);throw new Error("Unknown key type: "+t);case"EDDSA":case"EdDSA":if("private"===t)return function(e){var t=p(e,"version"),i=(t=(r.strictEqual(t.readUInt8(0),1),e.readString(a.Ber.OctetString,!0)),e.readSequence(160),e.readOID());r.strictEqual(i,"1.3.101.112","the ed25519 curve identifier"),e.readSequence(161),i=o.readBitString(e),e={type:"ed25519",parts:[{name:"A",data:o.zeroPadToLength(i,32)},{name:"k",data:t}]};return new u(e)}(i);throw new Error(t+" keys not supported with EdDSA");default:throw new Error("Unknown key algo: "+e)}},write:function(e,t){return h.write(e,t,"pkcs1")},writePkcs1:function(e,t){switch(e.startSequence(),t.type){case"rsa":(u.isPrivateKey(t)?function(e,t){var i=s.from([0]);e.writeBuffer(i,a.Ber.Integer),e.writeBuffer(t.part.n.data,a.Ber.Integer),e.writeBuffer(t.part.e.data,a.Ber.Integer),e.writeBuffer(t.part.d.data,a.Ber.Integer),e.writeBuffer(t.part.p.data,a.Ber.Integer),e.writeBuffer(t.part.q.data,a.Ber.Integer),t.part.dmodp&&t.part.dmodq||o.addRSAMissing(t),e.writeBuffer(t.part.dmodp.data,a.Ber.Integer),e.writeBuffer(t.part.dmodq.data,a.Ber.Integer),e.writeBuffer(t.part.iqmp.data,a.Ber.Integer)}:function(e,t){e.writeBuffer(t.part.n.data,a.Ber.Integer),e.writeBuffer(t.part.e.data,a.Ber.Integer)})(e,t);break;case"dsa":(u.isPrivateKey(t)?function(e,t){var i=s.from([0]);e.writeBuffer(i,a.Ber.Integer),e.writeBuffer(t.part.p.data,a.Ber.Integer),e.writeBuffer(t.part.q.data,a.Ber.Integer),e.writeBuffer(t.part.g.data,a.Ber.Integer),e.writeBuffer(t.part.y.data,a.Ber.Integer),e.writeBuffer(t.part.x.data,a.Ber.Integer)}:function(e,t){e.writeBuffer(t.part.y.data,a.Ber.Integer),e.writeBuffer(t.part.p.data,a.Ber.Integer),e.writeBuffer(t.part.q.data,a.Ber.Integer),e.writeBuffer(t.part.g.data,a.Ber.Integer)})(e,t);break;case"ecdsa":(u.isPrivateKey(t)?function(e,t){var i=s.from([1]);e.writeBuffer(i,a.Ber.Integer),e.writeBuffer(t.part.d.data,a.Ber.OctetString),e.startSequence(160),i=t.part.curve.data.toString(),i=n.curves[i].pkcs8oid,r.string(i,"a known ECDSA named curve"),e.writeOID(i),e.endSequence(),e.startSequence(161),i=o.ecNormalize(t.part.Q.data,!0);e.writeBuffer(i,a.Ber.BitString),e.endSequence()}:function(e,t){e.startSequence(),e.writeOID("1.2.840.10045.2.1");var i=t.part.curve.data.toString();i=n.curves[i].pkcs8oid,r.string(i,"a known ECDSA named curve"),e.writeOID(i),e.endSequence(),i=o.ecNormalize(t.part.Q.data,!0);e.writeBuffer(i,a.Ber.BitString)})(e,t);break;case"ed25519":u.isPrivateKey(t)?function(e,t){var i=s.from([1]);e.writeBuffer(i,a.Ber.Integer),e.writeBuffer(t.part.k.data,a.Ber.OctetString),e.startSequence(160),e.writeOID("1.3.101.112"),e.endSequence(),e.startSequence(161),o.writeBitString(e,t.part.A.data),e.endSequence()}(e,t):function(){throw new Error("Public keys are not supported for EdDSA PKCS#1")}();break;default:throw new Error("Unknown key algo: "+t.type)}e.endSequence()}};var r=i(10),a=i(58),s=i(12).Buffer,n=i(30),o=i(25),c=i(23),u=i(24),h=i(65),l=i(104).readECDSACurve;function p(e,t){return r.strictEqual(e.peek(),a.Ber.Integer,t+" is not an Integer"),o.mpNormalize(e.readString(a.Ber.Integer,!0))}},function(e,t,i){e.exports={read:function(e,t){"string"!=typeof e&&(r.buffer(e,"buf"),e=e.toString("ascii"));var i=e.split("\n");if(i[0].match(/^Private-key-format\: v1/)){e=i[1].split(" ");var c=parseInt(e[1],10);e=e[2];if(u[c])return function(e,t){if(u[e].match(/^RSA-/))return function(e){var t={};e.forEach((function(e){"Modulus:"===e.split(" ")[0]?t.n=h(e):"PublicExponent:"===e.split(" ")[0]?t.e=h(e):"PrivateExponent:"===e.split(" ")[0]?t.d=h(e):"Prime1:"===e.split(" ")[0]?t.p=h(e):"Prime2:"===e.split(" ")[0]?t.q=h(e):"Exponent1:"===e.split(" ")[0]?t.dmodp=h(e):"Exponent2:"===e.split(" ")[0]?t.dmodq=h(e):"Coefficient:"===e.split(" ")[0]&&(t.iqmp=h(e))})),e={type:"rsa",parts:[{name:"e",data:o.mpNormalize(t.e)},{name:"n",data:o.mpNormalize(t.n)},{name:"d",data:o.mpNormalize(t.d)},{name:"p",data:o.mpNormalize(t.p)},{name:"q",data:o.mpNormalize(t.q)},{name:"dmodp",data:o.mpNormalize(t.dmodp)},{name:"dmodq",data:o.mpNormalize(t.dmodq)},{name:"iqmp",data:o.mpNormalize(t.iqmp)}]};return new n(e)}(t);if("ECDSA-P384-SHA384"!==u[e]&&"ECDSA-P256-SHA256"!==u[e])throw new Error("Unsupported algorithm: "+u[e]);t=a.from(t[0].split(" ")[1],"base64");var i="nistp384",r=384;return"ECDSA-P256-SHA256"===u[e]&&(i="nistp256",r=256),e=o.publicFromPrivateECDSA(i,t).part.Q.data,r={type:"ecdsa",curve:i,size:r,parts:[{name:"curve",data:a.from(i)},{name:"d",data:t},{name:"Q",data:e}]},new n(r)}(c,i.slice(2));throw new Error("Unsupported algorithm: "+e)}for(var l=0;i[l].match(/^\;/);)l++;if(!i[l].match(/\. IN KEY /)&&!i[l].match(/\. IN DNSKEY /)||0!==i[l+1].length)throw new Error("Cannot parse dnssec key");return function(e){e=e.split(" ");var t=parseInt(e[5],10);if(!u[t])throw new Error("Unsupported algorithm: "+t);if(e=e.slice(6,e.length).join(),e=a.from(e,"base64"),u[t].match(/^RSA-/)){if(3!=(r=e.readUInt8(0))&&1!=r)throw new Error("Cannot parse dnssec key: unsupported exponent length");var i=e.slice(1,r+1),r=(i=o.mpNormalize(i),e.slice(1+r)),n=(r=o.mpNormalize(r),{type:"rsa",parts:[]});return n.parts.push({name:"e",data:i}),n.parts.push({name:"n",data:r}),new s(n)}if("ECDSA-P384-SHA384"!==u[t]&&"ECDSA-P256-SHA256"!==u[t])throw new Error("Unsupported algorithm: "+u[t]);return i="nistp384",r=384,u[t].match(/^ECDSA-P256-SHA256/)&&(i="nistp256",r=256),n={type:"ecdsa",curve:i,size:r,parts:[{name:"curve",data:a.from(i)},{name:"Q",data:o.ecNormalize(e)}]},new s(n)}(i[l])},write:function(e,t){if(n.isPrivateKey(e)){if("rsa"===e.type)return function(e,t){e.part.dmodp&&e.part.dmodq||o.addRSAMissing(e);var i="";i=(i+="Private-key-format: v1.3\n")+"Algorithm: "+function(e){if(e&&e.hashAlgo&&"sha1"!==e.hashAlgo){if("sha256"===e.hashAlgo)return"8 (RSASHA256)";if("sha512"===e.hashAlgo)return"10 (RSASHA512)";throw new Error("Unknown or unsupported hash: "+e.hashAlgo)}return"5 (RSASHA1)"}(t)+"\n",t=o.mpDenormalize(e.part.n.data),i+="Modulus: "+t.toString("base64")+"\n",t=o.mpDenormalize(e.part.e.data),i+="PublicExponent: "+t.toString("base64")+"\n",t=o.mpDenormalize(e.part.d.data),i+="PrivateExponent: "+t.toString("base64")+"\n",t=o.mpDenormalize(e.part.p.data),i+="Prime1: "+t.toString("base64")+"\n",t=o.mpDenormalize(e.part.q.data),i+="Prime2: "+t.toString("base64")+"\n",t=o.mpDenormalize(e.part.dmodp.data),i+="Exponent1: "+t.toString("base64")+"\n",t=o.mpDenormalize(e.part.dmodq.data),i+="Exponent2: "+t.toString("base64")+"\n",t=o.mpDenormalize(e.part.iqmp.data),i+="Coefficient: "+t.toString("base64")+"\n",e=new Date;return i=(i=(i+="Created: "+l(e)+"\n")+"Publish: "+l(e)+"\n")+"Activate: "+l(e)+"\n",a.from(i,"ascii")}(e,t);if("ecdsa"===e.type)return function(e){var t="";if(t+="Private-key-format: v1.3\n","nistp256"===e.curve)t+="Algorithm: 13 (ECDSAP256SHA256)\n";else{if("nistp384"!==e.curve)throw new Error("Unsupported curve");t+="Algorithm: 14 (ECDSAP384SHA384)\n"}return t+="PrivateKey: "+(e=e.part.d.data.toString("base64"))+"\n",t=(t=(t+="Created: "+l(e=new Date)+"\n")+"Publish: "+l(e)+"\n")+"Activate: "+l(e)+"\n",a.from(t,"ascii")}(e);throw new Error("Unsupported algorithm: "+e.type)}throw s.isKey(e)?new Error('Format "dnssec" only supports writing private keys'):new Error("key is not a Key or PrivateKey")}};var r=i(10),a=i(12).Buffer,s=i(23),n=i(24),o=i(25),c=(i(91),i(178),{"rsa-sha1":5,"rsa-sha256":8,"rsa-sha512":10,"ecdsa-p256-sha256":13,"ecdsa-p384-sha384":14}),u={};function h(e){return a.from(e.split(" ")[1],"base64")}function l(e){var t=e.getFullYear()+""+(e.getMonth()+1)+e.getUTCDate();return(t+=""+e.getUTCHours()+e.getUTCMinutes())+e.getUTCSeconds()}Object.keys(c).forEach((function(e){u[c[e]]=e.toUpperCase()}))},function(e,t,i){e.exports={read:function(e,t){for(var i,n,p=e.toString("ascii").split(/[\r\n]+/),d=!1,f=0;f<p.length;)if((i=l(p[f++]))&&(n={"putty-user-key-file-2":2,"putty-user-key-file-3":3}[i[0].toLowerCase()])){d=!0;break}if(!d)throw new Error("No PuTTY format first line found");e=i[1];var m=(i=l(p[f++]),r.equal(i[0].toLowerCase(),"encryption"),i[1]),g=(i=l(p[f++]),r.equal(i[0].toLowerCase(),"comment"),i[1]),v=(i=l(p[f++]),r.equal(i[0].toLowerCase(),"public-lines"),parseInt(i[1],10));if(!isFinite(v)||v<0||v>p.length)throw new Error("Invalid public-lines count");var y,b=a.from(p.slice(f,f+v).join(""),"base64"),w=s.algToKeyType(e);if((b=s.read(b)).type!==w)throw new Error("Outer key algorithm mismatch");if(p[f+=v]){if(i=l(p[f++]),r.equal(i[0].toLowerCase(),"private-lines"),v=parseInt(i[1],10),!isFinite(v)||v<0||v>p.length)throw new Error("Invalid private-lines count");if(v=a.from(p.slice(f,f+v).join(""),"base64"),"none"!==m&&3===n)throw new Error("Encrypted keys arenot supported for PuTTY format version 3");if("aes256-cbc"===m){if(!t.passphrase)throw new h.KeyEncryptedError(t.filename,"PEM");m=a.alloc(16,0),(t=c.createDecipheriv("aes-256-cbc",function(e){var t=c.createHash("sha1").update(a.concat([a.from([0,0,0,0]),a.from(e)])).digest();e=c.createHash("sha1").update(a.concat([a.from([0,0,0,1]),a.from(e)])).digest();return a.concat([t,e]).slice(0,32)}(t.passphrase),m)).setAutoPadding(!1),v=a.concat([t.update(v),t.final()])}if((b=new u(b)).type!==w)throw new Error("Outer key algorithm mismatch");if(m=new o({buffer:v}),"ssh-dss"===e)y=[{name:"x",data:m.readBuffer()}];else if("ssh-rsa"===e)y=[{name:"d",data:m.readBuffer()},{name:"p",data:m.readBuffer()},{name:"q",data:m.readBuffer()},{name:"iqmp",data:m.readBuffer()}];else if(e.match(/^ecdsa-sha2-nistp/))y=[{name:"d",data:m.readBuffer()}];else{if("ssh-ed25519"!==e)throw new Error("Unsupported PPK key type: "+e);y=[{name:"k",data:m.readBuffer()}]}b=new u({type:b.type,parts:b.parts.concat(y)})}return b.comment=g,b},write:function(e,t){var i,o;if(r.object(e),n.isKey(e))return i=s.keyTypeToAlg(e),o=s.write(e),e=e.comment||"",(o=function(e){for(var t=[],i=0;i<e.length;)t.push(e.slice(i,i+64)),i+=64;return t}(o.toString("base64"))).unshift("Public-Lines: "+o.length),o.unshift("Comment: "+e),o.unshift("Encryption: none"),o.unshift("PuTTY-User-Key-File-2: "+i),a.from(o.join("\n")+"\n");throw new Error("Must be a public key")}};var r=i(10),a=i(12).Buffer,s=i(66),n=i(23),o=i(91),c=i(8),u=i(24),h=i(51);function l(e){var t=e.indexOf(":");if(-1===t)return null;var i=e.slice(0,t);for(++t;" "===e[t];)++t;return[i,e.slice(t)]}},function(e,t){function i(e){this.dict=e||{}}i.prototype.set=function(e,t,i){var r,a;if("object"!=typeof e)return void 0===i&&(i=!0),r=this.has(e),!i&&r?this.dict[r]=this.dict[r]+","+t:this.dict[r||e]=t,r;for(a in e)this.set(a,e[a],t)},i.prototype.has=function(e){for(var t=Object.keys(this.dict),i=(e=e.toLowerCase(),0);i<t.length;i++)if(t[i].toLowerCase()===e)return t[i];return!1},i.prototype.get=function(e){e=e.toLowerCase();var t,i,r=this.dict;return Object.keys(r).forEach((function(a){i=a.toLowerCase(),e===i&&(t=r[a])})),t},i.prototype.swap=function(e){var t=this.has(e);if(t!==e){if(!t)throw new Error('There is no header than matches "'+e+'"');this.dict[e]=this.dict[t],delete this.dict[t]}},i.prototype.del=function(e){var t=this.has(e);return delete this.dict[t||e]},e.exports=function(e){return new i(e)},e.exports.httpify=function(e,t){var r=new i(t);return e.setHeader=function(e,t,i){if(void 0!==t)return r.set(e,t,i)},e.hasHeader=function(e){return r.has(e)},e.getHeader=function(e){return r.get(e)},e.removeHeader=function(e){return r.del(e)},e.headers=r.dict,r}},function(e,t,i){"use strict";var r=i(496),a=i(184),s=i(92),n=i(291),o=i(498);function c(e,t,i){var r,a,s,o=this._refs[i];if("string"==typeof o){if(!this._refs[o])return c.call(this,e,t,o);o=this._refs[o]}return(o=o||this._schemas[i])instanceof n?d(o.schema,this._opts.inlineRefs)?o.schema:o.validate||this._compile(o):((o=u.call(this,t,i))&&(r=o.schema,t=o.root,s=o.baseId),r instanceof n?a=r.validate||e.call(this,r.schema,t,void 0,s):void 0!==r&&(a=d(r,this._opts.inlineRefs)?r:e.call(this,r,t,void 0,s)),a)}function u(e,t){var i=r.parse(t),a=m(i),s=f(this._getId(e.schema));if(0===Object.keys(e.schema).length||a!==s){a=v(a);var o=this._refs[a];if("string"==typeof o)return function(e,t,i){var r,a;if(t=u.call(this,e,t))return r=t.schema,a=t.baseId,e=t.root,(t=this._getId(r))&&(a=y(a,t)),l.call(this,i,a,r,e)}.call(this,e,o,i);if(o instanceof n)o.validate||this._compile(o);else{if(!((o=this._schemas[a])instanceof n))return;if(o.validate||this._compile(o),a==v(t))return{schema:o,root:e,baseId:s}}if(!(e=o).schema)return;s=f(this._getId(e.schema))}return l.call(this,i,s,e.schema,e)}(e.exports=c).normalizeId=v,c.fullPath=f,c.url=y,c.ids=function(e){var t=v(this._getId(e)),i={"":t},n={"":f(t,!1)},c={},u=this;return o(e,{allKeys:!0},(function(e,t,o,h,l,p,d){if(""!==t){var f=u._getId(e),m=i[h];h=n[h]+"/"+l;if(void 0!==d&&(h+="/"+("number"==typeof d?d:s.escapeFragment(d))),"string"==typeof f)if(f=m=v(m?r.resolve(m,f):f),(l="string"==typeof(l=u._refs[f])?u._refs[l]:l)&&l.schema){if(!a(e,l.schema))throw new Error('id "'+f+'" resolves to more than one schema')}else if(f!=v(h))if("#"==f[0]){if(c[f]&&!a(e,c[f]))throw new Error('id "'+f+'" resolves to more than one schema');c[f]=e}else u._refs[f]=h;i[t]=m,n[t]=h}})),c},c.inlineRef=d,c.schema=u;var h=s.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function l(e,t,i,r){if(e.fragment=e.fragment||"","/"==e.fragment.slice(0,1)){for(var a=e.fragment.split("/"),n=1;n<a.length;n++){var o=a[n];if(o){if(void 0===(i=i[o=s.unescapeFragment(o)]))break;h[o]||((o=this._getId(i))&&(t=y(t,o)),i.$ref&&(o=y(t,i.$ref),o=u.call(this,r,o))&&(i=o.schema,r=o.root,t=o.baseId))}}return void 0!==i&&i!==r.schema?{schema:i,root:r,baseId:t}:void 0}}var p=s.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function d(e,t){return!1!==t&&(void 0===t||!0===t?function e(t){var i;if(Array.isArray(t)){for(var r=0;r<t.length;r++)if("object"==typeof(i=t[r])&&!e(i))return!1}else for(var a in t){if("$ref"==a)return!1;if("object"==typeof(i=t[a])&&!e(i))return!1}return!0}(e):t?function e(t){var i,r=0;if(Array.isArray(t)){for(var a=0;a<t.length;a++)if("object"==typeof(i=t[a])&&(r+=e(i)),r==1/0)return 1/0}else for(var s in t){if("$ref"==s)return 1/0;if(p[s])r++;else if("object"==typeof(i=t[s])&&(r+=e(i)+1),r==1/0)return 1/0}return r}(e)<=t:void 0)}function f(e,t){return!1!==t&&(e=v(e)),m(r.parse(e))}function m(e){return r.serialize(e).split("#")[0]+"#"}var g=/#\/?$/;function v(e){return e?e.replace(g,""):""}function y(e,t){return t=v(t),r.resolve(e,t)}},function(e,t,i){"use strict";e.exports=function e(t,i){if(t===i)return!0;if(t&&i&&"object"==typeof t&&"object"==typeof i){if(t.constructor!==i.constructor)return!1;var r,a,s;if(Array.isArray(t)){if((r=t.length)!=i.length)return!1;for(a=r;0!=a--;)if(!e(t[a],i[a]))return!1}else{if(t.constructor===RegExp)return t.source===i.source&&t.flags===i.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===i.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===i.toString();if((r=(s=Object.keys(t)).length)!==Object.keys(i).length)return!1;for(a=r;0!=a--;)if(!Object.prototype.hasOwnProperty.call(i,s[a]))return!1;for(a=r;0!=a--;){var n=s[a];if(!e(t[n],i[n]))return!1}}return!0}return t!=t&&i!=i}},function(e,t,i){"use strict";var r=i(183);function a(e,t,i){this.message=i||a.message(e,t),this.missingRef=r.url(e,t),this.missingSchema=r.normalizeId(r.fullPath(this.missingRef))}function s(e){return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e}e.exports={Validation:s((function(e){this.message="validation failed",this.errors=e,this.ajv=this.validation=!0})),MissingRef:s(a)},a.message=function(e,t){return"can't resolve reference "+t+" from id "+e}},function(e,t,i){var r=i(299),a=i(300);e.exports=function(e,t,i){var s=t&&i||0,n=("string"==typeof e&&(t="binary"===e?new Array(16):null,e=null),(e=e||{}).random||(e.rng||r)());if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t)for(var o=0;o<16;++o)t[s+o]=n[o];return t||a(n)}},function(e,t,i){
|
|
410
410
|
/*!
|
|
411
411
|
* selector.js
|
|
412
412
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -424,7 +424,7 @@ function r(e){let t=null;var i=r.list[e.contract.options.type];return i?new(t=i.
|
|
|
424
424
|
*
|
|
425
425
|
* @note 为了让打包程序正常工作,没有使用自动化方案来引入类文件
|
|
426
426
|
*/
|
|
427
|
-
const r=i(5).ContractType;e.exports=function(e){if(!e)return i(188);switch(e.oper){case r.cpRegister:return i(192);case r.cpChange:return i(194);case r.coinbase:return i(195);case r.contractPromise:return i(196);case r.scRegister:return i(199);case r.scUpdate:return i(200);case r.scState:return i(201);case r.scRun:return i(202);case r.scNotify:return i(208);case r.propFound:return i(209);case r.vote:return i(210);case r.propSale:return i(211);case r.notify:return i(212);case r.contractCreate:return i(213);case r.contractExecute:return i(214);case r.erIssue:return i(215);case r.erAbolish:return i(216);case r.enchanceCp:return i(217);default:try{return i(581)("./"+e.oper)}catch(e){return i(14)}}}},function(e,t,i){var r=i(14);const{nestingExtentCodes:a,unspendableCodes:s,opcodes:n}=i(19),o=i(117),c=i(3),u=i(118);e.exports=class extends r{async insert(){var e=this.getOpt();for(let i=0;i<e.tx.outputs.length;i++){var t=""+e.hash+i;e.env.middleHashMem.has(t)||this.setOutputIndex(e,i)&&(await o(e).insert(),e.env.middleHashMem.add(t))}}async erase(){var e=this.getOpt();for(let t=0;t<e.tx.outputs.length;t++)e.env.middleHashMem.delete(""+e.hash+t),this.setOutputIndex(e,t)&&await o(e).erase()}async confirm(){var e=this.getOpt();for(let i=0;i<e.tx.outputs.length;i++){var t=""+e.hash+i;e.env.middleHashChain.has(t)||this.setOutputIndex(e,i)&&(await o(e).confirm(),e.env.middleHashChain.add(t))}}async unconfirm(){var e=this.getOpt();for(let t=0;t<e.tx.outputs.length;t++)e.env.middleHashChain.delete(""+e.hash+t),this.setOutputIndex(e,t)&&await o(e).unconfirm()}async verify(){var e=this.getOpt();if(!u.unittest){let u=!0;var t=this.options.env.node;if(t)for(let p=0;p<e.tx.inputs.length;p++){var i=e.tx.inputs[p].prevout,r=await t.getMeta(i.hash);if(r&&r.tx){var h=o({env:this,tx:r.tx,hash:r.tx.hash("hex"),i:i.index,output:r.tx.outputs[i.index],type:r.tx.outputs[i.index].getReturnType(),data:r.tx.outputs[i.index].getReturnData(a)});switch(h.options.type){case n.OP_PROPCREATE:case n.OP_PROPEXCHANGE:{let t=!1;if(1!=e.tx.inputs.length||e.tx.inputs[0].prevout.hash==c.NULL_HASH||1!=e.tx.outputs.length||e.tx.outputs[0].getReturnType(s)){for(let i=0;i<e.tx.outputs.length;i++)if(this.setOutputIndex(e,i)){var l=o(e);if(l.options.type==n.OP_PROPEXCHANGE&&l.options.data.pid==h.options.data.pid){t=!0;break}}t||(u=!1)}else t=!0}}}if(!u)break}if(!u)return!1}for(let t=0;t<e.tx.outputs.length;t++)if(this.setOutputIndex(e,t)&&1!=await o(e).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}}setOutputIndex(e,t){return e.i=t,e.output=e.tx.outputs[t],e.type=e.output.getReturnType(),e.data=e.output.getReturnData(a),!!e.data}}},function(e,t,i){const{ContractEnvType:r,PropStatus:a}=i(5);var s=i(52);const n=i(7),o=i(118);e.exports=class extends s{async confirm(){var{env:e,i:t,output:i,data:s,hash:n,block:o,tx:c}=this.options,u=await e.propList.getVp(s.pid);!u||u.current.hash==n&&u.current.index==t?(s.current={hash:n,index:t,address:i.getAddress().toString()},s.height=0<e.curHeight?e.curHeight+1:0,s.pst=a.Ready,s.gold=i.value,await e.propList.setVp(s,c),e.mode==r.Block&&(i={pid:s.pid,oid:s.oid,cid:s.cid,dst:s.current.address,time:o.time,height:s.height,value:s.gold},e.node.transmit("prop.create",i))):e.logger.warning("PropCreate.conflict",s.pid,", height: ",o?o.height:0,"mode: ",e.mode,n,t,u.current.hash,u.current.index)}async unconfirm(){var{env:e,i:t,data:i,hash:a}=this.options,s=await e.propList.getVp(i.pid);s&&s.current.hash==a&&s.current.index==t&&(await e.propList.delVp(s),e.mode==r.Block)&&(a={pid:i.pid},e.node.transmit("prop.uncreate",a))}async verify(){var{env:e,output:t,data:i}=this.options;if(!o.unittest){var r=e.cpList.getItem(i.cid);if(!r||r.current.address!=t.getAddress().toString())return"PropCreate.errorAddress"}return t.value<n.MINPROPVALUE?"PropCreate.MINPROPVALUE":!e.network.tokenReg.test(i.pid)||"PropCreate.invalidPid"}}},function(e,t,i){const r=i(5).ContractEnvType;i=i(52);e.exports=class extends i{async insert(){var{env:e,output:t,hash:i,i:a,data:s}=this.options;e.mode==r.Mempool&&(s={data:s,height:0,gold:t.value,time:Date.now(),current:{hash:i,index:a,address:t.getAddress().toString()}},e.node.transmit("attach.insert",s))}async confirm(){var{env:e,i:t,output:i,data:a,hash:s,block:n}=this.options;e.mode==r.Block&&(a={data:a,height:0<e.curHeight?e.curHeight+1:0,gold:i.value,time:n.time,current:{hash:s,index:t,address:i.getAddress().toString()}},e.node.transmit("attach.confirm",a))}async unconfirm(){var{env:e,i:t,output:i,data:a,hash:s,block:n}=this.options;e.mode==r.Block&&(a={data:a,height:0<e.curHeight?e.curHeight+1:0,gold:i.value,time:n.time,current:{hash:s,index:t,address:i.getAddress().toString()}},e.node.transmit("attach.unconfirm",a))}async verify(){return!0}}},function(e,t,i){const r=i(0),a=i(19).opcodes,s=i(44).broadcast,n=i(
|
|
427
|
+
const r=i(5).ContractType;e.exports=function(e){if(!e)return i(188);switch(e.oper){case r.cpRegister:return i(192);case r.cpChange:return i(194);case r.coinbase:return i(195);case r.contractPromise:return i(196);case r.scRegister:return i(199);case r.scUpdate:return i(200);case r.scState:return i(201);case r.scRun:return i(202);case r.scNotify:return i(208);case r.propFound:return i(209);case r.vote:return i(210);case r.propSale:return i(211);case r.notify:return i(212);case r.contractCreate:return i(213);case r.contractExecute:return i(214);case r.erIssue:return i(215);case r.erAbolish:return i(216);case r.enchanceCp:return i(217);default:try{return i(581)("./"+e.oper)}catch(e){return i(14)}}}},function(e,t,i){var r=i(14);const{nestingExtentCodes:a,unspendableCodes:s,opcodes:n}=i(19),o=i(117),c=i(3),u=i(118);e.exports=class extends r{async insert(){var e=this.getOpt();for(let i=0;i<e.tx.outputs.length;i++){var t=""+e.hash+i;e.env.middleHashMem.has(t)||this.setOutputIndex(e,i)&&(await o(e).insert(),e.env.middleHashMem.add(t))}}async erase(){var e=this.getOpt();for(let t=0;t<e.tx.outputs.length;t++)e.env.middleHashMem.delete(""+e.hash+t),this.setOutputIndex(e,t)&&await o(e).erase()}async confirm(){var e=this.getOpt();for(let i=0;i<e.tx.outputs.length;i++){var t=""+e.hash+i;e.env.middleHashChain.has(t)||this.setOutputIndex(e,i)&&(await o(e).confirm(),e.env.middleHashChain.add(t))}}async unconfirm(){var e=this.getOpt();for(let t=0;t<e.tx.outputs.length;t++)e.env.middleHashChain.delete(""+e.hash+t),this.setOutputIndex(e,t)&&await o(e).unconfirm()}async verify(){var e=this.getOpt();if(!u.unittest){let u=!0;var t=this.options.env.node;if(t)for(let p=0;p<e.tx.inputs.length;p++){var i=e.tx.inputs[p].prevout,r=await t.getMeta(i.hash);if(r&&r.tx){var h=o({env:this,tx:r.tx,hash:r.tx.hash("hex"),i:i.index,output:r.tx.outputs[i.index],type:r.tx.outputs[i.index].getReturnType(),data:r.tx.outputs[i.index].getReturnData(a)});switch(h.options.type){case n.OP_PROPCREATE:case n.OP_PROPEXCHANGE:{let t=!1;if(1!=e.tx.inputs.length||e.tx.inputs[0].prevout.hash==c.NULL_HASH||1!=e.tx.outputs.length||e.tx.outputs[0].getReturnType(s)){for(let i=0;i<e.tx.outputs.length;i++)if(this.setOutputIndex(e,i)){var l=o(e);if(l.options.type==n.OP_PROPEXCHANGE&&l.options.data.pid==h.options.data.pid){t=!0;break}}t||(u=!1)}else t=!0}}}if(!u)break}if(!u)return!1}for(let t=0;t<e.tx.outputs.length;t++)if(this.setOutputIndex(e,t)&&1!=await o(e).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}}setOutputIndex(e,t){return e.i=t,e.output=e.tx.outputs[t],e.type=e.output.getReturnType(),e.data=e.output.getReturnData(a),!!e.data}}},function(e,t,i){const{ContractEnvType:r,PropStatus:a}=i(5);var s=i(52);const n=i(7),o=i(118);e.exports=class extends s{async confirm(){var{env:e,i:t,output:i,data:s,hash:n,block:o,tx:c}=this.options,u=await e.propList.getVp(s.pid);!u||u.current.hash==n&&u.current.index==t?(s.current={hash:n,index:t,address:i.getAddress().toString()},s.height=0<e.curHeight?e.curHeight+1:0,s.pst=a.Ready,s.gold=i.value,await e.propList.setVp(s,c),e.mode==r.Block&&(i={pid:s.pid,oid:s.oid,cid:s.cid,dst:s.current.address,time:o.time,height:s.height,value:s.gold},e.node.transmit("prop.create",i))):e.logger.warning("PropCreate.conflict",s.pid,", height: ",o?o.height:0,"mode: ",e.mode,n,t,u.current.hash,u.current.index)}async unconfirm(){var{env:e,i:t,data:i,hash:a}=this.options,s=await e.propList.getVp(i.pid);s&&s.current.hash==a&&s.current.index==t&&(await e.propList.delVp(s),e.mode==r.Block)&&(a={pid:i.pid},e.node.transmit("prop.uncreate",a))}async verify(){var{env:e,output:t,data:i}=this.options;if(!o.unittest){var r=e.cpList.getItem(i.cid);if(!r||r.current.address!=t.getAddress().toString())return"PropCreate.errorAddress"}return t.value<n.MINPROPVALUE?"PropCreate.MINPROPVALUE":!e.network.tokenReg.test(i.pid)||"PropCreate.invalidPid"}}},function(e,t,i){const r=i(5).ContractEnvType;i=i(52);e.exports=class extends i{async insert(){var{env:e,output:t,hash:i,i:a,data:s}=this.options;e.mode==r.Mempool&&(s={data:s,height:0,gold:t.value,time:Date.now(),current:{hash:i,index:a,address:t.getAddress().toString()}},e.node.transmit("attach.insert",s))}async confirm(){var{env:e,i:t,output:i,data:a,hash:s,block:n}=this.options;e.mode==r.Block&&(a={data:a,height:0<e.curHeight?e.curHeight+1:0,gold:i.value,time:n.time,current:{hash:s,index:t,address:i.getAddress().toString()}},e.node.transmit("attach.confirm",a))}async unconfirm(){var{env:e,i:t,output:i,data:a,hash:s,block:n}=this.options;e.mode==r.Block&&(a={data:a,height:0<e.curHeight?e.curHeight+1:0,gold:i.value,time:n.time,current:{hash:s,index:t,address:i.getAddress().toString()}},e.node.transmit("attach.unconfirm",a))}async verify(){return!0}}},function(e,t,i){const r=i(0),a=i(19).opcodes,s=i(44).broadcast,n=i(146).vpItem;var o=i(52);const{ContractEnvType:c,PropStatus:u}=i(5);e.exports=class extends o{async confirm(){let{env:e,i:t,output:i,data:r,hash:o,tx:h,block:l}=this.options;if(e.mode==c.Wallet){var p=await e.propList.getVp(r.pid);if(p&&(p.current.hash!=r.prev.hash||p.current.index!=r.prev.index))return void e.logger.warning("PropExchange.conflict",r.pid,", height: ",l?l.height:0,"mode: ",e.mode,"sim: ",o,t,"ori: ",p.current.hash,p.current.index);p=new n({pid:r.pid,cid:r.cid,oid:r.oid,gold:i.value,current:{hash:o,index:t,address:i.getAddress().toString()},height:0<e.curHeight?e.curHeight+1:0,pst:u.Ready,wid:0,account:""}),await e.propList.setVp(p,h),p={pid:p.pid,address:p.current.address,wid:p.wid,account:p.account,time:l.time,height:p.height,cid:p.cid},e.emit("prop/receive",p),s("prop/receive",p)}else{if(!(p=await e.propList.getVp(r.pid))||p.current.hash!=r.prev.hash||p.current.index!=r.prev.index)return void e.logger.warning("PropExchange.conflict",r.pid,", height: ",l?l.height:0,"mode: ",e.mode,"sim: ",o,t,"ori: ",p.current.hash,p.current.index);var d,f=p.current.address,m=i.getAddress().toString();if(p.current={hash:o,index:t,address:m},p.height=0<e.curHeight?e.curHeight+1:0,p.pst=u.Ready,await e.propList.setVp(p,h),e.mode==c.Block){if(p.cid==e.network.genesisId){for(d of(await e.propList.getVpByAddress(f)).list){if(d.cid==e.network.genesisId)break;e.voteMgr.delTokenAddress(f)}e.voteMgr.addTokenAddress(m)}m={pid:p.pid,oid:p.oid,cid:p.cid,src:f,dst:m,time:l.time,height:p.height,hash:p.current.hash,index:p.current.index},e.node.transmit("prop.exchange",m)}}let g=0,v=r;for(;i&&i.getReturnType(a.OP_PROPEXCHANGE)&&g++<2e3;){var y=v.prev,b=(e.middleHashChain.add(y.hash+y.index.toString()),await e.finder(y.hash));if(!b)break;if(i=b.outputs[y.index],!(v=i.getReturnData())||!v.prev||e.middleHashChain.has(v.prev.hash+v.prev.index.toString()))break}}async unconfirm(){var{env:e,data:t}=this.options,i=await e.finder(t.prev.hash);if(i&&i.outputs[t.prev.index]&&(n=i.outputs[t.prev.index]).getReturnData([a.OP_PROPEXCHANGE,a.OP_PROPCREATE])){var r=await e.propList.getVp(t.pid);if(r){var s,n=n.getAddress().toString(),o=r.current.address,u=r.height;if(r.current.hash=t.prev.hash,r.current.index=t.prev.index,r.current.address=n,await e.propList.setVp(r,i),e.mode==c.Block){if(r.cid==e.network.genesisId){for(s of(await e.propList.getVpByAddress(o)).list){if(s.cid==e.network.genesisId)break;e.voteMgr.delTokenAddress(o)}e.voteMgr.addTokenAddress(n)}t={pid:r.pid,src:o,dst:n,height:u},e.node.transmit("prop.unexchange",t)}}}}async verify(){var{env:e,tx:t,i:i,data:a}=this.options;return r.strictEqual(a.prev.hash,t.inputs[i].prevout.hash),r.strictEqual(a.prev.index,t.inputs[i].prevout.index),await e.propList.getVp(a.pid),!0}}},function(e,t,i){var r=i(14);const a=i(5).ContractEnvType,s=i(37).VerifyError;var{}=i(19);const n=i(193);e.exports=class extends r{async insert(){var e=this.options.env,t=this.options.tx,i=t.hash("hex"),r=this.data;r.current={hash:i,index:0,address:t.outputs[0].getAddress().toString()},r.height=-1,await e.cpMemList.addItem(r)}async erase(){var e=this.options.env,t=this.data;await e.cpMemList.delItem(t)}async confirm(){var e=this.options.env,t=this.options.tx,i=t.hash("hex"),r=this.data;r.current={hash:i,index:0,address:t.outputs[0].getAddress().toString()},r.height=this.options.coinbaseHeight,r.status=1,await e.cpList.addItem(r),await e.cpMemList.delItem(r),e.mode==a.Block&&(i={cid:r.cid,name:r.name,address:r.current.address},e.node.transmit("cp.create",i))}async unconfirm(){var e=this.options.env,t=this.data;this.options.tx,await e.cpMemList.addItem(t),await e.cpList.delItem(t),e.mode==a.Block&&(t={cid:t.cid},e.node.transmit("cp.uncreate",t))}async verify(){var e=this.options.env,t=this.options.tx;if(!this.data)throw new s(t,"invalid","null cpRegister data",100);var i=n.verifyDataFormat(this.data);if(i)throw new s(t,"invalid",i,100);if((this.mode!=a.Block||"spv"!=e.node.nodeType)&&(i=this.mode!=a.Mempool,!await e.rpcExecute({method:"canExecute",params:[{confirm:i,cid:this.data.cid,name:this.data.name,oper:this.data.oper}]})))throw new s(t,"invalid info on "+this.data.oper,"cp.create",0);return!0}}},function(e,t,i){"use strict";
|
|
428
428
|
/*!
|
|
429
429
|
* cpHelper.js
|
|
430
430
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -433,11 +433,11 @@ const r=i(5).ContractType;e.exports=function(e){if(!e)return i(188);switch(e.ope
|
|
|
433
433
|
* mnemonic.js - hd mnemonics for vallnet
|
|
434
434
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
435
435
|
* https://github.com/bookmansoft/gamegold
|
|
436
|
-
*/const r=i(0),a=i(2),s=i(6),n=i(94),o=i(70),c=i(148),u=i(4),h=i(1),l=i(3),p=i(301),d=i(
|
|
436
|
+
*/const r=i(0),a=i(2),s=i(6),n=i(94),o=i(70),c=i(148),u=i(4),h=i(1),l=i(3),p=i(301),d=i(139),f=i(303),{languages:m,languageEnum:g}=i(302),v=i(578),y=Object.create(null);class b{constructor(e){this.bits=d.MIN_ENTROPY,this.language=g.English,this.entropy=null,this.phrase=null,this.passphrase="",e&&this.fromOptions(e)}fromOptions(e){return null!=(e="string"==typeof e?{phrase:e}:e).bits&&(r(a.isU16(e.bits)),r(e.bits>=d.MIN_ENTROPY),r(e.bits<=d.MAX_ENTROPY),r(e.bits%32==0),this.bits=e.bits),e.language&&(r("string"==typeof e.language),r(-1!==m.indexOf(e.language)),this.language=e.language),e.passphrase&&(r("string"==typeof e.passphrase),this.passphrase=e.passphrase),e.phrase?this.fromPhrase(e.phrase):e.entropy&&this.fromEntropy(e.entropy),this}static fromOptions(e){return(new b).fromOptions(e)}destroy(){this.bits=d.MIN_ENTROPY,this.language="english",this.entropy&&(n(this.entropy),this.entropy=null),this.phrase=null,this.passphrase=""}toSeed(e){e=e||this.passphrase,this.passphrase=e;var t=f(this.getPhrase());e=f("mnemonic"+e);return c.derive(Buffer.from(t,"utf8"),Buffer.from(e,"utf8"),2048,64,"sha512")}getEntropy(){if(!this.entropy){this.entropy=o.randomBytes(this.bits/8);var e=new v,t=(e.seed(e.int()),e.randomBytes(this.bits/8));for(let e=0;e<this.entropy.length;e++)this.entropy[e]=this.entropy[e]^t[e]}return r(this.bits/8===this.entropy.length),this.entropy}getPhrase(){if(this.phrase)return this.phrase;var e=this.bits+this.bits/32,t=this.getEntropy(),i=s.sha256(t),r=Math.ceil(e/8),a=Buffer.allocUnsafe(r),n=(t.copy(a,0),i.copy(a,t.length),b.getWordlist(this.language));let o=[];for(let t=0;t<e/11;t++){let e=0;for(let i=0;i<11;i++){var c=11*t+i,u=c%8;e=(e<<=1)|a[(c-u)/8]>>>7-u&1}o.push(n.words[e])}return o="japanese"===this.language?o.join(" "):o.join(" "),this.phrase=o}fromPhrase(e){r("string"==typeof e),r(e.length<=1e3);var t=e.trim().split(/[\s\u3000]+/),i=(n=11*t.length)%32,a=(r(0!=i,"Invalid checksum."),n-i),n=(r(a>=d.MIN_ENTROPY),r(a<=d.MAX_ENTROPY),r(a%32==0),Math.ceil(n/8)),o=Buffer.allocUnsafe(n),c=(n=(o.fill(0),b.getLanguage(t[0])),b.getWordlist(n));for(let e=0;e<t.length;e++){var u=t[e],h=c.map[u];if(null==h)throw new Error("Could not find word.");for(let t=0;t<11;t++){var l=11*e+t,p=l%8,f=h>>>10-t&1;o[(l-p)/8]|=f<<7-p}}var m=Math.ceil(i/8),g=o.slice(0,o.length-m),v=o.slice(o.length-m),y=s.sha256(g);for(let e=0;e<i;e++){var w=e%8,x=(e-w)/8;if((v[x]>>>7-w&1)!=(y[x]>>>7-w&1))throw new Error("Invalid checksum.")}return r(a/8===g.length),this.bits=a,this.language=n,this.entropy=g,this.phrase=e,this}static fromPhrase(e){return(new b).fromPhrase(e)}fromEntropy(e,t){return r(Buffer.isBuffer(e)),r(8*e.length>=d.MIN_ENTROPY),r(8*e.length<=d.MAX_ENTROPY),r(8*e.length%32==0),r(!t||-1!==m.indexOf(t)),this.entropy=e,this.bits=8*e.length,t&&(this.language=t),this}static fromEntropy(e,t){return(new b).fromEntropy(e,t)}static getLanguage(e){for(const t of m)if(null!=b.getWordlist(t).map[e])return t;throw new Error("Could not determine language.")}static getWordlist(e){var t=y[e];return t||(t=new w(p.get(e)),y[e]=t)}toJSON(){return{bits:this.bits,language:this.language,entropy:this.getEntropy().toString("hex"),phrase:this.getPhrase(),passphrase:this.passphrase}}fromJSON(e){return r(a.isU16(e.bits)),r("string"==typeof e.language),r("string"==typeof e.entropy),r("string"==typeof e.phrase),r("string"==typeof e.passphrase),r(e.bits>=d.MIN_ENTROPY),r(e.bits<=d.MAX_ENTROPY),r(e.bits%32==0),r(e.bits/8==e.entropy.length/2),this.bits=e.bits,this.language=e.language,this.entropy=Buffer.from(e.entropy,"hex"),this.phrase=e.phrase,this.passphrase=e.passphrase,this}static fromJSON(e){return(new b).fromJSON(e)}getSize(){var e=0;return(e+=3)+this.getEntropy().length+l.sizeVarString(this.getPhrase(),"utf8")+l.sizeVarString(this.passphrase,"utf8")}toWriter(e){var t=m.indexOf(this.language);return r(-1!==t),e.writeU16(this.bits),e.writeU8(t),e.writeBytes(this.getEntropy()),e.writeVarString(this.getPhrase(),"utf8"),e.writeVarString(this.passphrase,"utf8"),e}toRaw(e){var t=this.getSize();return this.toWriter(new u(t)).render()}fromReader(e){var t=e.readU16(),i=(r(t>=d.MIN_ENTROPY),r(t<=d.MAX_ENTROPY),r(t%32==0),m[e.readU8()]);return r(i),this.bits=t,this.language=i,this.entropy=e.readBytes(t/8),this.phrase=e.readVarString("utf8"),this.passphrase=e.readVarString("utf8"),this}fromRaw(e){return this.fromReader(new h(e))}static fromReader(e){return(new b).fromReader(e)}static fromRaw(e){return(new b).fromRaw(e)}toString(){return this.getPhrase()}inspect(){return`<Mnemonic: ${this.getPhrase()}>`}static isMnemonic(e){return e instanceof b}}function w(e){this.words=e,this.map=Object.create(null);for(let i=0;i<e.length;i++){var t=e[i];this.map[t]=i}}e.exports=b},function(e,t,i){"use strict";
|
|
437
437
|
/*!
|
|
438
438
|
* mappedlock.js - lock and queue for vallnet
|
|
439
439
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
440
|
-
*/function r(e,t){this.resolve=e,this.reject=t}function a(){}e.exports=class{constructor(){this.jobs=new Map,this.busy=new Set,this.destroyed=!1}has(e){return this.busy.has(e)}hasPending(e){return this.jobs.has(e)}lock(e,t){return this.destroyed?Promise.reject(new Error("Lock is destroyed.")):null==e||t?Promise.resolve(a):this.busy.has(e)?new Promise((t,i)=>{this.jobs.has(e)||this.jobs.set(e,[]),this.jobs.get(e).push(new r(t,i))}):(this.busy.add(e),Promise.resolve(this.unlock(e)))}unlock(e){const t=this;return function i(){var r,a;!t.destroyed&&t.busy.has(e)&&(t.busy.delete(e),r=t.jobs.get(e))&&(0===r.length&&t.jobs.delete(e),a=r.shift(),0===r.length&&t.jobs.delete(e),t.busy.add(e),a.resolve(i))}}destroy(){if(!this.destroyed){this.destroyed=!0;var e=this.jobs;this.busy=new Map,this.jobs=new Map;for(const t of e.values())for(const e of t)e.reject(new Error("MappedLock was destroyed."))}}}},function(e,t,i){var r=i(14);const a=i(5).ContractEnvType,s=i(37).VerifyError,n=i(151).scItem,o=i(72).verifyData,c=i(0),u=i(44).broadcast;e.exports=class extends r{async confirm(){var e,t;this.mode==a.Block&&(e=this.options.env,t=this.options.tx,this.data.dst=t.outputs[1].getAddress().toString(),this.data.height=this.options.coinbaseHeight,this.data.indate?this.data.indate=this.data.height+Math.max(144,Math.min(52560,this.data.indate)):this.data.indate=this.data.height+4320,t=new n({type:this.data.type,addr:this.data.addr,dst:this.data.dst,height:this.data.height,state:1,ver:1,indate:this.data.indate}),this.data.cls&&(t.options.cls=this.data.cls,this.mode===a.Block)&&"publish"==this.data.cls&&u("sc/publish",t.options),t.do(),await e.scList.addItem(t))}async unconfirm(){this.mode==a.Block&&await this.options.env.scList.delItem(this.data)}async verify(){var e=this.options.env,t=this.options.tx,i=t.outputs[1];if(!i||1e8!=i.value||!this.data)throw new s(t,"invalid","null scRegister data",100);var r=this.data.sig;delete this.data.sig,c.strictEqual(!0,o({data:this.data,sig:r})),r=await e.node.cdb.get("primary");if(0<e.scList.query([["options.dst",this.data.dst]]).length)throw new s(t,"Contract Register Conflict","another contract already on "+this.data.dst,100);if(await r.ensureAccount({name:this.data.addr,witness:!0}),(await r.createReceive(this.data.addr,1)).getAddress("string")!=i.getAddress().toString())throw new s(t,"Invalid Smart Contract","Receive address error",100);return!0}}},function(e,t,i){var r=i(14);const{ContractEnvType:a,ContractState:s}=i(5),n=i(37).VerifyError;var{}=i(151);const o=i(72).verifyData,c=i(0);e.exports=class extends r{async confirm(){var e,t;this.mode==a.Block&&(e=this.options.env,t=this.options.tx,this.data.dst=t.outputs[1].getAddress().toString(),this.data.height=this.options.coinbaseHeight,1==(t=e.scList.query([["options.dst",this.data.dst]])).list.length)&&(t.list[0].options.ver+=1,t.list[0].options.type=this.data.type,t.list[0].options.height=this.data.height,t.list[0].do(),await e.scList.addItem(t.list[0]))}async unconfirm(){this.mode==a.Block&&await this.options.env.scList.delItem(this.data)}async verify(){var e=this.options.env,t=this.options.tx,i=t.outputs[1];if(!i||1e5!=i.value||!this.data)throw new n(t,"Invalid Smart Contract","null scRegister data",100);var r=this.data.sig;delete this.data.sig,c.strictEqual(!0,o({data:this.data,sig:r})),r=await e.node.cdb.get("primary");if(0==(e=e.scList.query([["options.dst",this.data.dst]])).list.length)throw new n(t,"Contract Not Exists","contract not exists",100);if(e.list[0].options.state!=s.Normal)throw new n(t,"Contract State Error","contract state error",100);if(await r.ensureAccount({name:this.data.addr,witness:!0}),(await r.createReceive(this.data.addr,1)).getAddress("string")!=i.getAddress().toString())throw new n(t,"Invalid Smart Contract","dst address error",100);return!0}}},function(e,t,i){var r=i(14);const{ContractEnvType:a,ContractState:s}=i(5),n=i(37).VerifyError;var{}=i(151);const o=i(72).verifyData,c=i(0);e.exports=class extends r{async confirm(){var e,t;this.mode==a.Block&&(e=this.options.env,t=this.options.tx,this.data.dst=t.outputs[1].getAddress().toString(),this.data.height=this.options.coinbaseHeight,1==(t=e.scList.query([["options.dst",this.data.dst]])).list.length)&&(t.list[0].options.state=this.data.state,t.list[0].options.height=this.data.height,t.list[0].do(),await e.scList.addItem(t.list[0]))}async unconfirm(){this.mode==a.Block&&await this.options.env.scList.delItem(this.data)}async verify(){var e=this.options.env,t=this.options.tx,i=t.outputs[1];if(!i||1e5!=i.value||!this.data)throw new n(t,"Invalid Smart Contract","null scRegister data",100);var r=this.data.sig;delete this.data.sig,c.strictEqual(!0,o({data:this.data,sig:r})),r=await e.node.cdb.get("primary");if(0==(e=e.scList.query([["options.dst",this.data.dst]])).list.length)throw new n(t,"Contract Not Exists","contract not exists",100);switch(e.list[0].options.state){case s.Normal:if(this.data.state!=s.Frozen&&this.data.state!=s.Destroy)throw new n(t,"Contract State Error","contract state error",100);break;case s.Frozen:if(this.data.state!=s.Normal&&this.data.state!=s.Destroy)throw new n(t,"Contract State Error","contract state error",100);break;default:throw new n(t,"Contract State Error","contract state error",100)}if(await r.ensureAccount({name:this.data.addr,witness:!0}),(await r.createReceive(this.data.addr,1)).getAddress("string")!=i.getAddress().toString())throw new n(t,"Invalid Smart Contract","dst address error",100);return!0}}},function(e,t,i){var r=i(14);const{ContractEnvType:a,ContractState:s}=i(5),n=i(37).VerifyError,o=i(7),c=i(152),u=i(42);e.exports=class extends r{async onPacking(){var e=this.options.env,t=this.options.tx.hash("hex"),i=await e.node.cdb.get("primary"),r=this.data.$top;let a={derive:[]};var s=await i.getStatusOfSC(t);if(s.txs)for(var n of s.txs)(n=await i.getTX(n))&&a.derive.push(n.tx);else if((s=await this.getContract())&&(s={height:e.curHeight,data:this.data,tx:this.options.tx,contract:s,wallet:i},s=c(s)))if((a=await s.run()).derive&&a.derive.length<o.MAX_PACKING_SIZE){let s=[];for(var h of a.derive)if((h=await(await u.FactoryOfContract({tx:h,env:e})).onPacking()).derive){if(!(a.derive.length+s.length+h.derive.length<o.MAX_PACKING_SIZE))break;s=s.concat(h.derive)}a.derive=a.derive.concat(s),r||await i.setStatusOfSC(t,a.derive.map(e=>e.hash("hex")))}else a.derive=[];return a}async confirm(){var e,t,i;if(this.mode==a.Block)return e=this.options.env,(t=await this.getContract())&&(i=c({data:this.data,tx:this.options.tx,contract:t,wallet:await this.options.env.node.cdb.get("primary")}))&&(t.do(),await e.scList.addItem(t),await i.confirm()),!0}async unconfirm(){var e,t,i;if(this.mode==a.Block)return e=this.options.env,(t=await this.getContract())&&(i={data:this.data,tx:this.options.tx,contract:t,wallet:await this.options.env.node.cdb.get("primary")},i=c(i))&&(t.undo(),await e.scList.addItem(t),await i.unconfirm()),!0}async verify(){var e=this.options.env,t=this.options.tx,i=await this.getContract();if(!i)throw new n(t,"invalid","contract not found",100);if(i.options.state!=s.Normal)throw new n(t,"invalid","contract version conflict",100);if(this.data.params.ver&&this.data.params.ver!=i.options.ver)throw new n(t,"invalid","contract version conflict",100);if(i.options.indate<e.curHeight)throw new n(t,"invalid","contract expired",100);return t={data:this.data,tx:t,contract:i,wallet:await e.node.cdb.get("primary")},(i=c(t))?i.verify():"scRun.errorType"}async getContract(){if(0<this.options.tx.outputs.length){var e=this.options.tx.outputs[1].getAddress().toString();if((e=await this.options.env.node.chain.db.getSCList([["options.dst",e]]))&&0<e.list.length)return e.list[0]}return null}}},function(e,t,i){i=i(81);e.exports=class extends i{async run(){var e,t,i,r,a,s;return await this.verify()?(e=await super.run(),t=this.options.contract.options.addr,i=this.options.tx.outputs[1].value,r=this.options.wallet,s=this.options.data.params.relay,a=this.options.data.$top||0,s=await r.send({sendafter:!(r=[]),subtractFee:!1,sort:!1,outputs:[{address:s,value:i}],comment:JSON.stringify({$tag:"inner",$top:a+1,oper:"scrun",hash:this.options.tx.hash("hex"),account:t,params:this.options.data.params.params})},t),r.push(s),e.derive=r,e):{derive:[]}}async confirm(){return!0}async unconfirm(){return!0}async verify(){return super.verify()}}},function(e,t,i){i=i(81);e.exports=class extends i{async run(){if(!await this.verify())return{derive:[]};var e=await super.run(),t=[],i=this.options.tx.outputs[1].value,r=this.options.wallet,a=this.options.contract.options.addr;let s=this.options.data.params.sim;s||(s=(n=this.options.tx.inputs[0]).getAddress().toString());var n=this.options.data.$top||0;r=await r.send({sendafter:!1,subtractFee:!1,sort:!1,outputs:[{address:s,value:i/2}],comment:JSON.stringify({$tag:"inner",$top:n+1,hash:this.options.tx.hash("hex"),account:a})},a);return t.push(r),e.derive=t,e}async confirm(){return!0}async unconfirm(){return!0}async verify(){return super.verify()}}},function(e,t,i){i=i(81);e.exports=class extends i{async run(){if(!await this.verify())return{derive:[]};var e=await super.run(),t=[],i=this.options.tx.outputs[1].value,r=this.options.wallet,a=this.options.contract.options.addr;let s=this.options.data.params.sim;s||(s=(n=this.options.tx.inputs[0]).getAddress().toString());var n=this.options.data.$top||0;r=await r.send({sendafter:!1,subtractFee:!1,sort:!1,outputs:[{address:s,value:i/2}],comment:JSON.stringify({$tag:"inner",$top:n+1,hash:this.options.tx.hash("hex"),account:a})},a);return t.push(r),e.derive=t,e}async confirm(){return!0}async unconfirm(){return!0}async verify(){return super.verify()}}},function(e,t,i){i=i(81);e.exports=class extends i{async run(){return await this.verify()?await super.run():{derive:[]}}async confirm(){return!0}async unconfirm(){return!0}async verify(){return super.verify()}}},function(e,t,i){i=i(81);e.exports=class extends i{async run(){if(!await this.verify())return{derive:[]};var e=await super.run(),t=[];let i=this.options.contract;var r=this.options.data.params.oper,a=this.options.wallet,s=i.options.addr;switch(r){case"pubk":{var n,o,c,u=this.options.data.params.addr,h=this.options.data.params.pubk,l=this.options.data.params.partner;"object"==typeof i.options.contacts&&!Array.isArray(i.options.contacts)||(i.options.contacts={}),l&&l.split(",").map(e=>{i.options.contacts[e]||(i.options.contacts[e]={st:0})});let e="";for(n of Object.keys(i.options.contacts))u!=n&&(o=i.options.contacts[n],c=await a.send({sendafter:!1,subtractFee:!1,sort:!1,outputs:[{address:n,value:1e4}],comment:JSON.stringify({oper:"scnotify",type:"mssendpubk",$tag:"inner",hash:this.options.tx.hash("hex"),data:h,m:i.options.m,n:i.options.n,contract:i.options.dst,account:s})},s),t.push(c),o.pubk)&&(e&&(e+=","),e+=o.pubk);e&&(l=await a.send({sendafter:!1,subtractFee:!1,sort:!1,outputs:[{address:u,value:1e4}],comment:JSON.stringify({oper:"scnotify",type:"mssendpubk",$tag:"inner",hash:this.options.tx.hash("hex"),data:e,contract:i.options.dst,account:s})},s),t.push(l)),i.options.contacts[u]?i.options.contacts[u].pubk||(i.options.contacts[u].pubk=h):i.options.contacts[u]={pubk:h,st:0};break}case"puba":{var p,d=this.options.data.params.addr,f=this.options.data.params.puba;let e=!0;for(p of(i.options.puba=i.options.puba||f,Object.keys(i.options.contacts))){var m=i.options.contacts[p];p==d&&i.options.puba==f&&(m.st=1),1!=m.st&&(e=!1)}i.options.status=e;break}case"sign":if(1==i.options.status){var g,v,y=this.options.data.params.addr;for(g of Object.keys(i.options.contacts))g!=y&&(v=await a.send({sendafter:!1,subtractFee:!1,sort:!1,outputs:[{address:g,value:1e4}],comment:JSON.stringify({oper:"scnotify",type:"mssendtx",$tag:"inner",hash:this.options.tx.hash("hex"),data:this.options.data.params.tx,contract:i.options.dst,account:s})},s),t.push(v))}break;default:return e}return e.derive=t,e}async confirm(){return!0}async unconfirm(){return!0}async verify(){return super.verify()}}},function(e,t,i){var r=i(14);const a=i(5).ContractEnvType,s=i(44).broadcast;e.exports=class extends r{async confirm(){var e;this.mode==a.Wallet&&(e=this.options.tx.outputs[1])&&(this.data.addr=e.getAddress().toString(),this.options.env.emit(this.data.type+"/receive",this.data),s(this.data.type+"/receive",this.data))}async verify(){return!0}}},function(e,t,i){const r=i(0);var a=i(14);const{ContractEnvType:s,PropStatus:n}=i(5);e.exports=class extends a{async confirm(){var e=this.options.env,t=await e.propList.getVp(this.data.ori.pid);return t&&(t.pst=n.Delete,await e.propList.setVp(t),e.mode==s.Block)&&(t={pid:t.pid},e.node.transmit("prop.found",t)),!0}async unconfirm(){var e=this.options.env,t=this.options.tx,i=await e.propList.getVp(this.data.ori.pid);return i&&i.current.hash==t.inputs[0].prevout.hash&&i.current.index==t.inputs[0].prevout.index&&(i.pst=n.Ready,await e.propList.setVp(i)),!0}async verify(){var e=this.options.env,t=this.options.tx,i=this.data;return i.ori&&i.ori.pid?e.network.tokenReg.test(i.ori.pid)?"propfound.protected":(e=await e.propList.getVp(i.ori.pid))&&e.pst==n.Ready?(r.strictEqual(e.current.hash,t.inputs[0].prevout.hash),r.strictEqual(e.current.index,t.inputs[0].prevout.index),!0):"propfound.invalidStatus":"propfound.invalidAncestor"}}},function(e,t,i){var r=i(14);const{ContractEnvType:a,ContractType:s}=i(5),n=i(7),o=i(19).opcodes;e.exports=class extends r{async confirm(){return this.options.env,this.options.tx.hash("hex"),this.mode===a.Block&&await this.HandleVoteTrans(!1),!0}async unconfirm(){return this.options.env,this.options.tx,this.mode===a.Block&&await this.HandleVoteTrans(!0),!0}async HandleVoteTrans(e){var t=this.options.env,i=this.options.tx,r=this.options.tx.outputs[0].script.code;if(r[0].value==o.OP_RETURN)try{var a=JSON.parse(Buffer.from(r[1].data).toString());if(a&&a.oper==s.vote)switch(a.type){case"mine":{let r=0;for(var c of i.inputs){var u,h=await t.getExtendTX(c.prevout.hash);h&&t.voteMgr.isIn(h.height)?(u=h.tx.outputs[c.prevout.index])&&u.value?r+=u.value/n.COIN|0:t.logger.warning("Voting: Invalid UTXO Info"):t.logger.warning("Voting: Invalid UTXO Height")}0<r&&await t.voteMgr.calcVote(r,a.ca,e);break}case"oracle":{let r=0;for(var l of i.inputs){var p,d=await t.getExtendTX(l.prevout.hash);d&&t.voteMgr.isIn(d.height)?(p=d.tx.outputs[l.prevout.index])&&p.value?r+=p.value/1e5|0:t.logger.warning("Oracle: Invalid UTXO Info"):t.logger.warning("Oracle: Invalid UTXO Height")}0<r&&await t.voteMgr.calcOracle(r,{k:a.k,v:a.v},e);break}}}catch(r){console.log(r)}}async verify(){return!0}}},function(e,t,i){const r=i(0);var a=i(14);const{BlockFinalType:s,ContractEnvType:n,ContractType:o,PropStatus:c}=i(5),u=i(37).VerifyError,h=i(7);var{}=i(44);i(2);const l=i(31);e.exports=class extends a{async insert(){var e=this.options.env,t=this.options.tx,i=2<t.outputs.length?t.outputs[2].getReturnData():null,a=await e.propList.getVp(this.data.pid);if(a){if(i){if(this.mode==n.Wallet&&a.bid&&(i=await e.getTX(a.bid.hash))&&(i=await e.getWalletsByTX(i)))for(const t of i){var s=await e.get(t);r(s),await s.remove(a.bid.hash)}i=t.outputs[1].value;var o=t.outputs[2].getAddress().toString();i>=this.data.fixed||e.curHeight>=this.data.period&&i>a.gold?(a.current={hash:this.options.hash,index:2,address:o},a.pst=c.Sale,a.bid={},a.bid.raw=this.options.raw,a.bid.fixed=this.data.fixed,a.bid.period=this.data.period,a.bid.hash=this.options.hash,a.bid.value=i,a.bid.address=o,await e.propList.setVp(a,t)):(a.pst=c.Sale,a.bid={},a.bid.raw=this.options.raw,a.bid.fixed=this.data.fixed,a.bid.period=this.data.period,a.bid.hash=this.options.hash,a.bid.value=i,a.bid.address=o,await e.propList.setVp(a))}else a.pst=c.Sale,a.bid={},a.bid.raw=this.options.raw,a.bid.fixed=this.data.fixed,a.bid.period=this.data.period,a.bid.hash=this.options.hash,a.bid.value=a.gold,a.bid.address="",await e.propList.setVp(a);this.mode==n.Mempool&&(e.node.bidList||(e.node.bidList=new l),e.node.bidList.set(a.pid,Object.assign({pid:a.pid,curAddress:a.current.address,curGold:a.gold,status:c.Sale},a.bid)))}return!0}async erase(){var e,t=this.options.env,i=2<(r=this.options.tx).outputs.length?r.outputs[2].getReturnData():null,r=r.inputs[0],a=await t.propList.getVp(this.data.pid);a&&(i?(i=await t.getExtendTX(r.prevout.hash))&&(e=i.tx.outputs[r.prevout.index],a.current={hash:r.prevout.hash,index:r.prevout.index,address:e.getAddress().toString()},a.bid={hash:this.options.hash,value:a.gold,address:"",raw:this.options.raw,fixed:this.data.fixed,period:this.data.period},a.pst=c.Sale,await t.propList.setVp(a,i.tx),this.mode==n.Mempool)&&(t.node.bidList||(t.node.bidList=new l),t.node.bidList.set(a.pid,Object.assign({pid:a.pid,curAddress:a.current.address,curGold:a.gold,status:c.Sale},a.bid))):(a.pst=c.Ready,await t.propList.setVp(a),this.mode==n.Mempool&&(t.node.bidList||(t.node.bidList=new l),t.node.bidList.delete(a.pid))))}async confirm(){var e=this.options.env,t=this.options.tx,i=t.hash("hex"),r=t.outputs[2].getAddress().toString(),a=await e.propList.getVp(this.data.pid);return a&&(this.mode==n.Block&&(e.node.bidList||(e.node.bidList=new l),e.node.bidList.delete(a.pid),e.node.transmit("prop.bid",{status:c.Ready,pid:a.pid,bid:Object.assign({},a.bid),height:this.options.coinbaseHeight})),a.current={hash:i,index:2,address:r},a.height=this.options.coinbaseHeight,a.pst=c.Ready,await e.propList.setVp(a,t)),!0}async unconfirm(){var e,t,i=this.options.env,r=this.options.tx,a=r.inputs[0].prevout,s=await i.getExtendTX(a.hash);return s?(t=(e=s.tx.outputs[a.index]).getReturnData(),(t=await i.propList.getVp(t.pid))&&(t.current={hash:a.hash,index:a.index,address:e.getAddress().toString()},t.height=s.height-1,await i.propList.setVp(t,r)),this.mode==n.Block&&i.node.transmit("prop.bid",{status:c.Delete,pid:t.pid,address:t.current.address,time:this.options.block.time,height:t.height})):this.mode==n.Wallet&&(a=await i.propList.getVp(this.data.pid),await i.propList.delVp(a)),!0}async verify(){var e=this.data,t=this.options.env,i=this.options.tx,a=2<i.outputs.length?i.outputs[2].getReturnData():null,s=await t.propList.getVp(e.pid);if(!s)return"propsale.notExist";switch(this.mode){case n.Mempool:if(r.strictEqual(e.prev.hash,i.inputs[0].prevout.hash),r.strictEqual(e.prev.index,i.inputs[0].prevout.index),r(t.curHeight+h.BLOCK_DAY>=this.data.period),r(e.cid!=t.network.genesisId),a){if(s.period<t.curHeight)throw new u(i,"sale order expired","contract",0);if(r.strictEqual(a.prev.hash,i.inputs[0].prevout.hash),r.strictEqual(a.prev.index,i.inputs[0].prevout.index),r.strictEqual(a.pid,e.pid),r.strictEqual(a.oper,o.propExchange),!s.bid)throw new u(i,"sale order lack bid info","contract",0);if(s.bid.value>=this.data.fixed)throw new u(i,"can not bid on sale order finished","contract",0);if(i.outputs[1].value<=s.bid.value||i.outputs[1].value<=s.gold)throw new u(i,"invalid bid price","contract",0);var c=await t.getTX(s.bid.hash);c&&await t.removeDoubleSpenders(c)}break;case n.Block:if(r.strictEqual(e.prev.hash,i.inputs[0].prevout.hash),r.strictEqual(e.prev.index,i.inputs[0].prevout.index),r(e.cid!=t.network.genesisId),r.strictEqual(a.prev.hash,i.inputs[0].prevout.hash),r.strictEqual(a.prev.index,i.inputs[0].prevout.index),r.strictEqual(a.pid,e.pid),r.strictEqual(a.oper,o.propExchange),i.outputs[1].value<=s.gold)throw new u(i,"invalid bid price","contract",0)}return!0}isBlockFinal(){var e=this.options.env,t=this.options.tx;return this.data.period<e.curHeight?s.Expired:2<=t.outputs.length&&(t.outputs[1].value>=this.data.fixed||this.data.period==e.curHeight&&t.outputs[1].value>=t.outputs[2].value)?s.Final:s.Waiting}isPreVerify(){var e=this.options.tx;return!!(2<e.outputs.length&&e.outputs[2].getReturnData())}}},function(e,t,i){const r=i(0),a=i(107),{ContractEnvType:s,BlockFinalType:n}=i(5);var o=i(14);const c=i(7),u=i(44).broadcast,h=i(6),l=i(13);e.exports=class extends o{async insert(){var e=this.options.env,t=this.options.tx;switch(this.data.body.dst=t.outputs[1].getAddress().toString(),this.mode){case s.Mempool:try{var i=JSON.parse(this.data.body.content);switch(i.cmd){case"peerdel":r(this.data.body.dst==e.node.config.notifyAddress),r(l.fromString(this.data.body.dst).hash.toString("hex")==h.hash160(Buffer.from(i.pub,"hex")).toString("hex")),r(a.verifyObj(i.payload,i.sig,i.pub)),await e.node.rpc._delPeer([i.payload.host,i.payload.an,i.payload.ai]);break;case"peeradd":r(this.data.body.dst==e.node.config.notifyAddress),r(l.fromString(this.data.body.dst).hash.toString("hex")==h.hash160(Buffer.from(i.pub,"hex")).toString("hex")),r(a.verifyObj(i.payload,i.sig,i.pub)),await e.node.rpc._addPeer([i.payload.host,i.payload.key,i.payload.an,i.payload.ai])}}catch(e){}break;case s.Wallet:if(e.NotifyList.get(this.data.sn))return;var n=this.data.body.dst,[n,o]=await e.getAccountByAddress(n,t);this.data.account=o,this.data.wid=n,e.emit("notify/receive",this.data),u("notify/receive",this.data),await e.NotifyList.set(this.data.sn,this.data)}return!0}async confirm(){}async unconfirm(){}async erase(){var e=this.options.env;return this.options.tx,this.mode===s.Wallet&&(await e.NotifyList.delete(this.data.sn),e.emit("notify/remove",this.data),u("notify/remove",this.data)),!0}async verify(){var e=this.options.env,t=this.options.tx;return t.getOutputValue()<.1*c.COIN?"Notify.invalidDeposit":2<t.outputs.length?"Notify.invalidFormat":!(this.data.h>e.curHeight)||"Notify.invalidHeight"}isBlockFinal(){var e=this.options.env;return this.data.h<e.curHeight-6?n.Expired:n.Waiting}}},function(e,t,i){var r=i(14);const{ContractEnvType:a,ContractStatus:s,BlockFinalType:n}=i(5),o=i(37).VerifyError;e.exports=class extends r{async insert(){var e=this.options.env;return this.data.period<e.curHeight?await e.transactionList.delTransContract(this.data,!0):(this.data.current={hash:this.options.hash,index:0},this.data.raw=this.options.raw,await e.transactionList.addTransContract(a.Mempool,this.data)),!0}async erase(){var e=this.options.env;switch(this.mode){case a.Mempool:await e.transactionList.delTransContract(this.data);break;case a.Wallet:await e.transactionList.delTransContract(this.data,!0)}}async verify(){var e=this.options.env,t=this.options.tx;if(this.data.period<e.curHeight)throw new o(t,"transaction contract expired","contract",0);if(e.transactionList.query(this.data.type,this.data.addr)!=s.None)throw new o(t,"Same Address Contract Finded","contract",0);return!0}isBlockFinal(){var e=this.options.env;return this.data.period<e.curHeight?n.Expired:n.Waiting}}},function(e,t,i){var r=i(14);const{ContractEnvType:a,ContractStatus:s}=i(5),n=i(108);e.exports=class extends r{async confirm(){var e=this.options.env;let t=s.Backed;switch(2==this.data.master&&(t=s.Exchanged),this.mode){case a.Block:var i=e.transactionList.get(this.data.type+"."+this.data.addr);i?(i.transStatus=t,await e.transactionList.saveContract(i,!0)):await e.transactionList.addTransContract(a.Block,this.data,!0);break;case a.Wallet:(i=e.transactionList.get(this.data.type+"."+this.data.addr))?(i.transStatus=t,await e.transactionList.saveContract(i,!0)):await e.transactionList.addTransContract(a.Wallet,this.data,!0)}return!0}async verify(){var e=this.options.env;switch(this.mode){case a.Mempool:case a.Block:case a.Wallet:{var t=this.data.master,i=e.transactionList.get(this.data.type+"."+this.data.addr);let r=i.transStatus;return r!==s.Expired&&r!==s.Confirmed&&r!==s.Backed&&r!==s.Exchanged&&(i=new n(e.network.txcheckpoint,i),[,r]=await i.execute(e)),r!==s.Expired&&r!==s.Confirmed&&r!==s.Backed&&r!==s.Exchanged?"ContractPromise.invalidStatus":!(r==s.Expired&&1!=t||r==s.Confirmed&&2!=t||r==s.Backed&&1!=t||r==s.Exchanged&&2!=t)||"ContractPromise.limited"}}}}},function(e,t,i){var r=i(14);const{ContractEnvType:a,VerifyCode:s}=i(5),n=i(153).ErItem,o=i(38),c=i(6),u=i(13),h=i(44).broadcast;e.exports=class extends r{async insert(){return!0}async confirm(){var e=this.options.env,t=this.options.tx;if(!(this.data.startHeight=e.curHeight,await e.erList.getEr(this.data.erid))){switch(await e.erList.setEr(this.data,t),this.mode){case a.Wallet:var i=u.fromWitnessPubkeyhash(c.hash160(Buffer.from(this.data.witness,"hex")),e.network),[i,r]=await e.getAccountByAddress(i,t);i&&r&&(this.data.account=r,this.data.wid=i,e.emit("ca/issue",this.data),h("ca/issue",this.data));break;case a.Block:e.node.transmit("ca.issue",this.data),e.node.config.alliancePrivateKey&&(r=o.fromPrivate(Buffer.from(e.node.config.alliancePrivateKey,"hex"),!0,e.network),o.fromPrivate(c.hash256(Buffer.concat([Buffer.from(this.data.source.cid+"-"+this.data.source.uid),r.privateKey]),!0,e.network)).publicKey.toString("hex")==this.data.witness)&&e.node.transmit("ca.issue.alliance",this.data)}return!0}e.logger.warning("ErIssue.conflict",this.data.erid,", height: ",e.curHeight,"mode: ",e.mode,t.txid())}async unconfirm(){var e=this.options.env,t=this.options.tx;switch(e.erList.delEr(this.data,t),this.mode){case a.Wallet:var i=u.fromWitnessPubkeyhash(c.hash160(Buffer.from(this.data.witness,"hex")),e.network),[i,r]=await e.getAccountByAddress(i,t);this.data.account=r,this.data.wid=i,e.emit("ca/unissue",this.data),h("ca/unissue",this.data);break;case a.Block:e.node.transmit("ca.unissue",this.data)}return!0}async erase(){return!0}async verify(){var e=this.options.env,t=this.data;e=o.fromPublic(Buffer.from(t.witness,"hex"),e.network);return!!new n(t).verifying(e)||s.SignatureNotMatch}}},function(e,t,i){var r=i(14);const{ContractEnvType:a,VerifyCode:s,ContractType:n}=i(5),o=i(154).ErAbolishItem,c=i(38),u=i(44).broadcast,h=i(6),l=i(13);e.exports=class extends r{async insert(){return!0}async confirm(){var e=this.options.env,t=this.options.tx;switch(this.data.startHeight=e.curHeight,await e.erAbList.setErAb(this.data,t),this.mode){case a.Wallet:var i=l.fromWitnessPubkeyhash(h.hash160(Buffer.from(this.data.witness,"hex")),e.network),[i,r]=await e.getAccountByAddress(i,t);this.data.account=r,this.data.wid=i,e.emit("ca/abolish",this.data),u("ca/abolish",this.data);break;case a.Block:e.node.transmit("ca.abolish",this.data)}return!0}async unconfirm(){var e=this.options.env,t=this.options.tx;switch(e.erAbList.delErAb(this.data,t),this.mode){case a.Wallet:var i=l.fromWitnessPubkeyhash(h.hash160(Buffer.from(this.data.witness,"hex")),e.network),[i,r]=await e.getAccountByAddress(i,t);this.data.account=r,this.data.wid=i,e.emit("ca/unabolish",this.data),u("ca/unabolish",this.data);break;case a.Block:e.node.transmit("ca.unabolish",this.data)}return!0}async erase(){return!0}async verify(){var e=this.options.env,t=this.data,i=await e.erList.getEr(t.erid);return i&&i.witness==t.witness?t&&t.oper==n.erAbolish&&(i=await e.erAbList.getErAb(t.erid))&&t.abolishHeight>=i.abolishHeight?s.NotExistER:(i=c.fromPublic(Buffer.from(t.witness,"hex"),e.network),!!new o(t).verifying(i)||s.SignatureNotMatch):s.SignatureNotMatch}}},function(e,t,i){var r=i(14);const{VerifyCode:a,ContractEnvType:s}=i(5),n=i(228).EnchancementItem,o=i(38);e.exports=class extends r{async insert(){return!0}async confirm(){var e,t;return this.mode==s.Block&&(e=this.options.env,t=this.options.tx,this.data.enchanceTx=t.txid(),e.enCpList.setEn(this.data),!0)}async unconfirm(){var e,t;return this.mode==s.Block&&(e=this.options.env,t=this.options.tx,e.enCpList.delEn(this.data,t),!0)}async erase(){return!0}async verify(){var e=this.options.env,t=this.options.tx,i=this.data,r=e.cpList.getItem(i.to);t=t.outputs[1].getAddress().toString();return r&&r.pubAddress&&r.pubAddress==t&&(r=e.cpList.getItem(i.from))&&r.pubAddress&&r.pubKey?(t=o.fromPublic(Buffer.from(r.pubKey,"hex"),e.network),!!new n(i).verifying(t)||a.SignatureNotMatch):a.NotExistCp}}},function(e,t,i){"use strict";
|
|
440
|
+
*/function r(e,t){this.resolve=e,this.reject=t}function a(){}e.exports=class{constructor(){this.jobs=new Map,this.busy=new Set,this.destroyed=!1}has(e){return this.busy.has(e)}hasPending(e){return this.jobs.has(e)}lock(e,t){return this.destroyed?Promise.reject(new Error("Lock is destroyed.")):null==e||t?Promise.resolve(a):this.busy.has(e)?new Promise((t,i)=>{this.jobs.has(e)||this.jobs.set(e,[]),this.jobs.get(e).push(new r(t,i))}):(this.busy.add(e),Promise.resolve(this.unlock(e)))}unlock(e){const t=this;return function i(){var r,a;!t.destroyed&&t.busy.has(e)&&(t.busy.delete(e),r=t.jobs.get(e))&&(0===r.length&&t.jobs.delete(e),a=r.shift(),0===r.length&&t.jobs.delete(e),t.busy.add(e),a.resolve(i))}}destroy(){if(!this.destroyed){this.destroyed=!0;var e=this.jobs;this.busy=new Map,this.jobs=new Map;for(const t of e.values())for(const e of t)e.reject(new Error("MappedLock was destroyed."))}}}},function(e,t,i){var r=i(14);const a=i(5).ContractEnvType,s=i(37).VerifyError,n=i(151).scItem,o=i(72).verifyData,c=i(0),u=i(44).broadcast;e.exports=class extends r{async confirm(){var e,t;this.mode==a.Block&&(e=this.options.env,t=this.options.tx,this.data.dst=t.outputs[1].getAddress().toString(),this.data.height=this.options.coinbaseHeight,this.data.indate?this.data.indate=this.data.height+Math.max(144,Math.min(52560,this.data.indate)):this.data.indate=this.data.height+4320,t=new n({type:this.data.type,addr:this.data.addr,dst:this.data.dst,height:this.data.height,state:1,ver:1,indate:this.data.indate}),this.data.cls&&(t.options.cls=this.data.cls,this.mode===a.Block)&&"publish"==this.data.cls&&u("sc/publish",t.options),t.do(),await e.scList.addItem(t))}async unconfirm(){this.mode==a.Block&&await this.options.env.scList.delItem(this.data)}async verify(){var e=this.options.env,t=this.options.tx,i=t.outputs[1];if(!i||1e8!=i.value||!this.data)throw new s(t,"invalid","null scRegister data",100);var r=this.data.sig;delete this.data.sig,c.strictEqual(!0,o({data:this.data,sig:r})),r=await e.node.cdb.get("primary");if(0<e.scList.query([["options.dst",this.data.dst]]).length)throw new s(t,"Contract Register Conflict","another contract already on "+this.data.dst,100);if(await r.ensureAccount({name:this.data.addr,witness:!0}),(await r.createReceive(this.data.addr,1)).getAddress("string")!=i.getAddress().toString())throw new s(t,"Invalid Smart Contract","Receive address error",100);return!0}}},function(e,t,i){var r=i(14);const{ContractEnvType:a,ContractState:s}=i(5),n=i(37).VerifyError;var{}=i(151);const o=i(72).verifyData,c=i(0);e.exports=class extends r{async confirm(){var e,t;this.mode==a.Block&&(e=this.options.env,t=this.options.tx,this.data.dst=t.outputs[1].getAddress().toString(),this.data.height=this.options.coinbaseHeight,1==(t=e.scList.query([["options.dst",this.data.dst]])).list.length)&&(t.list[0].options.ver+=1,t.list[0].options.type=this.data.type,t.list[0].options.height=this.data.height,t.list[0].do(),await e.scList.addItem(t.list[0]))}async unconfirm(){this.mode==a.Block&&await this.options.env.scList.delItem(this.data)}async verify(){var e=this.options.env,t=this.options.tx,i=t.outputs[1];if(!i||1e5!=i.value||!this.data)throw new n(t,"Invalid Smart Contract","null scRegister data",100);var r=this.data.sig;delete this.data.sig,c.strictEqual(!0,o({data:this.data,sig:r})),r=await e.node.cdb.get("primary");if(0==(e=e.scList.query([["options.dst",this.data.dst]])).list.length)throw new n(t,"Contract Not Exists","contract not exists",100);if(e.list[0].options.state!=s.Normal)throw new n(t,"Contract State Error","contract state error",100);if(await r.ensureAccount({name:this.data.addr,witness:!0}),(await r.createReceive(this.data.addr,1)).getAddress("string")!=i.getAddress().toString())throw new n(t,"Invalid Smart Contract","dst address error",100);return!0}}},function(e,t,i){var r=i(14);const{ContractEnvType:a,ContractState:s}=i(5),n=i(37).VerifyError;var{}=i(151);const o=i(72).verifyData,c=i(0);e.exports=class extends r{async confirm(){var e,t;this.mode==a.Block&&(e=this.options.env,t=this.options.tx,this.data.dst=t.outputs[1].getAddress().toString(),this.data.height=this.options.coinbaseHeight,1==(t=e.scList.query([["options.dst",this.data.dst]])).list.length)&&(t.list[0].options.state=this.data.state,t.list[0].options.height=this.data.height,t.list[0].do(),await e.scList.addItem(t.list[0]))}async unconfirm(){this.mode==a.Block&&await this.options.env.scList.delItem(this.data)}async verify(){var e=this.options.env,t=this.options.tx,i=t.outputs[1];if(!i||1e5!=i.value||!this.data)throw new n(t,"Invalid Smart Contract","null scRegister data",100);var r=this.data.sig;delete this.data.sig,c.strictEqual(!0,o({data:this.data,sig:r})),r=await e.node.cdb.get("primary");if(0==(e=e.scList.query([["options.dst",this.data.dst]])).list.length)throw new n(t,"Contract Not Exists","contract not exists",100);switch(e.list[0].options.state){case s.Normal:if(this.data.state!=s.Frozen&&this.data.state!=s.Destroy)throw new n(t,"Contract State Error","contract state error",100);break;case s.Frozen:if(this.data.state!=s.Normal&&this.data.state!=s.Destroy)throw new n(t,"Contract State Error","contract state error",100);break;default:throw new n(t,"Contract State Error","contract state error",100)}if(await r.ensureAccount({name:this.data.addr,witness:!0}),(await r.createReceive(this.data.addr,1)).getAddress("string")!=i.getAddress().toString())throw new n(t,"Invalid Smart Contract","dst address error",100);return!0}}},function(e,t,i){var r=i(14);const{ContractEnvType:a,ContractState:s}=i(5),n=i(37).VerifyError,o=i(7),c=i(152),u=i(42);e.exports=class extends r{async onPacking(){var e=this.options.env,t=this.options.tx.hash("hex"),i=await e.node.cdb.get("primary"),r=this.data.$top;let a={derive:[]};var s=await i.getStatusOfSC(t);if(s.txs)for(var n of s.txs)(n=await i.getTX(n))&&a.derive.push(n.tx);else if((s=await this.getContract())&&(s={height:e.curHeight,data:this.data,tx:this.options.tx,contract:s,wallet:i},s=c(s)))if((a=await s.run()).derive&&a.derive.length<o.MAX_PACKING_SIZE){let s=[];for(var h of a.derive)if((h=await(await u.FactoryOfContract({tx:h,env:e})).onPacking()).derive){if(!(a.derive.length+s.length+h.derive.length<o.MAX_PACKING_SIZE))break;s=s.concat(h.derive)}a.derive=a.derive.concat(s),r||await i.setStatusOfSC(t,a.derive.map(e=>e.hash("hex")))}else a.derive=[];return a}async confirm(){var e,t,i;if(this.mode==a.Block)return e=this.options.env,(t=await this.getContract())&&(i=c({data:this.data,tx:this.options.tx,contract:t,wallet:await this.options.env.node.cdb.get("primary")}))&&(t.do(),await e.scList.addItem(t),await i.confirm()),!0}async unconfirm(){var e,t,i;if(this.mode==a.Block)return e=this.options.env,(t=await this.getContract())&&(i={data:this.data,tx:this.options.tx,contract:t,wallet:await this.options.env.node.cdb.get("primary")},i=c(i))&&(t.undo(),await e.scList.addItem(t),await i.unconfirm()),!0}async verify(){var e=this.options.env,t=this.options.tx,i=await this.getContract();if(!i)throw new n(t,"invalid","contract not found",100);if(i.options.state!=s.Normal)throw new n(t,"invalid","contract version conflict",100);if(this.data.params.ver&&this.data.params.ver!=i.options.ver)throw new n(t,"invalid","contract version conflict",100);if(i.options.indate<e.curHeight)throw new n(t,"invalid","contract expired",100);return t={data:this.data,tx:t,contract:i,wallet:await e.node.cdb.get("primary")},(i=c(t))?i.verify():"scRun.errorType"}async getContract(){if(0<this.options.tx.outputs.length){var e=this.options.tx.outputs[1].getAddress().toString();if((e=await this.options.env.node.chain.db.getSCList([["options.dst",e]]))&&0<e.list.length)return e.list[0]}return null}}},function(e,t,i){i=i(81);e.exports=class extends i{async run(){var e,t,i,r,a,s;return await this.verify()?(e=await super.run(),t=this.options.contract.options.addr,i=this.options.tx.outputs[1].value,r=this.options.wallet,s=this.options.data.params.relay,a=this.options.data.$top||0,s=await r.send({sendafter:!(r=[]),subtractFee:!1,sort:!1,outputs:[{address:s,value:i}],comment:JSON.stringify({$tag:"inner",$top:a+1,oper:"scrun",hash:this.options.tx.hash("hex"),account:t,params:this.options.data.params.params})},t),r.push(s),e.derive=r,e):{derive:[]}}async confirm(){return!0}async unconfirm(){return!0}async verify(){return super.verify()}}},function(e,t,i){i=i(81);e.exports=class extends i{async run(){if(!await this.verify())return{derive:[]};var e=await super.run(),t=[],i=this.options.tx.outputs[1].value,r=this.options.wallet,a=this.options.contract.options.addr;let s=this.options.data.params.sim;s||(s=(n=this.options.tx.inputs[0]).getAddress().toString());var n=this.options.data.$top||0;r=await r.send({sendafter:!1,subtractFee:!1,sort:!1,outputs:[{address:s,value:i/2}],comment:JSON.stringify({$tag:"inner",$top:n+1,hash:this.options.tx.hash("hex"),account:a})},a);return t.push(r),e.derive=t,e}async confirm(){return!0}async unconfirm(){return!0}async verify(){return super.verify()}}},function(e,t,i){i=i(81);e.exports=class extends i{async run(){if(!await this.verify())return{derive:[]};var e=await super.run(),t=[],i=this.options.tx.outputs[1].value,r=this.options.wallet,a=this.options.contract.options.addr;let s=this.options.data.params.sim;s||(s=(n=this.options.tx.inputs[0]).getAddress().toString());var n=this.options.data.$top||0;r=await r.send({sendafter:!1,subtractFee:!1,sort:!1,outputs:[{address:s,value:i/2}],comment:JSON.stringify({$tag:"inner",$top:n+1,hash:this.options.tx.hash("hex"),account:a})},a);return t.push(r),e.derive=t,e}async confirm(){return!0}async unconfirm(){return!0}async verify(){return super.verify()}}},function(e,t,i){i=i(81);e.exports=class extends i{async run(){return await this.verify()?await super.run():{derive:[]}}async confirm(){return!0}async unconfirm(){return!0}async verify(){return super.verify()}}},function(e,t,i){i=i(81);e.exports=class extends i{async run(){if(!await this.verify())return{derive:[]};var e=await super.run(),t=[];let i=this.options.contract;var r=this.options.data.params.oper,a=this.options.wallet,s=i.options.addr;switch(r){case"pubk":{var n,o,c,u=this.options.data.params.addr,h=this.options.data.params.pubk,l=this.options.data.params.partner;"object"==typeof i.options.contacts&&!Array.isArray(i.options.contacts)||(i.options.contacts={}),l&&l.split(",").map(e=>{i.options.contacts[e]||(i.options.contacts[e]={st:0})});let e="";for(n of Object.keys(i.options.contacts))u!=n&&(o=i.options.contacts[n],c=await a.send({sendafter:!1,subtractFee:!1,sort:!1,outputs:[{address:n,value:1e4}],comment:JSON.stringify({oper:"scnotify",type:"mssendpubk",$tag:"inner",hash:this.options.tx.hash("hex"),data:h,m:i.options.m,n:i.options.n,contract:i.options.dst,account:s})},s),t.push(c),o.pubk)&&(e&&(e+=","),e+=o.pubk);e&&(l=await a.send({sendafter:!1,subtractFee:!1,sort:!1,outputs:[{address:u,value:1e4}],comment:JSON.stringify({oper:"scnotify",type:"mssendpubk",$tag:"inner",hash:this.options.tx.hash("hex"),data:e,contract:i.options.dst,account:s})},s),t.push(l)),i.options.contacts[u]?i.options.contacts[u].pubk||(i.options.contacts[u].pubk=h):i.options.contacts[u]={pubk:h,st:0};break}case"puba":{var p,d=this.options.data.params.addr,f=this.options.data.params.puba;let e=!0;for(p of(i.options.puba=i.options.puba||f,Object.keys(i.options.contacts))){var m=i.options.contacts[p];p==d&&i.options.puba==f&&(m.st=1),1!=m.st&&(e=!1)}i.options.status=e;break}case"sign":if(1==i.options.status){var g,v,y=this.options.data.params.addr;for(g of Object.keys(i.options.contacts))g!=y&&(v=await a.send({sendafter:!1,subtractFee:!1,sort:!1,outputs:[{address:g,value:1e4}],comment:JSON.stringify({oper:"scnotify",type:"mssendtx",$tag:"inner",hash:this.options.tx.hash("hex"),data:this.options.data.params.tx,contract:i.options.dst,account:s})},s),t.push(v))}break;default:return e}return e.derive=t,e}async confirm(){return!0}async unconfirm(){return!0}async verify(){return super.verify()}}},function(e,t,i){var r=i(14);const a=i(5).ContractEnvType,s=i(44).broadcast;e.exports=class extends r{async confirm(){var e;this.mode==a.Wallet&&(e=this.options.tx.outputs[1])&&(this.data.addr=e.getAddress().toString(),this.options.env.emit(this.data.type+"/receive",this.data),s(this.data.type+"/receive",this.data))}async verify(){return!0}}},function(e,t,i){const r=i(0);var a=i(14);const{ContractEnvType:s,PropStatus:n}=i(5);e.exports=class extends a{async confirm(){var e=this.options.env,t=await e.propList.getVp(this.data.ori.pid);return t&&(t.pst=n.Delete,await e.propList.setVp(t),e.mode==s.Block)&&(t={pid:t.pid},e.node.transmit("prop.found",t)),!0}async unconfirm(){var e=this.options.env,t=this.options.tx,i=await e.propList.getVp(this.data.ori.pid);return i&&i.current.hash==t.inputs[0].prevout.hash&&i.current.index==t.inputs[0].prevout.index&&(i.pst=n.Ready,await e.propList.setVp(i)),!0}async verify(){var e=this.options.env,t=this.options.tx,i=this.data;return i.ori&&i.ori.pid?e.network.tokenReg.test(i.ori.pid)?"propfound.protected":(e=await e.propList.getVp(i.ori.pid))&&e.pst==n.Ready?(r.strictEqual(e.current.hash,t.inputs[0].prevout.hash),r.strictEqual(e.current.index,t.inputs[0].prevout.index),!0):"propfound.invalidStatus":"propfound.invalidAncestor"}}},function(e,t,i){var r=i(14);const{ContractEnvType:a,ContractType:s}=i(5),n=i(7),o=i(19).opcodes;e.exports=class extends r{async confirm(){return this.options.env,this.options.tx.hash("hex"),this.mode===a.Block&&await this.HandleVoteTrans(!1),!0}async unconfirm(){return this.options.env,this.options.tx,this.mode===a.Block&&await this.HandleVoteTrans(!0),!0}async HandleVoteTrans(e){var t=this.options.env,i=this.options.tx,r=this.options.tx.outputs[0].script.code;if(r[0].value==o.OP_RETURN)try{var a=JSON.parse(Buffer.from(r[1].data).toString());if(a&&a.oper==s.vote)switch(a.type){case"mine":{let r=0;for(var c of i.inputs){var u,h=await t.getExtendTX(c.prevout.hash);h&&t.voteMgr.isIn(h.height)?(u=h.tx.outputs[c.prevout.index])&&u.value?r+=u.value/n.COIN|0:t.logger.warning("Voting: Invalid UTXO Info"):t.logger.warning("Voting: Invalid UTXO Height")}0<r&&await t.voteMgr.calcVote(r,a.ca,e);break}case"oracle":{let r=0;for(var l of i.inputs){var p,d=await t.getExtendTX(l.prevout.hash);d&&t.voteMgr.isIn(d.height)?(p=d.tx.outputs[l.prevout.index])&&p.value?r+=p.value/1e5|0:t.logger.warning("Oracle: Invalid UTXO Info"):t.logger.warning("Oracle: Invalid UTXO Height")}0<r&&await t.voteMgr.calcOracle(r,{k:a.k,v:a.v},e);break}}}catch(r){console.log(r)}}async verify(){return!0}}},function(e,t,i){const r=i(0);var a=i(14);const{BlockFinalType:s,ContractEnvType:n,ContractType:o,PropStatus:c}=i(5),u=i(37).VerifyError,h=i(7);var{}=i(44);i(2);const l=i(31);e.exports=class extends a{async insert(){var e=this.options.env,t=this.options.tx,i=2<t.outputs.length?t.outputs[2].getReturnData():null,a=await e.propList.getVp(this.data.pid);if(a){if(i){if(this.mode==n.Wallet&&a.bid&&(i=await e.getTX(a.bid.hash))&&(i=await e.getWalletsByTX(i)))for(const t of i){var s=await e.get(t);r(s),await s.remove(a.bid.hash)}i=t.outputs[1].value;var o=t.outputs[2].getAddress().toString();i>=this.data.fixed||e.curHeight>=this.data.period&&i>a.gold?(a.pst=c.Sale,a.bid={},a.bid.raw=this.options.raw,a.bid.fixed=this.data.fixed,a.bid.period=this.data.period,a.bid.hash=this.options.hash,a.bid.value=i,a.bid.address=o,await e.propList.setVp(a,t)):(a.pst=c.Sale,a.bid={},a.bid.raw=this.options.raw,a.bid.fixed=this.data.fixed,a.bid.period=this.data.period,a.bid.hash=this.options.hash,a.bid.value=i,a.bid.address=o,await e.propList.setVp(a))}else a.pst=c.Sale,a.bid={},a.bid.raw=this.options.raw,a.bid.fixed=this.data.fixed,a.bid.period=this.data.period,a.bid.hash=this.options.hash,a.bid.value=a.gold,a.bid.address="",await e.propList.setVp(a);this.mode==n.Mempool&&(e.node.bidList||(e.node.bidList=new l),e.node.bidList.set(a.pid,Object.assign({pid:a.pid,curAddress:a.current.address,curGold:a.gold,status:c.Sale},a.bid)))}return!0}async erase(){var e=this.options.env,t=2<(i=this.options.tx).outputs.length?i.outputs[2].getReturnData():null,i=i.inputs[0],r=await e.propList.getVp(this.data.pid);r&&(t?(t=await e.getExtendTX(i.prevout.hash))&&(t.tx.outputs[i.prevout.index],r.bid={hash:this.options.hash,value:r.gold,address:"",raw:this.options.raw,fixed:this.data.fixed,period:this.data.period},r.pst=c.Sale,await e.propList.setVp(r,t.tx),this.mode==n.Mempool)&&(e.node.bidList||(e.node.bidList=new l),e.node.bidList.set(r.pid,Object.assign({pid:r.pid,curAddress:r.current.address,curGold:r.gold,status:c.Sale},r.bid))):(r.pst=c.Ready,await e.propList.setVp(r),this.mode==n.Mempool&&(e.node.bidList||(e.node.bidList=new l),e.node.bidList.delete(r.pid))))}async confirm(){var e=this.options.env,t=this.options.tx,i=t.hash("hex"),r=t.outputs[2].getAddress().toString(),a=await e.propList.getVp(this.data.pid);return a&&(this.mode==n.Block&&(e.node.bidList||(e.node.bidList=new l),e.node.bidList.delete(a.pid),e.node.transmit("prop.bid",{status:c.Ready,pid:a.pid,bid:Object.assign({},a.bid),height:this.options.coinbaseHeight})),a.current={hash:i,index:2,address:r},a.height=this.options.coinbaseHeight,a.pst=c.Ready,await e.propList.setVp(a,t)),!0}async unconfirm(){var e,t,i=this.options.env,r=this.options.tx,a=r.inputs[0].prevout,s=await i.getExtendTX(a.hash);return s?(t=(e=s.tx.outputs[a.index]).getReturnData(),(t=await i.propList.getVp(t.pid))&&(t.current={hash:a.hash,index:a.index,address:e.getAddress().toString()},t.height=s.height-1,await i.propList.setVp(t,r)),this.mode==n.Block&&i.node.transmit("prop.bid",{status:c.Delete,pid:t.pid,address:t.current.address,time:this.options.block.time,height:t.height})):this.mode==n.Wallet&&(a=await i.propList.getVp(this.data.pid),await i.propList.delVp(a)),!0}async verify(){var e=this.data,t=this.options.env,i=this.options.tx,a=2<i.outputs.length?i.outputs[2].getReturnData():null,s=await t.propList.getVp(e.pid);if(!s)return"propsale.notExist";switch(this.mode){case n.Mempool:if(r.strictEqual(e.prev.hash,i.inputs[0].prevout.hash),r.strictEqual(e.prev.index,i.inputs[0].prevout.index),r(t.curHeight+h.BLOCK_DAY>=this.data.period),r(e.cid!=t.network.genesisId),a&&(r.strictEqual(a.prev.hash,i.inputs[0].prevout.hash),r.strictEqual(a.prev.index,i.inputs[0].prevout.index),r.strictEqual(a.pid,e.pid),r.strictEqual(a.oper,o.propExchange),s.bid)){if(s.period<t.curHeight)throw new u(i,"sale order expired","contract",0);if(s.bid.value>=this.data.fixed)throw new u(i,"can not bid on sale order finished","contract",0);if(i.outputs[1].value<=s.bid.value||i.outputs[1].value<=s.gold)throw new u(i,"invalid bid price","contract",0);var c=await t.getTX(s.bid.hash);c&&await t.removeDoubleSpenders(c)}break;case n.Block:if(r.strictEqual(e.prev.hash,i.inputs[0].prevout.hash),r.strictEqual(e.prev.index,i.inputs[0].prevout.index),r(e.cid!=t.network.genesisId),r.strictEqual(a.prev.hash,i.inputs[0].prevout.hash),r.strictEqual(a.prev.index,i.inputs[0].prevout.index),r.strictEqual(a.pid,e.pid),r.strictEqual(a.oper,o.propExchange),i.outputs[1].value<=s.gold)throw new u(i,"invalid bid price","contract",0)}return!0}isBlockFinal(){var e=this.options.env,t=this.options.tx;return this.data.period<e.curHeight?s.Expired:2<=t.outputs.length&&(t.outputs[1].value>=this.data.fixed||this.data.period==e.curHeight&&t.outputs[1].value>=t.outputs[2].value)?s.Final:s.Waiting}isPreVerify(){var e=this.options.tx;return!!(2<e.outputs.length&&e.outputs[2].getReturnData())}}},function(e,t,i){const r=i(0),a=i(107),{ContractEnvType:s,BlockFinalType:n}=i(5);var o=i(14);const c=i(7),u=i(44).broadcast,h=i(6),l=i(13);e.exports=class extends o{async insert(){var e=this.options.env,t=this.options.tx;switch(this.data.body.dst=t.outputs[1].getAddress().toString(),this.mode){case s.Mempool:try{var i=JSON.parse(this.data.body.content);switch(i.cmd){case"peerdel":r(this.data.body.dst==e.node.config.notifyAddress),r(l.fromString(this.data.body.dst).hash.toString("hex")==h.hash160(Buffer.from(i.pub,"hex")).toString("hex")),r(a.verifyObj(i.payload,i.sig,i.pub)),await e.node.rpc._delPeer([i.payload.host,i.payload.an,i.payload.ai]);break;case"peeradd":r(this.data.body.dst==e.node.config.notifyAddress),r(l.fromString(this.data.body.dst).hash.toString("hex")==h.hash160(Buffer.from(i.pub,"hex")).toString("hex")),r(a.verifyObj(i.payload,i.sig,i.pub)),await e.node.rpc._addPeer([i.payload.host,i.payload.key,i.payload.an,i.payload.ai])}}catch(e){}break;case s.Wallet:if(e.NotifyList.get(this.data.sn))return;var n=this.data.body.dst,[n,o]=await e.getAccountByAddress(n,t);this.data.account=o,this.data.wid=n,e.emit("notify/receive",this.data),u("notify/receive",this.data),await e.NotifyList.set(this.data.sn,this.data)}return!0}async confirm(){}async unconfirm(){}async erase(){var e=this.options.env;return this.options.tx,this.mode===s.Wallet&&(await e.NotifyList.delete(this.data.sn),e.emit("notify/remove",this.data),u("notify/remove",this.data)),!0}async verify(){var e=this.options.env,t=this.options.tx;return t.getOutputValue()<.1*c.COIN?"Notify.invalidDeposit":2<t.outputs.length?"Notify.invalidFormat":!(this.data.h>e.curHeight)||"Notify.invalidHeight"}isBlockFinal(){var e=this.options.env;return this.data.h<e.curHeight-6?n.Expired:n.Waiting}}},function(e,t,i){var r=i(14);const{ContractEnvType:a,ContractStatus:s,BlockFinalType:n}=i(5),o=i(37).VerifyError;e.exports=class extends r{async insert(){var e=this.options.env;return this.data.period<e.curHeight?await e.transactionList.delTransContract(this.data,!0):(this.data.current={hash:this.options.hash,index:0},this.data.raw=this.options.raw,await e.transactionList.addTransContract(a.Mempool,this.data)),!0}async erase(){var e=this.options.env;switch(this.mode){case a.Mempool:await e.transactionList.delTransContract(this.data);break;case a.Wallet:await e.transactionList.delTransContract(this.data,!0)}}async verify(){var e=this.options.env,t=this.options.tx;if(this.data.period<e.curHeight)throw new o(t,"transaction contract expired","contract",0);if(e.transactionList.query(this.data.type,this.data.addr)!=s.None)throw new o(t,"Same Address Contract Finded","contract",0);return!0}isBlockFinal(){var e=this.options.env;return this.data.period<e.curHeight?n.Expired:n.Waiting}}},function(e,t,i){var r=i(14);const{ContractEnvType:a,ContractStatus:s}=i(5),n=i(108);e.exports=class extends r{async confirm(){var e=this.options.env;let t=s.Backed;switch(2==this.data.master&&(t=s.Exchanged),this.mode){case a.Block:var i=e.transactionList.get(this.data.type+"."+this.data.addr);i?(i.transStatus=t,await e.transactionList.saveContract(i,!0)):await e.transactionList.addTransContract(a.Block,this.data,!0);break;case a.Wallet:(i=e.transactionList.get(this.data.type+"."+this.data.addr))?(i.transStatus=t,await e.transactionList.saveContract(i,!0)):await e.transactionList.addTransContract(a.Wallet,this.data,!0)}return!0}async verify(){var e=this.options.env;switch(this.mode){case a.Mempool:case a.Block:case a.Wallet:{var t=this.data.master,i=e.transactionList.get(this.data.type+"."+this.data.addr);let r=i.transStatus;return r!==s.Expired&&r!==s.Confirmed&&r!==s.Backed&&r!==s.Exchanged&&(i=new n(e.network.txcheckpoint,i),[,r]=await i.execute(e)),r!==s.Expired&&r!==s.Confirmed&&r!==s.Backed&&r!==s.Exchanged?"ContractPromise.invalidStatus":!(r==s.Expired&&1!=t||r==s.Confirmed&&2!=t||r==s.Backed&&1!=t||r==s.Exchanged&&2!=t)||"ContractPromise.limited"}}}}},function(e,t,i){var r=i(14);const{ContractEnvType:a,VerifyCode:s}=i(5),n=i(153).ErItem,o=i(38),c=i(6),u=i(13),h=i(44).broadcast;e.exports=class extends r{async insert(){return!0}async confirm(){var e=this.options.env,t=this.options.tx;if(!(this.data.startHeight=e.curHeight,await e.erList.getEr(this.data.erid))){switch(await e.erList.setEr(this.data,t),this.mode){case a.Wallet:var i=u.fromWitnessPubkeyhash(c.hash160(Buffer.from(this.data.witness,"hex")),e.network),[i,r]=await e.getAccountByAddress(i,t);i&&r&&(this.data.account=r,this.data.wid=i,e.emit("ca/issue",this.data),h("ca/issue",this.data));break;case a.Block:e.node.transmit("ca.issue",this.data),e.node.config.alliancePrivateKey&&(r=o.fromPrivate(Buffer.from(e.node.config.alliancePrivateKey,"hex"),!0,e.network),o.fromPrivate(c.hash256(Buffer.concat([Buffer.from(this.data.source.cid+"-"+this.data.source.uid),r.privateKey]),!0,e.network)).publicKey.toString("hex")==this.data.witness)&&e.node.transmit("ca.issue.alliance",this.data)}return!0}e.logger.warning("ErIssue.conflict",this.data.erid,", height: ",e.curHeight,"mode: ",e.mode,t.txid())}async unconfirm(){var e=this.options.env,t=this.options.tx;switch(e.erList.delEr(this.data,t),this.mode){case a.Wallet:var i=u.fromWitnessPubkeyhash(c.hash160(Buffer.from(this.data.witness,"hex")),e.network),[i,r]=await e.getAccountByAddress(i,t);this.data.account=r,this.data.wid=i,e.emit("ca/unissue",this.data),h("ca/unissue",this.data);break;case a.Block:e.node.transmit("ca.unissue",this.data)}return!0}async erase(){return!0}async verify(){var e=this.options.env,t=this.data;e=o.fromPublic(Buffer.from(t.witness,"hex"),e.network);return!!new n(t).verifying(e)||s.SignatureNotMatch}}},function(e,t,i){var r=i(14);const{ContractEnvType:a,VerifyCode:s,ContractType:n}=i(5),o=i(154).ErAbolishItem,c=i(38),u=i(44).broadcast,h=i(6),l=i(13);e.exports=class extends r{async insert(){return!0}async confirm(){var e=this.options.env,t=this.options.tx;switch(this.data.startHeight=e.curHeight,await e.erAbList.setErAb(this.data,t),this.mode){case a.Wallet:var i=l.fromWitnessPubkeyhash(h.hash160(Buffer.from(this.data.witness,"hex")),e.network),[i,r]=await e.getAccountByAddress(i,t);this.data.account=r,this.data.wid=i,e.emit("ca/abolish",this.data),u("ca/abolish",this.data);break;case a.Block:e.node.transmit("ca.abolish",this.data)}return!0}async unconfirm(){var e=this.options.env,t=this.options.tx;switch(e.erAbList.delErAb(this.data,t),this.mode){case a.Wallet:var i=l.fromWitnessPubkeyhash(h.hash160(Buffer.from(this.data.witness,"hex")),e.network),[i,r]=await e.getAccountByAddress(i,t);this.data.account=r,this.data.wid=i,e.emit("ca/unabolish",this.data),u("ca/unabolish",this.data);break;case a.Block:e.node.transmit("ca.unabolish",this.data)}return!0}async erase(){return!0}async verify(){var e=this.options.env,t=this.data,i=await e.erList.getEr(t.erid);return i&&i.witness==t.witness?t&&t.oper==n.erAbolish&&(i=await e.erAbList.getErAb(t.erid))&&t.abolishHeight>=i.abolishHeight?s.NotExistER:(i=c.fromPublic(Buffer.from(t.witness,"hex"),e.network),!!new o(t).verifying(i)||s.SignatureNotMatch):s.SignatureNotMatch}}},function(e,t,i){var r=i(14);const{VerifyCode:a,ContractEnvType:s}=i(5),n=i(228).EnchancementItem,o=i(38);e.exports=class extends r{async insert(){return!0}async confirm(){var e,t;return this.mode==s.Block&&(e=this.options.env,t=this.options.tx,this.data.enchanceTx=t.txid(),e.enCpList.setEn(this.data),!0)}async unconfirm(){var e,t;return this.mode==s.Block&&(e=this.options.env,t=this.options.tx,e.enCpList.delEn(this.data,t),!0)}async erase(){return!0}async verify(){var e=this.options.env,t=this.options.tx,i=this.data,r=e.cpList.getItem(i.to);t=t.outputs[1].getAddress().toString();return r&&r.pubAddress&&r.pubAddress==t&&(r=e.cpList.getItem(i.from))&&r.pubAddress&&r.pubKey?(t=o.fromPublic(Buffer.from(r.pubKey,"hex"),e.network),!!new n(i).verifying(t)||a.SignatureNotMatch):a.NotExistCp}}},function(e,t,i){"use strict";
|
|
441
441
|
/*!
|
|
442
442
|
* TXRecord.js
|
|
443
443
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -466,7 +466,7 @@ const r=i(5).ContractType;e.exports=function(e){if(!e)return i(188);switch(e.ope
|
|
|
466
466
|
/*!
|
|
467
467
|
* rollingfilter.js - rolling bloom filter for vallnet
|
|
468
468
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
469
|
-
*/const r=i(0),a=i(
|
|
469
|
+
*/const r=i(0),a=i(144),s=a.sum32,n=a.mul32,o=Buffer.alloc(0);function c(e,t){this.hi=e,this.lo=t}function u(e,t){return new c(e.readUInt32LE(t+4,!0),e.readUInt32LE(t,!0))}function h(e,t,i){e.writeUInt32LE(t.hi,i+4,!0),e.writeUInt32LE(t.lo,i,!0)}e.exports=class e{constructor(e,t){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!=e&&this.fromRate(e,t)}fromRate(e,t){r("number"==typeof e,"`items` must be a number."),r(0<e,"`items` must be greater than zero."),r(Number.isSafeInteger(e),"`items` must be an integer."),r("number"==typeof t,"`rate` must be a number."),r(0<=t&&t<=1,"`rate` must be between 0.0 and 1.0.");t=Math.log(t);var i=Math.max(1,Math.min(Math.round(t/Math.log(.5)),50)),a=(e+1)/2|0,s=(t=-1*i*(3*a)/Math.log(1-Math.exp(t/i)),e=(((t=Math.ceil(t))+63)/64|0)<<1,e>>>=0,e=Math.max(1,e),4294967296*Math.random()>>>0),n=Buffer.allocUnsafe(8*e);return n.fill(0),this.n=i,this.limit=a,this.size=t,this.items=e,this.tweak=s,this.filter=n,this}static fromRate(t,i){return(new e).fromRate(t,i)}hash(e,t){return a(e,s(n(t,4221880213),this.tweak))}reset(){0!==this.entries&&(this.entries=0,this.generation=1,this.filter.fill(0))}add(e,t){if("string"==typeof e&&(e=Buffer.from(e,t)),this.entries===this.limit){this.entries=0,this.generation+=1,4===this.generation&&(this.generation=1);var i=4294967295*(1&this.generation),r=4294967295*(this.generation>>>1);for(let e=0;e<this.items;e+=2){var a=8*e,s=8*(e+1),n=u(this.filter,a),o=u(this.filter,s),c=n.hi^i|o.hi^r,l=n.lo^i|o.lo^r;n.hi&=c,n.lo&=l,o.hi&=c,o.lo&=l,n.hi=n.hi>>>0,n.lo=n.lo>>>0,o.hi=o.hi>>>0,o.lo=o.lo>>>0,h(this.filter,n,a),h(this.filter,o,s)}}this.entries+=1;for(let t=0;t<this.n;t++){var p=63&(f=this.hash(e,t)),d=8*(-2&(f=(f>>>6)%this.items)),f=8*(1|f),m=p%8;p=(p-m)/8;this.filter[d+p]&=~(1<<m),this.filter[d+p]|=(1&this.generation)<<m,this.filter[f+p]&=~(1<<m),this.filter[f+p]|=this.generation>>>1<<m}}test(e,t){if(0===this.entries)return!1;"string"==typeof e&&(e=Buffer.from(e,t));for(let t=0;t<this.n;t++){var i=63&(r=this.hash(e,t)),r=(r>>>6)%this.items,a=i%8;i=(i-a)/8;if(0==(this.filter[8*(-2&r)+i]>>>a&1|this.filter[8*(1|r)+i]>>>a&1))return!1}return!0}added(e,t){return"string"==typeof e&&(e=Buffer.from(e,t)),!this.test(e)&&(this.add(e),!0)}}},function(e,t,i){var r=i(31);const a=i(4),s=i(3),n=i(6);class o extends r{constructor(e,t){super(),this.db=e||{setEn:()=>{},delEn:()=>{},loadCpEnList:()=>{}},this.options=t,this.rank={}}async loadHistory(){this.clear();let e=[];for(var t of e="cp"===this.options.type?await this.db.loadCpEnList():e)this.rank[t.to]||(this.rank[t.to]=[]),-1==this.rank[t.to].indexOf(t.from)&&this.rank[t.to].push(t.from)}async setEn(e){e&&e.to&&e.from&&(e=new c(e),"cp"===this.options.type&&await this.db.setCpEn(e),this.rank[e.to]||(this.rank[e.to]=[]),-1==this.rank[e.to].indexOf(e.from))&&this.rank[e.to].push(e.from)}async delEn(e){var t;e&&e.to&&e.from&&("cp"===this.options.type&&await this.db.delCpEn(e),this.rank[e.to])&&-1!=(t=this.rank[e.to].indexOf(e.from))&&this.rank[e.to].splice(t,1)}}class c{constructor(e){this.fromOptions(e=e||{})}fromOptions(e){this.oper=e.oper,this.to=e.to,this.from=e.from,this.enchanceHeight=e.enchanceHeight,this.enchanceTx=e.enchanceTx,this.signature=e.signature}toOptions(e){var t={};return t.oper=this.oper,t.to=this.to,t.from=this.from,t.enchanceHeight=this.enchanceHeight,"string"==typeof this.enchanceTx&&(t.enchanceTx=this.enchanceTx),e&&(t.signature=this.signature),t}getSignObjSize(){let e=0;return e=(e=(e+=s.sizeVarString(this.oper,"utf8"))+s.sizeVarString(this.to,"utf8"))+s.sizeVarString(this.from,"utf8")+4,"string"==typeof this.enchanceTx&&(e+=s.sizeVarString(this.enchanceTx,"utf8")),e}toWriter(e,t){return t.writeVarString(this.oper,"utf8"),t.writeVarString(this.to,"utf8"),t.writeVarString(this.from,"utf8"),t.writeU32(this.enchanceHeight),"string"==typeof this.enchanceTx&&t.writeVarString(this.enchanceTx,"utf8"),t}toHash(){var e=this.toOptions();return n.hash256(this.toWriter(e,new a(this.getSignObjSize(e))).render())}toRaw(){return Buffer.from(JSON.stringify(this.toOptions(!0)),"utf-8")}fromRaw(e){return e=JSON.parse(e.toString("utf8")),this.fromOptions(e),this}static fromRaw(e){return(new c).fromRaw(e)}sign(e){this.signature=e.sign(this.toHash()).toString("hex")}verifying(e){return e.verify(this.toHash(),Buffer.from(this.signature,"hex"))}}o.EnchancementItem=c,e.exports=o},function(e,t,i){"use strict";
|
|
470
470
|
/*!
|
|
471
471
|
* plugin.js - contract plugin for vallnet
|
|
472
472
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -561,7 +561,7 @@ const r=i(5).ContractType;e.exports=function(e){if(!e)return i(188);switch(e.ope
|
|
|
561
561
|
/*!
|
|
562
562
|
* undocoins.js - undocoins object for vallnet
|
|
563
563
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
564
|
-
*/const r=i(0),a=i(1),s=i(4),n=i(146);function o(){if(!(this instanceof o))return new o;this.items=[]}o.prototype.push=function(e){return this.items.push(e)},o.prototype.getSize=function(){let e=0;e+=4;for(const t of this.items)e+=t.getSize();return e},o.prototype.toRaw=function(){var e=this.getSize(),t=new s(e);t.writeU32(this.items.length);for(const e of this.items)e.toWriter(t);return t.render()},o.prototype.fromRaw=function(e){var t=new a(e),i=t.readU32();for(let e=0;e<i;e++)this.items.push(n.fromReader(t));return this},o.fromRaw=function(e){return(new o).fromRaw(e)},o.prototype.isEmpty=function(){return 0===this.items.length},o.prototype.commit=function(){var e=this.toRaw();return this.items.length=0,e},o.prototype.apply=function(e,t){var i=this.items.pop();r(i),e.addEntry(t,i)},e.exports=o},function(e,t,i){"use strict";function r(e,t){return e.listeners(t).length}var a,s,n=i(130),o=(e.exports=g,i(398)),c=(g.ReadableState=m,i(16).EventEmitter,i(249)),u=i(39).Buffer,h=global.Uint8Array||function(){},l=((e=Object.create(i(86))).inherits=i(49),i(9)),p=void 0,d=(p=l&&l.debuglog?l.debuglog("stream"):function(){},i(399)),f=(l=i(250),e.inherits(g,c),["error","close","destroy","pause","resume"]);function m(e,t){e=e||{};t=t instanceof(a=a||i(87));var r=(this.objectMode=!!e.objectMode,t&&(this.objectMode=this.objectMode||!!e.readableObjectMode),e.highWaterMark),n=e.readableHighWaterMark,o=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:t&&(n||0===n)?n:o,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new d,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(s=s||i(252).StringDecoder,this.decoder=new s(e.encoding),this.encoding=e.encoding)}function g(e){if(a=a||i(87),!(this instanceof g))return new g(e);this._readableState=new m(e,this),this.readable=!0,e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy)&&(this._destroy=e.destroy),c.call(this)}function v(e,t,i,r,a){var s,n,o,c,l=e._readableState;return null===t?(l.reading=!1,n=e,(c=l).ended||(c.decoder&&(o=c.decoder.end())&&o.length&&(c.buffer.push(o),c.length+=c.objectMode?1:o.length),c.ended=!0,x(n))):(s=a?s:function(e,t){var i;return!function(e){return u.isBuffer(e)||e instanceof h}(t)&&"string"!=typeof t&&void 0!==t&&!e.objectMode&&(i=new TypeError("Invalid non-string/buffer chunk")),i}(l,t))?e.emit("error",s):l.objectMode||t&&0<t.length?("string"==typeof t||l.objectMode||Object.getPrototypeOf(t)===u.prototype||(o=t,t=u.from(o)),r?l.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):y(e,l,t,!0):l.ended?e.emit("error",new Error("stream.push() after EOF")):(l.reading=!1,!l.decoder||i||(t=l.decoder.write(t),l.objectMode)||0!==t.length?y(e,l,t,!1):S(e,l))):r||(l.reading=!1),!(c=l).ended&&(c.needReadable||c.length<c.highWaterMark||0===c.length)}function y(e,t,i,r){t.flowing&&0===t.length&&!t.sync?(e.emit("data",i),e.read(0)):(t.length+=t.objectMode?1:i.length,r?t.buffer.unshift(i):t.buffer.push(i),t.needReadable&&x(e)),S(e,t)}Object.defineProperty(g.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),g.prototype.destroy=l.destroy,g.prototype._undestroy=l.undestroy,g.prototype._destroy=function(e,t){this.push(null),t(e)},g.prototype.push=function(e,t){var i,r=this._readableState;return r.objectMode?i=!0:"string"==typeof e&&((t=t||r.defaultEncoding)!==r.encoding&&(e=u.from(e,t),t=""),i=!0),v(this,e,t,!1,i)},g.prototype.unshift=function(e){return v(this,e,null,!0,!1)},g.prototype.isPaused=function(){return!1===this._readableState.flowing},g.prototype.setEncoding=function(e){return s=s||i(252).StringDecoder,this._readableState.decoder=new s(e),this._readableState.encoding=e,this};var b=8388608;function w(e,t){var i;return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?(t.flowing&&t.length?t.buffer.head.data:t).length:(e>t.highWaterMark&&(t.highWaterMark=(b<=(i=e)?i=b:(i--,i=(i=(i=(i=(i|=i>>>1)|i>>>2)|i>>>4)|i>>>8)|i>>>16,i++),i)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function x(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(p("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?n.nextTick(k,e):k(e))}function k(e){p("emit readable"),e.emit("readable"),A(e)}function S(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(_,e,t))}function _(e,t){for(var i=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length<t.highWaterMark&&(p("maybeReadMore read 0"),e.read(0),i!==t.length);)i=t.length;t.readingMore=!1}function E(e){p("readable nexttick read 0"),e.read(0)}function j(e,t){t.reading||(p("resume read 0"),e.read(0)),t.resumeScheduled=!1,t.awaitDrain=0,e.emit("resume"),A(e),t.flowing&&!t.reading&&e.read(0)}function A(e){var t=e._readableState;for(p("flow",t.flowing);t.flowing&&null!==e.read(););}function R(e,t){var i;return 0===t.length?null:(t.objectMode?i=t.buffer.shift():!e||e>=t.length?(i=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):i=function(e,t,i){var r;return e<t.head.data.length?(r=t.head.data.slice(0,e),t.head.data=t.head.data.slice(e)):r=e===t.head.data.length?t.shift():(i?function(e,t){var i=t.head,r=1,a=i.data;for(e-=a.length;i=i.next;){var s=i.data,n=e>s.length?s.length:e;if(n===s.length?a+=s:a+=s.slice(0,e),0==(e-=n)){n===s.length?(++r,i.next?t.head=i.next:t.head=t.tail=null):(t.head=i).data=s.slice(n);break}++r}return t.length-=r,a}:function(e,t){var i=u.allocUnsafe(e),r=t.head,a=1;for(r.data.copy(i),e-=r.data.length;r=r.next;){var s=r.data,n=e>s.length?s.length:e;if(s.copy(i,i.length-e,0,n),0==(e-=n)){n===s.length?(++a,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r).data=s.slice(n);break}++a}return t.length-=a,i})(e,t),r}(e,t.buffer,t.decoder),i)}function I(e){var t=e._readableState;if(0<t.length)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,n.nextTick(O,t,e))}function O(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function C(e,t){for(var i=0,r=e.length;i<r;i++)if(e[i]===t)return i;return-1}g.prototype.read=function(e){p("read",e),e=parseInt(e,10);var t,i=this._readableState,r=e;return 0!==e&&(i.emittedReadable=!1),0===e&&i.needReadable&&(i.length>=i.highWaterMark||i.ended)?(p("read: emitReadable",i.length,i.ended),(0===i.length&&i.ended?I:x)(this),null):0===(e=w(e,i))&&i.ended?(0===i.length&&I(this),null):(t=i.needReadable,p("need readable",t),(0===i.length||i.length-e<i.highWaterMark)&&p("length less than watermark",t=!0),i.ended||i.reading?p("reading or ended",t=!1):t&&(p("do read"),i.reading=!0,i.sync=!0,0===i.length&&(i.needReadable=!0),this._read(i.highWaterMark),i.sync=!1,i.reading||(e=w(r,i))),null===(t=0<e?R(e,i):null)?(i.needReadable=!0,e=0):i.length-=e,0===i.length&&(i.ended||(i.needReadable=!0),r!==e)&&i.ended&&I(this),null!==t&&this.emit("data",t),t)},g.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},g.prototype.pipe=function(e,t){var i=this,a=this._readableState;switch(a.pipesCount){case 0:a.pipes=e;break;case 1:a.pipes=[a.pipes,e];break;default:a.pipes.push(e)}function s(){p("onend"),e.end()}a.pipesCount+=1,p("pipe count=%d opts=%j",a.pipesCount,t),t=t&&!1===t.end||e===process.stdout||e===process.stderr?v:s,a.endEmitted?n.nextTick(t):i.once("end",t),e.on("unpipe",(function t(r,n){p("onunpipe"),r===i&&n&&!1===n.hasUnpiped&&(n.hasUnpiped=!0,p("cleanup"),e.removeListener("close",m),e.removeListener("finish",g),e.removeListener("drain",u),e.removeListener("error",f),e.removeListener("unpipe",t),i.removeListener("end",s),i.removeListener("end",v),i.removeListener("data",d),h=!0,!a.awaitDrain||e._writableState&&!e._writableState.needDrain||u())})),c=i;var c,u=function(){var e=c._readableState;p("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&r(c,"data")&&(e.flowing=!0,A(c))},h=(e.on("drain",u),!1),l=!1;function d(t){p("ondata"),(l=!1)!==e.write(t)||l||((1===a.pipesCount&&a.pipes===e||1<a.pipesCount&&-1!==C(a.pipes,e))&&!h&&(p("false write response, pause",i._readableState.awaitDrain),i._readableState.awaitDrain++,l=!0),i.pause())}function f(t){p("onerror",t),v(),e.removeListener("error",f),0===r(e,"error")&&e.emit("error",t)}function m(){e.removeListener("finish",g),v()}function g(){p("onfinish"),e.removeListener("close",m),v()}function v(){p("unpipe"),i.unpipe(e)}return i.on("data",d),function(e,t,i){if("function"==typeof e.prependListener)return e.prependListener(t,i);e._events&&e._events[t]?o(e._events[t])?e._events[t].unshift(i):e._events[t]=[i,e._events[t]]:e.on(t,i)}(e,"error",f),e.once("close",m),e.once("finish",g),e.emit("pipe",i),a.flowing||(p("pipe resume"),i.resume()),e},g.prototype.unpipe=function(e){var t=this._readableState,i={hasUnpiped:!1};if(0!==t.pipesCount)if(1===t.pipesCount)e&&e!==t.pipes||(e=e||t.pipes,t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,i));else if(e){var r=C(t.pipes,e);-1!==r&&(t.pipes.splice(r,1),--t.pipesCount,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,i))}else{var a=t.pipes,s=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var n=0;n<s;n++)a[n].emit("unpipe",this,i)}return this},g.prototype.addListener=g.prototype.on=function(e,t){return t=c.prototype.on.call(this,e,t),"data"===e?!1!==this._readableState.flowing&&this.resume():"readable"!==e||(e=this._readableState).endEmitted||e.readableListening||(e.readableListening=e.needReadable=!0,e.emittedReadable=!1,e.reading?e.length&&x(this):n.nextTick(E,this)),t},g.prototype.resume=function(){var e,t=this._readableState;return t.flowing||(p("resume"),t.flowing=!0,e=this,(t=t).resumeScheduled)||(t.resumeScheduled=!0,n.nextTick(j,e,t)),this},g.prototype.pause=function(){return p("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(p("pause"),this._readableState.flowing=!1,this.emit("pause")),this},g.prototype.wrap=function(e){var t,i=this,r=this._readableState,a=!1;for(t in e.on("end",(function(){var e;p("wrapped end"),r.decoder&&!r.ended&&(e=r.decoder.end())&&e.length&&i.push(e),i.push(null)})),e.on("data",(function(t){p("wrapped data"),r.decoder&&(t=r.decoder.write(t)),r.objectMode&&null==t||(r.objectMode||t&&t.length)&&!i.push(t)&&(a=!0,e.pause())})),e)void 0===this[t]&&"function"==typeof e[t]&&(this[t]=function(t){return function(){return e[t].apply(e,arguments)}}(t));for(var s=0;s<f.length;s++)e.on(f[s],this.emit.bind(this,f[s]));return this._read=function(t){p("wrapped _read",t),a&&(a=!1,e.resume())},this},Object.defineProperty(g.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),g._fromList=R},function(e,t,i){e.exports=i(47)},function(e,t,i){"use strict";var r=i(130);function a(e,t){e.emit("error",t)}e.exports={destroy:function(e,t){var i=this,s=this._readableState&&this._readableState.destroyed,n=this._writableState&&this._writableState.destroyed;return s||n?t?t(e):!e||this._writableState&&this._writableState.errorEmitted||r.nextTick(a,this,e):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,(function(e){!t&&e?(r.nextTick(a,i,e),i._writableState&&(i._writableState.errorEmitted=!0)):t&&t(e)}))),this},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}}},function(e,t,i){"use strict";var r=i(130);function a(e){var t=this;this.next=null,this.entry=null,this.finish=function(){var i=t,r=e,a=i.entry;for(i.entry=null;a;){var s=a.callback;r.pendingcb--,s(void 0),a=a.next}r.corkedRequestsFree?r.corkedRequestsFree.next=i:r.corkedRequestsFree=i}}e.exports=m;var s,n,o=!process.browser&&-1<["v0.10","v0.9."].indexOf(process.version.slice(0,5))?setImmediate:r.nextTick,c=((e=(m.WritableState=f,Object.create(i(86)))).inherits=i(49),{deprecate:i(400)}),u=i(249),h=i(39).Buffer,l=global.Uint8Array||function(){},p=i(250);function d(){}function f(e,t){s=s||i(87),e=e||{};var n=t instanceof s,c=(this.objectMode=!!e.objectMode,n&&(this.objectMode=this.objectMode||!!e.writableObjectMode),e.highWaterMark),u=e.writableHighWaterMark,h=this.objectMode?16:16384;this.highWaterMark=c||0===c?c:n&&(u||0===u)?u:h,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,c=(this.destroyed=!1)===e.decodeStrings;this.decodeStrings=!c,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){e=e,s=(a=(i=t)._writableState).sync,n=a.writecb;var i,a,s,n,c,u,h,l,p=a;p.writing=!1,p.writecb=null,p.length-=p.writelen,p.writelen=0,e?(p=i,u=s,h=e,l=n,--(c=a).pendingcb,u?(r.nextTick(l,h),r.nextTick(x,p,c),p._writableState.errorEmitted=!0,p.emit("error",h)):(l(h),p._writableState.errorEmitted=!0,p.emit("error",h),x(p,c))):((e=b(a))||a.corked||a.bufferProcessing||!a.bufferedRequest||y(i,a),s?o(v,i,a,e,n):v(i,a,e,n))},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new a(this)}e.inherits(m,u),f.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t};try{Object.defineProperty(f.prototype,"buffer",{get:c.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}function m(e){if(s=s||i(87),!(n.call(m,this)||this instanceof s))return new m(e);this._writableState=new f(e,this),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final)&&(this._final=e.final),u.call(this)}function g(e,t,i,r,a,s,n){t.writelen=r,t.writecb=n,t.writing=!0,t.sync=!0,i?e._writev(a,t.onwrite):e._write(a,s,t.onwrite),t.sync=!1}function v(e,t,i,r){var a;i||(i=e,0===(a=t).length&&a.needDrain&&(a.needDrain=!1,i.emit("drain"))),t.pendingcb--,r(),x(e,t)}function y(e,t){t.bufferProcessing=!0;var i=t.bufferedRequest;if(e._writev&&i&&i.next){for(var r=t.bufferedRequestCount,s=new Array(r),n=((r=t.corkedRequestsFree).entry=i,0),o=!0;i;)(s[n]=i).isBuf||(o=!1),i=i.next,n+=1;s.allBuffers=o,g(e,t,!0,t.length,s,"",r.finish),t.pendingcb++,t.lastBufferedRequest=null,r.next?(t.corkedRequestsFree=r.next,r.next=null):t.corkedRequestsFree=new a(t),t.bufferedRequestCount=0}else{for(;i;){var c=i.chunk,u=i.encoding,h=i.callback;if(g(e,t,!1,t.objectMode?1:c.length,c,u,h),i=i.next,t.bufferedRequestCount--,t.writing)break}null===i&&(t.lastBufferedRequest=null)}t.bufferedRequest=i,t.bufferProcessing=!1}function b(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function w(e,t){e._final((function(i){t.pendingcb--,i&&e.emit("error",i),t.prefinished=!0,e.emit("prefinish"),x(e,t)}))}function x(e,t){var i,a,s=b(t);return s&&(i=e,(a=t).prefinished||a.finalCalled||("function"==typeof i._final?(a.pendingcb++,a.finalCalled=!0,r.nextTick(w,i,a)):(a.prefinished=!0,i.emit("prefinish"))),0===t.pendingcb)&&(t.finished=!0,e.emit("finish")),s}"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(n=Function.prototype[Symbol.hasInstance],Object.defineProperty(m,Symbol.hasInstance,{value:function(e){return!!n.call(this,e)||this===m&&e&&e._writableState instanceof f}})):n=function(e){return e instanceof this},m.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},m.prototype.write=function(e,t,i){var a,s,n,o,c,u,p,f=this._writableState,m=!1,v=!f.objectMode&&(v=e,h.isBuffer(v)||v instanceof l);return v&&!h.isBuffer(e)&&(c=e,e=h.from(c)),"function"==typeof t&&(i=t,t=null),t=v?"buffer":t||f.defaultEncoding,"function"!=typeof i&&(i=d),f.ended?(c=this,u=i,p=new Error("write after end"),c.emit("error",p),r.nextTick(u,p)):(v||(u=this,p=f,s=i,o=!(n=!0),null===(a=e)?o=new TypeError("May not write null values to stream"):"string"==typeof a||void 0===a||p.objectMode||(o=new TypeError("Invalid non-string/buffer chunk")),o&&(u.emit("error",o),r.nextTick(s,o),n=!1),n))&&(f.pendingcb++,m=function(e,t,i,r,a,s){i||r!==(o=function(e,t,i){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=h.from(t,i)),t}(t,r,a))&&(i=!0,a="buffer",r=o);var n,o=t.objectMode?1:r.length,c=(t.length+=o,t.length<t.highWaterMark);return c||(t.needDrain=!0),t.writing||t.corked?(n=t.lastBufferedRequest,t.lastBufferedRequest={chunk:r,encoding:a,isBuf:i,callback:s,next:null},n?n.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1):g(e,t,!1,o,r,a,s),c}(this,f,v,e,t,i)),m},m.prototype.cork=function(){this._writableState.corked++},m.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||y(this,e))},m.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),-1<["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase()))return this._writableState.defaultEncoding=e,this;throw new TypeError("Unknown encoding: "+e)},Object.defineProperty(m.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),m.prototype._write=function(e,t,i){i(new Error("_write() is not implemented"))},m.prototype._writev=null,m.prototype.end=function(e,t,i){var a=this._writableState;"function"==typeof e?(i=e,t=e=null):"function"==typeof t&&(i=t,t=null),null!=e&&this.write(e,t),a.corked&&(a.corked=1,this.uncork()),a.ending||a.finished||(e=this,t=i,(i=a).ending=!0,x(e,i),t&&(i.finished?r.nextTick(t):e.once("finish",t)),i.ended=!0,e.writable=!1)},Object.defineProperty(m.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),m.prototype.destroy=p.destroy,m.prototype._undestroy=p.undestroy,m.prototype._destroy=function(e,t){this.end(),t(e)}},function(e,t,i){"use strict";var r=i(39).Buffer,a=r.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function s(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"==typeof t||r.isEncoding!==a&&a(e))return t||e;throw new Error("Unknown encoding: "+e)}(e),this.encoding){case"utf16le":this.text=c,this.end=u,t=4;break;case"utf8":this.fillLast=o,t=4;break;case"base64":this.text=h,this.end=l,t=3;break;default:return this.write=p,void(this.end=d)}this.lastNeed=0,this.lastTotal=0,this.lastChar=r.allocUnsafe(t)}function n(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function o(e){var t,i=this.lastTotal-this.lastNeed,r=(t=this,128!=(192&(r=e)[0])?(t.lastNeed=0,"�"):1<t.lastNeed&&1<r.length?128!=(192&r[1])?(t.lastNeed=1,"�"):2<t.lastNeed&&2<r.length&&128!=(192&r[2])?(t.lastNeed=2,"�"):void 0:void 0);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,i,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,i,0,e.length),void(this.lastNeed-=e.length))}function c(e,t){if((e.length-t)%2!=0)return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1);if(t=e.toString("utf16le",t)){var i=t.charCodeAt(t.length-1);if(55296<=i&&i<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],t.slice(0,-1)}return t}function u(e){var t;e=e&&e.length?this.write(e):"";return this.lastNeed?(t=this.lastTotal-this.lastNeed,e+this.lastChar.toString("utf16le",0,t)):e}function h(e,t){var i=(e.length-t)%3;return 0==i?e.toString("base64",t):(this.lastNeed=3-i,this.lastTotal=3,1==i?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-i))}function l(e){return e=e&&e.length?this.write(e):"",this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function p(e){return e.toString(this.encoding)}function d(e){return e&&e.length?this.write(e):""}(t.StringDecoder=s).prototype.write=function(e){if(0===e.length)return"";var t,i;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";i=this.lastNeed,this.lastNeed=0}else i=0;return i<e.length?t?t+this.text(e,i):this.text(e,i):t||""},s.prototype.end=function(e){return e=e&&e.length?this.write(e):"",this.lastNeed?e+"�":e},s.prototype.text=function(e,t){var i=function(e,t,i){var r=t.length-1;if(!(r<i)){var a=n(t[r]);if(0<=a)return 0<a&&(e.lastNeed=a-1),a;if(!(--r<i||-2===a)){if(0<=(a=n(t[r])))return 0<a&&(e.lastNeed=a-2),a;if(!(--r<i||-2===a)&&0<=(a=n(t[r])))return 0<a&&(2===a?a=0:e.lastNeed=a-3),a}}return 0}(this,e,t);return this.lastNeed?(this.lastTotal=i,i=e.length-(i-this.lastNeed),e.copy(this.lastChar,0,i),e.toString("utf8",t,i)):e.toString("utf8",t)},s.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},function(e,t,i){"use strict";e.exports=a;var r=i(87);function a(e){if(!(this instanceof a))return new a(e);r.call(this,e),this._transformState={afterTransform:function(e,t){var i=this._transformState,r=(i.transforming=!1,i.writecb);if(!r)return this.emit("error",new Error("write callback called multiple times"));i.writechunk=null,(i.writecb=null)!=t&&this.push(t),r(e),(i=this._readableState).reading=!1,(i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush)&&(this._flush=e.flush),this.on("prefinish",s)}function s(){var e=this;"function"==typeof this._flush?this._flush((function(t,i){n(e,t,i)})):n(this,null,null)}function n(e,t,i){if(t)return e.emit("error",t);if(null!=i&&e.push(i),e._writableState.length)throw new Error("Calling transform done when ws.length != 0");if(e._transformState.transforming)throw new Error("Calling transform done when still transforming");e.push(null)}(e=Object.create(i(86))).inherits=i(49),e.inherits(a,r),a.prototype.push=function(e,t){return this._transformState.needTransform=!1,r.prototype.push.call(this,e,t)},a.prototype._transform=function(e,t,i){throw new Error("_transform() is not implemented")},a.prototype._write=function(e,t,i){var r=this._transformState;r.writecb=i,r.writechunk=e,r.writeencoding=t,!r.transforming&&(i=this._readableState,r.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)},a.prototype._read=function(e){var t=this._transformState;null!==t.writechunk&&t.writecb&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0},a.prototype._destroy=function(e,t){var i=this;r.prototype._destroy.call(this,e,(function(e){t(e),i.emit("close")}))}},function(e,t,i){"use strict";function r(e){if("object"!=typeof e||null===e)throw new TypeError("First argument must be an abstract-leveldown compliant store");this.db=e,this._ended=!1,this._nexting=!1}r.prototype.next=function(e){let t=this;if(void 0===e)t=new Promise((function(t,i){e=function(e,r,a){e?i(e):void 0===r&&void 0===a?t():t([r,a])}}));else if("function"!=typeof e)throw new Error("next() requires a callback argument");return this._ended?this._nextTick(e,new Error("cannot call next() after end()")):this._nexting?this._nextTick(e,new Error("cannot call next() before previous next() has completed")):(this._nexting=!0,this._next((t,...i)=>{this._nexting=!1,e(t,...i)})),t},r.prototype._next=function(e){this._nextTick(e)},r.prototype.seek=function(e){if(this._ended)throw new Error("cannot call seek() after end()");if(this._nexting)throw new Error("cannot call seek() before next() has completed");e=this.db._serializeKey(e),this._seek(e)},r.prototype._seek=function(e){},r.prototype.end=function(e){let t;if(void 0===e)t=new Promise((function(t,i){e=function(e){e?i(e):t()}}));else if("function"!=typeof e)throw new Error("end() requires a callback argument");return this._ended?this._nextTick(e,new Error("end() already called on iterator")):(this._ended=!0,this._end(e)),t},r.prototype._end=function(e){this._nextTick(e)},r.prototype[Symbol.asyncIterator]=async function*(){try{for(var e;void 0!==(e=await this.next());)yield e}finally{this._ended||await this.end()}},r.prototype._nextTick=i(169),e.exports=r},function(e,t,i){"use strict";const r=Object.freeze({});function a(e){if("object"!=typeof e||null===e)throw new TypeError("First argument must be an abstract-leveldown compliant store");this.db=e,this._operations=[],this._written=!1}a.prototype._checkWritten=function(){if(this._written)throw new Error("write() already called on this batch")},a.prototype.put=function(e,t,i){this._checkWritten();var a=this.db._checkKey(e)||this.db._checkValue(t);if(a)throw a;return e=this.db._serializeKey(e),t=this.db._serializeValue(t),this._put(e,t,null!=i?i:r),this},a.prototype._put=function(e,t,i){this._operations.push({...i,type:"put",key:e,value:t})},a.prototype.del=function(e,t){this._checkWritten();var i=this.db._checkKey(e);if(i)throw i;return e=this.db._serializeKey(e),this._del(e,null!=t?t:r),this},a.prototype._del=function(e,t){this._operations.push({...t,type:"del",key:e})},a.prototype.clear=function(){return this._checkWritten(),this._clear(),this},a.prototype._clear=function(){this._operations=[]},a.prototype.write=function(e,t){if(this._checkWritten(),"function"!=typeof(t="function"==typeof e?e:t))throw new Error("write() requires a callback argument");"object"==typeof e&&null!==e||(e={}),this._written=!0,this._write(e,t)},a.prototype._write=function(e,t){this.db._batch(this._operations,e,t)},a.prototype._nextTick=i(169),e.exports=a},function(e,t,i){"use strict";t.getCallback=function(e,t){return"function"==typeof e?e:t},t.getOptions=function(e){return"object"==typeof e&&null!==e?e:{}}},function(e,t,i){"use strict";
|
|
564
|
+
*/const r=i(0),a=i(1),s=i(4),n=i(145);function o(){if(!(this instanceof o))return new o;this.items=[]}o.prototype.push=function(e){return this.items.push(e)},o.prototype.getSize=function(){let e=0;e+=4;for(const t of this.items)e+=t.getSize();return e},o.prototype.toRaw=function(){var e=this.getSize(),t=new s(e);t.writeU32(this.items.length);for(const e of this.items)e.toWriter(t);return t.render()},o.prototype.fromRaw=function(e){var t=new a(e),i=t.readU32();for(let e=0;e<i;e++)this.items.push(n.fromReader(t));return this},o.fromRaw=function(e){return(new o).fromRaw(e)},o.prototype.isEmpty=function(){return 0===this.items.length},o.prototype.commit=function(){var e=this.toRaw();return this.items.length=0,e},o.prototype.apply=function(e,t){var i=this.items.pop();r(i),e.addEntry(t,i)},e.exports=o},function(e,t,i){"use strict";function r(e,t){return e.listeners(t).length}var a,s,n=i(130),o=(e.exports=g,i(398)),c=(g.ReadableState=m,i(16).EventEmitter,i(249)),u=i(39).Buffer,h=global.Uint8Array||function(){},l=((e=Object.create(i(86))).inherits=i(49),i(9)),p=void 0,d=(p=l&&l.debuglog?l.debuglog("stream"):function(){},i(399)),f=(l=i(250),e.inherits(g,c),["error","close","destroy","pause","resume"]);function m(e,t){e=e||{};t=t instanceof(a=a||i(87));var r=(this.objectMode=!!e.objectMode,t&&(this.objectMode=this.objectMode||!!e.readableObjectMode),e.highWaterMark),n=e.readableHighWaterMark,o=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:t&&(n||0===n)?n:o,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new d,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(s=s||i(252).StringDecoder,this.decoder=new s(e.encoding),this.encoding=e.encoding)}function g(e){if(a=a||i(87),!(this instanceof g))return new g(e);this._readableState=new m(e,this),this.readable=!0,e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy)&&(this._destroy=e.destroy),c.call(this)}function v(e,t,i,r,a){var s,n,o,c,l=e._readableState;return null===t?(l.reading=!1,n=e,(c=l).ended||(c.decoder&&(o=c.decoder.end())&&o.length&&(c.buffer.push(o),c.length+=c.objectMode?1:o.length),c.ended=!0,x(n))):(s=a?s:function(e,t){var i;return!function(e){return u.isBuffer(e)||e instanceof h}(t)&&"string"!=typeof t&&void 0!==t&&!e.objectMode&&(i=new TypeError("Invalid non-string/buffer chunk")),i}(l,t))?e.emit("error",s):l.objectMode||t&&0<t.length?("string"==typeof t||l.objectMode||Object.getPrototypeOf(t)===u.prototype||(o=t,t=u.from(o)),r?l.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):y(e,l,t,!0):l.ended?e.emit("error",new Error("stream.push() after EOF")):(l.reading=!1,!l.decoder||i||(t=l.decoder.write(t),l.objectMode)||0!==t.length?y(e,l,t,!1):S(e,l))):r||(l.reading=!1),!(c=l).ended&&(c.needReadable||c.length<c.highWaterMark||0===c.length)}function y(e,t,i,r){t.flowing&&0===t.length&&!t.sync?(e.emit("data",i),e.read(0)):(t.length+=t.objectMode?1:i.length,r?t.buffer.unshift(i):t.buffer.push(i),t.needReadable&&x(e)),S(e,t)}Object.defineProperty(g.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),g.prototype.destroy=l.destroy,g.prototype._undestroy=l.undestroy,g.prototype._destroy=function(e,t){this.push(null),t(e)},g.prototype.push=function(e,t){var i,r=this._readableState;return r.objectMode?i=!0:"string"==typeof e&&((t=t||r.defaultEncoding)!==r.encoding&&(e=u.from(e,t),t=""),i=!0),v(this,e,t,!1,i)},g.prototype.unshift=function(e){return v(this,e,null,!0,!1)},g.prototype.isPaused=function(){return!1===this._readableState.flowing},g.prototype.setEncoding=function(e){return s=s||i(252).StringDecoder,this._readableState.decoder=new s(e),this._readableState.encoding=e,this};var b=8388608;function w(e,t){var i;return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?(t.flowing&&t.length?t.buffer.head.data:t).length:(e>t.highWaterMark&&(t.highWaterMark=(b<=(i=e)?i=b:(i--,i=(i=(i=(i=(i|=i>>>1)|i>>>2)|i>>>4)|i>>>8)|i>>>16,i++),i)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function x(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(p("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?n.nextTick(k,e):k(e))}function k(e){p("emit readable"),e.emit("readable"),A(e)}function S(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(_,e,t))}function _(e,t){for(var i=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length<t.highWaterMark&&(p("maybeReadMore read 0"),e.read(0),i!==t.length);)i=t.length;t.readingMore=!1}function E(e){p("readable nexttick read 0"),e.read(0)}function j(e,t){t.reading||(p("resume read 0"),e.read(0)),t.resumeScheduled=!1,t.awaitDrain=0,e.emit("resume"),A(e),t.flowing&&!t.reading&&e.read(0)}function A(e){var t=e._readableState;for(p("flow",t.flowing);t.flowing&&null!==e.read(););}function R(e,t){var i;return 0===t.length?null:(t.objectMode?i=t.buffer.shift():!e||e>=t.length?(i=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):i=function(e,t,i){var r;return e<t.head.data.length?(r=t.head.data.slice(0,e),t.head.data=t.head.data.slice(e)):r=e===t.head.data.length?t.shift():(i?function(e,t){var i=t.head,r=1,a=i.data;for(e-=a.length;i=i.next;){var s=i.data,n=e>s.length?s.length:e;if(n===s.length?a+=s:a+=s.slice(0,e),0==(e-=n)){n===s.length?(++r,i.next?t.head=i.next:t.head=t.tail=null):(t.head=i).data=s.slice(n);break}++r}return t.length-=r,a}:function(e,t){var i=u.allocUnsafe(e),r=t.head,a=1;for(r.data.copy(i),e-=r.data.length;r=r.next;){var s=r.data,n=e>s.length?s.length:e;if(s.copy(i,i.length-e,0,n),0==(e-=n)){n===s.length?(++a,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r).data=s.slice(n);break}++a}return t.length-=a,i})(e,t),r}(e,t.buffer,t.decoder),i)}function I(e){var t=e._readableState;if(0<t.length)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,n.nextTick(O,t,e))}function O(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function C(e,t){for(var i=0,r=e.length;i<r;i++)if(e[i]===t)return i;return-1}g.prototype.read=function(e){p("read",e),e=parseInt(e,10);var t,i=this._readableState,r=e;return 0!==e&&(i.emittedReadable=!1),0===e&&i.needReadable&&(i.length>=i.highWaterMark||i.ended)?(p("read: emitReadable",i.length,i.ended),(0===i.length&&i.ended?I:x)(this),null):0===(e=w(e,i))&&i.ended?(0===i.length&&I(this),null):(t=i.needReadable,p("need readable",t),(0===i.length||i.length-e<i.highWaterMark)&&p("length less than watermark",t=!0),i.ended||i.reading?p("reading or ended",t=!1):t&&(p("do read"),i.reading=!0,i.sync=!0,0===i.length&&(i.needReadable=!0),this._read(i.highWaterMark),i.sync=!1,i.reading||(e=w(r,i))),null===(t=0<e?R(e,i):null)?(i.needReadable=!0,e=0):i.length-=e,0===i.length&&(i.ended||(i.needReadable=!0),r!==e)&&i.ended&&I(this),null!==t&&this.emit("data",t),t)},g.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},g.prototype.pipe=function(e,t){var i=this,a=this._readableState;switch(a.pipesCount){case 0:a.pipes=e;break;case 1:a.pipes=[a.pipes,e];break;default:a.pipes.push(e)}function s(){p("onend"),e.end()}a.pipesCount+=1,p("pipe count=%d opts=%j",a.pipesCount,t),t=t&&!1===t.end||e===process.stdout||e===process.stderr?v:s,a.endEmitted?n.nextTick(t):i.once("end",t),e.on("unpipe",(function t(r,n){p("onunpipe"),r===i&&n&&!1===n.hasUnpiped&&(n.hasUnpiped=!0,p("cleanup"),e.removeListener("close",m),e.removeListener("finish",g),e.removeListener("drain",u),e.removeListener("error",f),e.removeListener("unpipe",t),i.removeListener("end",s),i.removeListener("end",v),i.removeListener("data",d),h=!0,!a.awaitDrain||e._writableState&&!e._writableState.needDrain||u())})),c=i;var c,u=function(){var e=c._readableState;p("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&r(c,"data")&&(e.flowing=!0,A(c))},h=(e.on("drain",u),!1),l=!1;function d(t){p("ondata"),(l=!1)!==e.write(t)||l||((1===a.pipesCount&&a.pipes===e||1<a.pipesCount&&-1!==C(a.pipes,e))&&!h&&(p("false write response, pause",i._readableState.awaitDrain),i._readableState.awaitDrain++,l=!0),i.pause())}function f(t){p("onerror",t),v(),e.removeListener("error",f),0===r(e,"error")&&e.emit("error",t)}function m(){e.removeListener("finish",g),v()}function g(){p("onfinish"),e.removeListener("close",m),v()}function v(){p("unpipe"),i.unpipe(e)}return i.on("data",d),function(e,t,i){if("function"==typeof e.prependListener)return e.prependListener(t,i);e._events&&e._events[t]?o(e._events[t])?e._events[t].unshift(i):e._events[t]=[i,e._events[t]]:e.on(t,i)}(e,"error",f),e.once("close",m),e.once("finish",g),e.emit("pipe",i),a.flowing||(p("pipe resume"),i.resume()),e},g.prototype.unpipe=function(e){var t=this._readableState,i={hasUnpiped:!1};if(0!==t.pipesCount)if(1===t.pipesCount)e&&e!==t.pipes||(e=e||t.pipes,t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,i));else if(e){var r=C(t.pipes,e);-1!==r&&(t.pipes.splice(r,1),--t.pipesCount,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,i))}else{var a=t.pipes,s=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var n=0;n<s;n++)a[n].emit("unpipe",this,i)}return this},g.prototype.addListener=g.prototype.on=function(e,t){return t=c.prototype.on.call(this,e,t),"data"===e?!1!==this._readableState.flowing&&this.resume():"readable"!==e||(e=this._readableState).endEmitted||e.readableListening||(e.readableListening=e.needReadable=!0,e.emittedReadable=!1,e.reading?e.length&&x(this):n.nextTick(E,this)),t},g.prototype.resume=function(){var e,t=this._readableState;return t.flowing||(p("resume"),t.flowing=!0,e=this,(t=t).resumeScheduled)||(t.resumeScheduled=!0,n.nextTick(j,e,t)),this},g.prototype.pause=function(){return p("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(p("pause"),this._readableState.flowing=!1,this.emit("pause")),this},g.prototype.wrap=function(e){var t,i=this,r=this._readableState,a=!1;for(t in e.on("end",(function(){var e;p("wrapped end"),r.decoder&&!r.ended&&(e=r.decoder.end())&&e.length&&i.push(e),i.push(null)})),e.on("data",(function(t){p("wrapped data"),r.decoder&&(t=r.decoder.write(t)),r.objectMode&&null==t||(r.objectMode||t&&t.length)&&!i.push(t)&&(a=!0,e.pause())})),e)void 0===this[t]&&"function"==typeof e[t]&&(this[t]=function(t){return function(){return e[t].apply(e,arguments)}}(t));for(var s=0;s<f.length;s++)e.on(f[s],this.emit.bind(this,f[s]));return this._read=function(t){p("wrapped _read",t),a&&(a=!1,e.resume())},this},Object.defineProperty(g.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),g._fromList=R},function(e,t,i){e.exports=i(47)},function(e,t,i){"use strict";var r=i(130);function a(e,t){e.emit("error",t)}e.exports={destroy:function(e,t){var i=this,s=this._readableState&&this._readableState.destroyed,n=this._writableState&&this._writableState.destroyed;return s||n?t?t(e):!e||this._writableState&&this._writableState.errorEmitted||r.nextTick(a,this,e):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,(function(e){!t&&e?(r.nextTick(a,i,e),i._writableState&&(i._writableState.errorEmitted=!0)):t&&t(e)}))),this},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}}},function(e,t,i){"use strict";var r=i(130);function a(e){var t=this;this.next=null,this.entry=null,this.finish=function(){var i=t,r=e,a=i.entry;for(i.entry=null;a;){var s=a.callback;r.pendingcb--,s(void 0),a=a.next}r.corkedRequestsFree?r.corkedRequestsFree.next=i:r.corkedRequestsFree=i}}e.exports=m;var s,n,o=!process.browser&&-1<["v0.10","v0.9."].indexOf(process.version.slice(0,5))?setImmediate:r.nextTick,c=((e=(m.WritableState=f,Object.create(i(86)))).inherits=i(49),{deprecate:i(400)}),u=i(249),h=i(39).Buffer,l=global.Uint8Array||function(){},p=i(250);function d(){}function f(e,t){s=s||i(87),e=e||{};var n=t instanceof s,c=(this.objectMode=!!e.objectMode,n&&(this.objectMode=this.objectMode||!!e.writableObjectMode),e.highWaterMark),u=e.writableHighWaterMark,h=this.objectMode?16:16384;this.highWaterMark=c||0===c?c:n&&(u||0===u)?u:h,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,c=(this.destroyed=!1)===e.decodeStrings;this.decodeStrings=!c,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){e=e,s=(a=(i=t)._writableState).sync,n=a.writecb;var i,a,s,n,c,u,h,l,p=a;p.writing=!1,p.writecb=null,p.length-=p.writelen,p.writelen=0,e?(p=i,u=s,h=e,l=n,--(c=a).pendingcb,u?(r.nextTick(l,h),r.nextTick(x,p,c),p._writableState.errorEmitted=!0,p.emit("error",h)):(l(h),p._writableState.errorEmitted=!0,p.emit("error",h),x(p,c))):((e=b(a))||a.corked||a.bufferProcessing||!a.bufferedRequest||y(i,a),s?o(v,i,a,e,n):v(i,a,e,n))},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new a(this)}e.inherits(m,u),f.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t};try{Object.defineProperty(f.prototype,"buffer",{get:c.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}function m(e){if(s=s||i(87),!(n.call(m,this)||this instanceof s))return new m(e);this._writableState=new f(e,this),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final)&&(this._final=e.final),u.call(this)}function g(e,t,i,r,a,s,n){t.writelen=r,t.writecb=n,t.writing=!0,t.sync=!0,i?e._writev(a,t.onwrite):e._write(a,s,t.onwrite),t.sync=!1}function v(e,t,i,r){var a;i||(i=e,0===(a=t).length&&a.needDrain&&(a.needDrain=!1,i.emit("drain"))),t.pendingcb--,r(),x(e,t)}function y(e,t){t.bufferProcessing=!0;var i=t.bufferedRequest;if(e._writev&&i&&i.next){for(var r=t.bufferedRequestCount,s=new Array(r),n=((r=t.corkedRequestsFree).entry=i,0),o=!0;i;)(s[n]=i).isBuf||(o=!1),i=i.next,n+=1;s.allBuffers=o,g(e,t,!0,t.length,s,"",r.finish),t.pendingcb++,t.lastBufferedRequest=null,r.next?(t.corkedRequestsFree=r.next,r.next=null):t.corkedRequestsFree=new a(t),t.bufferedRequestCount=0}else{for(;i;){var c=i.chunk,u=i.encoding,h=i.callback;if(g(e,t,!1,t.objectMode?1:c.length,c,u,h),i=i.next,t.bufferedRequestCount--,t.writing)break}null===i&&(t.lastBufferedRequest=null)}t.bufferedRequest=i,t.bufferProcessing=!1}function b(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function w(e,t){e._final((function(i){t.pendingcb--,i&&e.emit("error",i),t.prefinished=!0,e.emit("prefinish"),x(e,t)}))}function x(e,t){var i,a,s=b(t);return s&&(i=e,(a=t).prefinished||a.finalCalled||("function"==typeof i._final?(a.pendingcb++,a.finalCalled=!0,r.nextTick(w,i,a)):(a.prefinished=!0,i.emit("prefinish"))),0===t.pendingcb)&&(t.finished=!0,e.emit("finish")),s}"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(n=Function.prototype[Symbol.hasInstance],Object.defineProperty(m,Symbol.hasInstance,{value:function(e){return!!n.call(this,e)||this===m&&e&&e._writableState instanceof f}})):n=function(e){return e instanceof this},m.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},m.prototype.write=function(e,t,i){var a,s,n,o,c,u,p,f=this._writableState,m=!1,v=!f.objectMode&&(v=e,h.isBuffer(v)||v instanceof l);return v&&!h.isBuffer(e)&&(c=e,e=h.from(c)),"function"==typeof t&&(i=t,t=null),t=v?"buffer":t||f.defaultEncoding,"function"!=typeof i&&(i=d),f.ended?(c=this,u=i,p=new Error("write after end"),c.emit("error",p),r.nextTick(u,p)):(v||(u=this,p=f,s=i,o=!(n=!0),null===(a=e)?o=new TypeError("May not write null values to stream"):"string"==typeof a||void 0===a||p.objectMode||(o=new TypeError("Invalid non-string/buffer chunk")),o&&(u.emit("error",o),r.nextTick(s,o),n=!1),n))&&(f.pendingcb++,m=function(e,t,i,r,a,s){i||r!==(o=function(e,t,i){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=h.from(t,i)),t}(t,r,a))&&(i=!0,a="buffer",r=o);var n,o=t.objectMode?1:r.length,c=(t.length+=o,t.length<t.highWaterMark);return c||(t.needDrain=!0),t.writing||t.corked?(n=t.lastBufferedRequest,t.lastBufferedRequest={chunk:r,encoding:a,isBuf:i,callback:s,next:null},n?n.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1):g(e,t,!1,o,r,a,s),c}(this,f,v,e,t,i)),m},m.prototype.cork=function(){this._writableState.corked++},m.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||y(this,e))},m.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),-1<["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase()))return this._writableState.defaultEncoding=e,this;throw new TypeError("Unknown encoding: "+e)},Object.defineProperty(m.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),m.prototype._write=function(e,t,i){i(new Error("_write() is not implemented"))},m.prototype._writev=null,m.prototype.end=function(e,t,i){var a=this._writableState;"function"==typeof e?(i=e,t=e=null):"function"==typeof t&&(i=t,t=null),null!=e&&this.write(e,t),a.corked&&(a.corked=1,this.uncork()),a.ending||a.finished||(e=this,t=i,(i=a).ending=!0,x(e,i),t&&(i.finished?r.nextTick(t):e.once("finish",t)),i.ended=!0,e.writable=!1)},Object.defineProperty(m.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),m.prototype.destroy=p.destroy,m.prototype._undestroy=p.undestroy,m.prototype._destroy=function(e,t){this.end(),t(e)}},function(e,t,i){"use strict";var r=i(39).Buffer,a=r.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function s(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"==typeof t||r.isEncoding!==a&&a(e))return t||e;throw new Error("Unknown encoding: "+e)}(e),this.encoding){case"utf16le":this.text=c,this.end=u,t=4;break;case"utf8":this.fillLast=o,t=4;break;case"base64":this.text=h,this.end=l,t=3;break;default:return this.write=p,void(this.end=d)}this.lastNeed=0,this.lastTotal=0,this.lastChar=r.allocUnsafe(t)}function n(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function o(e){var t,i=this.lastTotal-this.lastNeed,r=(t=this,128!=(192&(r=e)[0])?(t.lastNeed=0,"�"):1<t.lastNeed&&1<r.length?128!=(192&r[1])?(t.lastNeed=1,"�"):2<t.lastNeed&&2<r.length&&128!=(192&r[2])?(t.lastNeed=2,"�"):void 0:void 0);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,i,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,i,0,e.length),void(this.lastNeed-=e.length))}function c(e,t){if((e.length-t)%2!=0)return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1);if(t=e.toString("utf16le",t)){var i=t.charCodeAt(t.length-1);if(55296<=i&&i<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],t.slice(0,-1)}return t}function u(e){var t;e=e&&e.length?this.write(e):"";return this.lastNeed?(t=this.lastTotal-this.lastNeed,e+this.lastChar.toString("utf16le",0,t)):e}function h(e,t){var i=(e.length-t)%3;return 0==i?e.toString("base64",t):(this.lastNeed=3-i,this.lastTotal=3,1==i?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-i))}function l(e){return e=e&&e.length?this.write(e):"",this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function p(e){return e.toString(this.encoding)}function d(e){return e&&e.length?this.write(e):""}(t.StringDecoder=s).prototype.write=function(e){if(0===e.length)return"";var t,i;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";i=this.lastNeed,this.lastNeed=0}else i=0;return i<e.length?t?t+this.text(e,i):this.text(e,i):t||""},s.prototype.end=function(e){return e=e&&e.length?this.write(e):"",this.lastNeed?e+"�":e},s.prototype.text=function(e,t){var i=function(e,t,i){var r=t.length-1;if(!(r<i)){var a=n(t[r]);if(0<=a)return 0<a&&(e.lastNeed=a-1),a;if(!(--r<i||-2===a)){if(0<=(a=n(t[r])))return 0<a&&(e.lastNeed=a-2),a;if(!(--r<i||-2===a)&&0<=(a=n(t[r])))return 0<a&&(2===a?a=0:e.lastNeed=a-3),a}}return 0}(this,e,t);return this.lastNeed?(this.lastTotal=i,i=e.length-(i-this.lastNeed),e.copy(this.lastChar,0,i),e.toString("utf8",t,i)):e.toString("utf8",t)},s.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},function(e,t,i){"use strict";e.exports=a;var r=i(87);function a(e){if(!(this instanceof a))return new a(e);r.call(this,e),this._transformState={afterTransform:function(e,t){var i=this._transformState,r=(i.transforming=!1,i.writecb);if(!r)return this.emit("error",new Error("write callback called multiple times"));i.writechunk=null,(i.writecb=null)!=t&&this.push(t),r(e),(i=this._readableState).reading=!1,(i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush)&&(this._flush=e.flush),this.on("prefinish",s)}function s(){var e=this;"function"==typeof this._flush?this._flush((function(t,i){n(e,t,i)})):n(this,null,null)}function n(e,t,i){if(t)return e.emit("error",t);if(null!=i&&e.push(i),e._writableState.length)throw new Error("Calling transform done when ws.length != 0");if(e._transformState.transforming)throw new Error("Calling transform done when still transforming");e.push(null)}(e=Object.create(i(86))).inherits=i(49),e.inherits(a,r),a.prototype.push=function(e,t){return this._transformState.needTransform=!1,r.prototype.push.call(this,e,t)},a.prototype._transform=function(e,t,i){throw new Error("_transform() is not implemented")},a.prototype._write=function(e,t,i){var r=this._transformState;r.writecb=i,r.writechunk=e,r.writeencoding=t,!r.transforming&&(i=this._readableState,r.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)},a.prototype._read=function(e){var t=this._transformState;null!==t.writechunk&&t.writecb&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0},a.prototype._destroy=function(e,t){var i=this;r.prototype._destroy.call(this,e,(function(e){t(e),i.emit("close")}))}},function(e,t,i){"use strict";function r(e){if("object"!=typeof e||null===e)throw new TypeError("First argument must be an abstract-leveldown compliant store");this.db=e,this._ended=!1,this._nexting=!1}r.prototype.next=function(e){let t=this;if(void 0===e)t=new Promise((function(t,i){e=function(e,r,a){e?i(e):void 0===r&&void 0===a?t():t([r,a])}}));else if("function"!=typeof e)throw new Error("next() requires a callback argument");return this._ended?this._nextTick(e,new Error("cannot call next() after end()")):this._nexting?this._nextTick(e,new Error("cannot call next() before previous next() has completed")):(this._nexting=!0,this._next((t,...i)=>{this._nexting=!1,e(t,...i)})),t},r.prototype._next=function(e){this._nextTick(e)},r.prototype.seek=function(e){if(this._ended)throw new Error("cannot call seek() after end()");if(this._nexting)throw new Error("cannot call seek() before next() has completed");e=this.db._serializeKey(e),this._seek(e)},r.prototype._seek=function(e){},r.prototype.end=function(e){let t;if(void 0===e)t=new Promise((function(t,i){e=function(e){e?i(e):t()}}));else if("function"!=typeof e)throw new Error("end() requires a callback argument");return this._ended?this._nextTick(e,new Error("end() already called on iterator")):(this._ended=!0,this._end(e)),t},r.prototype._end=function(e){this._nextTick(e)},r.prototype[Symbol.asyncIterator]=async function*(){try{for(var e;void 0!==(e=await this.next());)yield e}finally{this._ended||await this.end()}},r.prototype._nextTick=i(169),e.exports=r},function(e,t,i){"use strict";const r=Object.freeze({});function a(e){if("object"!=typeof e||null===e)throw new TypeError("First argument must be an abstract-leveldown compliant store");this.db=e,this._operations=[],this._written=!1}a.prototype._checkWritten=function(){if(this._written)throw new Error("write() already called on this batch")},a.prototype.put=function(e,t,i){this._checkWritten();var a=this.db._checkKey(e)||this.db._checkValue(t);if(a)throw a;return e=this.db._serializeKey(e),t=this.db._serializeValue(t),this._put(e,t,null!=i?i:r),this},a.prototype._put=function(e,t,i){this._operations.push({...i,type:"put",key:e,value:t})},a.prototype.del=function(e,t){this._checkWritten();var i=this.db._checkKey(e);if(i)throw i;return e=this.db._serializeKey(e),this._del(e,null!=t?t:r),this},a.prototype._del=function(e,t){this._operations.push({...t,type:"del",key:e})},a.prototype.clear=function(){return this._checkWritten(),this._clear(),this},a.prototype._clear=function(){this._operations=[]},a.prototype.write=function(e,t){if(this._checkWritten(),"function"!=typeof(t="function"==typeof e?e:t))throw new Error("write() requires a callback argument");"object"==typeof e&&null!==e||(e={}),this._written=!0,this._write(e,t)},a.prototype._write=function(e,t){this.db._batch(this._operations,e,t)},a.prototype._nextTick=i(169),e.exports=a},function(e,t,i){"use strict";t.getCallback=function(e,t){return"function"==typeof e?e:t},t.getOptions=function(e){return"object"==typeof e&&null!==e?e:{}}},function(e,t,i){"use strict";
|
|
565
565
|
/*!
|
|
566
566
|
* rbt.js - iterative red black tree for vallnet
|
|
567
567
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -720,7 +720,7 @@ const r=i(5).ContractType;e.exports=function(e){if(!e)return i(188);switch(e.ope
|
|
|
720
720
|
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
|
721
721
|
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
|
722
722
|
* POSSIBILITY OF SUCH DAMAGE.
|
|
723
|
-
*/t.pathMatch=function(e,t){if(t===e)return!0;if(0===e.indexOf(t)){if("/"===t.substr(-1))return!0;if("/"===e.substr(t.length,1))return!0}return!1}},function(e,t,i){e.exports={Verifier:c,Signer:u};var r=i(103),a=i(47),s=(e=i(9),i(10)),n=i(12).Buffer,o=i(57);function c(e,t){if("sha512"!==t.toLowerCase())throw new Error("ED25519 only supports the use of SHA-512 hashes");this.key=e,this.chunks=[],a.Writable.call(this,{})}function u(e,t){if("sha512"!==t.toLowerCase())throw new Error("ED25519 only supports the use of SHA-512 hashes");this.key=e,this.chunks=[],a.Writable.call(this,{})}e.inherits(c,a.Writable),c.prototype._write=function(e,t,i){this.chunks.push(e),i()},c.prototype.update=function(e){"string"==typeof e&&(e=n.from(e,"binary")),this.chunks.push(e)},c.prototype.verify=function(e,t){var i;if(o.isSignature(e,[2,0])){if("ed25519"!==e.type)return!1;i=e.toBuffer("raw")}else if("string"==typeof e)i=n.from(e,"base64");else if(o.isSignature(e,[1,0]))throw new Error("signature was created by too old a version of sshpk and cannot be verified");return s.buffer(i),r.sign.detached.verify(new Uint8Array(n.concat(this.chunks)),new Uint8Array(i),new Uint8Array(this.key.part.A.data))},e.inherits(u,a.Writable),u.prototype._write=function(e,t,i){this.chunks.push(e),i()},u.prototype.update=function(e){"string"==typeof e&&(e=n.from(e,"binary")),this.chunks.push(e)},u.prototype.sign=function(){var e=r.sign.detached(new Uint8Array(n.concat(this.chunks)),new Uint8Array(n.concat([this.key.part.k.data,this.key.part.A.data])));e=n.from(e);return(e=o.parse(e,"ed25519","raw")).hashAlgorithm="sha512",e}},function(e,t,i){e.exports={read:function(e,t){if("string"==typeof e){if(e.trim().match(/^[-]+[ ]*BEGIN/))return s.read(e,t);if(e.match(/^\s*ssh-[a-z]/))return n.read(e,t);if(e.match(/^\s*ecdsa-/))return n.read(e,t);if(e.match(/^putty-user-key-file-2:/i))return u.read(e,t);if(l(e))return c.read(e,t);e=a.from(e,"binary")}else{if(r.buffer(e),function(e){for(var t=0;t<e.length&&(32===e[t]||10===e[t]);)++t;if(45===e[t]){for(;t<e.length&&45===e[t];)++t;for(;t<e.length&&32===e[t];)++t;return!(t+5>e.length||"BEGIN"!==e.slice(t,t+5).toString("ascii"))}}(e))return s.read(e,t);if(function(e){for(var t=0;t<e.length&&(32===e[t]||10===e[t]||9===e[t]);)++t;return t+4<=e.length&&"ssh-"===e.slice(t,t+4).toString("ascii")||t+6<=e.length&&"ecdsa-"===e.slice(t,t+6).toString("ascii")}(e))return n.read(e,t);if(function(e){for(var t=0;t<e.length&&(32===e[t]||10===e[t]||9===e[t]);)++t;return t+22<=e.length&&"putty-user-key-file-2:"===e.slice(t,t+22).toString("ascii").toLowerCase()}(e))return u.read(e,t);if(l(e))return c.read(e,t)}if(e.readUInt32BE(0)<e.length)return o.read(e,t);throw new Error("Failed to auto-detect format of key")},write:function(e,t){throw new Error('"auto" format cannot be used for writing')}};var r=i(10),a=i(12).Buffer,s=(i(25),i(23),i(24),i(65)),n=i(277),o=i(66),c=i(180),u=i(181),h="Private-key-format: v1";function l(e){if(!(e.length<=h.length)){if(e.slice(0,h.length).toString("ascii")===h)return 1;for(var t=(e="string"!=typeof e?e.toString("ascii"):e).split("\n"),i=0;t[i].match(/^\;/);)i++;return t[i].toString("ascii").match(/\. IN KEY /)||!!t[i].toString("ascii").match(/\. IN DNSKEY /)}}},function(e,t,i){"use strict";function r(){this.S=[new Uint32Array([3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946]),new Uint32Array([1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055]),new Uint32Array([3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504]),new Uint32Array([976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462])],this.P=new Uint32Array([608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731])}var a=i(103).lowlevel.crypto_hash,s=0;function n(e,t,i){return(e[0][t[i+3]]+e[1][t[i+2]]^e[2][t[i+1]])+e[3][t[i]]}function o(e,t){for(var i=0,r=0;r<4;r++,s++)i=i<<8|e[s=t<=s?0:s];return i}function c(e,t,i){var a,s=new r,n=new Uint32Array(8),c=new Uint8Array([79,120,121,99,104,114,111,109,97,116,105,99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109,105,116,101]);for(s.expandstate(t,64,e,64),a=0;a<64;a++)s.expand0state(t,64),s.expand0state(e,64);for(a=0;a<8;a++)n[a]=o(c,c.byteLength);for(a=0;a<64;a++)s.enc(n,n.byteLength/8);for(a=0;a<8;a++)i[4*a+3]=n[a]>>>24,i[4*a+2]=n[a]>>>16,i[4*a+1]=n[a]>>>8,i[4*a+0]=n[a]}r.prototype.encipher=function(e,t){void 0===t&&(t=new Uint8Array(e.buffer),0!==e.byteOffset)&&(t=t.subarray(e.byteOffset)),e[0]^=this.P[0];for(var i=1;i<16;i+=2)e[1]^=n(this.S,t,0)^this.P[i],e[0]^=n(this.S,t,4)^this.P[i+1];var r=e[0];e[0]=e[1]^this.P[17],e[1]=r},r.prototype.decipher=function(e){var t=new Uint8Array(e.buffer);0!==e.byteOffset&&(t=t.subarray(e.byteOffset)),e[0]^=this.P[17];for(var i=16;0<i;i-=2)e[1]^=n(this.S,t,0)^this.P[i],e[0]^=n(this.S,t,4)^this.P[i-1];var r=e[0];e[0]=e[1]^this.P[0],e[1]=r},r.prototype.expand0state=function(e,t){var i,r=new Uint32Array(2),a=new Uint8Array(r.buffer),n=0;for(s=0;n<18;n++)this.P[n]^=o(e,t);for(n=s=0;n<18;n+=2)this.encipher(r,a),this.P[n]=r[0],this.P[n+1]=r[1];for(n=0;n<4;n++)for(i=0;i<256;i+=2)this.encipher(r,a),this.S[n][i]=r[0],this.S[n][i+1]=r[1]},r.prototype.expandstate=function(e,t,i,r){var a,n=new Uint32Array(2),c=0;for(s=0;c<18;c++)this.P[c]^=o(i,r);for(s=c=0;c<18;c+=2)n[0]^=o(e,t),n[1]^=o(e,t),this.encipher(n),this.P[c]=n[0],this.P[c+1]=n[1];for(c=0;c<4;c++)for(a=0;a<256;a+=2)n[0]^=o(e,t),n[1]^=o(e,t),this.encipher(n),this.S[c][a]=n[0],this.S[c][a+1]=n[1];s=0},r.prototype.enc=function(e,t){for(var i=0;i<t;i++)this.encipher(e.subarray(2*i))},r.prototype.dec=function(e,t){for(var i=0;i<t;i++)this.decipher(e.subarray(2*i))},e.exports={BLOCKS:8,HASHSIZE:32,hash:c,pbkdf:function(e,t,i,r,s,n,o){var u,h,l,p,d,f,m=new Uint8Array(64),g=new Uint8Array(64),v=new Uint8Array(32),y=new Uint8Array(32),b=new Uint8Array(r+4),w=n;if(o<1)return-1;if(0===t||0===r||0===n||n>v.byteLength*v.byteLength||1<<20<r)return-1;for(p=Math.floor((n+v.byteLength-1)/v.byteLength),l=Math.floor((n+p-1)/p),u=0;u<r;u++)b[u]=i[u];for(a(m,e,t),f=1;0<n;f++){for(b[r+0]=f>>>24,b[r+1]=f>>>16,b[r+2]=f>>>8,b[r+3]=f,a(g,b,r+4),c(m,g,y),u=v.byteLength;u--;)v[u]=y[u];for(u=1;u<o;u++)for(a(g,y,y.byteLength),c(m,g,y),h=0;h<v.byteLength;h++)v[h]^=y[h];for(l=Math.min(l,n),u=0;u<l&&!(w<=(d=u*p+(f-1)));u++)s[d]=v[u];n-=u}return 0}}},function(e,t,i){e.exports={read:function(e,t){"string"!=typeof e&&(r.buffer(e,"buf"),e=e.toString("ascii"));var i=(e=e.trim().replace(/[\\\r]/g,"")).match(o);i=i||e.match(c),r.ok(i,"key must match regex");var n,u=s.algToKeyType(i[1]),h=a.from(i[2],"base64"),l={};if(i[4])try{n=s.read(h)}catch(t){i=e.match(c),r.ok(i,"key must match regex"),h=a.from(i[2],"base64"),n=s.readInternal(l,"public",h)}else n=s.readInternal(l,"public",h);if(r.strictEqual(u,n.type),i[4]&&0<i[4].length)n.comment=i[4];else if(l.consumed){var p=i[2]+(i[3]||""),d=4*Math.ceil(l.consumed/3);for(p=p.slice(0,d-2).replace(/[^a-zA-Z0-9+\/=]/g,"")+p.slice(d-2),0<l.consumed%3&&"="!==p.slice(d-1,d)&&d--;"="===p.slice(d,d+1);)d++;(e=(e=p.slice(d)).replace(/[\r\n]/g," ").replace(/^\s+/,"")).match(/^[a-zA-Z0-9]/)&&(n.comment=e)}return n},write:function(e,t){if(r.object(e),!n.isKey(e))throw new Error("Must be a public key");var i=[],o=s.keyTypeToAlg(e);i.push(o),o=s.write(e);return i.push(o.toString("base64")),e.comment&&i.push(e.comment),a.from(i.join(" "))}};var r=i(10),a=i(12).Buffer,s=i(66),n=(i(25),i(23)),o=(i(24),i(135),/^([a-z0-9-]+)[ \t]+([a-zA-Z0-9+\/]+[=]*)([ \t]+([^ \t][^\n]*[\n]*)?)?$/),c=/^([a-z0-9-]+)[ \t\n]+([a-zA-Z0-9+\/][a-zA-Z0-9+\/ \t\n=]*)([^a-zA-Z0-9+\/ \t\n=].*)?$/},function(e,t,i){e.exports={read:function(e,t){"string"==typeof e&&(e=s.from(e,"binary")),r.buffer(e,"buf");var i=new a.BerReader(e);if(i.readSequence(),1<Math.abs(i.length-i.remain))throw new Error("DER sequence does not contain whole byte stream");var p=i.offset,g=(i.readSequence(),i.offset+i.length),y=g;i.peek()===l(0)&&(i.readSequence(l(0)),k=i.readInt(),r.ok(k<=3,"only x.509 versions up to v3 supported"));var x={signatures:{}},k=x.signatures.x509={extras:{}},S=(x.serial=function(e,t){return r.strictEqual(e.peek(),a.Ber.Integer,"serial is not an Integer"),n.mpNormalize(e.readString(a.Ber.Integer,!0))}(i),i.readSequence(),i.offset+i.length),_=i.readOID();if(void 0===d[_])throw new Error("unknown signature algorithm "+_);if(i._offset=S,x.issuer=o.parseAsn1(i),i.readSequence(),x.validFrom=m(i),x.validUntil=m(i),x.subjects=[o.parseAsn1(i)],i.readSequence(),S=i.offset+i.length,x.subjectKey=h.readPkcs8(void 0,"public",i),i._offset=S,i.peek()===l(1)&&(i.readSequence(l(1)),k.extras.issuerUniqueID=e.slice(i.offset,i.offset+i.length),i._offset+=i.length),i.peek()===l(2)&&(i.readSequence(l(2)),k.extras.subjectUniqueID=e.slice(i.offset,i.offset+i.length),i._offset+=i.length),i.peek()===l(3)){i.readSequence(l(3));var E=i.offset+i.length;for(i.readSequence();i.offset<E;)!function(e,t){t.readSequence();var i,r=t.offset+t.length,s=t.readOID(),n=e.signatures.x509;switch(n.extras.exts||(n.extras.exts=[]),t.peek()===a.Ber.Boolean&&(i=t.readBoolean()),s){case f.basicConstraints:t.readSequence(a.Ber.OctetString),t.readSequence();var c=t.offset+t.length,u=!1;u=(t.peek()===a.Ber.Boolean&&(u=t.readBoolean()),void 0===e.purposes&&(e.purposes=[]),!0===u&&e.purposes.push("ca"),{oid:s,critical:i});t.offset<c&&t.peek()===a.Ber.Integer&&(u.pathLen=t.readInt()),n.extras.exts.push(u);break;case f.extKeyUsage:t.readSequence(a.Ber.OctetString),t.readSequence(),void 0===e.purposes&&(e.purposes=[]);for(var h=t.offset+t.length;t.offset<h;){var l=t.readOID();e.purposes.push(b[l]||l)}-1!==e.purposes.indexOf("serverAuth")&&-1===e.purposes.indexOf("clientAuth")?e.subjects.forEach((function(e){"host"!==e.type&&(e.type="host",e.hostname=e.uid||e.email||e.components[0].value)})):-1!==e.purposes.indexOf("clientAuth")&&-1===e.purposes.indexOf("serverAuth")&&e.subjects.forEach((function(e){"user"!==e.type&&(e.type="user",e.uid=e.hostname||e.email||e.components[0].value)})),n.extras.exts.push({oid:s,critical:i});break;case f.keyUsage:t.readSequence(a.Ber.OctetString),function(e,t){for(var i=8*(e.length-1)-e[0],r={},a=0;a<i;++a){var s=1<<7-a%8,n=0!=(e[n=1+Math.floor(a/8)]&s);s=t[a];n&&"string"==typeof s&&(r[s]=!0)}return Object.keys(r)}(c=t.readString(a.Ber.BitString,!0),w).forEach((function(t){void 0===e.purposes&&(e.purposes=[]),-1===e.purposes.indexOf(t)&&e.purposes.push(t)})),n.extras.exts.push({oid:s,critical:i,bits:c});break;case f.altName:t.readSequence(a.Ber.OctetString),t.readSequence();for(var p=t.offset+t.length;t.offset<p;)switch(t.peek()){case v.OtherName:case v.EDIPartyName:t.readSequence(),t._offset+=t.length;break;case v.OID:t.readOID(v.OID);break;case v.RFC822Name:var d=t.readString(v.RFC822Name);d=o.forEmail(d),e.subjects[0].equals(d)||e.subjects.push(d);break;case v.DirectoryName:t.readSequence(v.DirectoryName),d=o.parseAsn1(t),e.subjects[0].equals(d)||e.subjects.push(d);break;case v.DNSName:var m=t.readString(v.DNSName);d=o.forHost(m),e.subjects[0].equals(d)||e.subjects.push(d);break;default:t.readString(t.peek())}n.extras.exts.push({oid:s,critical:i});break;default:n.extras.exts.push({oid:s,critical:i,data:t.readString(a.Ber.OctetString,!0)})}t._offset=r}(x,i);r.strictEqual(i.offset,E)}if(r.strictEqual(i.offset,g),i.readSequence(),S=i.offset+i.length,_=i.readOID(),void 0===(g=d[_]))throw new Error("unknown signature algorithm "+_);return i._offset=S,0===(_=i.readString(a.Ber.BitString,!0))[0]&&(_=_.slice(1)),S=g.split("-"),k.signature=c.parse(_,S[0],"asn1"),k.signature.hashAlgorithm=S[1],k.algo=g,k.cache=e.slice(p,y),new u(x)},verify:function(e,t){var i=e.signatures.x509,s=(r.object(i,"x509 signature"),i.algo.split("-"));if(s[0]!==t.type)return!1;var n,o=i.cache;return void 0===o&&(_(e,n=new a.BerWriter),o=n.buffer),(e=t.createVerify(s[1])).write(o),e.verify(i.signature)},sign:function(e,t){void 0===e.signatures.x509&&(e.signatures.x509={});var i,r=e.signatures.x509;return r.algo=t.type+"-"+t.defaultHashAlgorithm(),void 0!==d[r.algo]&&(_(e,i=new a.BerWriter),i=i.buffer,r.cache=i,(r=t.createSign()).write(i),e.signatures.x509.signature=r.sign(),!0)},signAsync:function(e,t,i){void 0===e.signatures.x509&&(e.signatures.x509={});var r=e.signatures.x509,s=new a.BerWriter;_(e,s),e=s.buffer;r.cache=e,t(e,(function(e,t){e?i(e):(r.algo=t.type+"-"+t.hashAlgorithm,void 0===d[r.algo]?i(new Error('Invalid signing algorithm "'+r.algo+'"')):(r.signature=t,i()))}))},write:function(e,t){var i=e.signatures.x509,n=(r.object(i,"x509 signature"),new a.BerWriter);return n.startSequence(),i.cache?(n._ensure(i.cache.length),i.cache.copy(n._buf,n._offset),n._offset+=i.cache.length):_(e,n),n.startSequence(),n.writeOID(d[i.algo]),i.algo.match(/^rsa-/)&&n.writeNull(),n.endSequence(),e=i.signature.toBuffer("asn1"),(i=s.alloc(e.length+1))[0]=0,e.copy(i,1),n.writeBuffer(i,a.Ber.BitString),n.endSequence(),n.buffer}};var r=i(10),a=i(58),s=i(12).Buffer,n=(i(30),i(25)),o=(i(23),i(24),i(65),i(106)),c=i(57),u=i(105),h=i(104);function l(e){return a.Ber.Context|a.Ber.Constructor|e}function p(e){return a.Ber.Context|e}var d={"rsa-md5":"1.2.840.113549.1.1.4","rsa-sha1":"1.2.840.113549.1.1.5","rsa-sha256":"1.2.840.113549.1.1.11","rsa-sha384":"1.2.840.113549.1.1.12","rsa-sha512":"1.2.840.113549.1.1.13","dsa-sha1":"1.2.840.10040.4.3","dsa-sha256":"2.16.840.1.101.3.4.3.2","ecdsa-sha1":"1.2.840.10045.4.1","ecdsa-sha256":"1.2.840.10045.4.3.2","ecdsa-sha384":"1.2.840.10045.4.3.3","ecdsa-sha512":"1.2.840.10045.4.3.4","ed25519-sha512":"1.3.101.112"},f=(Object.keys(d).forEach((function(e){d[d[e]]=e})),d["1.3.14.3.2.3"]="rsa-md5",d["1.3.14.3.2.29"]="rsa-sha1",{issuerKeyId:"2.5.29.35",altName:"2.5.29.17",basicConstraints:"2.5.29.19",keyUsage:"2.5.29.15",extKeyUsage:"2.5.29.37"});function m(e){var t,i,s,n,o;if(e.peek()===a.Ber.UTCTime)return t=(t=e.readString(a.Ber.UTCTime)).match(x),r.ok(t,"timestamps must be in UTC"),n=(i=new Date).getUTCFullYear(),o=100*Math.floor(n/100),s=parseInt(t[1],10),s+=n%100<50&&60<=s?o-1:o,i.setUTCFullYear(s,parseInt(t[2],10)-1,parseInt(t[3],10)),i.setUTCHours(parseInt(t[4],10),parseInt(t[5],10)),t[6]&&0<t[6].length&&i.setUTCSeconds(parseInt(t[6],10)),i;if(e.peek()===a.Ber.GeneralizedTime)return n=(n=e.readString(a.Ber.GeneralizedTime)).match(k),r.ok(n),(o=new Date).setUTCFullYear(parseInt(n[1],10),parseInt(n[2],10)-1,parseInt(n[3],10)),o.setUTCHours(parseInt(n[4],10),parseInt(n[5],10)),n[6]&&0<n[6].length&&o.setUTCSeconds(parseInt(n[6],10)),o;throw new Error("Unsupported date format")}function g(e,t){var i,r;2050<=t.getUTCFullYear()||t.getUTCFullYear()<1950?e.writeString((r="",r=(r=(r=(r=(r=(r+=S((i=t).getUTCFullYear(),4))+S(i.getUTCMonth()+1))+S(i.getUTCDate()))+S(i.getUTCHours()))+S(i.getUTCMinutes()))+S(i.getUTCSeconds())+"Z"),a.Ber.GeneralizedTime):e.writeString((i="",i=(i=(i=(i=(i=(i+=S((r=t).getUTCFullYear()%100))+S(r.getUTCMonth()+1))+S(r.getUTCDate()))+S(r.getUTCHours()))+S(r.getUTCMinutes()))+S(r.getUTCSeconds())+"Z"),a.Ber.UTCTime)}var v={OtherName:l(0),RFC822Name:p(1),DNSName:p(2),X400Address:l(3),DirectoryName:l(4),EDIPartyName:l(5),URI:p(6),IPAddress:p(7),OID:p(8)},y={serverAuth:"1.3.6.1.5.5.7.3.1",clientAuth:"1.3.6.1.5.5.7.3.2",codeSigning:"1.3.6.1.5.5.7.3.3",joyentDocker:"1.3.6.1.4.1.38678.1.4.1",joyentCmon:"1.3.6.1.4.1.38678.1.4.2"},b={},w=(Object.keys(y).forEach((function(e){b[y[e]]=e})),["signature","identity","keyEncryption","encryption","keyAgreement","ca","crl"]),x=/^([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/,k=/^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/;function S(e,t){void 0===t&&(t=2);for(var i=""+e;i.length<t;)i="0"+i;return i}function _(e,t){var i=e.signatures.x509,o=(r.object(i,"x509 signature"),t.startSequence(),t.startSequence(l(0)),t.writeInt(2),t.endSequence(),t.writeBuffer(n.mpNormalize(e.serial),a.Ber.Integer),t.startSequence(),t.writeOID(d[i.algo]),i.algo.match(/^rsa-/)&&t.writeNull(),t.endSequence(),e.issuer.toAsn1(t),t.startSequence(),g(t,e.validFrom),g(t,e.validUntil),t.endSequence(),e.subjects[0]),c=e.subjects.slice(1);if(o.toAsn1(t),h.writePkcs8(t,e.subjectKey),i.extras&&i.extras.issuerUniqueID&&t.writeBuffer(i.extras.issuerUniqueID,l(1)),i.extras&&i.extras.subjectUniqueID&&t.writeBuffer(i.extras.subjectUniqueID,l(2)),0<c.length||"host"===o.type||void 0!==e.purposes&&0<e.purposes.length||i.extras&&i.extras.exts){t.startSequence(l(3)),t.startSequence();var u=[];void 0!==e.purposes&&0<e.purposes.length&&(u.push({oid:f.basicConstraints,critical:!0}),u.push({oid:f.keyUsage,critical:!0}),u.push({oid:f.extKeyUsage,critical:!0})),u.push({oid:f.altName}),i.extras&&i.extras.exts&&(u=i.extras.exts);for(var m,b,x=0;x<u.length;++x){if(t.startSequence(),t.writeOID(u[x].oid),void 0!==u[x].critical&&t.writeBoolean(u[x].critical),u[x].oid===f.altName){t.startSequence(a.Ber.OctetString),t.startSequence(),"host"===o.type&&t.writeString(o.hostname,p(2));for(var k=0;k<c.length;++k)"host"===c[k].type?t.writeString(c[k].hostname,v.DNSName):"email"===c[k].type?t.writeString(c[k].email,v.RFC822Name):(t.startSequence(v.DirectoryName),c[k].toAsn1(t),t.endSequence());t.endSequence(),t.endSequence()}else u[x].oid===f.basicConstraints?(t.startSequence(a.Ber.OctetString),t.startSequence(),b=-1!==e.purposes.indexOf("ca"),m=u[x].pathLen,t.writeBoolean(b),void 0!==m&&t.writeInt(m),t.endSequence(),t.endSequence()):u[x].oid===f.extKeyUsage?(t.startSequence(a.Ber.OctetString),t.startSequence(),e.purposes.forEach((function(e){var i;"ca"!==e&&-1===w.indexOf(e)&&(void 0!==y[i=e]&&(i=y[e]),t.writeOID(i))})),t.endSequence(),t.endSequence()):u[x].oid===f.keyUsage?(t.startSequence(a.Ber.OctetString),void 0!==u[x].bits?t.writeBuffer(u[x].bits,a.Ber.BitString):(b=function(e,t){var i=t.length,r=Math.ceil(i/8),a=8*r-i,n=s.alloc(1+r);n[0]=a;for(var o=0;o<i;++o){var c=1+Math.floor(o/8),u=1<<7-o%8,h=t[o];void 0!==h&&-1!==e.indexOf(h)&&(n[c]|=u)}return n}(e.purposes,w),t.writeBuffer(b,a.Ber.BitString)),t.endSequence()):t.writeBuffer(u[x].data,a.Ber.OctetString);t.endSequence()}t.endSequence(),t.endSequence()}t.endSequence()}},function(e,t,i){var r=i(0),a=i(9);function s(e){var t,i,n,c,u,h,l,p,d,f=["([^%]*)","%","(['\\-+ #0]*?)","([1-9]\\d*)?","(\\.([1-9]\\d*))?","[lhjztL]*?","([diouxXfFeEgGaAcCsSp%jr])"].join(""),m=new RegExp(f),g=Array.prototype.slice.call(arguments,1),v="",y=1;for(r.equal("string",typeof e);null!==(d=m.exec(e));)if(v+=d[1],e=e.substring(d[0].length),t=d[2]||"",i=d[3]||0,n=d[4]||"",l=u=!1,h=" ","%"==(c=d[6]))v+="%";else{if(0===g.length)throw new Error("too few args to sprintf");if(p=g.shift(),y++,t.match(/[\' #]/))throw new Error("unsupported flags: "+t);if(0<n.length)throw new Error("non-zero precision not supported");switch(t.match(/-/)&&(u=!0),t.match(/0/)&&(h="0"),t.match(/\+/)&&(l=!0),c){case"s":if(null==p)throw new Error("argument "+y+": attempted to print undefined or null as a string");v+=o(h,i,u,p.toString());break;case"d":p=Math.floor(p);case"f":v+=(l=l&&0<p?"+":"")+o(h,i,u,p.toString());break;case"x":v+=o(h,i,u,p.toString(16));break;case"j":0===i&&(i=10),v+=a.inspect(p,!1,i);break;case"r":v+=function e(t){var i;if(!(t instanceof Error))throw new Error(s("invalid type for %%r: %j",t));return i="EXCEPTION: "+t.constructor.name+": "+t.stack,t.cause&&"function"==typeof t.cause&&(t=t.cause())&&(i+="\nCaused by: "+e(t)),i}(p);break;default:throw new Error("unsupported conversion: "+c)}}return v+e}function n(e){var t=Array.prototype.slice.call(arguments,1);return e.write(s.apply(this,t))}function o(e,t,i,r){for(var a=r;a.length<t;)i?a+=e:a=e+a;return a}t.sprintf=s,t.printf=function(){var e=Array.prototype.slice.call(arguments);e.unshift(process.stdout),n.apply(null,e)},t.fprintf=n},function(e,t,i){var r=i(9),a=i(47).Stream,s=i(481);function n(){this.writable=!1,this.readable=!0,this.dataSize=0,this.maxDataSize=2097152,this.pauseStreams=!0,this._released=!1,this._streams=[],this._currentStream=null,this._insideLoop=!1,this._pendingNext=!1}e.exports=n,r.inherits(n,a),n.create=function(e){var t,i=new this;for(t in e=e||{})i[t]=e[t];return i},n.isStreamLike=function(e){return"function"!=typeof e&&"string"!=typeof e&&"boolean"!=typeof e&&"number"!=typeof e&&!Buffer.isBuffer(e)},n.prototype.append=function(e){var t;return n.isStreamLike(e)&&(e instanceof s||(t=s.create(e,{maxDataSize:1/0,pauseStream:this.pauseStreams}),e.on("data",this._checkDataSize.bind(this)),e=t),this._handleErrors(e),this.pauseStreams)&&e.pause(),this._streams.push(e),this},n.prototype.pipe=function(e,t){return a.prototype.pipe.call(this,e,t),this.resume(),e},n.prototype._getNext=function(){if(this._currentStream=null,this._insideLoop)this._pendingNext=!0;else{this._insideLoop=!0;try{for(;this._pendingNext=!1,this._realGetNext(),this._pendingNext;);}finally{this._insideLoop=!1}}},n.prototype._realGetNext=function(){var e=this._streams.shift();void 0===e?this.end():"function"!=typeof e?this._pipeNext(e):e(function(e){n.isStreamLike(e)&&(e.on("data",this._checkDataSize.bind(this)),this._handleErrors(e)),this._pipeNext(e)}.bind(this))},n.prototype._pipeNext=function(e){this._currentStream=e,n.isStreamLike(e)?(e.on("end",this._getNext.bind(this)),e.pipe(this,{end:!1})):(this.write(e),this._getNext())},n.prototype._handleErrors=function(e){var t=this;e.on("error",(function(e){t._emitError(e)}))},n.prototype.write=function(e){this.emit("data",e)},n.prototype.pause=function(){this.pauseStreams&&(this.pauseStreams&&this._currentStream&&"function"==typeof this._currentStream.pause&&this._currentStream.pause(),this.emit("pause"))},n.prototype.resume=function(){this._released||(this._released=!0,this.writable=!0,this._getNext()),this.pauseStreams&&this._currentStream&&"function"==typeof this._currentStream.resume&&this._currentStream.resume(),this.emit("resume")},n.prototype.end=function(){this._reset(),this.emit("end")},n.prototype.destroy=function(){this._reset(),this.emit("close")},n.prototype._reset=function(){this.writable=!1,this._streams=[],this._currentStream=null},n.prototype._checkDataSize=function(){var e;this._updateDataSize(),this.dataSize<=this.maxDataSize||(e="DelayedStream#maxDataSize of "+this.maxDataSize+" bytes exceeded.",this._emitError(new Error(e)))},n.prototype._updateDataSize=function(){this.dataSize=0;var e=this;this._streams.forEach((function(t){t.dataSize&&(e.dataSize+=t.dataSize)})),this._currentStream&&this._currentStream.dataSize&&(this.dataSize+=this._currentStream.dataSize)},n.prototype._emitError=function(e){this._reset(),this.emit("error",e)}},function(e,t,i){var r=i(282),a=i(283);e.exports=function(e,t,i,s){var n=i.keyedList?i.keyedList[i.index]:i.index;i.jobs[n]=function(e,t,i,a){return e=2==e.length?e(i,r(a)):e(i,t,r(a))}(t,n,e[n],(function(e,t){n in i.jobs&&(delete i.jobs[n],e?a(i):i.results[n]=t,s(e,i.results))}))}},function(e,t,i){var r=i(484);e.exports=function(e){var t=!1;return r((function(){t=!0})),function(i,a){t?e(i,a):r((function(){e(i,a)}))}}},function(e,t){e.exports=function(e){Object.keys(e.jobs).forEach(function(e){"function"==typeof this.jobs[e]&&this.jobs[e]()}.bind(e)),e.jobs={}}},function(e,t){e.exports=function(e,t){var i=!Array.isArray(e),r={index:0,keyedList:i||t?Object.keys(e):null,jobs:{},results:i?{}:[],size:(i?Object.keys(e):e).length};return t&&r.keyedList.sort(i?t:function(i,r){return t(e[i],e[r])}),r}},function(e,t,i){var r=i(283),a=i(282);e.exports=function(e){Object.keys(this.jobs).length&&(this.index=this.size,r(this),a(e)(null,this.results))}},function(e,t,i){var r=i(281),a=i(284),s=i(285);function n(e,t){return e<t?-1:t<e?1:0}e.exports=function(e,t,i,n){var o=a(e,i);return r(e,t,o,(function i(a,s){a?n(a,s):(o.index++,o.index<(o.keyedList||e).length?r(e,t,o,i):n(null,o.results))})),s.bind(o,n)},e.exports.ascending=n,e.exports.descending=function(e,t){return-1*n(e,t)}},function(e,t,i){var r=i(47);function a(e){return e instanceof r.Stream}function s(e){return a(e)&&"function"==typeof e._read&&"object"==typeof e._readableState}function n(e){return a(e)&&"function"==typeof e._write&&"object"==typeof e._writableState}e.exports=a,e.exports.isReadable=s,e.exports.isWritable=n,e.exports.isDuplex=function(e){return s(e)&&n(e)}},function(e,t,i){"use strict";var r=i(490),a=i(491);i=i(290);e.exports={formats:i,parse:a,stringify:r}},function(e,t,i){"use strict";function r(e,t){for(var i=t&&t.plainObjects?Object.create(null):{},r=0;r<e.length;++r)void 0!==e[r]&&(i[r]=e[r]);return i}var a=Object.prototype.hasOwnProperty,s=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}();e.exports={arrayToObject:r,assign:function(e,t){return Object.keys(t).reduce((function(e,i){return e[i]=t[i],e}),e)},compact:function(e){for(var t=[{obj:{o:e},prop:"o"}],i=[],r=0;r<t.length;++r)for(var a=t[r],s=a.obj[a.prop],n=Object.keys(s),o=0;o<n.length;++o){var c=n[o],u=s[c];"object"==typeof u&&null!==u&&-1===i.indexOf(u)&&(t.push({obj:s,prop:c}),i.push(u))}for(var h=t;h.length;){var l=h.pop(),p=l.obj[l.prop];if(Array.isArray(p)){for(var d=[],f=0;f<p.length;++f)void 0!==p[f]&&d.push(p[f]);l.obj[l.prop]=d}}return p},decode:function(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(t){return e}},encode:function(e){if(0===e.length)return e;for(var t="string"==typeof e?e:String(e),i="",r=0;r<t.length;++r){var a=t.charCodeAt(r);45===a||46===a||95===a||126===a||48<=a&&a<=57||65<=a&&a<=90||97<=a&&a<=122?i+=t.charAt(r):a<128?i+=s[a]:a<2048?i+=s[192|a>>6]+s[128|63&a]:a<55296||57344<=a?i+=s[224|a>>12]+s[128|a>>6&63]+s[128|63&a]:(r+=1,a=65536+((1023&a)<<10|1023&t.charCodeAt(r)),i+=s[240|a>>18]+s[128|a>>12&63]+s[128|a>>6&63]+s[128|63&a])}return i},isBuffer:function(e){return null!=e&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))},isRegExp:function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},merge:function e(t,i,s){if(!i)return t;if("object"!=typeof i){if(Array.isArray(t))t.push(i);else{if(!t||"object"!=typeof t)return[t,i];(s&&(s.plainObjects||s.allowPrototypes)||!a.call(Object.prototype,i))&&(t[i]=!0)}return t}var n;return t&&"object"==typeof t?(n=t,Array.isArray(t)&&!Array.isArray(i)&&(n=r(t,s)),Array.isArray(t)&&Array.isArray(i)?(i.forEach((function(i,r){var n;a.call(t,r)?(n=t[r])&&"object"==typeof n&&i&&"object"==typeof i?t[r]=e(n,i,s):t.push(i):t[r]=i})),t):Object.keys(i).reduce((function(t,r){var n=i[r];return a.call(t,r)?t[r]=e(t[r],n,s):t[r]=n,t}),n)):[t].concat(i)}}},function(e,t,i){"use strict";var r=String.prototype.replace,a=/%20/g;e.exports={default:"RFC3986",formatters:{RFC1738:function(e){return r.call(e,a,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:"RFC3986"}},function(e,t,i){"use strict";var r=i(92);e.exports=function(e){r.copy(e,this)}},function(e,t,i){"use strict";e.exports=function(e,t){var i,r="boolean"==typeof(t="function"==typeof(t=t||{})?{cmp:t}:t).cycles&&t.cycles,a=t.cmp&&(i=t.cmp,function(e){return function(t,r){return t={key:t,value:e[t]},r={key:r,value:e[r]},i(t,r)}}),s=[];return function e(t){if(void 0!==(t=t&&t.toJSON&&"function"==typeof t.toJSON?t.toJSON():t)){if("number"==typeof t)return isFinite(t)?""+t:"null";if("object"!=typeof t)return JSON.stringify(t);if(Array.isArray(t)){for(o="[",c=0;c<t.length;c++)c&&(o+=","),o+=e(t[c])||"null";return o+"]"}if(null===t)return"null";if(-1!==s.indexOf(t)){if(r)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}for(var i=s.push(t)-1,n=Object.keys(t).sort(a&&a(t)),o="",c=0;c<n.length;c++){var u=n[c],h=e(t[u]);h&&(o&&(o+=","),o+=JSON.stringify(u)+":"+h)}return s.splice(i,1),"{"+o+"}"}}(e)}},function(e,t,i){"use strict";e.exports=function(e,t,i){var r="",a=!0===e.schema.$async,s=e.util.schemaHasRulesExcept(e.schema,e.RULES.all,"$ref"),n=e.self._getId(e.schema);if(e.opts.strictKeywords&&(I=e.util.schemaUnknownRules(e.schema,e.RULES.keywords))){if(I="unknown keyword: "+I,"log"!==e.opts.strictKeywords)throw new Error(I);e.logger.warn(I)}if(e.isTop&&(r+=" var validate = ",a&&(e.async=!0,r+="async "),r+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",n)&&(e.opts.sourceCode||e.opts.processCode)&&(r+=" /*# sourceURL="+n+" */ "),"boolean"==typeof e.schema||!s&&!e.schema.$ref)c=e.level,u=e.dataLevel,T=e.schema[t="false schema"],w=e.schemaPath+e.util.getProperty(t),x=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,h="data"+(u||""),p="valid"+c,!1===e.schema?(e.isTop?d=!0:r+=" var "+p+" = false; ",(U=U||[]).push(r),r="",!1!==e.createErrors?(r+=" { keyword: 'false schema' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(x)+" , params: {} ",!1!==e.opts.messages&&(r+=" , message: 'boolean schema is false' "),e.opts.verbose&&(r+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ",R=r,r=U.pop(),!e.compositeRule&&d?e.async?r+=" throw new ValidationError(["+R+"]); ":r+=" validate.errors = ["+R+"]; return false; ":r+=" var err = "+R+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "):e.isTop?r+=a?" return data; ":" validate.errors = null; return true; ":r+=" var "+p+" = true; ",e.isTop&&(r+=" }; return validate; ");else{if(e.isTop){var o=e.isTop,c=e.level=0,u=e.dataLevel=0,h="data";if(e.rootId=e.resolve.fullPath(e.self._getId(e.root.schema)),e.baseId=e.baseId||e.rootId,delete e.isTop,e.dataPathArr=[""],void 0!==e.schema.default&&e.opts.useDefaults&&e.opts.strictDefaults){var l="default is ignored in the schema root";if("log"!==e.opts.strictDefaults)throw new Error(l);e.logger.warn(l)}r=(r+=" var vErrors = null; ")+" var errors = 0; if (rootData === undefined) rootData = data; "}else{if(c=e.level,h="data"+((u=e.dataLevel)||""),n&&(e.baseId=e.resolve.url(e.baseId,n)),a&&!e.async)throw new Error("async schema in sync schema");r+=" var errs_"+c+" = errors;"}var p="valid"+c,d=!e.opts.allErrors,f="",m="",g=e.schema.type,v=Array.isArray(g);if(g&&e.opts.nullable&&!0===e.schema.nullable&&(v?-1==g.indexOf("null")&&(g=g.concat("null")):"null"!=g&&(g=[g,"null"],v=!0)),v&&1==g.length&&(g=g[0],v=!1),e.schema.$ref&&s){if("fail"==e.opts.extendRefs)throw new Error('$ref: validation keywords used in schema at path "'+e.errSchemaPath+'" (see option extendRefs)');!0!==e.opts.extendRefs&&(s=!1,e.logger.warn('$ref: keywords ignored in schema at path "'+e.errSchemaPath+'"'))}if(e.schema.$comment&&e.opts.$comment&&(r+=" "+e.RULES.all.$comment.code(e,"$comment")),g){e.opts.coerceTypes&&(y=e.util.coerceToTypes(e.opts.coerceTypes,g));var y,b=e.RULES.types[g];if(y||v||!0===b||b&&!$(b)){var w=e.schemaPath+".type",x=e.errSchemaPath+"/type";w=e.schemaPath+".type",x=e.errSchemaPath+"/type";if(r+=" if ("+e.util[v?"checkDataTypes":"checkDataType"](g,h,e.opts.strictNumbers,!0)+") { ",y){var k="dataType"+c,S="coerced"+c,_=(r+=" var "+k+" = typeof "+h+"; var "+S+" = undefined; ","array"==e.opts.coerceTypes&&(r+=" if ("+k+" == 'object' && Array.isArray("+h+") && "+h+".length == 1) { "+h+" = "+h+"[0]; "+k+" = typeof "+h+"; if ("+e.util.checkDataType(e.schema.type,h,e.opts.strictNumbers)+") "+S+" = "+h+"; } "),r+=" if ("+S+" !== undefined) ; ",y);if(_)for(var E,j=-1,A=_.length-1;j<A;)"string"==(E=_[j+=1])?r+=" else if ("+k+" == 'number' || "+k+" == 'boolean') "+S+" = '' + "+h+"; else if ("+h+" === null) "+S+" = ''; ":"number"==E||"integer"==E?(r+=" else if ("+k+" == 'boolean' || "+h+" === null || ("+k+" == 'string' && "+h+" && "+h+" == +"+h+" ","integer"==E&&(r+=" && !("+h+" % 1)"),r+=")) "+S+" = +"+h+"; "):"boolean"==E?r+=" else if ("+h+" === 'false' || "+h+" === 0 || "+h+" === null) "+S+" = false; else if ("+h+" === 'true' || "+h+" === 1) "+S+" = true; ":"null"==E?r+=" else if ("+h+" === '' || "+h+" === 0 || "+h+" === false) "+S+" = null; ":"array"==e.opts.coerceTypes&&"array"==E&&(r+=" else if ("+k+" == 'string' || "+k+" == 'number' || "+k+" == 'boolean' || "+h+" == null) "+S+" = ["+h+"]; ");(U=U||[]).push(r+=" else { "),r="",!1!==e.createErrors?(r=(r+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(x)+" , params: { type: '")+(v?""+g.join(","):""+g)+"' } ",!1!==e.opts.messages&&(r=(r+=" , message: 'should be ")+(v?""+g.join(","):""+g)+"' "),e.opts.verbose&&(r+=" , schema: validate.schema"+w+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ";var R=r,I=(r=U.pop(),!e.compositeRule&&d?e.async?r+=" throw new ValidationError(["+R+"]); ":r+=" validate.errors = ["+R+"]; return false; ":r+=" var err = "+R+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u?"data"+(u-1||""):"parentData");r=r+" } if ("+S+" !== undefined) { "+h+" = "+S+"; ",u||(r+="if ("+I+" !== undefined)"),r+=" "+I+"["+(u?e.dataPathArr[u]:"parentDataProperty")+"] = "+S+"; } "}else(U=U||[]).push(r),r="",!1!==e.createErrors?(r=(r+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(x)+" , params: { type: '")+(v?""+g.join(","):""+g)+"' } ",!1!==e.opts.messages&&(r=(r+=" , message: 'should be ")+(v?""+g.join(","):""+g)+"' "),e.opts.verbose&&(r+=" , schema: validate.schema"+w+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ",R=r,r=U.pop(),!e.compositeRule&&d?e.async?r+=" throw new ValidationError(["+R+"]); ":r+=" validate.errors = ["+R+"]; return false; ":r+=" var err = "+R+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";r+=" } "}}if(e.schema.$ref&&!s)r+=" "+e.RULES.all.$ref.code(e,"$ref")+" ",d&&(r=(r+=" } if (errors === ")+(o?"0":"errs_"+c)+") { ",m+="}");else{var O=e.RULES;if(O)for(var C=-1,P=O.length-1;C<P;)if($(b=O[C+=1])){if(b.type&&(r+=" if ("+e.util.checkDataType(b.type,h,e.opts.strictNumbers)+") { "),e.opts.useDefaults)if("object"==b.type&&e.schema.properties){var T=e.schema.properties,B=Object.keys(T);if(B)for(var N,z=-1,F=B.length-1;z<F;)if(void 0!==(D=T[N=B[z+=1]]).default){var L=h+e.util.getProperty(N);if(e.compositeRule){if(e.opts.strictDefaults){if(l="default is ignored for: "+L,"log"!==e.opts.strictDefaults)throw new Error(l);e.logger.warn(l)}}else r+=" if ("+L+" === undefined ","empty"==e.opts.useDefaults&&(r+=" || "+L+" === null || "+L+" === '' "),r+=" ) "+L+" = ","shared"==e.opts.useDefaults?r+=" "+e.useDefault(D.default)+" ":r+=" "+JSON.stringify(D.default)+" ",r+="; "}}else if("array"==b.type&&Array.isArray(e.schema.items)){var M=e.schema.items;if(M){j=-1;for(var D,H=M.length-1;j<H;)if(void 0!==(D=M[j+=1]).default)if(L=h+"["+j+"]",e.compositeRule){if(e.opts.strictDefaults){if(l="default is ignored for: "+L,"log"!==e.opts.strictDefaults)throw new Error(l);e.logger.warn(l)}}else r+=" if ("+L+" === undefined ","empty"==e.opts.useDefaults&&(r+=" || "+L+" === null || "+L+" === '' "),r+=" ) "+L+" = ","shared"==e.opts.useDefaults?r+=" "+e.useDefault(D.default)+" ":r+=" "+JSON.stringify(D.default)+" ",r+="; "}}var U,q=b.rules;if(q)for(var V,K=-1,W=q.length-1;K<W;)Y(V=q[K+=1])&&(V=V.code(e,V.keyword,b.type))&&(r+=" "+V+" ",d)&&(f+="}");d&&(r+=" "+f+" ",f=""),b.type&&(r+=" } ",g)&&g===b.type&&!y&&(r+=" else { ",w=e.schemaPath+".type",x=e.errSchemaPath+"/type",(U=U||[]).push(r),r="",!1!==e.createErrors?(r=(r+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(x)+" , params: { type: '")+(v?""+g.join(","):""+g)+"' } ",!1!==e.opts.messages&&(r=(r+=" , message: 'should be ")+(v?""+g.join(","):""+g)+"' "),e.opts.verbose&&(r+=" , schema: validate.schema"+w+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ",R=r,r=U.pop(),!e.compositeRule&&d?e.async?r+=" throw new ValidationError(["+R+"]); ":r+=" validate.errors = ["+R+"]; return false; ":r+=" var err = "+R+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",r+=" } "),d&&(r=(r+=" if (errors === ")+(o?"0":"errs_"+c)+") { ",m+="}")}}d&&(r+=" "+m+" "),o?r=r+(a?" if (errors === 0) return data; else throw new ValidationError(vErrors); ":" validate.errors = vErrors; return errors === 0; ")+" }; return validate;":r+=" var "+p+" = errors === errs_"+c+";"}return r;function $(e){for(var t=e.rules,i=0;i<t.length;i++)if(Y(t[i]))return 1}function Y(t){return void 0!==e.schema[t.keyword]||t.implements&&function(t){for(var i=t.implements,r=0;r<i.length;r++)if(void 0!==e.schema[i[r]])return 1}(t)}}},function(e,t,i){"use strict";e.exports=function(e,t,i){var r,a,s,n,o,c=" ",u=e.level,h=e.dataLevel,l=e.schema[t],p=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,m="data"+(h||""),g=e.opts.$data&&l&&l.$data,v=g?(c+=" var schema"+u+" = "+e.util.getData(l.$data,h,e.dataPathArr)+"; ","schema"+u):l,y="maximum"==t,b=y?"exclusiveMaximum":"exclusiveMinimum",w=e.schema[b],x=e.opts.$data&&w&&w.$data,k=y?"<":">",S=y?">":"<",_=void 0;if(!g&&"number"!=typeof l&&void 0!==l)throw new Error(t+" must be number");if(!x&&void 0!==w&&"number"!=typeof w&&"boolean"!=typeof w)throw new Error(b+" must be number or boolean");x?(h=e.util.getData(w.$data,h,e.dataPathArr),s="exclIsNumber"+u,n="' + "+(o="op"+u)+" + '",_=b,(E=E||[]).push(c=c+" var schemaExcl"+u+" = "+h+"; var "+(r="exclusive"+u)+"; var "+(a="exclType"+u)+" = typeof "+(h="schemaExcl"+u)+"; if ("+a+" != 'boolean' && "+a+" != 'undefined' && "+a+" != 'number') { "),c="",!1!==e.createErrors?(c+=" { keyword: '"+(_||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: {} ",!1!==e.opts.messages&&(c+=" , message: '"+b+" should be boolean' "),e.opts.verbose&&(c+=" , schema: validate.schema"+p+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),c+=" } "):c+=" {} ",j=c,c=E.pop(),!e.compositeRule&&f?e.async?c+=" throw new ValidationError(["+j+"]); ":c+=" validate.errors = ["+j+"]; return false; ":c+=" var err = "+j+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c+=" } else if ( ",g&&(c+=" ("+v+" !== undefined && typeof "+v+" != 'number') || "),c+=" "+a+" == 'number' ? ( ("+r+" = "+v+" === undefined || "+h+" "+k+"= "+v+") ? "+m+" "+S+"= "+h+" : "+m+" "+S+" "+v+" ) : ( ("+r+" = "+h+" === true) ? "+m+" "+S+"= "+v+" : "+m+" "+S+" "+v+" ) || "+m+" !== "+m+") { var op"+u+" = "+r+" ? '"+k+"' : '"+k+"='; ",void 0===l&&(d=e.errSchemaPath+"/"+(_=b),v=h,g=x)):(n=k,(s="number"==typeof w)&&g?(o="'"+n+"'",c+=" if ( ",g&&(c+=" ("+v+" !== undefined && typeof "+v+" != 'number') || "),c+=" ( "+v+" === undefined || "+w+" "+k+"= "+v+" ? "+m+" "+S+"= "+w+" : "+m+" "+S+" "+v+" ) || "+m+" !== "+m+") { "):(s&&void 0===l?(r=!0,d=e.errSchemaPath+"/"+(_=b),v=w,S+="="):(s&&(v=Math[y?"min":"max"](w,l)),w===(!s||v)?(r=!0,d=e.errSchemaPath+"/"+(_=b),S+="="):(r=!1,n+="=")),o="'"+n+"'",c+=" if ( ",g&&(c+=" ("+v+" !== undefined && typeof "+v+" != 'number') || "),c+=" "+m+" "+S+" "+v+" || "+m+" !== "+m+") { ")),_=_||t,(E=E||[]).push(c),c="",!1!==e.createErrors?(c+=" { keyword: '"+(_||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { comparison: "+o+", limit: "+v+", exclusive: "+r+" } ",!1!==e.opts.messages&&(c=c+" , message: 'should be "+n+" "+(g?"' + "+v:v+"'")),e.opts.verbose&&(c=(c+=" , schema: ")+(g?"validate.schema"+p:""+l)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),c+=" } "):c+=" {} ";var E,j=c;return c=E.pop(),!e.compositeRule&&f?e.async?c+=" throw new ValidationError(["+j+"]); ":c+=" validate.errors = ["+j+"]; return false; ":c+=" var err = "+j+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c+=" } ",f&&(c+=" else { "),c}},function(e,t,i){"use strict";e.exports=function(e,t,i){var r,a=" ",s=e.level,n=e.dataLevel,o=e.schema[t],c=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,h=!e.opts.allErrors,l="data"+(n||""),p=e.opts.$data&&o&&o.$data;n=p?(a+=" var schema"+s+" = "+e.util.getData(o.$data,n,e.dataPathArr)+"; ","schema"+s):o;if(p||"number"==typeof o)return a+="if ( ",p&&(a+=" ("+n+" !== undefined && typeof "+n+" != 'number') || "),(s=[]).push(a+=" "+l+".length "+("maxItems"==(r=t)?">":"<")+" "+n+") { "),a="",!1!==e.createErrors?(a+=" { keyword: '"+(r||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+n+" } ",!1!==e.opts.messages&&(a=(a=(a+=" , message: 'should NOT have ")+("maxItems"==t?"more":"fewer")+" than ")+(p?"' + "+n+" + '":""+o)+" items' "),e.opts.verbose&&(a=(a+=" , schema: ")+(p?"validate.schema"+c:""+o)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),a+=" } "):a+=" {} ",r=a,a=s.pop(),!e.compositeRule&&h?e.async?a+=" throw new ValidationError(["+r+"]); ":a+=" validate.errors = ["+r+"]; return false; ":a+=" var err = "+r+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+="} ",h&&(a+=" else { "),a;throw new Error(t+" must be number")}},function(e,t,i){"use strict";e.exports=function(e,t,i){var r,a=" ",s=e.level,n=e.dataLevel,o=e.schema[t],c=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,h=!e.opts.allErrors,l="data"+(n||""),p=e.opts.$data&&o&&o.$data;n=p?(a+=" var schema"+s+" = "+e.util.getData(o.$data,n,e.dataPathArr)+"; ","schema"+s):o;if(p||"number"==typeof o)return a+="if ( ",p&&(a+=" ("+n+" !== undefined && typeof "+n+" != 'number') || "),!1===e.opts.unicode?a+=" "+l+".length ":a+=" ucs2length("+l+") ",(s=[]).push(a+=" "+("maxLength"==(r=t)?">":"<")+" "+n+") { "),a="",!1!==e.createErrors?(a+=" { keyword: '"+(r||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+n+" } ",!1!==e.opts.messages&&(a=(a=(a+=" , message: 'should NOT be ")+("maxLength"==t?"longer":"shorter")+" than ")+(p?"' + "+n+" + '":""+o)+" characters' "),e.opts.verbose&&(a=(a+=" , schema: ")+(p?"validate.schema"+c:""+o)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),a+=" } "):a+=" {} ",r=a,a=s.pop(),!e.compositeRule&&h?e.async?a+=" throw new ValidationError(["+r+"]); ":a+=" validate.errors = ["+r+"]; return false; ":a+=" var err = "+r+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+="} ",h&&(a+=" else { "),a;throw new Error(t+" must be number")}},function(e,t,i){"use strict";e.exports=function(e,t,i){var r,a=" ",s=e.level,n=e.dataLevel,o=e.schema[t],c=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,h=!e.opts.allErrors,l="data"+(n||""),p=e.opts.$data&&o&&o.$data;n=p?(a+=" var schema"+s+" = "+e.util.getData(o.$data,n,e.dataPathArr)+"; ","schema"+s):o;if(p||"number"==typeof o)return a+="if ( ",p&&(a+=" ("+n+" !== undefined && typeof "+n+" != 'number') || "),(s=[]).push(a+=" Object.keys("+l+").length "+("maxProperties"==(r=t)?">":"<")+" "+n+") { "),a="",!1!==e.createErrors?(a+=" { keyword: '"+(r||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+n+" } ",!1!==e.opts.messages&&(a=(a=(a+=" , message: 'should NOT have ")+("maxProperties"==t?"more":"fewer")+" than ")+(p?"' + "+n+" + '":""+o)+" properties' "),e.opts.verbose&&(a=(a+=" , schema: ")+(p?"validate.schema"+c:""+o)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),a+=" } "):a+=" {} ",r=a,a=s.pop(),!e.compositeRule&&h?e.async?a+=" throw new ValidationError(["+r+"]); ":a+=" validate.errors = ["+r+"]; return false; ":a+=" var err = "+r+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+="} ",h&&(a+=" else { "),a;throw new Error(t+" must be number")}},function(e){e.exports=JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://json-schema.org/draft-07/schema#","title":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}},"type":["object","boolean"],"properties":{"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"$comment":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"default":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"propertyNames":{"format":"regex"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"contentMediaType":{"type":"string"},"contentEncoding":{"type":"string"},"if":{"$ref":"#"},"then":{"$ref":"#"},"else":{"$ref":"#"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"default":true}')},function(e,t,i){var r=i(8);e.exports=function(){return r.randomBytes(16)}},function(e,t){for(var i=[],r=0;r<256;++r)i[r]=(r+256).toString(16).substr(1);e.exports=function(e,t){t=t||0;var r=i;return[r[e[t++]],r[e[t++]],r[e[t++]],r[e[t++]],"-",r[e[t++]],r[e[t++]],"-",r[e[t++]],r[e[t++]],"-",r[e[t++]],r[e[t++]],"-",r[e[t++]],r[e[t++]],r[e[t++]],r[e[t++]],r[e[t++]],r[e[+t]]].join("")}},function(e,t,i){"use strict";
|
|
723
|
+
*/t.pathMatch=function(e,t){if(t===e)return!0;if(0===e.indexOf(t)){if("/"===t.substr(-1))return!0;if("/"===e.substr(t.length,1))return!0}return!1}},function(e,t,i){e.exports={Verifier:c,Signer:u};var r=i(103),a=i(47),s=(e=i(9),i(10)),n=i(12).Buffer,o=i(57);function c(e,t){if("sha512"!==t.toLowerCase())throw new Error("ED25519 only supports the use of SHA-512 hashes");this.key=e,this.chunks=[],a.Writable.call(this,{})}function u(e,t){if("sha512"!==t.toLowerCase())throw new Error("ED25519 only supports the use of SHA-512 hashes");this.key=e,this.chunks=[],a.Writable.call(this,{})}e.inherits(c,a.Writable),c.prototype._write=function(e,t,i){this.chunks.push(e),i()},c.prototype.update=function(e){"string"==typeof e&&(e=n.from(e,"binary")),this.chunks.push(e)},c.prototype.verify=function(e,t){var i;if(o.isSignature(e,[2,0])){if("ed25519"!==e.type)return!1;i=e.toBuffer("raw")}else if("string"==typeof e)i=n.from(e,"base64");else if(o.isSignature(e,[1,0]))throw new Error("signature was created by too old a version of sshpk and cannot be verified");return s.buffer(i),r.sign.detached.verify(new Uint8Array(n.concat(this.chunks)),new Uint8Array(i),new Uint8Array(this.key.part.A.data))},e.inherits(u,a.Writable),u.prototype._write=function(e,t,i){this.chunks.push(e),i()},u.prototype.update=function(e){"string"==typeof e&&(e=n.from(e,"binary")),this.chunks.push(e)},u.prototype.sign=function(){var e=r.sign.detached(new Uint8Array(n.concat(this.chunks)),new Uint8Array(n.concat([this.key.part.k.data,this.key.part.A.data])));e=n.from(e);return(e=o.parse(e,"ed25519","raw")).hashAlgorithm="sha512",e}},function(e,t,i){e.exports={read:function(e,t){if("string"==typeof e){if(e.trim().match(/^[-]+[ ]*BEGIN/))return s.read(e,t);if(e.match(/^\s*ssh-[a-z]/))return n.read(e,t);if(e.match(/^\s*ecdsa-/))return n.read(e,t);if(e.match(/^putty-user-key-file-2:/i))return u.read(e,t);if(l(e))return c.read(e,t);e=a.from(e,"binary")}else{if(r.buffer(e),function(e){for(var t=0;t<e.length&&(32===e[t]||10===e[t]);)++t;if(45===e[t]){for(;t<e.length&&45===e[t];)++t;for(;t<e.length&&32===e[t];)++t;return!(t+5>e.length||"BEGIN"!==e.slice(t,t+5).toString("ascii"))}}(e))return s.read(e,t);if(function(e){for(var t=0;t<e.length&&(32===e[t]||10===e[t]||9===e[t]);)++t;return t+4<=e.length&&"ssh-"===e.slice(t,t+4).toString("ascii")||t+6<=e.length&&"ecdsa-"===e.slice(t,t+6).toString("ascii")}(e))return n.read(e,t);if(function(e){for(var t=0;t<e.length&&(32===e[t]||10===e[t]||9===e[t]);)++t;return t+22<=e.length&&"putty-user-key-file-2:"===e.slice(t,t+22).toString("ascii").toLowerCase()}(e))return u.read(e,t);if(l(e))return c.read(e,t)}if(e.readUInt32BE(0)<e.length)return o.read(e,t);throw new Error("Failed to auto-detect format of key")},write:function(e,t){throw new Error('"auto" format cannot be used for writing')}};var r=i(10),a=i(12).Buffer,s=(i(25),i(23),i(24),i(65)),n=i(277),o=i(66),c=i(180),u=i(181),h="Private-key-format: v1";function l(e){if(!(e.length<=h.length)){if(e.slice(0,h.length).toString("ascii")===h)return 1;for(var t=(e="string"!=typeof e?e.toString("ascii"):e).split("\n"),i=0;t[i].match(/^\;/);)i++;return t[i].toString("ascii").match(/\. IN KEY /)||!!t[i].toString("ascii").match(/\. IN DNSKEY /)}}},function(e,t,i){"use strict";function r(){this.S=[new Uint32Array([3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946]),new Uint32Array([1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055]),new Uint32Array([3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504]),new Uint32Array([976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462])],this.P=new Uint32Array([608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731])}var a=i(103).lowlevel.crypto_hash,s=0;function n(e,t,i){return(e[0][t[i+3]]+e[1][t[i+2]]^e[2][t[i+1]])+e[3][t[i]]}function o(e,t){for(var i=0,r=0;r<4;r++,s++)i=i<<8|e[s=t<=s?0:s];return i}function c(e,t,i){var a,s=new r,n=new Uint32Array(8),c=new Uint8Array([79,120,121,99,104,114,111,109,97,116,105,99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109,105,116,101]);for(s.expandstate(t,64,e,64),a=0;a<64;a++)s.expand0state(t,64),s.expand0state(e,64);for(a=0;a<8;a++)n[a]=o(c,c.byteLength);for(a=0;a<64;a++)s.enc(n,n.byteLength/8);for(a=0;a<8;a++)i[4*a+3]=n[a]>>>24,i[4*a+2]=n[a]>>>16,i[4*a+1]=n[a]>>>8,i[4*a+0]=n[a]}r.prototype.encipher=function(e,t){void 0===t&&(t=new Uint8Array(e.buffer),0!==e.byteOffset)&&(t=t.subarray(e.byteOffset)),e[0]^=this.P[0];for(var i=1;i<16;i+=2)e[1]^=n(this.S,t,0)^this.P[i],e[0]^=n(this.S,t,4)^this.P[i+1];var r=e[0];e[0]=e[1]^this.P[17],e[1]=r},r.prototype.decipher=function(e){var t=new Uint8Array(e.buffer);0!==e.byteOffset&&(t=t.subarray(e.byteOffset)),e[0]^=this.P[17];for(var i=16;0<i;i-=2)e[1]^=n(this.S,t,0)^this.P[i],e[0]^=n(this.S,t,4)^this.P[i-1];var r=e[0];e[0]=e[1]^this.P[0],e[1]=r},r.prototype.expand0state=function(e,t){var i,r=new Uint32Array(2),a=new Uint8Array(r.buffer),n=0;for(s=0;n<18;n++)this.P[n]^=o(e,t);for(n=s=0;n<18;n+=2)this.encipher(r,a),this.P[n]=r[0],this.P[n+1]=r[1];for(n=0;n<4;n++)for(i=0;i<256;i+=2)this.encipher(r,a),this.S[n][i]=r[0],this.S[n][i+1]=r[1]},r.prototype.expandstate=function(e,t,i,r){var a,n=new Uint32Array(2),c=0;for(s=0;c<18;c++)this.P[c]^=o(i,r);for(s=c=0;c<18;c+=2)n[0]^=o(e,t),n[1]^=o(e,t),this.encipher(n),this.P[c]=n[0],this.P[c+1]=n[1];for(c=0;c<4;c++)for(a=0;a<256;a+=2)n[0]^=o(e,t),n[1]^=o(e,t),this.encipher(n),this.S[c][a]=n[0],this.S[c][a+1]=n[1];s=0},r.prototype.enc=function(e,t){for(var i=0;i<t;i++)this.encipher(e.subarray(2*i))},r.prototype.dec=function(e,t){for(var i=0;i<t;i++)this.decipher(e.subarray(2*i))},e.exports={BLOCKS:8,HASHSIZE:32,hash:c,pbkdf:function(e,t,i,r,s,n,o){var u,h,l,p,d,f,m=new Uint8Array(64),g=new Uint8Array(64),v=new Uint8Array(32),y=new Uint8Array(32),b=new Uint8Array(r+4),w=n;if(o<1)return-1;if(0===t||0===r||0===n||n>v.byteLength*v.byteLength||1<<20<r)return-1;for(p=Math.floor((n+v.byteLength-1)/v.byteLength),l=Math.floor((n+p-1)/p),u=0;u<r;u++)b[u]=i[u];for(a(m,e,t),f=1;0<n;f++){for(b[r+0]=f>>>24,b[r+1]=f>>>16,b[r+2]=f>>>8,b[r+3]=f,a(g,b,r+4),c(m,g,y),u=v.byteLength;u--;)v[u]=y[u];for(u=1;u<o;u++)for(a(g,y,y.byteLength),c(m,g,y),h=0;h<v.byteLength;h++)v[h]^=y[h];for(l=Math.min(l,n),u=0;u<l&&!(w<=(d=u*p+(f-1)));u++)s[d]=v[u];n-=u}return 0}}},function(e,t,i){e.exports={read:function(e,t){"string"!=typeof e&&(r.buffer(e,"buf"),e=e.toString("ascii"));var i=(e=e.trim().replace(/[\\\r]/g,"")).match(o);i=i||e.match(c),r.ok(i,"key must match regex");var n,u=s.algToKeyType(i[1]),h=a.from(i[2],"base64"),l={};if(i[4])try{n=s.read(h)}catch(t){i=e.match(c),r.ok(i,"key must match regex"),h=a.from(i[2],"base64"),n=s.readInternal(l,"public",h)}else n=s.readInternal(l,"public",h);if(r.strictEqual(u,n.type),i[4]&&0<i[4].length)n.comment=i[4];else if(l.consumed){var p=i[2]+(i[3]||""),d=4*Math.ceil(l.consumed/3);for(p=p.slice(0,d-2).replace(/[^a-zA-Z0-9+\/=]/g,"")+p.slice(d-2),0<l.consumed%3&&"="!==p.slice(d-1,d)&&d--;"="===p.slice(d,d+1);)d++;(e=(e=p.slice(d)).replace(/[\r\n]/g," ").replace(/^\s+/,"")).match(/^[a-zA-Z0-9]/)&&(n.comment=e)}return n},write:function(e,t){if(r.object(e),!n.isKey(e))throw new Error("Must be a public key");var i=[],o=s.keyTypeToAlg(e);i.push(o),o=s.write(e);return i.push(o.toString("base64")),e.comment&&i.push(e.comment),a.from(i.join(" "))}};var r=i(10),a=i(12).Buffer,s=i(66),n=(i(25),i(23)),o=(i(24),i(134),/^([a-z0-9-]+)[ \t]+([a-zA-Z0-9+\/]+[=]*)([ \t]+([^ \t][^\n]*[\n]*)?)?$/),c=/^([a-z0-9-]+)[ \t\n]+([a-zA-Z0-9+\/][a-zA-Z0-9+\/ \t\n=]*)([^a-zA-Z0-9+\/ \t\n=].*)?$/},function(e,t,i){e.exports={read:function(e,t){"string"==typeof e&&(e=s.from(e,"binary")),r.buffer(e,"buf");var i=new a.BerReader(e);if(i.readSequence(),1<Math.abs(i.length-i.remain))throw new Error("DER sequence does not contain whole byte stream");var p=i.offset,g=(i.readSequence(),i.offset+i.length),y=g;i.peek()===l(0)&&(i.readSequence(l(0)),k=i.readInt(),r.ok(k<=3,"only x.509 versions up to v3 supported"));var x={signatures:{}},k=x.signatures.x509={extras:{}},S=(x.serial=function(e,t){return r.strictEqual(e.peek(),a.Ber.Integer,"serial is not an Integer"),n.mpNormalize(e.readString(a.Ber.Integer,!0))}(i),i.readSequence(),i.offset+i.length),_=i.readOID();if(void 0===d[_])throw new Error("unknown signature algorithm "+_);if(i._offset=S,x.issuer=o.parseAsn1(i),i.readSequence(),x.validFrom=m(i),x.validUntil=m(i),x.subjects=[o.parseAsn1(i)],i.readSequence(),S=i.offset+i.length,x.subjectKey=h.readPkcs8(void 0,"public",i),i._offset=S,i.peek()===l(1)&&(i.readSequence(l(1)),k.extras.issuerUniqueID=e.slice(i.offset,i.offset+i.length),i._offset+=i.length),i.peek()===l(2)&&(i.readSequence(l(2)),k.extras.subjectUniqueID=e.slice(i.offset,i.offset+i.length),i._offset+=i.length),i.peek()===l(3)){i.readSequence(l(3));var E=i.offset+i.length;for(i.readSequence();i.offset<E;)!function(e,t){t.readSequence();var i,r=t.offset+t.length,s=t.readOID(),n=e.signatures.x509;switch(n.extras.exts||(n.extras.exts=[]),t.peek()===a.Ber.Boolean&&(i=t.readBoolean()),s){case f.basicConstraints:t.readSequence(a.Ber.OctetString),t.readSequence();var c=t.offset+t.length,u=!1;u=(t.peek()===a.Ber.Boolean&&(u=t.readBoolean()),void 0===e.purposes&&(e.purposes=[]),!0===u&&e.purposes.push("ca"),{oid:s,critical:i});t.offset<c&&t.peek()===a.Ber.Integer&&(u.pathLen=t.readInt()),n.extras.exts.push(u);break;case f.extKeyUsage:t.readSequence(a.Ber.OctetString),t.readSequence(),void 0===e.purposes&&(e.purposes=[]);for(var h=t.offset+t.length;t.offset<h;){var l=t.readOID();e.purposes.push(b[l]||l)}-1!==e.purposes.indexOf("serverAuth")&&-1===e.purposes.indexOf("clientAuth")?e.subjects.forEach((function(e){"host"!==e.type&&(e.type="host",e.hostname=e.uid||e.email||e.components[0].value)})):-1!==e.purposes.indexOf("clientAuth")&&-1===e.purposes.indexOf("serverAuth")&&e.subjects.forEach((function(e){"user"!==e.type&&(e.type="user",e.uid=e.hostname||e.email||e.components[0].value)})),n.extras.exts.push({oid:s,critical:i});break;case f.keyUsage:t.readSequence(a.Ber.OctetString),function(e,t){for(var i=8*(e.length-1)-e[0],r={},a=0;a<i;++a){var s=1<<7-a%8,n=0!=(e[n=1+Math.floor(a/8)]&s);s=t[a];n&&"string"==typeof s&&(r[s]=!0)}return Object.keys(r)}(c=t.readString(a.Ber.BitString,!0),w).forEach((function(t){void 0===e.purposes&&(e.purposes=[]),-1===e.purposes.indexOf(t)&&e.purposes.push(t)})),n.extras.exts.push({oid:s,critical:i,bits:c});break;case f.altName:t.readSequence(a.Ber.OctetString),t.readSequence();for(var p=t.offset+t.length;t.offset<p;)switch(t.peek()){case v.OtherName:case v.EDIPartyName:t.readSequence(),t._offset+=t.length;break;case v.OID:t.readOID(v.OID);break;case v.RFC822Name:var d=t.readString(v.RFC822Name);d=o.forEmail(d),e.subjects[0].equals(d)||e.subjects.push(d);break;case v.DirectoryName:t.readSequence(v.DirectoryName),d=o.parseAsn1(t),e.subjects[0].equals(d)||e.subjects.push(d);break;case v.DNSName:var m=t.readString(v.DNSName);d=o.forHost(m),e.subjects[0].equals(d)||e.subjects.push(d);break;default:t.readString(t.peek())}n.extras.exts.push({oid:s,critical:i});break;default:n.extras.exts.push({oid:s,critical:i,data:t.readString(a.Ber.OctetString,!0)})}t._offset=r}(x,i);r.strictEqual(i.offset,E)}if(r.strictEqual(i.offset,g),i.readSequence(),S=i.offset+i.length,_=i.readOID(),void 0===(g=d[_]))throw new Error("unknown signature algorithm "+_);return i._offset=S,0===(_=i.readString(a.Ber.BitString,!0))[0]&&(_=_.slice(1)),S=g.split("-"),k.signature=c.parse(_,S[0],"asn1"),k.signature.hashAlgorithm=S[1],k.algo=g,k.cache=e.slice(p,y),new u(x)},verify:function(e,t){var i=e.signatures.x509,s=(r.object(i,"x509 signature"),i.algo.split("-"));if(s[0]!==t.type)return!1;var n,o=i.cache;return void 0===o&&(_(e,n=new a.BerWriter),o=n.buffer),(e=t.createVerify(s[1])).write(o),e.verify(i.signature)},sign:function(e,t){void 0===e.signatures.x509&&(e.signatures.x509={});var i,r=e.signatures.x509;return r.algo=t.type+"-"+t.defaultHashAlgorithm(),void 0!==d[r.algo]&&(_(e,i=new a.BerWriter),i=i.buffer,r.cache=i,(r=t.createSign()).write(i),e.signatures.x509.signature=r.sign(),!0)},signAsync:function(e,t,i){void 0===e.signatures.x509&&(e.signatures.x509={});var r=e.signatures.x509,s=new a.BerWriter;_(e,s),e=s.buffer;r.cache=e,t(e,(function(e,t){e?i(e):(r.algo=t.type+"-"+t.hashAlgorithm,void 0===d[r.algo]?i(new Error('Invalid signing algorithm "'+r.algo+'"')):(r.signature=t,i()))}))},write:function(e,t){var i=e.signatures.x509,n=(r.object(i,"x509 signature"),new a.BerWriter);return n.startSequence(),i.cache?(n._ensure(i.cache.length),i.cache.copy(n._buf,n._offset),n._offset+=i.cache.length):_(e,n),n.startSequence(),n.writeOID(d[i.algo]),i.algo.match(/^rsa-/)&&n.writeNull(),n.endSequence(),e=i.signature.toBuffer("asn1"),(i=s.alloc(e.length+1))[0]=0,e.copy(i,1),n.writeBuffer(i,a.Ber.BitString),n.endSequence(),n.buffer}};var r=i(10),a=i(58),s=i(12).Buffer,n=(i(30),i(25)),o=(i(23),i(24),i(65),i(106)),c=i(57),u=i(105),h=i(104);function l(e){return a.Ber.Context|a.Ber.Constructor|e}function p(e){return a.Ber.Context|e}var d={"rsa-md5":"1.2.840.113549.1.1.4","rsa-sha1":"1.2.840.113549.1.1.5","rsa-sha256":"1.2.840.113549.1.1.11","rsa-sha384":"1.2.840.113549.1.1.12","rsa-sha512":"1.2.840.113549.1.1.13","dsa-sha1":"1.2.840.10040.4.3","dsa-sha256":"2.16.840.1.101.3.4.3.2","ecdsa-sha1":"1.2.840.10045.4.1","ecdsa-sha256":"1.2.840.10045.4.3.2","ecdsa-sha384":"1.2.840.10045.4.3.3","ecdsa-sha512":"1.2.840.10045.4.3.4","ed25519-sha512":"1.3.101.112"},f=(Object.keys(d).forEach((function(e){d[d[e]]=e})),d["1.3.14.3.2.3"]="rsa-md5",d["1.3.14.3.2.29"]="rsa-sha1",{issuerKeyId:"2.5.29.35",altName:"2.5.29.17",basicConstraints:"2.5.29.19",keyUsage:"2.5.29.15",extKeyUsage:"2.5.29.37"});function m(e){var t,i,s,n,o;if(e.peek()===a.Ber.UTCTime)return t=(t=e.readString(a.Ber.UTCTime)).match(x),r.ok(t,"timestamps must be in UTC"),n=(i=new Date).getUTCFullYear(),o=100*Math.floor(n/100),s=parseInt(t[1],10),s+=n%100<50&&60<=s?o-1:o,i.setUTCFullYear(s,parseInt(t[2],10)-1,parseInt(t[3],10)),i.setUTCHours(parseInt(t[4],10),parseInt(t[5],10)),t[6]&&0<t[6].length&&i.setUTCSeconds(parseInt(t[6],10)),i;if(e.peek()===a.Ber.GeneralizedTime)return n=(n=e.readString(a.Ber.GeneralizedTime)).match(k),r.ok(n),(o=new Date).setUTCFullYear(parseInt(n[1],10),parseInt(n[2],10)-1,parseInt(n[3],10)),o.setUTCHours(parseInt(n[4],10),parseInt(n[5],10)),n[6]&&0<n[6].length&&o.setUTCSeconds(parseInt(n[6],10)),o;throw new Error("Unsupported date format")}function g(e,t){var i,r;2050<=t.getUTCFullYear()||t.getUTCFullYear()<1950?e.writeString((r="",r=(r=(r=(r=(r=(r+=S((i=t).getUTCFullYear(),4))+S(i.getUTCMonth()+1))+S(i.getUTCDate()))+S(i.getUTCHours()))+S(i.getUTCMinutes()))+S(i.getUTCSeconds())+"Z"),a.Ber.GeneralizedTime):e.writeString((i="",i=(i=(i=(i=(i=(i+=S((r=t).getUTCFullYear()%100))+S(r.getUTCMonth()+1))+S(r.getUTCDate()))+S(r.getUTCHours()))+S(r.getUTCMinutes()))+S(r.getUTCSeconds())+"Z"),a.Ber.UTCTime)}var v={OtherName:l(0),RFC822Name:p(1),DNSName:p(2),X400Address:l(3),DirectoryName:l(4),EDIPartyName:l(5),URI:p(6),IPAddress:p(7),OID:p(8)},y={serverAuth:"1.3.6.1.5.5.7.3.1",clientAuth:"1.3.6.1.5.5.7.3.2",codeSigning:"1.3.6.1.5.5.7.3.3",joyentDocker:"1.3.6.1.4.1.38678.1.4.1",joyentCmon:"1.3.6.1.4.1.38678.1.4.2"},b={},w=(Object.keys(y).forEach((function(e){b[y[e]]=e})),["signature","identity","keyEncryption","encryption","keyAgreement","ca","crl"]),x=/^([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/,k=/^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/;function S(e,t){void 0===t&&(t=2);for(var i=""+e;i.length<t;)i="0"+i;return i}function _(e,t){var i=e.signatures.x509,o=(r.object(i,"x509 signature"),t.startSequence(),t.startSequence(l(0)),t.writeInt(2),t.endSequence(),t.writeBuffer(n.mpNormalize(e.serial),a.Ber.Integer),t.startSequence(),t.writeOID(d[i.algo]),i.algo.match(/^rsa-/)&&t.writeNull(),t.endSequence(),e.issuer.toAsn1(t),t.startSequence(),g(t,e.validFrom),g(t,e.validUntil),t.endSequence(),e.subjects[0]),c=e.subjects.slice(1);if(o.toAsn1(t),h.writePkcs8(t,e.subjectKey),i.extras&&i.extras.issuerUniqueID&&t.writeBuffer(i.extras.issuerUniqueID,l(1)),i.extras&&i.extras.subjectUniqueID&&t.writeBuffer(i.extras.subjectUniqueID,l(2)),0<c.length||"host"===o.type||void 0!==e.purposes&&0<e.purposes.length||i.extras&&i.extras.exts){t.startSequence(l(3)),t.startSequence();var u=[];void 0!==e.purposes&&0<e.purposes.length&&(u.push({oid:f.basicConstraints,critical:!0}),u.push({oid:f.keyUsage,critical:!0}),u.push({oid:f.extKeyUsage,critical:!0})),u.push({oid:f.altName}),i.extras&&i.extras.exts&&(u=i.extras.exts);for(var m,b,x=0;x<u.length;++x){if(t.startSequence(),t.writeOID(u[x].oid),void 0!==u[x].critical&&t.writeBoolean(u[x].critical),u[x].oid===f.altName){t.startSequence(a.Ber.OctetString),t.startSequence(),"host"===o.type&&t.writeString(o.hostname,p(2));for(var k=0;k<c.length;++k)"host"===c[k].type?t.writeString(c[k].hostname,v.DNSName):"email"===c[k].type?t.writeString(c[k].email,v.RFC822Name):(t.startSequence(v.DirectoryName),c[k].toAsn1(t),t.endSequence());t.endSequence(),t.endSequence()}else u[x].oid===f.basicConstraints?(t.startSequence(a.Ber.OctetString),t.startSequence(),b=-1!==e.purposes.indexOf("ca"),m=u[x].pathLen,t.writeBoolean(b),void 0!==m&&t.writeInt(m),t.endSequence(),t.endSequence()):u[x].oid===f.extKeyUsage?(t.startSequence(a.Ber.OctetString),t.startSequence(),e.purposes.forEach((function(e){var i;"ca"!==e&&-1===w.indexOf(e)&&(void 0!==y[i=e]&&(i=y[e]),t.writeOID(i))})),t.endSequence(),t.endSequence()):u[x].oid===f.keyUsage?(t.startSequence(a.Ber.OctetString),void 0!==u[x].bits?t.writeBuffer(u[x].bits,a.Ber.BitString):(b=function(e,t){var i=t.length,r=Math.ceil(i/8),a=8*r-i,n=s.alloc(1+r);n[0]=a;for(var o=0;o<i;++o){var c=1+Math.floor(o/8),u=1<<7-o%8,h=t[o];void 0!==h&&-1!==e.indexOf(h)&&(n[c]|=u)}return n}(e.purposes,w),t.writeBuffer(b,a.Ber.BitString)),t.endSequence()):t.writeBuffer(u[x].data,a.Ber.OctetString);t.endSequence()}t.endSequence(),t.endSequence()}t.endSequence()}},function(e,t,i){var r=i(0),a=i(9);function s(e){var t,i,n,c,u,h,l,p,d,f=["([^%]*)","%","(['\\-+ #0]*?)","([1-9]\\d*)?","(\\.([1-9]\\d*))?","[lhjztL]*?","([diouxXfFeEgGaAcCsSp%jr])"].join(""),m=new RegExp(f),g=Array.prototype.slice.call(arguments,1),v="",y=1;for(r.equal("string",typeof e);null!==(d=m.exec(e));)if(v+=d[1],e=e.substring(d[0].length),t=d[2]||"",i=d[3]||0,n=d[4]||"",l=u=!1,h=" ","%"==(c=d[6]))v+="%";else{if(0===g.length)throw new Error("too few args to sprintf");if(p=g.shift(),y++,t.match(/[\' #]/))throw new Error("unsupported flags: "+t);if(0<n.length)throw new Error("non-zero precision not supported");switch(t.match(/-/)&&(u=!0),t.match(/0/)&&(h="0"),t.match(/\+/)&&(l=!0),c){case"s":if(null==p)throw new Error("argument "+y+": attempted to print undefined or null as a string");v+=o(h,i,u,p.toString());break;case"d":p=Math.floor(p);case"f":v+=(l=l&&0<p?"+":"")+o(h,i,u,p.toString());break;case"x":v+=o(h,i,u,p.toString(16));break;case"j":0===i&&(i=10),v+=a.inspect(p,!1,i);break;case"r":v+=function e(t){var i;if(!(t instanceof Error))throw new Error(s("invalid type for %%r: %j",t));return i="EXCEPTION: "+t.constructor.name+": "+t.stack,t.cause&&"function"==typeof t.cause&&(t=t.cause())&&(i+="\nCaused by: "+e(t)),i}(p);break;default:throw new Error("unsupported conversion: "+c)}}return v+e}function n(e){var t=Array.prototype.slice.call(arguments,1);return e.write(s.apply(this,t))}function o(e,t,i,r){for(var a=r;a.length<t;)i?a+=e:a=e+a;return a}t.sprintf=s,t.printf=function(){var e=Array.prototype.slice.call(arguments);e.unshift(process.stdout),n.apply(null,e)},t.fprintf=n},function(e,t,i){var r=i(9),a=i(47).Stream,s=i(481);function n(){this.writable=!1,this.readable=!0,this.dataSize=0,this.maxDataSize=2097152,this.pauseStreams=!0,this._released=!1,this._streams=[],this._currentStream=null,this._insideLoop=!1,this._pendingNext=!1}e.exports=n,r.inherits(n,a),n.create=function(e){var t,i=new this;for(t in e=e||{})i[t]=e[t];return i},n.isStreamLike=function(e){return"function"!=typeof e&&"string"!=typeof e&&"boolean"!=typeof e&&"number"!=typeof e&&!Buffer.isBuffer(e)},n.prototype.append=function(e){var t;return n.isStreamLike(e)&&(e instanceof s||(t=s.create(e,{maxDataSize:1/0,pauseStream:this.pauseStreams}),e.on("data",this._checkDataSize.bind(this)),e=t),this._handleErrors(e),this.pauseStreams)&&e.pause(),this._streams.push(e),this},n.prototype.pipe=function(e,t){return a.prototype.pipe.call(this,e,t),this.resume(),e},n.prototype._getNext=function(){if(this._currentStream=null,this._insideLoop)this._pendingNext=!0;else{this._insideLoop=!0;try{for(;this._pendingNext=!1,this._realGetNext(),this._pendingNext;);}finally{this._insideLoop=!1}}},n.prototype._realGetNext=function(){var e=this._streams.shift();void 0===e?this.end():"function"!=typeof e?this._pipeNext(e):e(function(e){n.isStreamLike(e)&&(e.on("data",this._checkDataSize.bind(this)),this._handleErrors(e)),this._pipeNext(e)}.bind(this))},n.prototype._pipeNext=function(e){this._currentStream=e,n.isStreamLike(e)?(e.on("end",this._getNext.bind(this)),e.pipe(this,{end:!1})):(this.write(e),this._getNext())},n.prototype._handleErrors=function(e){var t=this;e.on("error",(function(e){t._emitError(e)}))},n.prototype.write=function(e){this.emit("data",e)},n.prototype.pause=function(){this.pauseStreams&&(this.pauseStreams&&this._currentStream&&"function"==typeof this._currentStream.pause&&this._currentStream.pause(),this.emit("pause"))},n.prototype.resume=function(){this._released||(this._released=!0,this.writable=!0,this._getNext()),this.pauseStreams&&this._currentStream&&"function"==typeof this._currentStream.resume&&this._currentStream.resume(),this.emit("resume")},n.prototype.end=function(){this._reset(),this.emit("end")},n.prototype.destroy=function(){this._reset(),this.emit("close")},n.prototype._reset=function(){this.writable=!1,this._streams=[],this._currentStream=null},n.prototype._checkDataSize=function(){var e;this._updateDataSize(),this.dataSize<=this.maxDataSize||(e="DelayedStream#maxDataSize of "+this.maxDataSize+" bytes exceeded.",this._emitError(new Error(e)))},n.prototype._updateDataSize=function(){this.dataSize=0;var e=this;this._streams.forEach((function(t){t.dataSize&&(e.dataSize+=t.dataSize)})),this._currentStream&&this._currentStream.dataSize&&(this.dataSize+=this._currentStream.dataSize)},n.prototype._emitError=function(e){this._reset(),this.emit("error",e)}},function(e,t,i){var r=i(282),a=i(283);e.exports=function(e,t,i,s){var n=i.keyedList?i.keyedList[i.index]:i.index;i.jobs[n]=function(e,t,i,a){return e=2==e.length?e(i,r(a)):e(i,t,r(a))}(t,n,e[n],(function(e,t){n in i.jobs&&(delete i.jobs[n],e?a(i):i.results[n]=t,s(e,i.results))}))}},function(e,t,i){var r=i(484);e.exports=function(e){var t=!1;return r((function(){t=!0})),function(i,a){t?e(i,a):r((function(){e(i,a)}))}}},function(e,t){e.exports=function(e){Object.keys(e.jobs).forEach(function(e){"function"==typeof this.jobs[e]&&this.jobs[e]()}.bind(e)),e.jobs={}}},function(e,t){e.exports=function(e,t){var i=!Array.isArray(e),r={index:0,keyedList:i||t?Object.keys(e):null,jobs:{},results:i?{}:[],size:(i?Object.keys(e):e).length};return t&&r.keyedList.sort(i?t:function(i,r){return t(e[i],e[r])}),r}},function(e,t,i){var r=i(283),a=i(282);e.exports=function(e){Object.keys(this.jobs).length&&(this.index=this.size,r(this),a(e)(null,this.results))}},function(e,t,i){var r=i(281),a=i(284),s=i(285);function n(e,t){return e<t?-1:t<e?1:0}e.exports=function(e,t,i,n){var o=a(e,i);return r(e,t,o,(function i(a,s){a?n(a,s):(o.index++,o.index<(o.keyedList||e).length?r(e,t,o,i):n(null,o.results))})),s.bind(o,n)},e.exports.ascending=n,e.exports.descending=function(e,t){return-1*n(e,t)}},function(e,t,i){var r=i(47);function a(e){return e instanceof r.Stream}function s(e){return a(e)&&"function"==typeof e._read&&"object"==typeof e._readableState}function n(e){return a(e)&&"function"==typeof e._write&&"object"==typeof e._writableState}e.exports=a,e.exports.isReadable=s,e.exports.isWritable=n,e.exports.isDuplex=function(e){return s(e)&&n(e)}},function(e,t,i){"use strict";var r=i(490),a=i(491);i=i(290);e.exports={formats:i,parse:a,stringify:r}},function(e,t,i){"use strict";function r(e,t){for(var i=t&&t.plainObjects?Object.create(null):{},r=0;r<e.length;++r)void 0!==e[r]&&(i[r]=e[r]);return i}var a=Object.prototype.hasOwnProperty,s=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}();e.exports={arrayToObject:r,assign:function(e,t){return Object.keys(t).reduce((function(e,i){return e[i]=t[i],e}),e)},compact:function(e){for(var t=[{obj:{o:e},prop:"o"}],i=[],r=0;r<t.length;++r)for(var a=t[r],s=a.obj[a.prop],n=Object.keys(s),o=0;o<n.length;++o){var c=n[o],u=s[c];"object"==typeof u&&null!==u&&-1===i.indexOf(u)&&(t.push({obj:s,prop:c}),i.push(u))}for(var h=t;h.length;){var l=h.pop(),p=l.obj[l.prop];if(Array.isArray(p)){for(var d=[],f=0;f<p.length;++f)void 0!==p[f]&&d.push(p[f]);l.obj[l.prop]=d}}return p},decode:function(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(t){return e}},encode:function(e){if(0===e.length)return e;for(var t="string"==typeof e?e:String(e),i="",r=0;r<t.length;++r){var a=t.charCodeAt(r);45===a||46===a||95===a||126===a||48<=a&&a<=57||65<=a&&a<=90||97<=a&&a<=122?i+=t.charAt(r):a<128?i+=s[a]:a<2048?i+=s[192|a>>6]+s[128|63&a]:a<55296||57344<=a?i+=s[224|a>>12]+s[128|a>>6&63]+s[128|63&a]:(r+=1,a=65536+((1023&a)<<10|1023&t.charCodeAt(r)),i+=s[240|a>>18]+s[128|a>>12&63]+s[128|a>>6&63]+s[128|63&a])}return i},isBuffer:function(e){return null!=e&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))},isRegExp:function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},merge:function e(t,i,s){if(!i)return t;if("object"!=typeof i){if(Array.isArray(t))t.push(i);else{if(!t||"object"!=typeof t)return[t,i];(s&&(s.plainObjects||s.allowPrototypes)||!a.call(Object.prototype,i))&&(t[i]=!0)}return t}var n;return t&&"object"==typeof t?(n=t,Array.isArray(t)&&!Array.isArray(i)&&(n=r(t,s)),Array.isArray(t)&&Array.isArray(i)?(i.forEach((function(i,r){var n;a.call(t,r)?(n=t[r])&&"object"==typeof n&&i&&"object"==typeof i?t[r]=e(n,i,s):t.push(i):t[r]=i})),t):Object.keys(i).reduce((function(t,r){var n=i[r];return a.call(t,r)?t[r]=e(t[r],n,s):t[r]=n,t}),n)):[t].concat(i)}}},function(e,t,i){"use strict";var r=String.prototype.replace,a=/%20/g;e.exports={default:"RFC3986",formatters:{RFC1738:function(e){return r.call(e,a,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:"RFC3986"}},function(e,t,i){"use strict";var r=i(92);e.exports=function(e){r.copy(e,this)}},function(e,t,i){"use strict";e.exports=function(e,t){var i,r="boolean"==typeof(t="function"==typeof(t=t||{})?{cmp:t}:t).cycles&&t.cycles,a=t.cmp&&(i=t.cmp,function(e){return function(t,r){return t={key:t,value:e[t]},r={key:r,value:e[r]},i(t,r)}}),s=[];return function e(t){if(void 0!==(t=t&&t.toJSON&&"function"==typeof t.toJSON?t.toJSON():t)){if("number"==typeof t)return isFinite(t)?""+t:"null";if("object"!=typeof t)return JSON.stringify(t);if(Array.isArray(t)){for(o="[",c=0;c<t.length;c++)c&&(o+=","),o+=e(t[c])||"null";return o+"]"}if(null===t)return"null";if(-1!==s.indexOf(t)){if(r)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}for(var i=s.push(t)-1,n=Object.keys(t).sort(a&&a(t)),o="",c=0;c<n.length;c++){var u=n[c],h=e(t[u]);h&&(o&&(o+=","),o+=JSON.stringify(u)+":"+h)}return s.splice(i,1),"{"+o+"}"}}(e)}},function(e,t,i){"use strict";e.exports=function(e,t,i){var r="",a=!0===e.schema.$async,s=e.util.schemaHasRulesExcept(e.schema,e.RULES.all,"$ref"),n=e.self._getId(e.schema);if(e.opts.strictKeywords&&(I=e.util.schemaUnknownRules(e.schema,e.RULES.keywords))){if(I="unknown keyword: "+I,"log"!==e.opts.strictKeywords)throw new Error(I);e.logger.warn(I)}if(e.isTop&&(r+=" var validate = ",a&&(e.async=!0,r+="async "),r+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",n)&&(e.opts.sourceCode||e.opts.processCode)&&(r+=" /*# sourceURL="+n+" */ "),"boolean"==typeof e.schema||!s&&!e.schema.$ref)c=e.level,u=e.dataLevel,T=e.schema[t="false schema"],w=e.schemaPath+e.util.getProperty(t),x=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,h="data"+(u||""),p="valid"+c,!1===e.schema?(e.isTop?d=!0:r+=" var "+p+" = false; ",(U=U||[]).push(r),r="",!1!==e.createErrors?(r+=" { keyword: 'false schema' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(x)+" , params: {} ",!1!==e.opts.messages&&(r+=" , message: 'boolean schema is false' "),e.opts.verbose&&(r+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ",R=r,r=U.pop(),!e.compositeRule&&d?e.async?r+=" throw new ValidationError(["+R+"]); ":r+=" validate.errors = ["+R+"]; return false; ":r+=" var err = "+R+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "):e.isTop?r+=a?" return data; ":" validate.errors = null; return true; ":r+=" var "+p+" = true; ",e.isTop&&(r+=" }; return validate; ");else{if(e.isTop){var o=e.isTop,c=e.level=0,u=e.dataLevel=0,h="data";if(e.rootId=e.resolve.fullPath(e.self._getId(e.root.schema)),e.baseId=e.baseId||e.rootId,delete e.isTop,e.dataPathArr=[""],void 0!==e.schema.default&&e.opts.useDefaults&&e.opts.strictDefaults){var l="default is ignored in the schema root";if("log"!==e.opts.strictDefaults)throw new Error(l);e.logger.warn(l)}r=(r+=" var vErrors = null; ")+" var errors = 0; if (rootData === undefined) rootData = data; "}else{if(c=e.level,h="data"+((u=e.dataLevel)||""),n&&(e.baseId=e.resolve.url(e.baseId,n)),a&&!e.async)throw new Error("async schema in sync schema");r+=" var errs_"+c+" = errors;"}var p="valid"+c,d=!e.opts.allErrors,f="",m="",g=e.schema.type,v=Array.isArray(g);if(g&&e.opts.nullable&&!0===e.schema.nullable&&(v?-1==g.indexOf("null")&&(g=g.concat("null")):"null"!=g&&(g=[g,"null"],v=!0)),v&&1==g.length&&(g=g[0],v=!1),e.schema.$ref&&s){if("fail"==e.opts.extendRefs)throw new Error('$ref: validation keywords used in schema at path "'+e.errSchemaPath+'" (see option extendRefs)');!0!==e.opts.extendRefs&&(s=!1,e.logger.warn('$ref: keywords ignored in schema at path "'+e.errSchemaPath+'"'))}if(e.schema.$comment&&e.opts.$comment&&(r+=" "+e.RULES.all.$comment.code(e,"$comment")),g){e.opts.coerceTypes&&(y=e.util.coerceToTypes(e.opts.coerceTypes,g));var y,b=e.RULES.types[g];if(y||v||!0===b||b&&!$(b)){var w=e.schemaPath+".type",x=e.errSchemaPath+"/type";w=e.schemaPath+".type",x=e.errSchemaPath+"/type";if(r+=" if ("+e.util[v?"checkDataTypes":"checkDataType"](g,h,e.opts.strictNumbers,!0)+") { ",y){var k="dataType"+c,S="coerced"+c,_=(r+=" var "+k+" = typeof "+h+"; var "+S+" = undefined; ","array"==e.opts.coerceTypes&&(r+=" if ("+k+" == 'object' && Array.isArray("+h+") && "+h+".length == 1) { "+h+" = "+h+"[0]; "+k+" = typeof "+h+"; if ("+e.util.checkDataType(e.schema.type,h,e.opts.strictNumbers)+") "+S+" = "+h+"; } "),r+=" if ("+S+" !== undefined) ; ",y);if(_)for(var E,j=-1,A=_.length-1;j<A;)"string"==(E=_[j+=1])?r+=" else if ("+k+" == 'number' || "+k+" == 'boolean') "+S+" = '' + "+h+"; else if ("+h+" === null) "+S+" = ''; ":"number"==E||"integer"==E?(r+=" else if ("+k+" == 'boolean' || "+h+" === null || ("+k+" == 'string' && "+h+" && "+h+" == +"+h+" ","integer"==E&&(r+=" && !("+h+" % 1)"),r+=")) "+S+" = +"+h+"; "):"boolean"==E?r+=" else if ("+h+" === 'false' || "+h+" === 0 || "+h+" === null) "+S+" = false; else if ("+h+" === 'true' || "+h+" === 1) "+S+" = true; ":"null"==E?r+=" else if ("+h+" === '' || "+h+" === 0 || "+h+" === false) "+S+" = null; ":"array"==e.opts.coerceTypes&&"array"==E&&(r+=" else if ("+k+" == 'string' || "+k+" == 'number' || "+k+" == 'boolean' || "+h+" == null) "+S+" = ["+h+"]; ");(U=U||[]).push(r+=" else { "),r="",!1!==e.createErrors?(r=(r+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(x)+" , params: { type: '")+(v?""+g.join(","):""+g)+"' } ",!1!==e.opts.messages&&(r=(r+=" , message: 'should be ")+(v?""+g.join(","):""+g)+"' "),e.opts.verbose&&(r+=" , schema: validate.schema"+w+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ";var R=r,I=(r=U.pop(),!e.compositeRule&&d?e.async?r+=" throw new ValidationError(["+R+"]); ":r+=" validate.errors = ["+R+"]; return false; ":r+=" var err = "+R+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u?"data"+(u-1||""):"parentData");r=r+" } if ("+S+" !== undefined) { "+h+" = "+S+"; ",u||(r+="if ("+I+" !== undefined)"),r+=" "+I+"["+(u?e.dataPathArr[u]:"parentDataProperty")+"] = "+S+"; } "}else(U=U||[]).push(r),r="",!1!==e.createErrors?(r=(r+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(x)+" , params: { type: '")+(v?""+g.join(","):""+g)+"' } ",!1!==e.opts.messages&&(r=(r+=" , message: 'should be ")+(v?""+g.join(","):""+g)+"' "),e.opts.verbose&&(r+=" , schema: validate.schema"+w+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ",R=r,r=U.pop(),!e.compositeRule&&d?e.async?r+=" throw new ValidationError(["+R+"]); ":r+=" validate.errors = ["+R+"]; return false; ":r+=" var err = "+R+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";r+=" } "}}if(e.schema.$ref&&!s)r+=" "+e.RULES.all.$ref.code(e,"$ref")+" ",d&&(r=(r+=" } if (errors === ")+(o?"0":"errs_"+c)+") { ",m+="}");else{var O=e.RULES;if(O)for(var C=-1,P=O.length-1;C<P;)if($(b=O[C+=1])){if(b.type&&(r+=" if ("+e.util.checkDataType(b.type,h,e.opts.strictNumbers)+") { "),e.opts.useDefaults)if("object"==b.type&&e.schema.properties){var T=e.schema.properties,B=Object.keys(T);if(B)for(var N,z=-1,F=B.length-1;z<F;)if(void 0!==(D=T[N=B[z+=1]]).default){var L=h+e.util.getProperty(N);if(e.compositeRule){if(e.opts.strictDefaults){if(l="default is ignored for: "+L,"log"!==e.opts.strictDefaults)throw new Error(l);e.logger.warn(l)}}else r+=" if ("+L+" === undefined ","empty"==e.opts.useDefaults&&(r+=" || "+L+" === null || "+L+" === '' "),r+=" ) "+L+" = ","shared"==e.opts.useDefaults?r+=" "+e.useDefault(D.default)+" ":r+=" "+JSON.stringify(D.default)+" ",r+="; "}}else if("array"==b.type&&Array.isArray(e.schema.items)){var M=e.schema.items;if(M){j=-1;for(var D,H=M.length-1;j<H;)if(void 0!==(D=M[j+=1]).default)if(L=h+"["+j+"]",e.compositeRule){if(e.opts.strictDefaults){if(l="default is ignored for: "+L,"log"!==e.opts.strictDefaults)throw new Error(l);e.logger.warn(l)}}else r+=" if ("+L+" === undefined ","empty"==e.opts.useDefaults&&(r+=" || "+L+" === null || "+L+" === '' "),r+=" ) "+L+" = ","shared"==e.opts.useDefaults?r+=" "+e.useDefault(D.default)+" ":r+=" "+JSON.stringify(D.default)+" ",r+="; "}}var U,q=b.rules;if(q)for(var V,K=-1,W=q.length-1;K<W;)Y(V=q[K+=1])&&(V=V.code(e,V.keyword,b.type))&&(r+=" "+V+" ",d)&&(f+="}");d&&(r+=" "+f+" ",f=""),b.type&&(r+=" } ",g)&&g===b.type&&!y&&(r+=" else { ",w=e.schemaPath+".type",x=e.errSchemaPath+"/type",(U=U||[]).push(r),r="",!1!==e.createErrors?(r=(r+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(x)+" , params: { type: '")+(v?""+g.join(","):""+g)+"' } ",!1!==e.opts.messages&&(r=(r+=" , message: 'should be ")+(v?""+g.join(","):""+g)+"' "),e.opts.verbose&&(r+=" , schema: validate.schema"+w+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),r+=" } "):r+=" {} ",R=r,r=U.pop(),!e.compositeRule&&d?e.async?r+=" throw new ValidationError(["+R+"]); ":r+=" validate.errors = ["+R+"]; return false; ":r+=" var err = "+R+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",r+=" } "),d&&(r=(r+=" if (errors === ")+(o?"0":"errs_"+c)+") { ",m+="}")}}d&&(r+=" "+m+" "),o?r=r+(a?" if (errors === 0) return data; else throw new ValidationError(vErrors); ":" validate.errors = vErrors; return errors === 0; ")+" }; return validate;":r+=" var "+p+" = errors === errs_"+c+";"}return r;function $(e){for(var t=e.rules,i=0;i<t.length;i++)if(Y(t[i]))return 1}function Y(t){return void 0!==e.schema[t.keyword]||t.implements&&function(t){for(var i=t.implements,r=0;r<i.length;r++)if(void 0!==e.schema[i[r]])return 1}(t)}}},function(e,t,i){"use strict";e.exports=function(e,t,i){var r,a,s,n,o,c=" ",u=e.level,h=e.dataLevel,l=e.schema[t],p=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,m="data"+(h||""),g=e.opts.$data&&l&&l.$data,v=g?(c+=" var schema"+u+" = "+e.util.getData(l.$data,h,e.dataPathArr)+"; ","schema"+u):l,y="maximum"==t,b=y?"exclusiveMaximum":"exclusiveMinimum",w=e.schema[b],x=e.opts.$data&&w&&w.$data,k=y?"<":">",S=y?">":"<",_=void 0;if(!g&&"number"!=typeof l&&void 0!==l)throw new Error(t+" must be number");if(!x&&void 0!==w&&"number"!=typeof w&&"boolean"!=typeof w)throw new Error(b+" must be number or boolean");x?(h=e.util.getData(w.$data,h,e.dataPathArr),s="exclIsNumber"+u,n="' + "+(o="op"+u)+" + '",_=b,(E=E||[]).push(c=c+" var schemaExcl"+u+" = "+h+"; var "+(r="exclusive"+u)+"; var "+(a="exclType"+u)+" = typeof "+(h="schemaExcl"+u)+"; if ("+a+" != 'boolean' && "+a+" != 'undefined' && "+a+" != 'number') { "),c="",!1!==e.createErrors?(c+=" { keyword: '"+(_||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: {} ",!1!==e.opts.messages&&(c+=" , message: '"+b+" should be boolean' "),e.opts.verbose&&(c+=" , schema: validate.schema"+p+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),c+=" } "):c+=" {} ",j=c,c=E.pop(),!e.compositeRule&&f?e.async?c+=" throw new ValidationError(["+j+"]); ":c+=" validate.errors = ["+j+"]; return false; ":c+=" var err = "+j+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c+=" } else if ( ",g&&(c+=" ("+v+" !== undefined && typeof "+v+" != 'number') || "),c+=" "+a+" == 'number' ? ( ("+r+" = "+v+" === undefined || "+h+" "+k+"= "+v+") ? "+m+" "+S+"= "+h+" : "+m+" "+S+" "+v+" ) : ( ("+r+" = "+h+" === true) ? "+m+" "+S+"= "+v+" : "+m+" "+S+" "+v+" ) || "+m+" !== "+m+") { var op"+u+" = "+r+" ? '"+k+"' : '"+k+"='; ",void 0===l&&(d=e.errSchemaPath+"/"+(_=b),v=h,g=x)):(n=k,(s="number"==typeof w)&&g?(o="'"+n+"'",c+=" if ( ",g&&(c+=" ("+v+" !== undefined && typeof "+v+" != 'number') || "),c+=" ( "+v+" === undefined || "+w+" "+k+"= "+v+" ? "+m+" "+S+"= "+w+" : "+m+" "+S+" "+v+" ) || "+m+" !== "+m+") { "):(s&&void 0===l?(r=!0,d=e.errSchemaPath+"/"+(_=b),v=w,S+="="):(s&&(v=Math[y?"min":"max"](w,l)),w===(!s||v)?(r=!0,d=e.errSchemaPath+"/"+(_=b),S+="="):(r=!1,n+="=")),o="'"+n+"'",c+=" if ( ",g&&(c+=" ("+v+" !== undefined && typeof "+v+" != 'number') || "),c+=" "+m+" "+S+" "+v+" || "+m+" !== "+m+") { ")),_=_||t,(E=E||[]).push(c),c="",!1!==e.createErrors?(c+=" { keyword: '"+(_||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { comparison: "+o+", limit: "+v+", exclusive: "+r+" } ",!1!==e.opts.messages&&(c=c+" , message: 'should be "+n+" "+(g?"' + "+v:v+"'")),e.opts.verbose&&(c=(c+=" , schema: ")+(g?"validate.schema"+p:""+l)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),c+=" } "):c+=" {} ";var E,j=c;return c=E.pop(),!e.compositeRule&&f?e.async?c+=" throw new ValidationError(["+j+"]); ":c+=" validate.errors = ["+j+"]; return false; ":c+=" var err = "+j+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c+=" } ",f&&(c+=" else { "),c}},function(e,t,i){"use strict";e.exports=function(e,t,i){var r,a=" ",s=e.level,n=e.dataLevel,o=e.schema[t],c=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,h=!e.opts.allErrors,l="data"+(n||""),p=e.opts.$data&&o&&o.$data;n=p?(a+=" var schema"+s+" = "+e.util.getData(o.$data,n,e.dataPathArr)+"; ","schema"+s):o;if(p||"number"==typeof o)return a+="if ( ",p&&(a+=" ("+n+" !== undefined && typeof "+n+" != 'number') || "),(s=[]).push(a+=" "+l+".length "+("maxItems"==(r=t)?">":"<")+" "+n+") { "),a="",!1!==e.createErrors?(a+=" { keyword: '"+(r||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+n+" } ",!1!==e.opts.messages&&(a=(a=(a+=" , message: 'should NOT have ")+("maxItems"==t?"more":"fewer")+" than ")+(p?"' + "+n+" + '":""+o)+" items' "),e.opts.verbose&&(a=(a+=" , schema: ")+(p?"validate.schema"+c:""+o)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),a+=" } "):a+=" {} ",r=a,a=s.pop(),!e.compositeRule&&h?e.async?a+=" throw new ValidationError(["+r+"]); ":a+=" validate.errors = ["+r+"]; return false; ":a+=" var err = "+r+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+="} ",h&&(a+=" else { "),a;throw new Error(t+" must be number")}},function(e,t,i){"use strict";e.exports=function(e,t,i){var r,a=" ",s=e.level,n=e.dataLevel,o=e.schema[t],c=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,h=!e.opts.allErrors,l="data"+(n||""),p=e.opts.$data&&o&&o.$data;n=p?(a+=" var schema"+s+" = "+e.util.getData(o.$data,n,e.dataPathArr)+"; ","schema"+s):o;if(p||"number"==typeof o)return a+="if ( ",p&&(a+=" ("+n+" !== undefined && typeof "+n+" != 'number') || "),!1===e.opts.unicode?a+=" "+l+".length ":a+=" ucs2length("+l+") ",(s=[]).push(a+=" "+("maxLength"==(r=t)?">":"<")+" "+n+") { "),a="",!1!==e.createErrors?(a+=" { keyword: '"+(r||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+n+" } ",!1!==e.opts.messages&&(a=(a=(a+=" , message: 'should NOT be ")+("maxLength"==t?"longer":"shorter")+" than ")+(p?"' + "+n+" + '":""+o)+" characters' "),e.opts.verbose&&(a=(a+=" , schema: ")+(p?"validate.schema"+c:""+o)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),a+=" } "):a+=" {} ",r=a,a=s.pop(),!e.compositeRule&&h?e.async?a+=" throw new ValidationError(["+r+"]); ":a+=" validate.errors = ["+r+"]; return false; ":a+=" var err = "+r+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+="} ",h&&(a+=" else { "),a;throw new Error(t+" must be number")}},function(e,t,i){"use strict";e.exports=function(e,t,i){var r,a=" ",s=e.level,n=e.dataLevel,o=e.schema[t],c=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,h=!e.opts.allErrors,l="data"+(n||""),p=e.opts.$data&&o&&o.$data;n=p?(a+=" var schema"+s+" = "+e.util.getData(o.$data,n,e.dataPathArr)+"; ","schema"+s):o;if(p||"number"==typeof o)return a+="if ( ",p&&(a+=" ("+n+" !== undefined && typeof "+n+" != 'number') || "),(s=[]).push(a+=" Object.keys("+l+").length "+("maxProperties"==(r=t)?">":"<")+" "+n+") { "),a="",!1!==e.createErrors?(a+=" { keyword: '"+(r||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+n+" } ",!1!==e.opts.messages&&(a=(a=(a+=" , message: 'should NOT have ")+("maxProperties"==t?"more":"fewer")+" than ")+(p?"' + "+n+" + '":""+o)+" properties' "),e.opts.verbose&&(a=(a+=" , schema: ")+(p?"validate.schema"+c:""+o)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),a+=" } "):a+=" {} ",r=a,a=s.pop(),!e.compositeRule&&h?e.async?a+=" throw new ValidationError(["+r+"]); ":a+=" validate.errors = ["+r+"]; return false; ":a+=" var err = "+r+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+="} ",h&&(a+=" else { "),a;throw new Error(t+" must be number")}},function(e){e.exports=JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://json-schema.org/draft-07/schema#","title":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}},"type":["object","boolean"],"properties":{"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"$comment":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"default":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"propertyNames":{"format":"regex"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"contentMediaType":{"type":"string"},"contentEncoding":{"type":"string"},"if":{"$ref":"#"},"then":{"$ref":"#"},"else":{"$ref":"#"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"default":true}')},function(e,t,i){var r=i(8);e.exports=function(){return r.randomBytes(16)}},function(e,t){for(var i=[],r=0;r<256;++r)i[r]=(r+256).toString(16).substr(1);e.exports=function(e,t){t=t||0;var r=i;return[r[e[t++]],r[e[t++]],r[e[t++]],r[e[t++]],"-",r[e[t++]],r[e[t++]],"-",r[e[t++]],r[e[t++]],"-",r[e[t++]],r[e[t++]],"-",r[e[t++]],r[e[t++]],r[e[t++]],r[e[t++]],r[e[t++]],r[e[+t]]].join("")}},function(e,t,i){"use strict";
|
|
724
724
|
/*!
|
|
725
725
|
* wordlist.js - wordlists for vallnet
|
|
726
726
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -735,7 +735,7 @@ const r=i(5).ContractType;e.exports=function(e){if(!e)return i(188);switch(e.ope
|
|
|
735
735
|
* public.js - hd public keys for vallnet
|
|
736
736
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
737
737
|
* https://github.com/bookmansoft/gamegold
|
|
738
|
-
*/const r=i(0),a=i(2),s=i(6),n=i(94),o=i(26),c=i(15),u=i(4),h=i(1),l=i(69),p=i(3),d=i(
|
|
738
|
+
*/const r=i(0),a=i(2),s=i(6),n=i(94),o=i(26),c=i(15),u=i(4),h=i(1),l=i(69),p=i(3),d=i(139);class f{constructor(e){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,e&&this.fromOptions(e)}fromOptions(e){return r(e,"No options for HDPublicKey"),r(a.isU8(e.depth)),r(a.isU32(e.parentFingerPrint)),r(a.isU32(e.childIndex)),r(Buffer.isBuffer(e.chainCode)),r(Buffer.isBuffer(e.publicKey)),e.network&&(this.network=c.get(e.network)),this.depth=e.depth,this.parentFingerPrint=e.parentFingerPrint,this.childIndex=e.childIndex,this.chainCode=e.chainCode,this.publicKey=e.publicKey,this}static fromOptions(e){return(new f).fromOptions(e)}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,n(this.chainCode),n(this.publicKey),this.fingerPrint=-1,this._xpubkey=null}derive(e,t){if(r("number"==typeof e),e>>>0!==e)throw new Error("Index out of range.");if(e&d.HARDENED||t)throw new Error("Cannot derive hardened.");if(255<=this.depth)throw new Error("Depth too high.");t=this.getID(e);if(i=d.cache.get(t))return i;var i=((i=u.pool(37)).writeBytes(this.publicKey),i.writeU32BE(e),i.render()),a=(i=s.hmac("sha512",i,this.chainCode)).slice(0,32);i=i.slice(32,64);let n;try{n=o.publicKeyTweakAdd(this.publicKey,a,!0)}catch(t){return this.derive(e+1)}return-1===this.fingerPrint&&(a=s.hash160(this.publicKey),this.fingerPrint=a.readUInt32BE(0,!0)),(a=new f).network=this.network,a.depth=this.depth+1,a.parentFingerPrint=this.fingerPrint,a.childIndex=e,a.chainCode=i,a.publicKey=n,d.cache.set(t,a),a}getID(e){return this.network.keyPrefix.xpubkey58+this.publicKey.toString("hex")+e}deriveAccount(e,t){return r(a.isU32(e)),r(a.isU32(t)),r(this.isAccount(t),"Cannot derive account index."),this}isMaster(){return d.isMaster(this)}isAccount(e){return d.isAccount(this,e)}static isValidPath(e){try{return d.parsePath(e,!1),!0}catch(e){return!1}}derivePath(e){let t=this;for(const i of d.parsePath(e,!1))t=t.derive(i);return t}equals(e){return r(f.isHDPublicKey(e)),this.network===e.network&&this.depth===e.depth&&this.parentFingerPrint===e.parentFingerPrint&&this.childIndex===e.childIndex&&this.chainCode.equals(e.chainCode)&&this.publicKey.equals(e.publicKey)}compare(e){r(f.isHDPublicKey(e));var t=this.depth-e.depth;return 0!=t||0!=(t=this.parentFingerPrint-e.parentFingerPrint)||0!=(t=this.childIndex-e.childIndex)||0!==(t=this.chainCode.compare(e.chainCode))||0!==(t=this.publicKey.compare(e.publicKey))?t:0}toJSON(){return{xpubkey:this.xpubkey()}}fromJSON(e,t){return r(e.xpubkey,"Could not handle HD key JSON."),this.fromBase58(e.xpubkey,t),this}static fromJSON(e,t){return(new f).fromJSON(e,t)}static isBase58(e,t){if("string"!=typeof e)return!1;if(e.length<4)return!1;e=e.substring(0,4);try{return c.fromPublic58(e,t),!0}catch(e){return!1}}static isRaw(e,t){if(!Buffer.isBuffer(e))return!1;if(e.length<4)return!1;e=e.readUInt32BE(0,!0);try{return c.fromPublic(e,t),!0}catch(e){return!1}}fromBase58(e,t){return r("string"==typeof e),this._xpubkey=e,this.fromRaw(l.decode(e),t)}fromReader(e,t){var i=e.readU32BE();return this.network=c.fromPublic(i,t),this.depth=e.readU8(),this.parentFingerPrint=e.readU32BE(),this.childIndex=e.readU32BE(),this.chainCode=e.readBytes(32),this.publicKey=e.readBytes(33),e.verifyChecksum(),this}fromRaw(e,t){return this.fromReader(new h(e),t)}toBase58(e){return l.encode(this.toRaw(e))}toWriter(e,t){return t=t||this.network,t=c.get(t),e.writeU32BE(t.keyPrefix.xpubkey),e.writeU8(this.depth),e.writeU32BE(this.parentFingerPrint),e.writeU32BE(this.childIndex),e.writeBytes(this.chainCode),e.writeBytes(this.publicKey),e.writeChecksum(),e}getSize(){return 82}toRaw(e){return this.toWriter(new u(82),e).render()}static fromBase58(e,t){return(new f).fromBase58(e,t)}static fromReader(e,t){return(new f).fromReader(e,t)}static fromRaw(e,t){return(new f).fromRaw(e,t)}static isHDPublicKey(e){return e instanceof f}}e.exports=f},function(e,t,i){"use strict";
|
|
739
739
|
/*!
|
|
740
740
|
* siphash.js - siphash for vallnet
|
|
741
741
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -766,7 +766,7 @@ const r=i(5).ContractType;e.exports=function(e){if(!e)return i(188);switch(e.ope
|
|
|
766
766
|
/*!
|
|
767
767
|
* CoinSelector.js
|
|
768
768
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
769
|
-
*/const r=i(0),a=i(2),s=i(
|
|
769
|
+
*/const r=i(0),a=i(2),s=i(142);i(20);const n=i(28);i(54);const o=i(13),c=i(3),u=i(7),h=i(29);i(33);const l=i(587);class p{constructor(e,t){this.tx=e.clone(),this.coins=[],this.outputValue=0,this.index=0,this.chosen=[],this.change=0,this.fee=p.MIN_FEE,this.selection="value",this.subtractFee=!1,this.subtractIndex=null,this.height=-1,this.depth=-1,this.hardFee=-1,this.rate=p.FEE_RATE,this.maxFee=-1,this.round=!1,this.changeAddress=null,this.estimate=null,this.network=s.testnet,t&&this.fromOptions(t)}fromOptions(e){if(e.selection&&(r("string"==typeof e.selection),this.selection=e.selection),null!=e.subtractFee&&(r("boolean"==typeof e.subtractFee),this.subtractFee=e.subtractFee),null!=e.subtractIndex){let i=null;if(0<(i="number"==typeof e.subtractIndex?[e.subtractIndex]:(r(Array.isArray(e.subtractIndex)),e.subtractIndex)).length){var t=new Set;for(const e of i)r(a.isU32(e)),r(e<this.tx.outputs.length),t.add(e);this.subtractIndex=t,this.subtractFee=!0}}var i;return null!=e.height&&(r(a.isInt(e.height)),r(-1<=e.height),this.height=e.height),null!=e.confirmations&&(r(a.isInt(e.confirmations)),r(-1<=e.confirmations),this.depth=e.confirmations),null!=e.depth&&(r(a.isInt(e.depth)),r(-1<=e.depth),this.depth=e.depth),null!=e.hardFee&&(r(a.isInt(e.hardFee)),r(-1<=e.hardFee),this.hardFee=e.hardFee),null!=e.rate&&(r(a.isU64(e.rate)),this.rate=e.rate),null!=e.maxFee&&(r(a.isInt(e.maxFee)),r(-1<=e.maxFee),this.maxFee=e.maxFee),null!=e.round&&(r("boolean"==typeof e.round),this.round=e.round),e.changeAddress&&("string"==typeof(i=e.changeAddress)?this.changeAddress=o.fromString(i):(r(i instanceof o),this.changeAddress=i)),e.estimate&&(r("function"==typeof e.estimate),this.estimate=e.estimate),this.allowPreInput=e.allowPreInput||!1,e.network&&(this.network=e.network),this}init(e){switch(this.coins=e.slice(),this.outputValue=this.tx.getOutputValue(),this.index=0,this.chosen=[],this.change=0,this.fee=p.MIN_FEE,this.cltvTime=null,this.allowPreInput||(this.tx.inputs.length=0),this.selection){case"all":case"random":this.coins.sort(f);break;case"age":this.coins.sort(m);break;case"value":this.coins.sort(d);break;default:throw new l(`Bad selection type: ${this.selection}.`)}}total(){return this.subtractFee?this.outputValue:this.outputValue+this.fee}isFull(){return this.tx.getInputValue()>=this.total()}isSpendable(e){return!(-1!==this.height&&(e.coinbase?-1===e.height||0<e.height&&this.height<e.height+u.COINBASE_MATURITY:e.isColored||e.lockedByLocktime(this.height,this.network.now())||e.lockedBySequence(this.height,this.network.now())||-1!==this.depth&&e.getDepth(this.height)<this.depth))}getFee(e){let t=0;return t=this.round?h.getRoundFee(e,this.rate):h.getMinFee(e,this.rate),Math.min(t,p.MAX_FEE)}fund(){if(!this.isFull())for(;this.index<this.coins.length;){var e=this.coins[this.index++];if(this.isSpendable(e)){var t=e.getLocktime();if(!(0<t&&(null==this.cltvTime&&(this.cltvTime=t>u.LOCKTIME_THRESHOLD),this.cltvTime!==t>u.LOCKTIME_THRESHOLD))&&((t=e.getSequence())&u.SEQUENCE_DISABLE_FLAG||(null==this.cltvTime&&(this.cltvTime=t&u.SEQUENCE_TYPE_FLAG),this.cltvTime===(t&u.SEQUENCE_TYPE_FLAG)))&&(this.tx.addCoin(e),this.chosen.push(e),"all"!==this.selection)&&this.isFull())break}}}async select(e){if(this.init(e),-1!==this.hardFee?this.selectHard():await this.selectEstimate(),this.isFull())return this.change=this.tx.getInputValue()-this.total(),this;throw new l("Not enough funds.",this.tx.getInputValue(),this.total())}async selectEstimate(){this.fee=p.MIN_FEE,this.fund();var e=new n;this.changeAddress?e.script.fromAddress(this.changeAddress):e.script.createScript(c.ZERO_HASH160),this.tx.outputs.push(e);do{var t=await this.tx.estimateSize(this.estimate);if(this.fee=this.getFee(t),0<this.maxFee&&this.fee>this.maxFee)throw new l("Fee is too high.")}while(this.isFull()||this.fund(),!this.isFull()&&this.index<this.coins.length)}selectHard(){this.fee=Math.min(this.hardFee,p.MAX_FEE),this.fund()}}function d(e,t){return-1===e.height&&-1!==t.height?1:-1!==e.height&&-1===t.height?-1:t.value-e.value}function f(e,t){return.5<Math.random()?1:-1}function m(e,t){return(e=-1===e.height?2147483647:e.height)-(-1===t.height?2147483647:t.height)}p.FEE_RATE=1e4,p.MIN_FEE=1e4,p.MAX_FEE=u.COIN/10,e.exports=p},function(e,t,i){"use strict";
|
|
770
770
|
/*!
|
|
771
771
|
* mine.js - mining function for vallnet
|
|
772
772
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -781,10 +781,10 @@ const r=i(5).ContractType;e.exports=function(e){if(!e)return i(188);switch(e.ope
|
|
|
781
781
|
* CheckResultPacket.js - worker packets for vallnet
|
|
782
782
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
783
783
|
* https://github.com/bookmansoft/gamegold
|
|
784
|
-
*/const r=i(1),a=i(3),s=i(112);var n=i(21);const o=i(18);class c extends n{constructor(e){super(),this.error=e||null,this.cmd=o.CHECKRESULT}getSize(){var e=this.error;let t=0;return e?t=(t=(t=(t=(t+=1)+a.sizeVarString(u(e.message),"utf8"))+a.sizeVarString(u(e.stack),"utf8"))+a.sizeVarString(u(e.code),"utf8"))+1+4:t+=1}toWriter(e){var t=this.error;return t?(e.writeU8(1),e.writeVarString(u(t.message),"utf8"),e.writeVarString(u(t.stack),"utf8"),e.writeVarString(u(t.code),"utf8"),e.writeU8(-1===t.op?255:t.op),e.writeU32(-1===t.ip?4294967295:t.ip)):e.writeU8(0),e}fromRaw(e){var t;return 0!==(e=new r(e,!0)).readU8()&&((t=new s("")).message=e.readVarString("utf8"),t.stack=e.readVarString("utf8"),t.code=e.readVarString("utf8"),t.op=e.readU8(),t.ip=e.readU32(),255===t.op&&(t.op=-1),4294967295===t.ip&&(t.ip=-1),this.error=t),this}static fromRaw(e){return(new c).fromRaw(e)}}function u(e){return"string"!=typeof e?"":e}e.exports=c},function(e,t,i){const r=i(
|
|
784
|
+
*/const r=i(1),a=i(3),s=i(112);var n=i(21);const o=i(18);class c extends n{constructor(e){super(),this.error=e||null,this.cmd=o.CHECKRESULT}getSize(){var e=this.error;let t=0;return e?t=(t=(t=(t=(t+=1)+a.sizeVarString(u(e.message),"utf8"))+a.sizeVarString(u(e.stack),"utf8"))+a.sizeVarString(u(e.code),"utf8"))+1+4:t+=1}toWriter(e){var t=this.error;return t?(e.writeU8(1),e.writeVarString(u(t.message),"utf8"),e.writeVarString(u(t.stack),"utf8"),e.writeVarString(u(t.code),"utf8"),e.writeU8(-1===t.op?255:t.op),e.writeU32(-1===t.ip?4294967295:t.ip)):e.writeU8(0),e}fromRaw(e){var t;return 0!==(e=new r(e,!0)).readU8()&&((t=new s("")).message=e.readVarString("utf8"),t.stack=e.readVarString("utf8"),t.code=e.readVarString("utf8"),t.op=e.readU8(),t.ip=e.readU32(),255===t.op&&(t.op=-1),4294967295===t.ip&&(t.ip=-1),this.error=t),this}static fromRaw(e){return(new c).fromRaw(e)}}function u(e){return"string"!=typeof e?"":e}e.exports=c},function(e,t,i){const r=i(141),a=i(5).ContractType;var s=i(31);const n=i(4),o=i(1),c=i(3);i(22);class u extends s{constructor(e){super(),this.cpNameMap=new Map,this.cpIndexMap=new Map,this.env=e}async loadHistory(){var e;for(e of await this.env.getCps())this.set(e.cid,e),this.cpNameMap.set(e.name,e),this.cpIndexMap.set(r(e.cid),e)}async addItem(e){var t=new h(e);(e=(this.set(t.cid,t),this.getItem(e.cid)))&&this.removeNameIndex(e.name),this.cpNameMap.set(t.name,t),this.cpIndexMap.set(r(t.cid),t),await this.env.setCp(t)}async delItem(e){await this.env.delCp(e.cid),this.cpIndexMap.delete(r(e.cid)),this.removeNameIndex(e.name),this.delete(e.cid)}getItem(e){return this.has(e)?this.get(e):null}getItemByName(e){return this.cpNameMap.get(e)}getRecord(e){return(e=this.get(e))||null}removeNameIndex(e){this.cpNameMap.delete(e)}async canExecute(e){switch(e.oper){case a.cpRegister:if(this.cpIndexMap.has(r(e.cid))||this.has(e.cid)||this.cpNameMap.has(e.name))break;return!0;case a.cpChange:var t=this.getItem(e.cid),i=this.cpNameMap.get(e.name);if(t)return!i||i.cid===e.cid}return!1}getCPList(e,t){let i=[];return 0<e.length?(i=this.where([["cid","include",e]]).paginate(50,1).records(),t.pageCount=this.pageNum):(t.pageSize=t.pageSize||10,i=(e=t.cls?this.where([["cls",t.cls]]):this).paginate(t.pageSize,t.page).records(),t.pageCount=e.pageNum),t.page=Math.min(t.page,t.pageCount),i}getCPListByName(e,t){let i=[];return i=(0<e.length?this.where([["name","include",e]]).paginate(50,1):this.paginate(10,page)).records(),t.pageCount=this.pageNum,t.page=Math.min(t.page,t.pageCount),i}}class h{constructor(e){this.cid=(e=e||{}).cid,this.name=e.name,this.ip=e.ip||"",this.cls=e.cls||"",this.grate=e.grate||0,this.current={hash:"",index:0,address:""},e.current&&(this.current.hash=e.current.hash,this.current.index=e.current.index,this.current.address=e.current.address),this.pubAddress=e.pubAddress||"",this.pubKey=e.pubKey||"",this.signMethod=e.signMethod||"secp256k1",this.register=e.register||"",this.stock=e.stock||{hHeight:0,hSum:0,hPrice:0,hBonus:0,hAds:0,sum:0,price:0,height:0},this.height=e.height,this.status=e.status||0}getSize(){var e=0;return(e+=c.sizeVarString(this.cid,"utf8"))+c.sizeVarString(this.name,"utf8")+c.sizeVarString(this.ip,"utf8")+c.sizeVarString(this.cls,"utf8")+4+c.sizeVarString(this.current.hash,"utf8")+4+c.sizeVarString(this.current.address,"utf8")+c.sizeVarString(this.pubAddress,"utf8")+c.sizeVarString(this.pubKey,"utf8")+c.sizeVarString(this.signMethod,"utf8")+c.sizeVarString(this.register,"hex")+4+4+4+8+8+4+4+4+4+4}toWriter(e){return e.writeVarString(this.cid,"utf8"),e.writeVarString(this.name,"utf8"),e.writeVarString(this.ip,"utf8"),e.writeVarString(this.cls,"utf8"),e.writeU32(this.grate),this.current||(this.current={hash:"",index:0,address:""}),e.writeVarString(this.current.hash,"utf8"),e.writeU32(this.current.index),e.writeVarString(this.current.address,"utf8"),e.writeVarString(this.pubAddress,"utf8"),e.writeVarString(this.pubKey,"utf8"),e.writeVarString(this.signMethod,"utf8"),e.writeVarString(this.register,"hex"),e.writeU32(this.stock.hHeight),e.writeU32(this.stock.hSum),e.writeU32(this.stock.hPrice),e.writeU64(this.stock.hBonus),e.writeU64(this.stock.hAds),e.writeU32(this.stock.sum),e.writeU32(this.stock.price),e.writeU32(this.stock.height),e.writeI32(this.height),e.writeI32(this.status),e}toRaw(){var e=this.getSize();return this.toWriter(new n(e)).render()}fromReader(e){return this.cid=e.readVarString("utf8"),this.name=e.readVarString("utf8"),this.ip=e.readVarString("utf8"),this.cls=e.readVarString("utf8"),this.grate=e.readU32(),this.current={},this.current.hash=e.readVarString("utf8"),this.current.index=e.readU32(),this.current.address=e.readVarString("utf8"),this.pubAddress=e.readVarString("utf8"),this.pubKey=e.readVarString("utf8"),this.signMethod=e.readVarString("utf8"),this.register=e.readVarString("hex"),this.stock={},this.stock.hHeight=e.readU32(),this.stock.hSum=e.readU32(),this.stock.hPrice=e.readU32(),this.stock.hBonus=e.readU64(),this.stock.hAds=e.readU64(),this.stock.sum=e.readU32(),this.stock.price=e.readU32(),this.stock.height=e.readU32(),this.height=e.readI32(),this.status=e.readI32(),this}fromRaw(e){return this.fromReader(new o(e))}clone(){return h.fromRaw(this.toRaw())}static fromReader(e){return(new h).fromReader(e)}static fromRaw(e){return(new h).fromRaw(e)}}u.cpItem=h,e.exports=u},,,,,,,function(e,t){e.exports=class e{constructor(e){this.indicate=e||0}get value(){return this.indicate}set(e){return this.indicate=this.indicate|e,this}unSet(e){return this.indicate=this.indicate&~e,this}check(e){return!!this.indicate&&(this.indicate&e)==e}static inst(t){return new e(t)}}},function(e,t,i){"use strict";
|
|
785
785
|
/*!
|
|
786
786
|
* coins.js - coins object
|
|
787
|
-
*/const r=i(0),a=i(
|
|
787
|
+
*/const r=i(0),a=i(145);e.exports=class e{constructor(){this.outputs=new Map}clone(){var t,i,r=new e;for([t,i]of this.outputs)r.outputs.set(t,a.fromRaw(i.toRaw()));return r}add(e,t){return r(e>>>0===e),r(t),this.outputs.set(e,t),t}addOutput(e,t){return this.add(e,a.fromOutput(t))}addCoin(e){return this.add(e.index,a.fromCoin(e))}has(e){return this.outputs.has(e)}isUnspent(e){return!(!(e=this.outputs.get(e))||e.spent)}get(e){return this.outputs.get(e)||null}getOutput(e){return(e=this.outputs.get(e))?e.output:null}getCoin(e){var t=this.outputs.get(e.index);return t?t.toCoin(e):null}spend(e){return!(e=this.get(e))||e.spent?null:(e.spent=!0,e)}remove(e){var t=this.get(e);return t?(this.outputs.delete(e),t):null}isEmpty(){return 0===this.outputs.size}fromTX(e,t,i){r("number"==typeof t),r("number"==typeof i);for(let r=0;r<e.outputs.length;r++){var s;e.outputs[r].script.isUnspendable()||(s=a.fromTX(e,r,t,i),this.outputs.set(r,s))}return this}static fromTX(t,i,r){return(new e).fromTX(t,i,r)}}},function(e,t,i){"use strict";
|
|
788
788
|
/*!
|
|
789
789
|
* compress.js - coin compressor for vallnet
|
|
790
790
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -830,7 +830,7 @@ const r=i(5).ContractType;e.exports=function(e){if(!e)return i(188);switch(e.ope
|
|
|
830
830
|
/*!
|
|
831
831
|
* accountdb.js - storage for account management
|
|
832
832
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
833
|
-
*/const r=i(8),a=i(0),s=i(73),n=i(119),o=i(157),c=i(609),u=i(85),h=u.walletdb,l=i(6),p=i(158),d=i(125),f=i(167);var{}=i(37);const m=i(46),g=i(13);i(20),i(68);const v=i(197),y=i(67),b=i(42),{BlockFinalType:w,ContractEnvType:x}=i(5),k=i(159),S=i(611),_=i(31);var E=i(71);const j=i(2),A=i(141).sortWithSeq,R=i(35),I=i(198),O=i(63),C=i(100),P=i(3),T=P.U32,B=i(338),N=i(339),z=i(340),F=z.vpItem,L=i(616),M=L.vpItem,D=i(314);i(617);const H=D.cpItem,U=i(154),q=U.ErAbolishItem,V=i(44).broadcast,K=i(132),W=K.vpItem,$=i(153),Y=$.ErItem,G=i(618),X=G.AuditItem,J=i(307),Q=i(109),Z=i(619),ee=i(308),te=i(120),ie=i(620),re=i(218),ae=i(38),se=i(36),ne=i(59),oe=i(78),ce=oe.errors,ue=i(77);class he extends E{constructor(e){super(),this.readyLoad=!1,this.options=new c(e),this.network=this.options.network,this.logger=this.options.logger.context("wallet"),this.workers=this.options.workers,this.keys={hmacSalt:P.DefaultChainCode},e.keys&&e.keys.hmacSalt&&(a(Buffer.isBuffer(e.keys.hmacSalt)),this.keys.hmacSalt=e.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 B(this),this.primary=null,this.state=new Z,this.wallets=new Map,this.depth=0,this.rescanning=!1,this.bound=!1,this.newRecord=!0,this.readLock=new I,this.writeLock=new R,this.txLock=new R,this.scanLock=new R,this.widCache=new O(1e4),this.pathMapCache=new O(1e5),this.filter=new C,this.middleHashMem=new Set,this.middleHashChain=new Set,this.autoTaskMgr=new k(this),this.transactionList=new N(this),this.htlcList=new z(this),this.commentList=new L(this),this.NotifyList=new _,this.propList=new K(this),this.$contacts=new _,this.cpList=new D(this),this.cpMemList=new D(this),this.auditList=new G(this),this.erList=new $(this),this.erAbList=new U(this),this.hmacConnection=[],this._init()}async logAudit(e){e.height=this.curHeight,e.time=j.now(),e.erid=l.sha256(j.stringify(e)).toString("hex"),e=new X(e),await this.auditList.setAudit(e)}async getAccountByAddress(e,t){if(e){let a=null;if(a=t?await this.getWalletsByTX(t):await this.getWallets())for(const t of a){var i=await this.get(t);if(i){var r=await i.getPath(e);if(r)return[i.wid,r.name,i.id]}}}return[0,"",""]}_init(){let e=1e6,t=-1;this.spv&&(e=2e4,t=C.flags.ALL),this.filter=C.fromRate(e,.001,t)}get mode(){return x.Wallet}async getTXFromAll(e){return this.getTXFromDb(e)}async checkNewRecord(){var e={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 t=await this.db.checkVersion(h,6);this.newRecord="new"==t}catch(e){if(-1!=e.message.indexOf("does not exist (create_if_missing is false)"))this.newRecord=!0;else{if(-1==e.message.indexOf("exists (error_if_exists is true)"))throw e;this.newRecord=!1}}try{await this.db.close()}catch(e){}this.db.options.createIfMissing=e.createIfMissing,this.db.options.errorIfExists=e.errorIfExists}async isNewRecord(){return await this.checkNewRecord(),this.newRecord}setmnemonic(e){if(this.options.mnemonic=this.options.mnemonic||{},e.bits)this.options.mnemonic={bits:e.bits};else if(e.entropy)this.options.mnemonic={entropy:Buffer.from(e.entropy,"hex")};else if(e.phrase){var t=this.testmnemonic(e.phrase);if(0!=t.code)throw t.msg;this.options.mnemonic={phrase:e.phrase}}e.passphrase&&(this.options.mnemonic.passphrase=e.passphrase),e.language&&(this.options.mnemonic.language=e.language)}testmnemonic(e){try{return new v(e),{code:0}}catch(e){return{code:-1,msg:e.message}}}async getContracts(e){var t=await this.db.values({gte:u.txdb.tx(P.NULL_HASH),lte:u.txdb.tx(P.HIGH_HASH),parse:e=>j.parseJson(e.toString())});return e?t.filter(t=>t.srcact==e||t.dstact==e):t}isFull(){return this.spv||this.synced||!1}async _open(e){}async handleNotify(e,t=!1){if(!t){let i=e.body.content;if("string"==typeof i)try{i=JSON.parse(e.body.content)}catch(e){return}"object"==typeof i&&"secret"===i.type&&(t={contact:e.body.src,messenger:e.body.dst},i.init&&(t.init=Buffer.from(i.init,"hex")),i.packet&&(t.packet=Buffer.from(i.packet)),await this.handleSecret(t))}}async handleSecret(e){if(e.contact&&e.messenger&&e.contact!=e.messenger){try{g.fromString(e.contact,this.network.type),g.fromString(e.messenger,this.network.type)}catch(e){return}var t=await this.ensureContact(e);t&&await t.ensureMessenger(e).answer(e)}}async scanContact(e,t=-1){var i=async e=>{var t;e.witness&&"witnesspubkeyhash"==e.getType()&&(t=e.witness.getPubkeyhashInput()[1],e=g.fromWitness(e.witness).toString(),t)&&e&&await this.ensureContact({contact:e,publicKey:t})};if(0<=t&&t<e.inputs.length)await i(e.inputs[t]);else for(var r of e.inputs)await i(r)}async ensureContact(e){if(!e.contact||e.contact==e.messenger)return null;try{g.fromString(e.contact,this.network.type),e.messenger&&g.fromString(e.messenger,this.network.type)}catch(e){return null}e.network=this.network.type,this.$contacts.get(e.contact)||this.$contacts.set(e.contact,new S(e));var t=this.$contacts.get(e.contact);if(e.messenger&&!(e=t.ensureMessenger(e)).wallet){var i,[i,r]=await this.getAccountByAddress(e.address);if(!(i=await this.get(i)))return;e.wallet=i,e.account=r}return t}getCps(){return this.db.values({gte:u.txdb.cp(P.ZERO_CID,"hex"),lte:u.txdb.cp(P.MAX_CID,"hex"),parse:e=>H.fromRaw(e)})}async _close(){await this.disconnect(),this.http&&this.options.listen&&await this.http.close();for(const e of this.wallets.values())await e.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(e){if(this.readyLoad){var t=await this.ensure({id:"primary",witness:!0,mnemonic:this.options.mnemonic}),i=await this.txLock.lock();try{await this.init(e),await this.watch(),await t.createReceive(0,1,t.master,this.network.type),await t.ensureNotifyKey(),await this.sync()}finally{i()}setTimeout(()=>{this.resend()},5e3)}}async disconnect(){this.client&&await this.client._close(),this.jsonp&&await this.jsonp._close()}async flushCP(e,t=!1){this.client&&(e=e||[],t||(e=this.cpList.excludeCids(e),t=t||0<e.length),t)&&await this.client.execute("cp.remoteQuery",[[["cid","include",e]]])}async watch(){let e=this.db.iterator({gte:h.p(P.NULL_HASH),lte:h.p(P.HIGH_HASH)}),t=0,i=0;for(;;){var r=await e.next();if(!r)break;try{var a=h.pp(r.key);this.addHash(a,!1)}catch(t){throw await e.end(),t}t++}for(e=this.db.iterator({gte:h.o(P.NULL_HASH,0),lte:h.o(P.HIGH_HASH,4294967295)});;){var s=await e.next();if(!s)break;try{var[n,o]=h.oo(s.key);this.addOutpoint(n,o)}catch(t){throw await e.end(),t}i++}this.logger.info("Filter: Added %d hashes to AccountDB filter.",t),this.logger.info("Filter: Added %d outpoints to AccountDB filter.",i),await this.setFilter()}async sync(){if(this.client){let t,i=this.curHeight;for(;0<=i;){var e=await this.getBlock(i);if(!e)break;if(t=await this.client.getEntry(e.hash))break;i--}t||(i=this.state.startHeight,t=await this.client.getEntry(this.state.startHash))||(i=0),await this.cpList.loadHistory(),await this.cpMemList.loadHistory(),await this.propList.loadHistory(),await this.htlcList.loadHistory(),await this.commentList.loadHistory(),await this.transactionList.loadHistory(),await this.loadContact(),await this.erList.loadHistory(),await this.auditList.loadHistory(),await this.erAbList.loadHistory(),await this._rescan(i,!1)}}async _rescan(e,t=!0){if(this.client){null==e&&(e=this.state.startHeight),a(e>>>0===e,"WDB: Must pass in a height.");var i=this.curHeight;t=(await this.rollback(e,t),this.logger.info("AccountDB is scanning %d blocks.",i-e+1),await this.getTip());try{this.rescanning=!0,await this.client.rescan(t.hash,this.eid)}finally{this.rescanning=!1}}}async rescan(e){var t=await this.txLock.lock();try{return await this._rescan(e,!1)}finally{t()}}async send(e){return this.client?this.client.send(e):(this.emit("send",e),Promise.resolve())}async getTX(e){for(const i of this.wallets.values()){var t=await i.getTX(e);if(t)return t.tx}return null}async getTXFromDb(e){for(const i of this.wallets.values()){var t=await i.getTX(e);if(t)return t.tx}return null}async getExtendTX(e){for(const i of this.wallets.values()){var t=await i.getTX(e);if(t)return t}return null}async removeTX(e){this.client?await this.client.removeTX(e):this.emit("remove",e)}async estimateFee(e){return 0<this.feeRate?this.feeRate:!this.client||(e=await this.client.estimateFee(e))<this.network.feeRate?this.network.feeRate:e>this.network.maxFeeRate?this.network.maxFeeRate:e}setFilter(){return this.client?this.client.setFilter(this.filter):(this.emit("filter.set",this.filter),Promise.resolve())}resetFilter(){return this.client?this.client.resetFilter():(this.emit("filter.reset"),Promise.resolve())}backup(e){return this.db.backup(e)}async wipe(){this.logger.warning("Wiping AccountDB TXDB..."),this.logger.warning("I hope you know what you're doing.");var e=this.db.iterator({gte:Buffer.from([0]),lte:Buffer.from([255])}),t=this.db.batch();let i=0;for(;;){var r=await e.next();if(!r)break;try{switch(r.key[0]){case 98:case 99:case 101:case 116:case 111:case 104:case 82:t.del(r.key),i++}}catch(t){throw await e.end(),t}}this.logger.warning("Wiped %d txdb records.",i),await t.write()}async getDepth(){var e=this.db.iterator({gte:h.w(0),lte:h.w(4294967295),reverse:!0,limit:1}),t=await e.next();return t?(await e.end(),h.ww(t.key)+1):1}start(e){return a(!e.current,"WDB: Batch already started."),e.current=this.db.batch(),e.accountCache.start(),e.pathCache.start(),e.current}drop(e){var t=this.batch(e);e.current=null,e.accountCache.drop(),e.pathCache.drop(),t.clear()}clear(e){var t=this.batch(e);e.accountCache.clear(),e.pathCache.clear(),t.clear()}batch(e){return a(e.current,"WDB: Batch does not exist."),e.current}async commit(e){var t=this.batch(e);try{await t.write()}catch(e){throw this.drop(),e}e.current=null,e.accountCache.commit(),e.pathCache.commit()}testFilter(e){return this.filter.test(e,"hex")}addHash(e,t=!0){this.filter.add(e,"hex"),t&&(t=Buffer.from(e,"hex"),this.client?this.client.addFilter(t):this.emit("filter.add",t))}addOutpoint(e,t){e=new m(e,t),this.filter.add(e.toRaw())}dump(){return this.db.dump()}register(e){a(!this.wallets.has(e.wid)),this.wallets.set(e.wid,e)}unregister(e){a(this.wallets.has(e.wid)),this.wallets.delete(e.wid)}async getWalletID(e){var t;return e?"number"==typeof e?e:this.widCache.get(e)||((t=await this.db.get(h.l(e)))?(t=t.readUInt32LE(0,!0),this.widCache.set(e,t),t):null):null}async get(e){if(!(e=await this.getWalletID(e)))return null;var t=await this.readLock.lock(e);try{return await this._get(e)}finally{t()}}async _get(e){var t=this.wallets.get(e);return t||((t=await this.db.get(h.w(e)))?(await(e=n.fromRaw(this,t)).open(),this.register(e),e):null)}async loadBackup(e){if(ne.unsupported)throw new ue(ce.INTERNAL_ERROR,"FS not available.");let t=null;var i;for(i of(await ne.readFile(e,"utf8")).split(/\n+/))if(0!==(i=i.trim()).length&&!/^\s*#/.test(i)){var r=i.split(/\s+/);if(r.length<4)throw new ue(ce.DESERIALIZATION_ERROR,"Malformed wallet Data File.");switch(r[0]){case"W":var s=Buffer.from(r[1],"base64");s=n.fromRaw(this,s);await this.replace(s),t=await this.get(s.id),this.logger.info("Import Wallet %s(%s)",t.id,t.wid);break;case"C":s=Buffer.from(r[1],"base64");(c=((u=o.fromRaw(this,s)).wallet=t,u.wid=t.wid,u.id=t.id,u.initialized=!0,u.watchOnly=t.watchOnly,u.receive=u.deriveReceive(u.receiveDepth-1),u.change=u.deriveChange(u.changeDepth-1),u.witness&&(u.nested=u.deriveNested(u.nestedDepth-1)),t.master.key.deriveAccount(44,u.accountIndex))).publicKey.toString("hex")!==u.accountKey.publicKey.toString("hex")&&a(c.publicKey.toString("hex")==u.accountKey.publicKey.toString("hex")),await t.saveAccount(u),this.logger.info("Import Account %s(%s)",u.name,u.accountIndex);break;case"A":var c=oe.parseSecret(r[1],this.network),u=parseInt(r[5]),h=parseInt(r[7]),l=parseInt(r[9]),p=r[11].trim();if(h<0||l<0)try{await t.importKey(u,c)}catch(e){this.logger.error(`loadBackup: ${e.message} account/secret: ${u}/`+p)}else{var d=await t.deriveKey(u,h,l),f=await t.deriveKey(u,h,l,t.master);d.getAddress("string")!==f.getAddress("string")&&this.logger.error(`loadBackup: not-equal-1: ${d.getAddress("string")} != `+f.getAddress("string")),d.getAddress("string")!==p&&this.logger.error(`loadBackup: not-equal-2: ${d.getAddress("string")} != `+p)}this.logger.info("Import Address %s %s %s %s",u,h,l,p)}}return t.accountCache.reset(),t}save(e){var t=e.wid,i=e.id,r=this.batch(e);this.widCache.set(i,t),r.put(h.w(t),e.toRaw()),r.put(h.l(i),T(t))}async rename(e,t){var i=await this.writeLock.lock();try{return await this._rename(e,t)}finally{i()}}async _rename(e,t){var i=e.id;if(!s.isName(t))throw new Error("WDB: Bad wallet ID.");if(await this.has(t))throw new Error("WDB: ID not available.");this.start(e).del(h.l(i)),e.id=t,this.save(e),await this.commit(e),this.widCache.remove(i),i=e.pathCache.values();for(const e of i)e.id=t}async replace(e){var t=await this.writeLock.lock();try{return await this._replace(e)}finally{t()}}async _replace(e){var t=this.start(e);t.del(h.l(e.id)),t.del(h.w(e.wid)),this.save(e),await this.commit(e),this.widCache.remove(e.id),this.wallets.delete(e.wid)}renameAccount(e,t){var i=e.wallet;this.batch(i).del(h.i(e.wid,e.name)),e.name=t,this.saveAccount(e)}async auth(e,t){if("string"==typeof t){if(!j.isHex256(t))throw new Error("WDB Authentication: Invalid Token.");t=Buffer.from(t,"hex")}e=y.getHmac(e.toString(),this.keys.hmacSalt);var i=r.createHmac("sha256",e.random);i=Buffer.from(i.update(e.token).digest("hex"),"hex");if(!p(t,i))throw new Error("WDB Authentication: CRC Error.")}async create(e){var t=await this.writeLock.lock();e=e||{};try{return await this._create(e)}finally{t()}}async _create(e){if(await this.has(e.id))throw new Error("WDB: Wallet already exists.");"string"==typeof e.mnemonic&&(e.mnemonic={phrase:e.mnemonic}),e.mnemonic=e.mnemonic||{},!e.mnemonic.language&&this.options.mnemonic&&this.options.mnemonic.language&&(e.mnemonic.language=this.options.mnemonic.language);var t=n.fromOptions(this,e);return t.wid=this.depth++,await t.init(e),this.register(t),this.logger.info("Created wallet %s in AccountDB.",t.id),t}async has(e){return null!=await this.getWalletID(e)}async ensure(e){return await this.get(e.id)||this.create(e)}async getAccount(e,t){return(e=await this.db.get(h.a(e,t)))?o.fromRaw(this,e):null}getAccounts(e){return this.db.values({gte:h.n(e,0),lte:h.n(e,4294967295),parse:e=>e.toString("ascii")})}async getAccountMap(e){for(var t={},i=this.db.iterator({gte:h.n(e,0),lte:h.n(e,4294967295),values:!0});;){var r=await i.next();if(!r)break;try{var[,a]=h.nn(r.key);t[a]=r.value.toString("ascii")}catch(e){throw await i.end(),e}}return t}async getAccountIndex(e,t){return(e=await this.db.get(h.i(e,t)))?e.readUInt32LE(0,!0):-1}async getAccountName(e,t){return(e=await this.db.get(h.n(e,t)))?e.toString("ascii"):null}saveAccount(e){var t=e.wid,i=e.wallet,r=e.accountIndex,a=e.name,s=this.batch(i);s.put(h.a(t,r),e.toRaw()),s.put(h.i(t,a),T(r)),s.put(h.n(t,r),Buffer.from(a,"ascii")),i.accountCache.push(r,e)}hasAccount(e,t){return"number"==typeof e&&"number"==typeof t&&this.db.has(h.a(e,t))}async getPathMap(e){var t=this.pathMapCache.get(e);return t||((t=await this.db.get(h.p(e)))?(t=ie.fromRaw(e,t),this.pathMapCache.set(e,t),t):null)}saveKey(e,t){return this.savePath(e,t.toPath())}async savePath(e,t){var i=e.wid,r=t.hash,a=this.batch(e);this.addHash(r);let s=await this.getPathMap(r);(s=s||new ie(r)).add(i)&&(this.pathMapCache.set(r,s),e.pathCache.push(r,t),a.put(h.p(r),s.toRaw()),a.put(h.P(i,r),t.toRaw()),a.put(h.r(i,t.account,r),null))}async getPath(e,t){var i=await this.db.get(h.P(e,t));return i?((i=Q.fromRaw(i)).wid=e,i.hash=t,i):null}hasPath(e,t){return this.db.has(h.P(e,t))}getHashes(){return this.db.keys({gte:h.p(P.NULL_HASH),lte:h.p(P.HIGH_HASH),parse:h.pp})}getOutpoints(){return this.db.keys({gte:h.o(P.NULL_HASH,0),lte:h.o(P.HIGH_HASH,4294967295),parse:e=>{var[e,t]=h.oo(e);return new m(e,t)}})}getWalletHashes(e){return this.db.keys({gte:h.P(e,P.NULL_HASH),lte:h.P(e,P.HIGH_HASH),parse:h.Pp})}getAccountHashes(e,t){return this.db.keys({gte:h.r(e,t,P.NULL_HASH),lte:h.r(e,t,P.HIGH_HASH),parse:h.rr})}async getWalletPaths(e){var t=[];for(const a of await this.db.range({gte:h.P(e,P.NULL_HASH),lte:h.P(e,P.HIGH_HASH)})){var i=h.Pp(a.key),r=Q.fromRaw(a.value);r.hash=i,r.wid=e,t.push(r)}return t}async encryptKeys(e,t){var i,r,s=e.wid,n=await e.getPaths(),o=this.batch(e);for(i of n)i.data&&(a(!i.encrypted),r=Buffer.from(i.hash,"hex").slice(0,16),(i=i.clone()).data=d.encipher(i.data,t,r),i.encrypted=!0,e.pathCache.push(i.hash,i),o.put(h.P(s,i.hash),i.toRaw()))}async decryptKeys(e,t){var i,r,s=e.wid,n=await e.getPaths(),o=this.batch(e);for(i of n)i.data&&(a(i.encrypted),r=Buffer.from(i.hash,"hex").slice(0,16),(i=i.clone()).data=d.decipher(i.data,t,r),i.encrypted=!1,e.pathCache.push(i.hash,i),o.put(h.P(s,i.hash),i.toRaw()))}async resend(){var e,t={};for(const e of await this.db.keys({gte:h.w(0),lte:h.w(4294967295)})){var i=h.ww(e),r=await this.resendPending(i);r&&Array.isArray(r)&&(t[i]=r)}for(e of Object.keys(t))if(await this.get(parseInt(e)))for(const i of t[e]){try{await this.send(i)}catch(e){this.logger.warning("wdb resend:",e.message)}await se.timeout(50)}}async resendPending(e){var t=await this.get(e),i=await this.db.keys({gte:u.txdb.prefix(e,u.txdb.p(P.NULL_HASH)),lte:u.txdb.prefix(e,u.txdb.p(P.HIGH_HASH))});if(0!==i.length){this.logger.info("Rebroadcasting %d transactions for %d.",i.length,e);var r=[];for(const o of i){var a=u.txdb.pp(o),s=u.txdb.prefix(e,u.txdb.t(a));if((s=await this.db.get(s))&&!(s=re.fromRaw(s)).tx.isCoinbase())try{var n=await b.FactoryOfContract({tx:s.tx,env:this});await n.isBlockFinal()==w.Expired?t&&(await this.removeTX(s.tx),await t.remove(a),await n.erase()):"notify"!=n.oper&&r.push(s.tx)}catch(e){this.logger.error("TX(%s) Smart Contract Error: %s",s.tx.txid(),e.message)}}return A(r)}}getWallets(){return this.db.keys({gte:h.l("\0"),lte:h.l("ÿ"),parse:h.ll})}async getWalletsByTX(e){var t=new Set;if(!e.isCoinbase())for(const r of e.inputs){var i=r.prevout;if(this.testFilter(i.toRaw())&&(i=await this.getOutpointMap(i.hash,i.index)))for(const e of i.wids)t.add(e)}for(const i of e.getOutputHashes("hex"))if(this.testFilter(i)){var r=await this.getPathMap(i);if(r)for(const e of r.wids)t.add(e)}return 0===t.size?null:t}async getState(){var e=await this.db.get(h.R);return e?Z.fromRaw(e):null}async init(e){var t=this.options.startHeight;let i;if(this.client){if(null!=t){if(!(i=await this.client.getEntry(t)))throw new Error("WDB: Could not find start block.")}else i=await this.client.getTip();i=te.fromEntry(i)}else i=te.fromEntry(this.network.genesis);this.logger.info("Initializing AccountDB chain state (height %d).",i.height),(t=await this.getState())?this.state=t:await this.resetState(i,!1),await this.ensure({id:"primary",witness:!0,mnemonic:this.options.mnemonic}),e&&e.backup&&await this.loadBackup(e.backup)}async resetState(e,t){for(var i=this.state.clone(),r=(i.startHeight=e.height,i.startHash=e.hash,i.height=e.height,i.marked=t,this.db.batch()),a=this.db.iterator({gte:h.h(e.height),lte:h.h(4294967295),values:!1});;){var s=await a.next();if(!s)break;try{r.del(s.key)}catch(e){throw await a.end(),e}}r.put(h.h(e.height),e.toHash()),r.put(h.R,i.toRaw()),await r.write(),this.state=i}async syncState(e){var t=this.state.clone(),i=this.db.batch();if(e.height<t.height){let a=t.height;var r=a-e.height;for(let e=0;e<r;e++)i.del(h.h(a--))}else e.height>t.height&&a(e.height===t.height+1,`Bad chain sync tip ${e.height} while state `+t.height);t.height=e.height,i.put(h.h(e.height),e.toHash()),i.put(h.R,t.toRaw()),await i.write(),this.state=t,V("block/tips",t)}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(e){var t=await this.db.get(h.b(e));return t?ee.fromRaw(e,t):null}writeBlockMap(e,t,i){this.batch(e).put(h.b(t),i.toRaw())}unwriteBlockMap(e,t){this.batch(e).del(h.b(t))}async getOutpointMap(e,t){var i=await this.db.get(h.o(e,t));return i?J.fromRaw(e,t,i):null}writeOutpointMap(e,t,i,r){e=this.batch(e),this.addOutpoint(t,i),e.put(h.o(t,i),r.toRaw())}unwriteOutpointMap(e,t,i){this.batch(e).del(h.o(t,i))}async writeBalanceLog(e,t){var i=h.log(e.wid,t.aidx,t.height,t.hash),r=(t=Buffer.from(JSON.stringify(t)),await this.writeLock.lock());try{this.start(e).put(i,t),await this.commit(e)}finally{r()}}async queryBalanceLog(e,t,i=0){return this.db.values({gte:h.log(e,t,i,P.NULL_HASH),lte:h.log(e,t,this.curHeight,P.HIGH_HASH),parse:e=>JSON.parse(e.toString())})}async getBlock(e){var t,i=await this.db.get(h.h(e));return i?((t=new te).hash=i.toString("hex"),t.height=e,t):null}async getTip(){var e=await this.getBlock(this.curHeight);if(e)return e;throw new Error("WDB: Tip not found!")}async rollback(e,t=!0){if(e>this.curHeight)throw new Error("WDB: Cannot rollback to the future.");if(e===this.curHeight)return this.logger.debug("Rolled back to same height (%d).",e),!0;this.logger.info("Rolling back %d AccountDB blocks to height %d.",this.curHeight-e,e);var i=await this.getBlock(e);let r=!1;return i?(await this.revert(i.height),await this.syncState(i),t):(i=new te,e>=this.state.startHeight?(i.height=this.state.startHeight,i.hash=this.state.startHash,r=this.state.marked,this.logger.warning("Rolling back AccountDB to start block (%d).",i.height)):(i.height=0,i.hash=this.network.genesis.hash,r=!1,this.logger.warning("Rolling back AccountDB to genesis block.")),await this.revert(i.height),await this.resetState(i,r),!1)}async revert(e){var t=this.db.iterator({gte:h.b(e+1),lte:h.b(4294967295),reverse:!0,values:!0});let i=0;for(;;){var r=await t.next();if(!r)break;try{var a=h.bb(r.key),s=ee.fromRaw(a,r.value),n=s.toArray();i+=n.length;for(let e=n.length-1;0<=e;e--){var o=await this.getTX(n[e].hash);o&&await this._unconfirm(o,s)}}catch(e){throw await t.end(),e}}this.logger.info("Rolled back %d AccountDB transactions.",i)}async addBlock(e,t){var i=await this.txLock.lock();try{return await this._addBlock(e,t)}finally{i()}}async _addBlock(e,t){var i=te.fromEntry(e);let r=0;if(i.height<this.curHeight)this.logger.warning("AccountDB is connecting low blocks (%d).",i.height);else{if(i.height===this.curHeight)this.logger.warning("Already saw AccountDB block (%d).",i.height);else if(i.height!==this.curHeight+1)throw new Error(`WDB(addBlock): Bad disconnection (height mismatch, tip ${i.height} while state ${this.curHeight})`);if(await this.syncState(i),await this.propList.save(),!(this.options.checkpoints&&i.height<=this.network.lastCheckpoint)){for(const e of t)await this._insert(e,i)&&r++;0<r&&this.logger.info("Connected AccountDB block %s (tx=%d).",j.revHex(i.hash),r)}}return r}async removeBlock(e,t){var i=await this.txLock.lock();try{return await this._removeBlock(e,t)}finally{i()}}async _removeBlock(e,t){if((e=te.fromEntry(e)).height>this.curHeight)return this.logger.warning("AccountDB is disconnecting high blocks (%d).",e.height),0;if(e.height!==this.curHeight)throw new Error(`WDB(removeBlock): Bad disconnection (height mismatch, tip ${e.height} / ${j.revHex(e.hash)} while state ${this.curHeight})`);var i=await this.getBlock(e.height-1);if(!i)throw new Error(`WDB(removeBlock): Bad disconnection (no previous block of ${e.height} / ${j.revHex(e.hash)}).`);var r=await this.getBlockMap(e.height);if(r){for(let e=t.length-1;0<=e;e--)await this._unconfirm(t[e],r);this.logger.warning("Disconnected wallet block %s (tx=%d).",j.revHex(e.hash),r.txs.size)}return await this.syncState(i),await this.propList.save(),r?r.txs.size:0}async rescanBlock(e,t){if(this.rescanning){var i=await this.scanLock.lock();try{await this._addBlock(e,t)}catch(e){throw this.emit("error",e),e}finally{i()}}else this.logger.warning("Unsolicited rescan block: %s.",e.height)}async addTX(e,t,i){var r=await this.txLock.lock();try{return await this._insert(e,t,i)}finally{r()}}listNotify(e){return this.NotifyList.deletes([["h","<",this.curHeight-12]]),this.NotifyList.query(e)}listContact(e,t,i){return this.$contacts.query(e,t,i)}async setCp(e){await this.batchPut(u.txdb.cp(e.cid),e.toRaw())}async delCp(e){await this.batchDel(u.txdb.cp(e))}async delVp(e){var t=this.db.batch();t.del(u.txdb.VP(e.pid)),await t.write()}async setVp(e,t){var i=this.db.batch();i.put(u.txdb.VP(e.pid),e.toRaw()),await i.write()}async getVp(e){return(e=await this.db.get(u.txdb.VP(e)))?W.fromRaw(e):null}async getVpByAddress(e){return{list:[],count:0}}async getVpByOid(e){return{list:[],count:0}}async loadVpList(){return this.db.values({gte:u.txdb.VP(P.ZERO_CID,"hex"),lte:u.txdb.VP(P.MAX_CID,"hex"),parse:e=>W.fromRaw(e)})}async saveContact(e){var t=this.db.batch();t.put(u.txdb.CT(e.getAddress()),e.toRaw()),await t.write()}async loadContact(e){var t;for(t of await this.db.values({gte:u.txdb.CT(P.ZERO_HASH160_HEX),lte:u.txdb.CT(P.MAX_HASH160_HEX),parse:e=>S.fromRaw(e,this)}))t.sender&&(t.sender.wallet=await this.get(t.sender.wid)),this.$contacts.set(t.address,t)}async delHtlc(e){var t;(e=new F(e)).id&&(this.htlcList.delete(e.id),this.htlcList.delAccount(e),(t=this.db.batch()).del(u.txdb.VH(e.shash,e.sidx)),await t.write())}async setSuggest(e){e=new F(e);var t,[t,i]=(this.htlcList.set(e.id,e),await this.getAccountByAddress(e.aa)),[t,i]=(t&&this.htlcList.setAccount(e,t,i),await this.getAccountByAddress(e.ba));(t=(t&&this.htlcList.setAccount(e,t,i),this.db.batch())).put(u.txdb.VH(e.shash,e.sidx),e.toRaw()),await t.write()}async setAssent(e){e=new F(e);var t,[t,i]=(this.htlcList.set(e.id,e),await this.getAccountByAddress(e.ab)),[t,i]=(t&&this.htlcList.setAccount(e,t,i),await this.getAccountByAddress(e.bb));(t=(t&&this.htlcList.setAccount(e,t,i),this.db.batch())).put(u.txdb.VH(e.shash,e.sidx),e.toRaw()),await t.write()}async loadHtlcList(){return this.db.values({gte:u.txdb.VH(P.ZERO_CID,0),lte:u.txdb.VH(P.MAX_CID,4294967295),parse:e=>F.fromRaw(e)})}async delComment(e){var t;(e=new M(e)).id&&(this.commentList.delete(e.id),this.commentList.delAccount(e),(t=this.db.batch()).del(u.txdb.VC(e.shash,e.sidx)),await t.write())}async setComment(e){e=new M(e);var t,[t,i]=(this.commentList.set(e.id,e),await this.getAccountByAddress(e.bob));(t=(t&&(this.commentList.setAccount(e,t,i),this.emit("comm.comment",e)),this.db.batch())).put(u.txdb.VC(e.shash,e.sidx),e.toRaw()),await t.write()}async loadCommentList(){return this.db.values({gte:u.txdb.VC(P.ZERO_CID,0),lte:u.txdb.VC(P.MAX_CID,4294967295),parse:e=>M.fromRaw(e)})}async delEr(e){var t=this.db.batch();t.del(u.txdb.ER(e.erid)),t.del(u.txdb.ERR(e.witness,e.erid,e.txid)),await t.write()}async setEr(e,t){t&&e.source&&(i=g.fromWitnessPubkeyhash(l.hash160(Buffer.from(e.source.pubkey,"hex")),this.network),[i,t]=await this.getAccountByAddress(i,t),e.wid=i,e.account=t);var i=this.db.batch();t=u.txdb.ERR(e.witness,e.erid,e.txid);i.put(t,e.toRaw()),i.put(u.txdb.ER(e.erid),t),await i.write()}async getEr(e){var t;return(e=await this.db.get(u.txdb.ER(e)))&&([,,t]=u.txdb.ERRR(e),e=await this.db.get(e))?((e=Y.fromRaw(e)).txid=t,e):null}async byPubkey(e,t,i=!1){var r,a=new _;e=await this.db.values({gte:u.txdb.ERR(e,P.NULL_HASH,P.NULL_HASH),lte:u.txdb.ERR(e,P.HIGH_HASH,P.HIGH_HASH),parse:e=>Y.fromRaw(e)});let s=[],n=new Map;if(i){for(var o of e)(!n.get(o.source.cluster)||o.startHeight>n.get(o.source.cluster).startHeight)&&n.set(o.source.cluster,await this.caVerifyObj(o));s=n.values()}else s=e;for(r of s)a.set(r.erid,r);return a.query(t)}async caVerifyObj(e){var t={verify:!1};if(!e||e.validHeight<=this.curHeight)return t;var i=await this.erAbList.getErAb(e.erid);return i&&i.abolishHeight<this.curHeight?t:(i=ae.fromPublic(Buffer.from(e.witness,"hex"),this.network.type),e.verify(i)?(e.verify=!0,0<(i=this.cpList.query([["pubKey",e.witness]])).list.length&&(e.cpid=i.list[0].cid),e):t)}async delErAbolish(e){var t=this.db.batch();t.del(u.txdb.ERA(e.erid)),await t.write()}async setErAbolish(e){var t=this.db.batch();t.put(u.txdb.ERA(e.erid),e.toRaw()),await t.write()}async getErAbolish(e){return(e=await this.db.get(u.txdb.ERA(e)))?q.fromRaw(e):null}loadErAbolishList(){return this.db.values({gte:u.txdb.ERA(P.ZERO_CID),lte:u.txdb.ERA(P.MAX_CID),parse:e=>q.fromRaw(e)})}async delAudit(e){var t=this.db.batch();t.del(u.txdb.AU(e.erid)),await t.write()}async setAudit(e){var t=this.db.batch();t.put(u.txdb.AU(e.erid),e.toRaw()),await t.write()}async getAudit(e){return(e=await this.db.get(u.txdb.AU(e)))?X.fromRaw(e):null}async loadAuditList(){return this.db.values({gte:u.txdb.AU(P.NULL_HASH),lte:u.txdb.AU(P.HIGH_HASH),parse:e=>X.fromRaw(e)})}async batchPut(e,t){var i=this.db.batch();i.put(e,t),await i.write()}async batchDel(e){var t=this.db.batch();t.del(e),await t.write()}async _insert(e,t,i){a(!e.mutable,"WDB: Cannot add mutable TX.");let r=await this.getWalletsByTX(e);if(r){this.logger.info("Incoming transaction for %d wallets in AccountDB (%s).",r.size,e.txid()),!t||this.state.marked||(this.logger.info("Marking AccountDB start block at %s (%d).",j.revHex(t.hash),t.height),await this.resetState(t,!0));let n=!1;for(const o of r){var s=await this.get(o);a(s),await s.add(e,t,i)&&(this.logger.info("Added transaction to wallet in AccountDB: %s (%d).",s.id,o),n=!0)}n||(r=null)}try{var n=await b.FactoryOfContract({env:this,block:t,tx:e});t?await n.confirm():await n.insert()}catch(n){t?this.logger.error("TX(%s) Smart Contract Confirm Error: %s",e.txid(),n.message):this.logger.error("TX(%s) Smart Contract Insert Error: %s",e.txid(),n.message)}return r}async _unconfirm(e,t){if(t)try{await(await b.FactoryOfContract({env:this,block:t,tx:e})).unconfirm()}catch(e){this.logger.error("Smart Contract Unconfirm Error: %s",e.message)}var i=e.hash("hex");if(!(e=t.txs.get(i).wids))return null;for(const t of e){var r=await this.get(t);a(r),await r.unconfirm(i)}}async resetChain(e){var t=await this.txLock.lock();try{return await this._resetChain(e)}finally{t()}}async _resetChain(e){if(e.height>this.curHeight)throw new Error(`WDB: Bad reset height ${e.height} while curHeight `+this.curHeight);var t;for(t of(await this.rollback(e.height)||await this._rescan(),await this.getWallets())){var i=await this.get(t);for(const t of await i.getPending())try{await i.abandon(t.hash)}catch(e){}}}async saveMSTrans(e){var t=await this.writeLock.lock();try{return await this._saveMSTrans(e)}finally{t()}}async _saveMSTrans(e){var t=this.db.batch();t.put(h.ms(g.getHash(e.addr,"hex"),e.txid),Buffer.from(JSON.stringify(e))),await t.write()}async listMSTrans(e){return e=g.getHash(e,"hex"),this.db.values({gte:h.ms(e,P.NULL_HASH),lte:h.ms(e,P.HIGH_HASH),parse:e=>JSON.parse(e.toString())})}async delMSTrans(e,t){var i=await this.writeLock.lock();try{return await this._delMSTrans(e,t)}finally{i()}}async _delMSTrans(e,t){e=g.getHash(e,"hex");var i=this.db.batch();i.del(h.ms(e,t)),await i.write()}}he.layout=h,e.exports=he},function(e,t,i){"use strict";
|
|
833
|
+
*/const r=i(8),a=i(0),s=i(73),n=i(119),o=i(157),c=i(609),u=i(85),h=u.walletdb,l=i(6),p=i(158),d=i(125),f=i(167);var{}=i(37);const m=i(46),g=i(13);i(20),i(68);const v=i(197),y=i(67),b=i(42),{BlockFinalType:w,ContractEnvType:x}=i(5),k=i(159),S=i(611),_=i(31);var E=i(71);const j=i(2),A=i(140).sortWithSeq,R=i(35),I=i(198),O=i(63),C=i(100),P=i(3),T=P.U32,B=i(338),N=i(339),z=i(340),F=z.vpItem,L=i(616),M=L.vpItem,D=i(314);i(617);const H=D.cpItem,U=i(154),q=U.ErAbolishItem,V=i(44).broadcast,K=i(146),W=K.vpItem,$=i(153),Y=$.ErItem,G=i(618),X=G.AuditItem,J=i(307),Q=i(109),Z=i(619),ee=i(308),te=i(120),ie=i(620),re=i(218),ae=i(38),se=i(36),ne=i(59),oe=i(78),ce=oe.errors,ue=i(77);class he extends E{constructor(e){super(),this.readyLoad=!1,this.options=new c(e),this.network=this.options.network,this.logger=this.options.logger.context("wallet"),this.workers=this.options.workers,this.keys={hmacSalt:P.DefaultChainCode},e.keys&&e.keys.hmacSalt&&(a(Buffer.isBuffer(e.keys.hmacSalt)),this.keys.hmacSalt=e.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 B(this),this.primary=null,this.state=new Z,this.wallets=new Map,this.depth=0,this.rescanning=!1,this.bound=!1,this.newRecord=!0,this.readLock=new I,this.writeLock=new R,this.txLock=new R,this.scanLock=new R,this.widCache=new O(1e4),this.pathMapCache=new O(1e5),this.filter=new C,this.middleHashMem=new Set,this.middleHashChain=new Set,this.autoTaskMgr=new k(this),this.transactionList=new N(this),this.htlcList=new z(this),this.commentList=new L(this),this.NotifyList=new _,this.propList=new K(this),this.$contacts=new _,this.cpList=new D(this),this.cpMemList=new D(this),this.auditList=new G(this),this.erList=new $(this),this.erAbList=new U(this),this.hmacConnection=[],this._init()}async logAudit(e){e.height=this.curHeight,e.time=j.now(),e.erid=l.sha256(j.stringify(e)).toString("hex"),e=new X(e),await this.auditList.setAudit(e)}async getAccountByAddress(e,t){if(e){let a=null;if(a=t?await this.getWalletsByTX(t):await this.getWallets())for(const t of a){var i=await this.get(t);if(i){var r=await i.getPath(e);if(r)return[i.wid,r.name,i.id]}}}return[0,"",""]}_init(){let e=1e6,t=-1;this.spv&&(e=2e4,t=C.flags.ALL),this.filter=C.fromRate(e,.001,t)}get mode(){return x.Wallet}async getTXFromAll(e){return this.getTXFromDb(e)}async checkNewRecord(){var e={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 t=await this.db.checkVersion(h,6);this.newRecord="new"==t}catch(e){if(-1!=e.message.indexOf("does not exist (create_if_missing is false)"))this.newRecord=!0;else{if(-1==e.message.indexOf("exists (error_if_exists is true)"))throw e;this.newRecord=!1}}try{await this.db.close()}catch(e){}this.db.options.createIfMissing=e.createIfMissing,this.db.options.errorIfExists=e.errorIfExists}async isNewRecord(){return await this.checkNewRecord(),this.newRecord}setmnemonic(e){if(this.options.mnemonic=this.options.mnemonic||{},e.bits)this.options.mnemonic={bits:e.bits};else if(e.entropy)this.options.mnemonic={entropy:Buffer.from(e.entropy,"hex")};else if(e.phrase){var t=this.testmnemonic(e.phrase);if(0!=t.code)throw t.msg;this.options.mnemonic={phrase:e.phrase}}e.passphrase&&(this.options.mnemonic.passphrase=e.passphrase),e.language&&(this.options.mnemonic.language=e.language)}testmnemonic(e){try{return new v(e),{code:0}}catch(e){return{code:-1,msg:e.message}}}async getContracts(e){var t=await this.db.values({gte:u.txdb.tx(P.NULL_HASH),lte:u.txdb.tx(P.HIGH_HASH),parse:e=>j.parseJson(e.toString())});return e?t.filter(t=>t.srcact==e||t.dstact==e):t}isFull(){return this.spv||this.synced||!1}async _open(e){}async handleNotify(e,t=!1){if(!t){let i=e.body.content;if("string"==typeof i)try{i=JSON.parse(e.body.content)}catch(e){return}"object"==typeof i&&"secret"===i.type&&(t={contact:e.body.src,messenger:e.body.dst},i.init&&(t.init=Buffer.from(i.init,"hex")),i.packet&&(t.packet=Buffer.from(i.packet)),await this.handleSecret(t))}}async handleSecret(e){if(e.contact&&e.messenger&&e.contact!=e.messenger){try{g.fromString(e.contact,this.network.type),g.fromString(e.messenger,this.network.type)}catch(e){return}var t=await this.ensureContact(e);t&&await t.ensureMessenger(e).answer(e)}}async scanContact(e,t=-1){var i=async e=>{var t;e.witness&&"witnesspubkeyhash"==e.getType()&&(t=e.witness.getPubkeyhashInput()[1],e=g.fromWitness(e.witness).toString(),t)&&e&&await this.ensureContact({contact:e,publicKey:t})};if(0<=t&&t<e.inputs.length)await i(e.inputs[t]);else for(var r of e.inputs)await i(r)}async ensureContact(e){if(!e.contact||e.contact==e.messenger)return null;try{g.fromString(e.contact,this.network.type),e.messenger&&g.fromString(e.messenger,this.network.type)}catch(e){return null}e.network=this.network.type,this.$contacts.get(e.contact)||this.$contacts.set(e.contact,new S(e));var t=this.$contacts.get(e.contact);if(e.messenger&&!(e=t.ensureMessenger(e)).wallet){var i,[i,r]=await this.getAccountByAddress(e.address);if(!(i=await this.get(i)))return;e.wallet=i,e.account=r}return t}getCps(){return this.db.values({gte:u.txdb.cp(P.ZERO_CID,"hex"),lte:u.txdb.cp(P.MAX_CID,"hex"),parse:e=>H.fromRaw(e)})}async _close(){await this.disconnect(),this.http&&this.options.listen&&await this.http.close();for(const e of this.wallets.values())await e.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(e){if(this.readyLoad){var t=await this.ensure({id:"primary",witness:!0,mnemonic:this.options.mnemonic}),i=await this.txLock.lock();try{await this.init(e),await this.watch(),await t.createReceive(0,1,t.master,this.network.type),await t.ensureNotifyKey(),await this.sync()}finally{i()}setTimeout(()=>{this.resend()},5e3)}}async disconnect(){this.client&&await this.client._close(),this.jsonp&&await this.jsonp._close()}async flushCP(e,t=!1){this.client&&(e=e||[],t||(e=this.cpList.excludeCids(e),t=t||0<e.length),t)&&await this.client.execute("cp.remoteQuery",[[["cid","include",e]]])}async watch(){let e=this.db.iterator({gte:h.p(P.NULL_HASH),lte:h.p(P.HIGH_HASH)}),t=0,i=0;for(;;){var r=await e.next();if(!r)break;try{var a=h.pp(r.key);this.addHash(a,!1)}catch(t){throw await e.end(),t}t++}for(e=this.db.iterator({gte:h.o(P.NULL_HASH,0),lte:h.o(P.HIGH_HASH,4294967295)});;){var s=await e.next();if(!s)break;try{var[n,o]=h.oo(s.key);this.addOutpoint(n,o)}catch(t){throw await e.end(),t}i++}this.logger.info("Filter: Added %d hashes to AccountDB filter.",t),this.logger.info("Filter: Added %d outpoints to AccountDB filter.",i),await this.setFilter()}async sync(){if(this.client){let t,i=this.curHeight;for(;0<=i;){var e=await this.getBlock(i);if(!e)break;if(t=await this.client.getEntry(e.hash))break;i--}t||(i=this.state.startHeight,t=await this.client.getEntry(this.state.startHash))||(i=0),await this.cpList.loadHistory(),await this.cpMemList.loadHistory(),await this.propList.loadHistory(),await this.htlcList.loadHistory(),await this.commentList.loadHistory(),await this.transactionList.loadHistory(),await this.loadContact(),await this.erList.loadHistory(),await this.auditList.loadHistory(),await this.erAbList.loadHistory(),await this._rescan(i,!1)}}async _rescan(e,t=!0){if(this.client){null==e&&(e=this.state.startHeight),a(e>>>0===e,"WDB: Must pass in a height.");var i=this.curHeight;t=(await this.rollback(e,t),this.logger.info("AccountDB is scanning %d blocks.",i-e+1),await this.getTip());try{this.rescanning=!0,await this.client.rescan(t.hash,this.eid)}finally{this.rescanning=!1}}}async rescan(e){var t=await this.txLock.lock();try{return await this._rescan(e,!1)}finally{t()}}async send(e){return this.client?this.client.send(e):(this.emit("send",e),Promise.resolve())}async getTX(e){for(const i of this.wallets.values()){var t=await i.getTX(e);if(t)return t.tx}return null}async getTXFromDb(e){for(const i of this.wallets.values()){var t=await i.getTX(e);if(t)return t.tx}return null}async getExtendTX(e){for(const i of this.wallets.values()){var t=await i.getTX(e);if(t)return t}return null}async removeTX(e){this.client?await this.client.removeTX(e):this.emit("remove",e)}async estimateFee(e){return 0<this.feeRate?this.feeRate:!this.client||(e=await this.client.estimateFee(e))<this.network.feeRate?this.network.feeRate:e>this.network.maxFeeRate?this.network.maxFeeRate:e}setFilter(){return this.client?this.client.setFilter(this.filter):(this.emit("filter.set",this.filter),Promise.resolve())}resetFilter(){return this.client?this.client.resetFilter():(this.emit("filter.reset"),Promise.resolve())}backup(e){return this.db.backup(e)}async wipe(){this.logger.warning("Wiping AccountDB TXDB..."),this.logger.warning("I hope you know what you're doing.");var e=this.db.iterator({gte:Buffer.from([0]),lte:Buffer.from([255])}),t=this.db.batch();let i=0;for(;;){var r=await e.next();if(!r)break;try{switch(r.key[0]){case 98:case 99:case 101:case 116:case 111:case 104:case 82:t.del(r.key),i++}}catch(t){throw await e.end(),t}}this.logger.warning("Wiped %d txdb records.",i),await t.write()}async getDepth(){var e=this.db.iterator({gte:h.w(0),lte:h.w(4294967295),reverse:!0,limit:1}),t=await e.next();return t?(await e.end(),h.ww(t.key)+1):1}start(e){return a(!e.current,"WDB: Batch already started."),e.current=this.db.batch(),e.accountCache.start(),e.pathCache.start(),e.current}drop(e){var t=this.batch(e);e.current=null,e.accountCache.drop(),e.pathCache.drop(),t.clear()}clear(e){var t=this.batch(e);e.accountCache.clear(),e.pathCache.clear(),t.clear()}batch(e){return a(e.current,"WDB: Batch does not exist."),e.current}async commit(e){var t=this.batch(e);try{await t.write()}catch(e){throw this.drop(),e}e.current=null,e.accountCache.commit(),e.pathCache.commit()}testFilter(e){return this.filter.test(e,"hex")}addHash(e,t=!0){this.filter.add(e,"hex"),t&&(t=Buffer.from(e,"hex"),this.client?this.client.addFilter(t):this.emit("filter.add",t))}addOutpoint(e,t){e=new m(e,t),this.filter.add(e.toRaw())}dump(){return this.db.dump()}register(e){a(!this.wallets.has(e.wid)),this.wallets.set(e.wid,e)}unregister(e){a(this.wallets.has(e.wid)),this.wallets.delete(e.wid)}async getWalletID(e){var t;return e?"number"==typeof e?e:this.widCache.get(e)||((t=await this.db.get(h.l(e)))?(t=t.readUInt32LE(0,!0),this.widCache.set(e,t),t):null):null}async get(e){if(!(e=await this.getWalletID(e)))return null;var t=await this.readLock.lock(e);try{return await this._get(e)}finally{t()}}async _get(e){var t=this.wallets.get(e);return t||((t=await this.db.get(h.w(e)))?(await(e=n.fromRaw(this,t)).open(),this.register(e),e):null)}async loadBackup(e){if(ne.unsupported)throw new ue(ce.INTERNAL_ERROR,"FS not available.");let t=null;var i;for(i of(await ne.readFile(e,"utf8")).split(/\n+/))if(0!==(i=i.trim()).length&&!/^\s*#/.test(i)){var r=i.split(/\s+/);if(r.length<4)throw new ue(ce.DESERIALIZATION_ERROR,"Malformed wallet Data File.");switch(r[0]){case"W":var s=Buffer.from(r[1],"base64");s=n.fromRaw(this,s);await this.replace(s),t=await this.get(s.id),this.logger.info("Import Wallet %s(%s)",t.id,t.wid);break;case"C":s=Buffer.from(r[1],"base64");(c=((u=o.fromRaw(this,s)).wallet=t,u.wid=t.wid,u.id=t.id,u.initialized=!0,u.watchOnly=t.watchOnly,u.receive=u.deriveReceive(u.receiveDepth-1),u.change=u.deriveChange(u.changeDepth-1),u.witness&&(u.nested=u.deriveNested(u.nestedDepth-1)),t.master.key.deriveAccount(44,u.accountIndex))).publicKey.toString("hex")!==u.accountKey.publicKey.toString("hex")&&a(c.publicKey.toString("hex")==u.accountKey.publicKey.toString("hex")),await t.saveAccount(u),this.logger.info("Import Account %s(%s)",u.name,u.accountIndex);break;case"A":var c=oe.parseSecret(r[1],this.network),u=parseInt(r[5]),h=parseInt(r[7]),l=parseInt(r[9]),p=r[11].trim();if(h<0||l<0)try{await t.importKey(u,c)}catch(e){this.logger.error(`loadBackup: ${e.message} account/secret: ${u}/`+p)}else{var d=await t.deriveKey(u,h,l),f=await t.deriveKey(u,h,l,t.master);d.getAddress("string")!==f.getAddress("string")&&this.logger.error(`loadBackup: not-equal-1: ${d.getAddress("string")} != `+f.getAddress("string")),d.getAddress("string")!==p&&this.logger.error(`loadBackup: not-equal-2: ${d.getAddress("string")} != `+p)}this.logger.info("Import Address %s %s %s %s",u,h,l,p)}}return t.accountCache.reset(),t}save(e){var t=e.wid,i=e.id,r=this.batch(e);this.widCache.set(i,t),r.put(h.w(t),e.toRaw()),r.put(h.l(i),T(t))}async rename(e,t){var i=await this.writeLock.lock();try{return await this._rename(e,t)}finally{i()}}async _rename(e,t){var i=e.id;if(!s.isName(t))throw new Error("WDB: Bad wallet ID.");if(await this.has(t))throw new Error("WDB: ID not available.");this.start(e).del(h.l(i)),e.id=t,this.save(e),await this.commit(e),this.widCache.remove(i),i=e.pathCache.values();for(const e of i)e.id=t}async replace(e){var t=await this.writeLock.lock();try{return await this._replace(e)}finally{t()}}async _replace(e){var t=this.start(e);t.del(h.l(e.id)),t.del(h.w(e.wid)),this.save(e),await this.commit(e),this.widCache.remove(e.id),this.wallets.delete(e.wid)}renameAccount(e,t){var i=e.wallet;this.batch(i).del(h.i(e.wid,e.name)),e.name=t,this.saveAccount(e)}async auth(e,t){if("string"==typeof t){if(!j.isHex256(t))throw new Error("WDB Authentication: Invalid Token.");t=Buffer.from(t,"hex")}e=y.getHmac(e.toString(),this.keys.hmacSalt);var i=r.createHmac("sha256",e.random);i=Buffer.from(i.update(e.token).digest("hex"),"hex");if(!p(t,i))throw new Error("WDB Authentication: CRC Error.")}async create(e){var t=await this.writeLock.lock();e=e||{};try{return await this._create(e)}finally{t()}}async _create(e){if(await this.has(e.id))throw new Error("WDB: Wallet already exists.");"string"==typeof e.mnemonic&&(e.mnemonic={phrase:e.mnemonic}),e.mnemonic=e.mnemonic||{},!e.mnemonic.language&&this.options.mnemonic&&this.options.mnemonic.language&&(e.mnemonic.language=this.options.mnemonic.language);var t=n.fromOptions(this,e);return t.wid=this.depth++,await t.init(e),this.register(t),this.logger.info("Created wallet %s in AccountDB.",t.id),t}async has(e){return null!=await this.getWalletID(e)}async ensure(e){return await this.get(e.id)||this.create(e)}async getAccount(e,t){return(e=await this.db.get(h.a(e,t)))?o.fromRaw(this,e):null}getAccounts(e){return this.db.values({gte:h.n(e,0),lte:h.n(e,4294967295),parse:e=>e.toString("ascii")})}async getAccountMap(e){for(var t={},i=this.db.iterator({gte:h.n(e,0),lte:h.n(e,4294967295),values:!0});;){var r=await i.next();if(!r)break;try{var[,a]=h.nn(r.key);t[a]=r.value.toString("ascii")}catch(e){throw await i.end(),e}}return t}async getAccountIndex(e,t){return(e=await this.db.get(h.i(e,t)))?e.readUInt32LE(0,!0):-1}async getAccountName(e,t){return(e=await this.db.get(h.n(e,t)))?e.toString("ascii"):null}saveAccount(e){var t=e.wid,i=e.wallet,r=e.accountIndex,a=e.name,s=this.batch(i);s.put(h.a(t,r),e.toRaw()),s.put(h.i(t,a),T(r)),s.put(h.n(t,r),Buffer.from(a,"ascii")),i.accountCache.push(r,e)}hasAccount(e,t){return"number"==typeof e&&"number"==typeof t&&this.db.has(h.a(e,t))}async getPathMap(e){var t=this.pathMapCache.get(e);return t||((t=await this.db.get(h.p(e)))?(t=ie.fromRaw(e,t),this.pathMapCache.set(e,t),t):null)}saveKey(e,t){return this.savePath(e,t.toPath())}async savePath(e,t){var i=e.wid,r=t.hash,a=this.batch(e);this.addHash(r);let s=await this.getPathMap(r);(s=s||new ie(r)).add(i)&&(this.pathMapCache.set(r,s),e.pathCache.push(r,t),a.put(h.p(r),s.toRaw()),a.put(h.P(i,r),t.toRaw()),a.put(h.r(i,t.account,r),null))}async getPath(e,t){var i=await this.db.get(h.P(e,t));return i?((i=Q.fromRaw(i)).wid=e,i.hash=t,i):null}hasPath(e,t){return this.db.has(h.P(e,t))}getHashes(){return this.db.keys({gte:h.p(P.NULL_HASH),lte:h.p(P.HIGH_HASH),parse:h.pp})}getOutpoints(){return this.db.keys({gte:h.o(P.NULL_HASH,0),lte:h.o(P.HIGH_HASH,4294967295),parse:e=>{var[e,t]=h.oo(e);return new m(e,t)}})}getWalletHashes(e){return this.db.keys({gte:h.P(e,P.NULL_HASH),lte:h.P(e,P.HIGH_HASH),parse:h.Pp})}getAccountHashes(e,t){return this.db.keys({gte:h.r(e,t,P.NULL_HASH),lte:h.r(e,t,P.HIGH_HASH),parse:h.rr})}async getWalletPaths(e){var t=[];for(const a of await this.db.range({gte:h.P(e,P.NULL_HASH),lte:h.P(e,P.HIGH_HASH)})){var i=h.Pp(a.key),r=Q.fromRaw(a.value);r.hash=i,r.wid=e,t.push(r)}return t}async encryptKeys(e,t){var i,r,s=e.wid,n=await e.getPaths(),o=this.batch(e);for(i of n)i.data&&(a(!i.encrypted),r=Buffer.from(i.hash,"hex").slice(0,16),(i=i.clone()).data=d.encipher(i.data,t,r),i.encrypted=!0,e.pathCache.push(i.hash,i),o.put(h.P(s,i.hash),i.toRaw()))}async decryptKeys(e,t){var i,r,s=e.wid,n=await e.getPaths(),o=this.batch(e);for(i of n)i.data&&(a(i.encrypted),r=Buffer.from(i.hash,"hex").slice(0,16),(i=i.clone()).data=d.decipher(i.data,t,r),i.encrypted=!1,e.pathCache.push(i.hash,i),o.put(h.P(s,i.hash),i.toRaw()))}async resend(){var e,t={};for(const e of await this.db.keys({gte:h.w(0),lte:h.w(4294967295)})){var i=h.ww(e),r=await this.resendPending(i);r&&Array.isArray(r)&&(t[i]=r)}for(e of Object.keys(t))if(await this.get(parseInt(e)))for(const i of t[e]){try{await this.send(i)}catch(e){this.logger.warning("wdb resend:",e.message)}await se.timeout(50)}}async resendPending(e){var t=await this.get(e),i=await this.db.keys({gte:u.txdb.prefix(e,u.txdb.p(P.NULL_HASH)),lte:u.txdb.prefix(e,u.txdb.p(P.HIGH_HASH))});if(0!==i.length){this.logger.info("Rebroadcasting %d transactions for %d.",i.length,e);var r=[];for(const o of i){var a=u.txdb.pp(o),s=u.txdb.prefix(e,u.txdb.t(a));if((s=await this.db.get(s))&&!(s=re.fromRaw(s)).tx.isCoinbase())try{var n=await b.FactoryOfContract({tx:s.tx,env:this});await n.isBlockFinal()==w.Expired?t&&(await this.removeTX(s.tx),await t.remove(a),await n.erase()):"notify"!=n.oper&&r.push(s.tx)}catch(e){this.logger.error("TX(%s) Smart Contract Error: %s",s.tx.txid(),e.message)}}return A(r)}}getWallets(){return this.db.keys({gte:h.l("\0"),lte:h.l("ÿ"),parse:h.ll})}async getWalletsByTX(e){var t=new Set;if(!e.isCoinbase())for(const r of e.inputs){var i=r.prevout;if(this.testFilter(i.toRaw())&&(i=await this.getOutpointMap(i.hash,i.index)))for(const e of i.wids)t.add(e)}for(const i of e.getOutputHashes("hex"))if(this.testFilter(i)){var r=await this.getPathMap(i);if(r)for(const e of r.wids)t.add(e)}return 0===t.size?null:t}async getState(){var e=await this.db.get(h.R);return e?Z.fromRaw(e):null}async init(e){var t=this.options.startHeight;let i;if(this.client){if(null!=t){if(!(i=await this.client.getEntry(t)))throw new Error("WDB: Could not find start block.")}else i=await this.client.getTip();i=te.fromEntry(i)}else i=te.fromEntry(this.network.genesis);this.logger.info("Initializing AccountDB chain state (height %d).",i.height),(t=await this.getState())?this.state=t:await this.resetState(i,!1),await this.ensure({id:"primary",witness:!0,mnemonic:this.options.mnemonic}),e&&e.backup&&await this.loadBackup(e.backup)}async resetState(e,t){for(var i=this.state.clone(),r=(i.startHeight=e.height,i.startHash=e.hash,i.height=e.height,i.marked=t,this.db.batch()),a=this.db.iterator({gte:h.h(e.height),lte:h.h(4294967295),values:!1});;){var s=await a.next();if(!s)break;try{r.del(s.key)}catch(e){throw await a.end(),e}}r.put(h.h(e.height),e.toHash()),r.put(h.R,i.toRaw()),await r.write(),this.state=i}async syncState(e){var t=this.state.clone(),i=this.db.batch();if(e.height<t.height){let a=t.height;var r=a-e.height;for(let e=0;e<r;e++)i.del(h.h(a--))}else e.height>t.height&&a(e.height===t.height+1,`Bad chain sync tip ${e.height} while state `+t.height);t.height=e.height,i.put(h.h(e.height),e.toHash()),i.put(h.R,t.toRaw()),await i.write(),this.state=t,V("block/tips",t)}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(e){var t=await this.db.get(h.b(e));return t?ee.fromRaw(e,t):null}writeBlockMap(e,t,i){this.batch(e).put(h.b(t),i.toRaw())}unwriteBlockMap(e,t){this.batch(e).del(h.b(t))}async getOutpointMap(e,t){var i=await this.db.get(h.o(e,t));return i?J.fromRaw(e,t,i):null}writeOutpointMap(e,t,i,r){e=this.batch(e),this.addOutpoint(t,i),e.put(h.o(t,i),r.toRaw())}unwriteOutpointMap(e,t,i){this.batch(e).del(h.o(t,i))}async writeBalanceLog(e,t){var i=h.log(e.wid,t.aidx,t.height,t.hash),r=(t=Buffer.from(JSON.stringify(t)),await this.writeLock.lock());try{this.start(e).put(i,t),await this.commit(e)}finally{r()}}async queryBalanceLog(e,t,i=0){return this.db.values({gte:h.log(e,t,i,P.NULL_HASH),lte:h.log(e,t,this.curHeight,P.HIGH_HASH),parse:e=>JSON.parse(e.toString())})}async getBlock(e){var t,i=await this.db.get(h.h(e));return i?((t=new te).hash=i.toString("hex"),t.height=e,t):null}async getTip(){var e=await this.getBlock(this.curHeight);if(e)return e;throw new Error("WDB: Tip not found!")}async rollback(e,t=!0){if(e>this.curHeight)throw new Error("WDB: Cannot rollback to the future.");if(e===this.curHeight)return this.logger.debug("Rolled back to same height (%d).",e),!0;this.logger.info("Rolling back %d AccountDB blocks to height %d.",this.curHeight-e,e);var i=await this.getBlock(e);let r=!1;return i?(await this.revert(i.height),await this.syncState(i),t):(i=new te,e>=this.state.startHeight?(i.height=this.state.startHeight,i.hash=this.state.startHash,r=this.state.marked,this.logger.warning("Rolling back AccountDB to start block (%d).",i.height)):(i.height=0,i.hash=this.network.genesis.hash,r=!1,this.logger.warning("Rolling back AccountDB to genesis block.")),await this.revert(i.height),await this.resetState(i,r),!1)}async revert(e){var t=this.db.iterator({gte:h.b(e+1),lte:h.b(4294967295),reverse:!0,values:!0});let i=0;for(;;){var r=await t.next();if(!r)break;try{var a=h.bb(r.key),s=ee.fromRaw(a,r.value),n=s.toArray();i+=n.length;for(let e=n.length-1;0<=e;e--){var o=await this.getTX(n[e].hash);o&&await this._unconfirm(o,s)}}catch(e){throw await t.end(),e}}this.logger.info("Rolled back %d AccountDB transactions.",i)}async addBlock(e,t){var i=await this.txLock.lock();try{return await this._addBlock(e,t)}finally{i()}}async _addBlock(e,t){var i=te.fromEntry(e);let r=0;if(i.height<this.curHeight)this.logger.warning("AccountDB is connecting low blocks (%d).",i.height);else{if(i.height===this.curHeight)this.logger.warning("Already saw AccountDB block (%d).",i.height);else if(i.height!==this.curHeight+1)throw new Error(`WDB(addBlock): Bad disconnection (height mismatch, tip ${i.height} while state ${this.curHeight})`);if(await this.syncState(i),await this.propList.save(),!(this.options.checkpoints&&i.height<=this.network.lastCheckpoint)){for(const e of t)await this._insert(e,i)&&r++;0<r&&this.logger.info("Connected AccountDB block %s (tx=%d).",j.revHex(i.hash),r)}}return r}async removeBlock(e,t){var i=await this.txLock.lock();try{return await this._removeBlock(e,t)}finally{i()}}async _removeBlock(e,t){if((e=te.fromEntry(e)).height>this.curHeight)return this.logger.warning("AccountDB is disconnecting high blocks (%d).",e.height),0;if(e.height!==this.curHeight)throw new Error(`WDB(removeBlock): Bad disconnection (height mismatch, tip ${e.height} / ${j.revHex(e.hash)} while state ${this.curHeight})`);var i=await this.getBlock(e.height-1);if(!i)throw new Error(`WDB(removeBlock): Bad disconnection (no previous block of ${e.height} / ${j.revHex(e.hash)}).`);var r=await this.getBlockMap(e.height);if(r){for(let e=t.length-1;0<=e;e--)await this._unconfirm(t[e],r);this.logger.warning("Disconnected wallet block %s (tx=%d).",j.revHex(e.hash),r.txs.size)}return await this.syncState(i),await this.propList.save(),r?r.txs.size:0}async rescanBlock(e,t){if(this.rescanning){var i=await this.scanLock.lock();try{await this._addBlock(e,t)}catch(e){throw this.emit("error",e),e}finally{i()}}else this.logger.warning("Unsolicited rescan block: %s.",e.height)}async addTX(e,t,i){var r=await this.txLock.lock();try{return await this._insert(e,t,i)}finally{r()}}listNotify(e){return this.NotifyList.deletes([["h","<",this.curHeight-12]]),this.NotifyList.query(e)}listContact(e,t,i){return this.$contacts.query(e,t,i)}async setCp(e){await this.batchPut(u.txdb.cp(e.cid),e.toRaw())}async delCp(e){await this.batchDel(u.txdb.cp(e))}async delVp(e){var t=this.db.batch();t.del(u.txdb.VP(e.pid)),await t.write()}async setVp(e,t){var i=this.db.batch();i.put(u.txdb.VP(e.pid),e.toRaw()),await i.write()}async getVp(e){return(e=await this.db.get(u.txdb.VP(e)))?W.fromRaw(e):null}async getVpByAddress(e){return{list:[],count:0}}async getVpByOid(e){return{list:[],count:0}}async loadVpList(){return this.db.values({gte:u.txdb.VP(P.ZERO_CID,"hex"),lte:u.txdb.VP(P.MAX_CID,"hex"),parse:e=>W.fromRaw(e)})}async saveContact(e){var t=this.db.batch();t.put(u.txdb.CT(e.getAddress()),e.toRaw()),await t.write()}async loadContact(e){var t;for(t of await this.db.values({gte:u.txdb.CT(P.ZERO_HASH160_HEX),lte:u.txdb.CT(P.MAX_HASH160_HEX),parse:e=>S.fromRaw(e,this)}))t.sender&&(t.sender.wallet=await this.get(t.sender.wid)),this.$contacts.set(t.address,t)}async delHtlc(e){var t;(e=new F(e)).id&&(this.htlcList.delete(e.id),this.htlcList.delAccount(e),(t=this.db.batch()).del(u.txdb.VH(e.shash,e.sidx)),await t.write())}async setSuggest(e){e=new F(e);var t,[t,i]=(this.htlcList.set(e.id,e),await this.getAccountByAddress(e.aa)),[t,i]=(t&&this.htlcList.setAccount(e,t,i),await this.getAccountByAddress(e.ba));(t=(t&&this.htlcList.setAccount(e,t,i),this.db.batch())).put(u.txdb.VH(e.shash,e.sidx),e.toRaw()),await t.write()}async setAssent(e){e=new F(e);var t,[t,i]=(this.htlcList.set(e.id,e),await this.getAccountByAddress(e.ab)),[t,i]=(t&&this.htlcList.setAccount(e,t,i),await this.getAccountByAddress(e.bb));(t=(t&&this.htlcList.setAccount(e,t,i),this.db.batch())).put(u.txdb.VH(e.shash,e.sidx),e.toRaw()),await t.write()}async loadHtlcList(){return this.db.values({gte:u.txdb.VH(P.ZERO_CID,0),lte:u.txdb.VH(P.MAX_CID,4294967295),parse:e=>F.fromRaw(e)})}async delComment(e){var t;(e=new M(e)).id&&(this.commentList.delete(e.id),this.commentList.delAccount(e),(t=this.db.batch()).del(u.txdb.VC(e.shash,e.sidx)),await t.write())}async setComment(e){e=new M(e);var t,[t,i]=(this.commentList.set(e.id,e),await this.getAccountByAddress(e.bob));(t=(t&&(this.commentList.setAccount(e,t,i),this.emit("comm.comment",e)),this.db.batch())).put(u.txdb.VC(e.shash,e.sidx),e.toRaw()),await t.write()}async loadCommentList(){return this.db.values({gte:u.txdb.VC(P.ZERO_CID,0),lte:u.txdb.VC(P.MAX_CID,4294967295),parse:e=>M.fromRaw(e)})}async delEr(e){var t=this.db.batch();t.del(u.txdb.ER(e.erid)),t.del(u.txdb.ERR(e.witness,e.erid,e.txid)),await t.write()}async setEr(e,t){t&&e.source&&(i=g.fromWitnessPubkeyhash(l.hash160(Buffer.from(e.source.pubkey,"hex")),this.network),[i,t]=await this.getAccountByAddress(i,t),e.wid=i,e.account=t);var i=this.db.batch();t=u.txdb.ERR(e.witness,e.erid,e.txid);i.put(t,e.toRaw()),i.put(u.txdb.ER(e.erid),t),await i.write()}async getEr(e){var t;return(e=await this.db.get(u.txdb.ER(e)))&&([,,t]=u.txdb.ERRR(e),e=await this.db.get(e))?((e=Y.fromRaw(e)).txid=t,e):null}async byPubkey(e,t,i=!1){var r,a=new _;e=await this.db.values({gte:u.txdb.ERR(e,P.NULL_HASH,P.NULL_HASH),lte:u.txdb.ERR(e,P.HIGH_HASH,P.HIGH_HASH),parse:e=>Y.fromRaw(e)});let s=[],n=new Map;if(i){for(var o of e)(!n.get(o.source.cluster)||o.startHeight>n.get(o.source.cluster).startHeight)&&n.set(o.source.cluster,await this.caVerifyObj(o));s=n.values()}else s=e;for(r of s)a.set(r.erid,r);return a.query(t)}async caVerifyObj(e){var t={verify:!1};if(!e||e.validHeight<=this.curHeight)return t;var i=await this.erAbList.getErAb(e.erid);return i&&i.abolishHeight<this.curHeight?t:(i=ae.fromPublic(Buffer.from(e.witness,"hex"),this.network.type),e.verify(i)?(e.verify=!0,0<(i=this.cpList.query([["pubKey",e.witness]])).list.length&&(e.cpid=i.list[0].cid),e):t)}async delErAbolish(e){var t=this.db.batch();t.del(u.txdb.ERA(e.erid)),await t.write()}async setErAbolish(e){var t=this.db.batch();t.put(u.txdb.ERA(e.erid),e.toRaw()),await t.write()}async getErAbolish(e){return(e=await this.db.get(u.txdb.ERA(e)))?q.fromRaw(e):null}loadErAbolishList(){return this.db.values({gte:u.txdb.ERA(P.ZERO_CID),lte:u.txdb.ERA(P.MAX_CID),parse:e=>q.fromRaw(e)})}async delAudit(e){var t=this.db.batch();t.del(u.txdb.AU(e.erid)),await t.write()}async setAudit(e){var t=this.db.batch();t.put(u.txdb.AU(e.erid),e.toRaw()),await t.write()}async getAudit(e){return(e=await this.db.get(u.txdb.AU(e)))?X.fromRaw(e):null}async loadAuditList(){return this.db.values({gte:u.txdb.AU(P.NULL_HASH),lte:u.txdb.AU(P.HIGH_HASH),parse:e=>X.fromRaw(e)})}async batchPut(e,t){var i=this.db.batch();i.put(e,t),await i.write()}async batchDel(e){var t=this.db.batch();t.del(e),await t.write()}async _insert(e,t,i){a(!e.mutable,"WDB: Cannot add mutable TX.");let r=await this.getWalletsByTX(e);if(r){this.logger.info("Incoming transaction for %d wallets in AccountDB (%s).",r.size,e.txid()),!t||this.state.marked||(this.logger.info("Marking AccountDB start block at %s (%d).",j.revHex(t.hash),t.height),await this.resetState(t,!0));let n=!1;for(const o of r){var s=await this.get(o);a(s),await s.add(e,t,i)&&(this.logger.info("Added transaction to wallet in AccountDB: %s (%d).",s.id,o),n=!0)}n||(r=null)}try{var n=await b.FactoryOfContract({env:this,block:t,tx:e});t?await n.confirm():await n.insert()}catch(n){t?this.logger.error("TX(%s) Smart Contract Confirm Error: %s",e.txid(),n.message):this.logger.error("TX(%s) Smart Contract Insert Error: %s",e.txid(),n.message)}return r}async _unconfirm(e,t){if(t)try{await(await b.FactoryOfContract({env:this,block:t,tx:e})).unconfirm()}catch(e){this.logger.error("Smart Contract Unconfirm Error: %s",e.message)}var i=e.hash("hex");if(!(e=t.txs.get(i).wids))return null;for(const t of e){var r=await this.get(t);a(r),await r.unconfirm(i)}}async resetChain(e){var t=await this.txLock.lock();try{return await this._resetChain(e)}finally{t()}}async _resetChain(e){if(e.height>this.curHeight)throw new Error(`WDB: Bad reset height ${e.height} while curHeight `+this.curHeight);var t;for(t of(await this.rollback(e.height)||await this._rescan(),await this.getWallets())){var i=await this.get(t);for(const t of await i.getPending())try{await i.abandon(t.hash)}catch(e){}}}async saveMSTrans(e){var t=await this.writeLock.lock();try{return await this._saveMSTrans(e)}finally{t()}}async _saveMSTrans(e){var t=this.db.batch();t.put(h.ms(g.getHash(e.addr,"hex"),e.txid),Buffer.from(JSON.stringify(e))),await t.write()}async listMSTrans(e){return e=g.getHash(e,"hex"),this.db.values({gte:h.ms(e,P.NULL_HASH),lte:h.ms(e,P.HIGH_HASH),parse:e=>JSON.parse(e.toString())})}async delMSTrans(e,t){var i=await this.writeLock.lock();try{return await this._delMSTrans(e,t)}finally{i()}}async _delMSTrans(e,t){e=g.getHash(e,"hex");var i=this.db.batch();i.del(h.ms(e,t)),await i.write()}}he.layout=h,e.exports=he},function(e,t,i){"use strict";
|
|
834
834
|
/*!
|
|
835
835
|
* txdb.js - persistent transaction pool
|
|
836
836
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -848,7 +848,7 @@ const r=i(5).ContractType;e.exports=function(e){if(!e)return i(188);switch(e.ope
|
|
|
848
848
|
* rpc.js - bitcoind-compatible json rpc for vallnet.
|
|
849
849
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
850
850
|
* https://github.com/bookmansoft/gamegold
|
|
851
|
-
*/const r=i(0),a=i(73);i(119);const s=i(85).walletdb,n=i(157),o=i(78),c=o.errors,u=o.MAGIC_STRING,h=i(77),l=i(59),p=i(107),d=i(2),f=i(193),m=i(3),g=i(80),v=i(33),y=i(17),b=i(7),w=i(6),x=i(26),k=i(13),S=i(38),_=i(131),E=i(68),j=i(46),A=i(20),R=i(136),I=i(137),{ContractType:O,ContractState:C,PropStatus:P,HtlcStatus:T}=i(5),B=i(138),N=i(123),z=i(142),F=i(19).opcodes,L=i(34),M=i(612);e.exports=class extends o{constructor(e){super(e),r(e,"RPC requires a WalletDB."),this.wdb=e,this.keys=e.keys,this.network=e.network,this.logger=e.logger.context("rpc"),this.client=e.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.admin",this.exportMnemonic),this.add("wallet.importmnemonic.admin",this.importMnemonic),this.add("wallet.export",this.dumpWallet),this.add("wallet.exports.admin",this.dumpWallets),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("wallet.rescan",this.rescan),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.map",this.mapAccounts),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("account.virtualadd.admin",this.accountVirtualAdd),this.add("account.checkamount",this.accountCheckAmount),this.add("balance.confirmed",this.getBalance),this.add("balance.all",this.getBalanceAll),this.add("balance.check",this.checkBalance),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.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.ownedAddress),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.query.remote",this.cpQueryRemote),this.add("cp.mine",this.cpMine),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.list.remote",this.queryErList),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("prop",this.routerOfProp),this.add("prop.create",this.propCreate),this.add("prop.createlist",this.propCreateList),this.add("prop.send",this.propExchange),this.add("prop.sendlist",this.propSendList),this.add("prop.sendlist.admin",this.propSendListAdmin),this.add("prop.found",this.propFound),this.add("inscription.create",this.inscriptionCreate),this.add("prop.wallet.byid",this.propGet),this.add("prop.wallet.byoid",this.listPropByOid),this.add("prop.wallet.byaddress",this.listProp),this.add("prop.sale",this.propSale),this.add("prop.buy",this.propBuy),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("tx.get.wallet",this.getTransaction),this.add("tx.list",this.listTransactions),this.add("tx.create",this.createTX),this.add("tx.attach",this.attach),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.spent",this.getSpent),this.add("coin.cache",this.getCoincacheSize),this.add("coin.check",this.checkUnspent),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(e){throw new h(c.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(e){throw new h(c.MISC_ERROR,"\n contract.create 发布交易对合约\n contract.promise 签署交易对合约\n contract.execute 执行交易对合约\n contract.mine 获取已签署交易对合约列表\n contract.list 查询并返回交易对\n ")}async routerOfHTLC(e){throw new h(c.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(e){throw new h(c.MISC_ERROR,"\n wallet.create 创建钱包\n wallet.list 列表钱包\n wallet.info 查询钱包概要\n wallet.block 查询区块信息\n wallet.exportmnemonic.admin 导出钱包助记词备份\n wallet.importmnemonic.admin 导入钱包助记词备份\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(e){throw new h(c.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(e){throw new h(c.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(e){throw new h(c.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(e){throw new h(c.MISC_ERROR,"\n cp.create 创建CP记录\n cp.change 修改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.user 生成用户令牌(钱包)\n ")}async routerOfSc(e){throw new h(c.MISC_ERROR,"\n sc.model 查询托管合约模板列表\n sc.register 指定托管合约模板,创建新的实例\n sc.query 查询托管合约实例列表\n sc.run 调用托管合约实例\n ")}async routerOfCa(e){throw new h(c.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 routerOfProp(e){throw new h(c.MISC_ERROR,"\n prop.create 创建道具\n prop.send 转移道具\n prop.createlist 批量创建道具\n prop.sendlist 批量转移道具\n prop.found 熔铸道具\n prop.byaddress 根据地址查询道具\n prop.byid 根据PID查询道具\n prop.wallet.byaddress 根据地址查询自己拥有的道具\n prop.wallet.byid 根据PID查询自己拥有的道具\n prop.wallet.byoid 根据OID查询自己拥有的道具\n ")}async allianceCreate(e,t,i){if(t||e.length<3)throw new h(c.MISC_ERROR,"sys.alliance.create password nodeid alliancename (host): 创建联盟节点证书 备份密码 节点编号 盟友名称 (节点地址)");e=(t=new g([e])).str(0);var r=t.uint(1,0),a=t.str(2,"").trim();t=t.str(3,"");if(!r||!e)throw new h(c.MISC_ERROR,"节点编号、备份密码都不能为空");if(a==this.wdb.$parent.config.allianceName)throw new h(c.MISC_ERROR,`子网名称不能和当前网络名称[${this.wdb.$parent.config.allianceName}]相同`);if(!this.wdb.$parent||!this.wdb.$parent.config.identityKey)throw new h(c.MISC_ERROR,"identityKey not set yet, please run sys.alliance.gettoken without params first");var[i,s]=await this.accessControl(i,""),n={body:{language:(n=await i.createAllianceInfo(a,r)).mnemonic.language,phrase:n.mnemonic.getPhrase(),passphrase:n.mnemonic.passphrase,alliancePrivateKey:n.alliancePrivateKey.toString("hex"),allianceName:a,allianceNodeId:r,awardAddress:n.awardAddress,allianceNodeToken:{network:this.network.type,alliancename:a,sn:r,prv:n.prv.toString("hex"),pub:n.pub.toString("hex"),address:n.address},notifyAddress:i.notifyAddress,authorized:""},password:e,network:this.network.type,file:this.network.type+`-${a}-${r}.keystore`};let o=N.encrypt(n);if(this.wdb.$parent){let i=!1;for(var u of this.wdb.$parent.config.alliances)if((u=u.split("|"))[0]==a&&u[1]==r){i=!0;break}i||(this.wdb.$parent.pool.authdb.addKnown(t,Buffer.from(n.body.allianceNodeToken.pub,"hex")),o=N.encrypt(n),this.wdb.$parent.config.alliances.push(`${a}|${r}|${o}|${e}|${n.body.awardAddress}|`+t),await this.wdb.$parent.saveConfigAsync())}e={host:t,an:n.body.allianceNodeToken.alliancename,ai:n.body.allianceNodeToken.sn,key:n.body.allianceNodeToken.pub};var d=p.signObj(e,i.notifyKey.privateKey);return await i.commNotify({dst:i.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:e,sig:d,pub:i.notifyKey.publicKey.toString("hex")})}),l.unsupported||await l.writeFile(n.file,o,"utf8"),e=(await i.getAccount(s)).getReceive().toString(),await this.wdb.logAudit({address:e,oper:"node.create",hash:a+"."+r,index:0}),{nodeid:r,alliancename:a,host:t,peerPubkey:n.body.allianceNodeToken.pub,awardAddress:n.body.awardAddress,file:n.file,notifyAddress:i.notifyAddress}}async allianceImport(e,t,i){if(t||e.length<3)throw new h(c.MISC_ERROR,"sys.alliance.import password nodeid alliancename key (host): 导入联盟节点 备份密码 节点编号 盟友名称 节点公钥 (节点地址)");if(!this.wdb.$parent||!this.wdb.$parent.config.identityKey)throw new h(c.MISC_ERROR,"identityKey not set yet, please run sys.alliance.gettoken without params first");e=(t=new g([e])).str(0);var r=t.uint(1,0),a=t.str(2,""),s=t.str(3,"");t=t.str(4,"");if(!r||!e||!s)throw new h(c.MISC_ERROR,"节点编号、备份密码、节点公钥都不能为空");var[i,n]=await this.accessControl(i,""),o={body:{alliancePrivateKey:(o=await i.createAllianceInfo(a,r,s)).alliancePrivateKey.toString("hex"),allianceName:a,allianceNodeId:r,allianceNodeToken:{network:this.network.type,alliancename:a,sn:r,pub:o.pub.toString("hex"),address:o.address},awardAddress:o.awardAddress,notifyAddress:i.notifyAddress,authorized:""},password:e,network:this.network.type,file:this.network.type+`-${a}-${r}.keystore`};let u;if(this.wdb.$parent){let i=!1;for(var d of this.wdb.$parent.config.alliances)if((d=d.split("|"))[0]==a&&d[1]==r){i=!0;break}i||(this.wdb.$parent.pool.authdb.addKnown(t,Buffer.from(s,"hex")),u=N.encrypt(o),this.wdb.$parent.config.alliances.push(`${a}|${r}|${u}|${e}|${o.body.awardAddress}|`+t),await this.wdb.$parent.saveConfigAsync())}else u=N.encrypt(o);return l.unsupported||await l.writeFile(o.file,u,"utf8"),s={host:t,key:o.body.allianceNodeToken.pub,an:o.body.allianceNodeToken.alliancename,ai:o.body.allianceNodeToken.sn},e=p.signObj(s,i.notifyKey.privateKey),await i.commNotify({dst:i.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:s,sig:e,pub:i.notifyKey.publicKey.toString("hex")})}),s=(await i.getAccount(n)).getReceive().toString(),await this.wdb.logAudit({address:s,oper:"node.create",hash:a+"."+r,index:0}),{nodeid:r,alliancename:a,host:t,peerPubkey:o.body.allianceNodeToken.pub,awardAddress:o.body.awardAddress,file:o.file,notifyAddress:i.notifyAddress}}async refreshAlliance(e,t,i){if(t)throw new h(c.MISC_ERROR,"sys.alliance.refresh amount: 为联盟成员批量充值 充值金额");var r=new g([e]).uint(0,0);if(r<1e4||5e9<r)throw new h(c.MISC_ERROR,"无效的充值金额(10000~5000000000)");var[a,s]=await this.accessControl(i);if(this.wdb.$parent)for(var n of this.wdb.$parent.config.alliances){n=n.split("|");var o=(k.fromString(n[4],this.network.type).isWitnessPubkeyhash()&&await a.send({outputs:[{address:n[4],value:r}]},s),N.decrypt({network:this.network.type,password:n[3],body:n[2]}));n=(this.wdb.$parent.rpc.addPeer&&await this.wdb.$parent.rpc.addPeer([n[5],o.allianceNodeToken.pub]),{host:n[5],key:o.allianceNodeToken.pub,an:o.allianceNodeToken.alliancename,ai:o.allianceNodeToken.sn}),o=p.signObj(n,a.notifyKey.privateKey);await a.commNotify({dst:a.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:n,sig:o,pub:a.notifyKey.publicKey.toString("hex")})})}}async refreshAllianceAsync(e,t,i){if(t)throw new h(c.MISC_ERROR,"sys.alliance.refresh.async amount: 为联盟成员批量充值 充值金额");var r=new g([e]).uint(0,0);if(r<1e4||5e9<r)throw new h(c.MISC_ERROR,"无效的充值金额(10000~5000000000)");var[a,s]=await this.accessControl(i);if(this.wdb.$parent)for(var n of this.wdb.$parent.config.alliances){n=n.split("|");var o=(k.fromString(n[4],this.network.type).isWitnessPubkeyhash()&&a.send({outputs:[{address:n[4],value:r}]},s),N.decrypt({network:this.network.type,password:n[3],body:n[2]}));n=(this.wdb.$parent.rpc.addPeer&&await this.wdb.$parent.rpc.addPeer([n[5],o.allianceNodeToken.pub]),{host:n[5],key:o.allianceNodeToken.pub,an:o.allianceNodeToken.alliancename,ai:o.allianceNodeToken.sn}),o=p.signObj(n,a.notifyKey.privateKey);a.commNotify({dst:a.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:n,sig:o,pub:a.notifyKey.publicKey.toString("hex")})})}}async allianceDelete(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"sys.alliance.delete nodeid alliancename: 删除联盟节点证书 节点编号 盟友名称");var r=(t=new g([e])).uint(0,0),a=t.str(1,""),[s,e]=await this.accessControl(i,"");if(!r||!a)throw new h(c.MISC_ERROR,"节点编号、节点名称都不能为空");if(this.wdb.$parent)for(let e=0;e<this.wdb.$parent.config.alliances.length;e++){var n,o=this.wdb.$parent.config.alliances[e].split("|");o[0]==a&&o[1]==r&&(this.wdb.$parent.config.alliances.splice(e,1),await this.wdb.$parent.config.saveAsync(),o[5])&&(o={host:o[5],an:a,ai:r},n=p.signObj(o,s.notifyKey.privateKey),await s.commNotify({dst:s.notifyAddress,content:JSON.stringify({cmd:"peerdel",payload:o,sig:n,pub:s.notifyKey.publicKey.toString("hex")})}))}return t=(await s.getAccount(e)).getReceive().toString(),await this.wdb.logAudit({address:t,oper:"node.delete",hash:a+"."+r,index:0}),!0}async getAllianceNodeToken(e,t,i){if(t)throw new h(c.MISC_ERROR,"sys.alliance.gettoken (nodeid alliancename pubkey): 创建联盟节点信道密钥 (节点编号 盟友名称)");e=(t=new g([e])).uint(0,0);var r=t.str(1);t=t.str(2);if(this.wdb.$parent)return[i]=await this.accessControl(i),i=await i.createAllianceInfo(r,e,t),r||(this.wdb.$parent.config.identityKey?(i.prv=Buffer.from(this.wdb.$parent.config.identityKey,"hex"),i.pub=x.publicKeyCreate(i.prv,!0),i.address=k.fromWitnessPubkeyhash(w.hash160(i.pub),this.network.type).toString()):(this.wdb.$parent.pool.options.identityKey=i.prv,this.wdb.$parent.config.identityKey=i.prv.toString("hex"),await this.wdb.$parent.saveConfigAsync())),{network:this.network.type,alliancename:r,sn:e,prv:i.prv.toString("hex"),pub:i.pub.toString("hex"),address:i.address};throw new h(c.MISC_ERROR,"this cmd can only run on fullnode.")}async allianceUserCreate(e,t,i){if(t)throw new h(c.MISC_ERROR,"sys.alliance.user cid uid (alliancename): 创建企业用户 企业编号 用户编号 (盟友名称)");return this.$allianceUserCreate(e,i)}async $allianceUserCreate(e,t,i){var r=(e=new g([e])).str(0),a=e.uint(1);let s=null,n=null;return n=(e=e.str(2,""))?([t]=await this.accessControl(t),w.hash256(Buffer.concat([Buffer.from(e),t.master.key.privateKey]))):Buffer.from(this.wdb.$parent.config.alliancePrivateKey,"hex"),e=S.fromPrivate(n,!0,this.network),(t=S.fromPrivate(w.hash256(Buffer.concat([Buffer.from(r+"-"+a),e.privateKey]),!0,this.network))).witness=!0,s=t.signData({cid:r,uid:a}),i&&(s.prvkey=t.privateKey.toString("hex")),s}async isReady(e){return this.wdb.isFull()}async shutdown(e,t){return this.wdb.$parent&&this.wdb.$parent.close().catch(e=>{setImmediate(()=>{throw e})}).finally(async()=>{await new Promise(e=>{setTimeout(e,1e4)}),process.exit(0)}),"Stopping."}async stop(e,t,i){if(t||0!==e.length)throw new h(c.MISC_ERROR,"sys.walletdb.stop");return this.wdb.close(),"Stopping walletdb..."}async destroyWalletDb(e,t,i){if(t||0!==e.length)throw new h(c.MISC_ERROR,"sys.walletdb.destroy: 删除钱包数据库");return await this.wdb.close(),await this.wdb.destroy(),"Destroyed."}async createWalletDb(e,t,i){if(t||0!==e.length)throw new h(c.MISC_ERROR,"sys.walletdb.create: 删除原有钱包数据库并重建");return await this.wdb.close(),await this.wdb.destroy(),await this.wdb.open(),"Created."}async fundRawTransaction(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,'tx.fund.admin "hexstring" ( options openid )');const r=new g([e]);var[t,e]=await this.accessControl(i,r.str(2,"")),a=(i=r.buf(0),r.obj(1));if(!i)throw new h(c.TYPE_ERROR,"Invalid hex string.");if(0===(i=E.fromRaw(i)).outputs.length)throw new h(c.INVALID_PARAMETER,"TX must have at least one output.");let s=null,n=null;if(a){const e=new g([a]);s=e.ufixed("feeRate",8),n=(n=e.str("changeAddress"))&&o.parseAddress(n,this.network)}return await t.fund(i,{rate:s,changeAddress:n,account:e}),{hex:i.toRaw().toString("hex"),changepos:i.changeIndex,fee:v.btc(i.getFee(),!0)}}async dumpPrivKey(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"key.export.private address [account]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));t=t.str(0,"");if(!await e.belongToAccount(i,t))throw new h(c.MISC_ERROR,"Invald Account.");if(i=o.parseHash(t,this.network),t=await e.getPrivateKey(i))return t.toSecret();throw new h(c.MISC_ERROR,"Key not found.")}async exportMnemonic(e,t,i){if(t||1!==e.length)throw new h(c.MISC_ERROR,"wallet.exportmnemonic.admin password: 备份钱包助记符 备份密码");t=new g([e]);var[e,i]=await this.accessControl(i);if(!(t=t.str(0)))throw new h(c.MISC_ERROR,"wallet.exportmnemonic.admin: Invalid password");if("primary"==e.id&&"default"!=i)throw new h(c.MISC_ERROR,"wallet.exportmnemonic.admin: Invalid Account");return i={body:{phrase:e.master.mnemonic.getPhrase(),language:e.master.mnemonic.language,passphrase:e.master.mnemonic.passphrase},password:t,network:this.network,file:`./${this.network.type}-wallet${e.db.options.spv?"-spv":""}.keystore`},this.wdb.$parent&&(i.body.awardAddress=this.wdb.$parent.config.coinbaseAddress),await N.writeEncryptFile(i),N.encrypt(i)}async importMnemonic(e,t,i){if(t||2!==e.length)throw new h(c.MISC_ERROR,"wallet.importmnemonic.admin encrypt password: 导入钱包助记符 备份文本 备份密码");var r;t=new g([e]);let a=N.decrypt({body:t.str(0),password:t.str(1),network:this.network});for(r of("string"==typeof a&&(a=JSON.parse(a)),this.wdb.$parent&&(a.awardAddress=this.wdb.$parent.config.coinbaseAddress),await this.wdb.getWallets()))if((await this.wdb.get(r)).master.mnemonic.getPhrase()===a.phrase)throw new h(c.MISC_ERROR,"wallet.importmnemonic.admin: 相同助记词已被使用");return(e=await this.wdb.ensure({id:z(),type:"pubkeyhash",m:1,n:1,mnemonic:a,passphrase:null,master:null,witness:!0,watchOnly:!1,accountKey:null}))?e.toJSON(!1):null}async dumpWallet(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"wallet.export filename (fragment): 导出钱包备份 备份文件全路径 (分片存储 true/false)");t=new g([e]);var[e,,]=await this.accessControl(i);if(i=t.str(0))return t=t.bool(1,!1),await e.exportToFile({file:i,fragment:t}),!0;throw new h(c.TYPE_ERROR,"Invalid filename.")}async dumpWallets(e,t,i){if(t)throw new h(c.MISC_ERROR,"wallet.exports.admin: 导出所有钱包备份");for(var r of await this.wdb.getWallets())await(await this.wdb.get(r)).exportToFile({file:`backup-${r}.txt`});return!0}async encryptWallet(e,t,i){if(t||1!==e.length)throw new h(c.MISC_ERROR,'wallet.encrypt "passphrase"');t=new g([e]);var[e,i]=await this.accessControl(i);t=t.str(0,"");if("primary"==e.id&&"default"!=i)throw new h(c.MISC_ERROR,"Invalid Account");if(e.master.encrypted)throw new h(c.WALLET_WRONG_ENC_STATE,"Already running with an encrypted wallet.");if(t.length<1)throw new h(c.MISC_ERROR,'wallet.encrypt "passphrase"');try{await e.setPassphrase(null,t)}catch(e){throw new h(c.WALLET_ENCRYPTION_FAILED,"Encryption failed.")}return"wallet encrypted"}async getAccount(e,t,i){if(t||1!==e.length)throw new h(c.MISC_ERROR,'address.account "address"');t=new g([e]);var[e,i]=await this.accessControl(i);return("primary"!=e.id||"default"==i)&&(i=t.str(0,""),t=o.parseHash(i,this.network),i=await e.getPath(t))?i.name:""}async getAddressesByIndex(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,'address.index "index"');t=new g([e]);var[e,i]=await this.accessControl(i);if("primary"!=e.id||"default"==i){var r=t.uint(0);for(const t of await e.getPaths("default")){var a=t.toAddress();if(0==t.branch&&t.index==r)return a.toString(this.network)}}}async accessControl(e,t){let i=await this.wdb.get("primary");if(this.wdb.options.acl.isRoot(e.options.cid))"primary"!==e.options.wid?(i=await this.wdb.get(e.options.wid),t=null):"*"===(t=t||"default")&&(t=null);else if("primary"!==e.options.wid){if(!await i.belongToAccount(e.options.cid,e.options.wid))throw new h(c.TYPE_ERROR,"Invalid wid.");i=await this.wdb.get(e.options.wid),t=null}else t=e.options.cid;return await i.ensureAccount({name:t,witness:!0}),[i,t]}async getAddressesByAccount(e,t,i){if(t)throw new h(c.MISC_ERROR,'address.list "account"');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=[],a=[],s=[];for(const t of await e.getPaths(i)){var n=t.toAddress();(0==t.branch?r:1==t.branch?a:s).push(n.toString(this.network))}return[r,a,s]}async getAccountAddress(e,t,i){if(t)throw new h(c.MISC_ERROR,'address.receive "account"');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));if(t=await e.getAccount(i))return t.receive.getAddress("string")}async getAccountChangeAddress(e,t,i){if(t)throw new h(c.MISC_ERROR,"address.change account");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));if(t=await e.getAccount(i))return t.change.getAddress("string")}async getAccountNestedAddress(e,t,i){if(t)throw new h(c.MISC_ERROR,'address.nested.list "account"');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));if(t=await e.getAccount(i))return t.nested.getAddress("string")}async getBalance(e,t,i){if(t||3<e.length)throw new h(c.MISC_ERROR,'balance.confirmed ( "account" minconf includeWatchonly )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=t.u32(1,0);t=t.bool(2,!1);if(e.watchOnly!==t)return 0;let a;return t=await e.getBalance(i),a=0<r?t.confirmed:t.unconfirmed,v.btc(a,!0)}async getBalanceLog(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,'balance.log "account" (height)');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0));t=t.uint(1,0);return e.queryBalanceLog(i,t)}async getBalanceAll(e,t,i){if(t||3<e.length)throw new h(c.MISC_ERROR,'balance.all ( "account" minconf includeWatchonly )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0));return(await e.getBalance(i)).toJSON()}async checkBalance(e,t,i){if(t)throw new h(c.MISC_ERROR,"balance.check");t=new g([e]);var[e,,]=await this.accessControl(i,t.str(0));return(await e.resetBalance()).toJSON()}async getUserToken(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"cp.user cid uid: 生成登录令牌 厂商编码 用户编码");e=(t=new g([e])).str(0),t=t.str(1);var[i]=await this.accessControl(i);return i.tokenCreate({cid:e,uid:t},t)}async masterkey(e,t,i){var[i,r]=await this.accessControl(i);if("primary"==i.id||"default"==r)return i.master.toJSON(!0)}async getHistory(e,t,i){if(t||1<e.length)throw new h(c.MISC_ERROR,"tx.history (page acct):查询交易历史记录 (页码 账号)");var r=(t=new g([e])).uint(0,1);if(r<1)throw new h(c.MISC_ERROR,"页面必须是大于0的数字");var[e,i]=await this.accessControl(i,t.str(1));t=await e.getHistory(i);a.sortTX(t);let s=0;var n,o=[];for(n of t){if(s<10*(r-1));else{if(s>=10*r)break;o.push(n)}s++}return i=await e.toDetails(o),(e={}).items=i,e.pageSize=10,e.pageNum=r,e.total=t.length,e}async sendSecret(e,t,i){if(t||e.length<3)throw new h(c.MISC_ERROR,"comm.secret dst message (openid): 安全通信消息 收信地址 信息内容 (玩家账号)");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(3,"")),r=t.str(0,"");t=t.str(1,"");if(o.parseAddress(r,this.network))return e.sendSecret(r,t,i);throw new h(c.TYPE_ERROR,"Invalid Destination Address.")}async calcHash(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"comm.hash content: 计算输入的哈希值");return t=new g([e]).str(0,""),w.hash256(Buffer.from(t)).toString("hex")}async commNotify(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"comm.notify addr content (openid): 发送点对点消息 地址 内容 (玩家账号)");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0,"");t=t.obj(1,{});return e.commNotify({dst:r,content:t,account:i})}async scanContact(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,'comm.scanContact "txid" ( index )');t=new g([e]);var[e,,]=await this.accessControl(i);i=t.hash(0),r(i,"Hash is required."),t=t.uint(1,-1);if(!i)throw new h(c.TYPE_ERROR,"Invalid parameter");if(e=await e.getTX(i))return this.wdb.scanContact(e.tx,t);throw new h(c.WALLET_ERROR,"TX not found.")}async listContact(e,t,i){if(t)throw new h(c.MISC_ERROR,"sys.listContact: 列表联系人");return t=new g([e]).array(0,[]),this.wdb.listContact(t,null,["address"])}async listNotify(e,t,i){if(t)throw new h(c.MISC_ERROR,"comm.listNotify (query): 通知列表 (查询条件,使用 account 参数可分账号查询)");return t=new g([e]).array(0,[]),this.wdb.listNotify(t)}async getReceivedByAccount(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,'account.received "account" ( minconf )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=t.u32(1,0),a=this.wdb.curHeight,s=(t=await e.getPaths(i),new Set);for(const e of t)s.add(e.hash);let n=0,o=-1;for(const t of await e.getHistory(i)){var u=t.getDepth(a);if(!(u<r)){(-1===o||u<o)&&(o=u);for(const e of t.tx.outputs){var l=e.getHash("hex");l&&s.has(l)&&(n+=e.value)}}}return v.btc(n,!0)}async getReceivedByAddress(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,'address.received "address" ( minconf )');t=new g([e]);var[e,,]=await this.accessControl(i),r=(i=t.str(0,""),t.u32(1,0)),a=this.wdb.curHeight,s=o.parseHash(i,this.network);let n=0;for(const t of await e.getHistory())if(!(t.getDepth(a)<r))for(const e of t.tx.outputs)e.getHash("hex")===s&&(n+=e.value);return v.btc(n,!0)}async _toWalletTX(e,t){var[e,,]=await this.accessControl(e),i=await e.toDetails(t);if(!i)throw new h(c.WALLET_ERROR,"TX not found.");let r=!0;for(const e of i.inputs)if(e.path){r=!1;break}var a=[];let s=0,n=0;for(let e=0;e<i.outputs.length;e++){var o=i.outputs[e];o.path?1!==o.path.branch&&(a.push({account:o.path.name,address:o.address.toString(this.network),category:"receive",amount:v.btc(o.value,!0),label:o.path.name,vout:e}),n+=o.value):r||(a.push({account:"",address:o.address?o.address.toString(this.network):null,category:"send",amount:-v.btc(o.value,!0),fee:-v.btc(i.getFee(),!0),vout:e}),s+=o.value)}return{amount:v.btc(r?n:-s,!0),confirmations:i.confirmations,blockhash:i.block?d.revHex(i.block):null,blockindex:i.index,blocktime:i.time,txid:d.revHex(i.hash),walletconflicts:[],time:i.mtime,timereceived:i.mtime,"bip125-replaceable":"no",details:a,hex:i.tx.toRaw().toString("hex")}}async getTransaction(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,'tx.get.wallet "txid" ( includeWatchonly )');t=new g([e]);var[e,,]=await this.accessControl(i),a=t.hash(0);r(a,"Hash is required."),t=t.bool(1,!1);if(!a)throw new h(c.TYPE_ERROR,"Invalid parameter");if(e=await e.getTX(a))return this._toWalletTX(i,e,t);throw new h(c.WALLET_ERROR,"TX not found.")}async abandonPending(e,t,i){if(t)throw new h(c.MISC_ERROR,"tx.abandonall.admin [account]: 废弃所有挂起的交易");t=new g([e]);var[r,e]=await this.accessControl(i,t.str(0,""));for(const t of await r.getPending(e))try{await r.abandon(t.hash)}catch(e){this.logger.warning(e.message)}return null}async abandonTransaction(e,t,i){if(t||1!==e.length)throw new h(c.MISC_ERROR,'tx.abandon.admin "txid"');t=new g([e]);var[e,,]=await this.accessControl(i);if(!(i=t.hash(0)))throw new h(c.TYPE_ERROR,"Invalid parameter.");if(await e.abandon(i))return null;throw new h(c.WALLET_ERROR,"Transaction not in wallet.")}async getUnconfirmedBalance(e,t,i){if(t||1<e.length)throw new h(c.MISC_ERROR,"balance.unconfirmed");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));t=await e.getBalance(i);return v.btc(t.unconfirmed,!0)}async importPrivKey(e,t,i){if(t||e.length<1||4<e.length)throw new h(c.MISC_ERROR,'key.import.private account "privatekey" passphrase [rescan]');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=t.str(1),a=t.str(2);t=t.bool(3,!1);return(r=o.parseSecret(r,this.network)).witness=!0,await e.importKey(i,r,a),t&&await this.wdb.rescan(0),!0}async walletAuth(e,t,i){return!0}async importWallet(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,'wallet.import "filename" ( rescan )');t=new g([e]);var[,]=await this.accessControl(i);e=t.str(0),i=t.bool(1,!1);return await this.wdb.loadBackup(e),i&&await this.wdb.rescan(0),!0}async importAddress(e,t,i){if(t||e.length<1||4<e.length)throw new h(c.MISC_ERROR,"address.import account address [rescan p2sh]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));let r=t.str(1,"");var a=t.bool(2,!1);if(t.bool(3,!1)){let e=t.buf(0);if(!e)throw new h(c.TYPE_ERROR,"Invalid parameters.");e=y.fromRaw(e),e=y.createScript(e.hash160(),y.types.SCRIPTHASH),r=k.fromScript(e)}else r=o.parseAddress(r,this.network);return await e.importAddress(i,r),a&&await this.wdb.rescan(0),!0}async importPubkey(e,t,i){if(t||e.length<1||4<e.length)throw new h(c.MISC_ERROR,"key.import.public account pubkey [rescan]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=t.buf(1);t=t.bool(2,!1);if(r)return r=S.fromPublic(r,this.network),await e.importKey(i,r),t&&await this.wdb.rescan(0),!0;throw new h(c.TYPE_ERROR,"Invalid parameter.")}async listAccounts(e,t,i){if(t||2<e.length)throw new h(c.MISC_ERROR,"account.list ( minconf includeWatchonly)");t=new g([e]);var[r]=await this.accessControl(i),a=t.u32(0,0),s=t.bool(1,!1),n={};for(const e of await r.getAccounts()){var o=await r.getBalance(e);let t=o.unconfirmed;0<a&&(t=o.confirmed),r.watchOnly!==s&&(t=0),n[e]=v.btc(t,!0)}return n}async mapAccounts(e,t,i){if(t||2<e.length)throw new h(c.MISC_ERROR,"account.list ( minconf includeWatchonly)");t=new g([e]);var[e]=await this.accessControl(i);return t.u32(0,0),t.bool(1,!1),e.getAccountMap()}async listConservedUnspent(e,t,i){if(t||0<e.length)throw new h(c.MISC_ERROR,"coin.conserved.list: 查询已经保持的Unspent列表");var[t]=await this.accessControl(i),r=[];for(const e of t.getConserved())r.push({txid:e.txid(),vout:e.index});return r}async accountVirtualAdd(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"account.virtualadd.admin account amount: 虚增账户余额 账户名称 金额");t=new g([e]);var[e]=await this.accessControl(i,t.str(2,""));i=t.str(0),t=t.u64(1),i=await e.ensureIndex(i);return e.txdb.addAccountAmount(i,t),!0}async accountCheckAmount(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"account.checkamount account: 验证账户余额 账户名称");t=new g([e]);var[e]=await this.accessControl(i,t.str(2,""));i=t.str(0),t=await e.ensureIndex(i);return e.txdb.checkAccountAmount(t),!0}async listReceivedByAccount(e,t,i){if(t||3<e.length)throw new h(c.MISC_ERROR,"account.listreceived ( minconf includeempty includeWatchonly )");e=(t=new g([e])).u32(0,0);var r=t.bool(1,!1);t=t.bool(2,!1);return this._listReceived(i,e,r,t,!0)}async listReceivedByAddress(e,t,i){if(t||3<e.length)throw new h(c.MISC_ERROR,"address.received.list ( minconf includeempty includeWatchonly )");e=(t=new g([e])).u32(0,0);var r=t.bool(1,!1);t=t.bool(2,!1);return this._listReceived(i,e,r,t,!1)}async _listReceived(e,t,i,r,a){var[s]=await this.accessControl(e),n=(e=await s.getPaths(),this.wdb.curHeight);const o=new Map;for(const t of e){var c=t.toAddress();o.set(t.hash,{involvesWatchonly:s.watchOnly,address:c.toString(this.network),account:t.name,amount:0,confirmations:-1,label:""})}for(const e of await s.getHistory()){var u=e.getDepth(n);if(!(u<t))for(const t of e.tx.outputs){var h,l=t.getAddress();l&&(h=l.getHash("hex"),h=o.get(h))&&((-1===h.confirmations||u<h.confirmations)&&(h.confirmations=u),h.address=l.toString(this.network),h.amount+=t.value)}}let p=[];for(const e of o.values())p.push(e);if(a){const e=new Map;for(const t of p){var d=e.get(t.account);d?d.amount+=t.amount:(e.set(t.account,t),t.address=void 0)}p=[];for(const t of e.values())p.push(t)}var f=[];for(const t of p)if(i||0!==t.amount){-1===t.confirmations&&(t.confirmations=0);try{t.amount=v.btc(t.amount,!0),f.push(t)}catch(e){this.logger.error("invalid amount:entry(%s) msg(%s)",JSON.stringify(t),e.message)}}return f}async listSinceBlock(e,t,i){if(t)throw new h(c.MISC_ERROR,'tx.history.since ( "blockhash" target-confirmations includeWatchonly account)');var r=this.wdb.curHeight,[e,a]=(t=new g([e]),await this.accessControl(i,t.str(3,""))),s=t.hash(0),n=t.u32(1,0);t=t.bool(2,!1);if(e.watchOnly!==t)return[];let o=-1;-1===(o=s&&(t=await this.client.getEntry(s))?t.height:o)&&(o=r);var u,l=[];let p;for(const t of await e.getHistory(a))t.height<o||t.getDepth(r)<n||((!p||t.height>p)&&(p=t),u=await this._toListTX(i,t),l.push(u));return{transactions:l,lastblock:p&&p.block?d.revHex(p.block):m.NULL_HASH}}async _toListTX(e,t){var[e]=await this.accessControl(e),i=await e.toDetails(t);if(!i)throw new h(c.WALLET_ERROR,"TX not found.");let a=!0;for(const e of i.inputs)if(e.path){a=!1;break}let s,n,o,u,l,p,f=0,m=0;for(let e=0;e<i.outputs.length;e++){const t=i.outputs[e];t.path?1!==t.path.branch&&(m+=t.value,n=t,u=e):(f+=t.value,s=t,o=e)}return p=a?(l=n,u):(l=s,o),l||(r(!a),a=!0,l=n,p=u),{account:l.path?l.path.name:"",address:l.address?l.address.toString(this.network):null,category:a?"receive":"send",amount:v.btc(a?m:-f,!0),label:l.path?l.path.name:void 0,vout:p,confirmations:i.getDepth(),blockhash:i.block?d.revHex(i.block):null,blockindex:i.index,blocktime:i.time,txid:d.revHex(i.hash),walletconflicts:[],time:i.mtime,timereceived:i.mtime,"bip125-replaceable":"no"}}async listTransactions(e,t,i){if(t||4<e.length)throw new h(c.MISC_ERROR,'tx.list ( "account" count from includeWatchonly)');t=new g([e]);var[e,r]=await this.accessControl(i,t.str(0,"")),s=t.u32(1,10),n=t.u32(2,0);t=t.bool(3,!1);if(e.watchOnly!==t)return[];var o=await e.getHistory(r),u=(t=(a.sortTX(o),n+s),Math.min(t,o.length)),l=[];for(let e=n;e<u;e++){var p=o[e];p=await this._toListTX(i,p);l.push(p)}return l}async selectone(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"coin.selectone options (account)");t=new g([e]);var[r,e]=await this.accessControl(i,t.str(1,"")),a=t.obj(0,{}),s=[];for(const t of await r.getCoins(e)){var n=t.getDepth(this.wdb.curHeight),o=t.getAddress();if(o){var u=t.getHash("hex");if(u&&!t.isColored&&!(a.value&&t.value<a.value||t.coinbase&&0<t.height&&this.wdb.curHeight<t.height+b.COINBASE_MATURITY)&&(u=await r.getKey(u),s.push({txid:t.txid(),vout:t.index,address:o?o.toString(this.network):null,account:u?u.name:void 0,redeemScript:u&&u.script?u.script.toJSON():void 0,scriptPubKey:t.script.toJSON(),amount:v.btc(t.value,!0),confirmations:n,spendable:!r.isConserved(t),solvable:!0}),a.len&&s.length>=a.len))break}}return s}async listUnspent(e,t,i){if(t||4<e.length)throw new h(c.MISC_ERROR,'coin.list ( minconf maxconf ["address", account] )');const r=new g([e]);var[s,t]=await this.accessControl(i,r.str(3,"")),n=r.u32(0,1),u=r.u32(1,9999999),l=r.array(2),p=this.wdb.curHeight,d=new Set;if(l&&0<l.length){const e=new g([l]);for(let t=0;t<l.length;t++){var f=e.str(t,"");f=o.parseHash(f,this.network);if(d.has(f))throw new h(c.INVALID_PARAMETER,"Duplicate address.");d.add(f)}}e=await s.getCoins(t);var m,y,b,w=(a.sortCoins(e),[]);for(const t of e)t.isColored||(m=t.getDepth(p))<n||u<m||((y=t.getAddress())?(b=t.getHash("hex"),l&&0<l.length&&(!b||!d.has(b))||(b=await s.getKey(b),w.push({txid:t.txid(),vout:t.index,address:y?y.toString(this.network):null,account:b?b.name:void 0,redeemScript:b&&b.script?b.script.toJSON():void 0,scriptPubKey:t.script.toJSON(),amount:v.btc(t.value,!0),confirmations:m,spendable:!s.isConserved(t),solvable:!0}))):this.logger.error("mistaken coin: miss address",t.hash,t.index));return w}async checkUnspent(e,t,i){if(t)throw new h(c.MISC_ERROR,"coin.check (account)");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=[];if(this.wdb.$parent)for(const t of await e.getCoins(i))await this.wdb.$parent.getCoin(t.hash,t.index)||r.push(t.txid(),t.index);return r}async listProp(e,t,i){if(t||4<e.length)throw new h(c.MISC_ERROR,"prop.wallet.byaddress ( minconf maxconf [address, account] )");const r=new g([e]);var[s,t]=await this.accessControl(i,r.str(3,"")),n=r.u32(0,1),u=r.u32(1,9999999),l=r.array(2),p=this.wdb.curHeight,d=new Set;if(l){const e=new g([l]);for(let t=0;t<l.length;t++){var f=e.str(t,"");f=o.parseHash(f,this.network);if(d.has(f))throw new h(c.INVALID_PARAMETER,"Duplicate address.");d.add(f)}}e=await s.getCoins(t);var m=(a.sortCoins(e),[]);for(const t of e){var y,b,w,x=t.getDepth(p);x<n||u<x||(y=t.getAddress())&&(b=t.getHash("hex"),!l||b&&d.has(b))&&(b=await s.getKey(b),w=t.getReturnData([F.OP_PROPCREATE,F.OP_PROPCREATE]))&&m.push({txid:t.txid(),vout:t.index,address:y?y.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 m}async listPropByOid(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"prop.wallet.byoid oid");t=new g([e]);var[r,e]=await this.accessControl(i,t.str(1,"")),s=t.str(0),n=this.wdb.curHeight,o=(i=await r.getCoins(e),a.sortCoins(i),[]);for(const e of i){var u,l,p,d=e.getDepth(n);d<0||9999999<d||(u=e.getAddress())&&(l=e.getHash("hex"),l=await r.getKey(l),p=e.getReturnData([F.OP_PROPCREATE,F.OP_PROPEXCHANGE]))&&p.oid==s&&o.push({txid:e.txid(),vout:e.index,address:u?u.toString(this.network):null,account:l?l.name:void 0,amount:v.btc(e.value,!0),confirmations:d,spendable:!r.isConserved(e),solvable:!0,nd:p})}return{list:o,count:o.length}}async listLockedUnspent(e,t,i){if(t||2<e.length)throw new h(c.MISC_ERROR,'coin.list.locked ["address", account]');const r=new g([e]);var[s,t]=await this.accessControl(i,r.str(1,"")),n=r.array(0),u=this.wdb.curHeight,l=d.now(),p=new Set;if(n){const e=new g([n]);for(let t=0;t<n.length;t++){var f=e.str(t,"");f=o.parseHash(f,this.network);if(p.has(f))throw new h(c.INVALID_PARAMETER,"Duplicate address.");p.add(f)}}let m;m=account?await s.getCoins(t):s.getLockedCoins(),a.sortCoins(m);var y,b,w,x,k,S,_=[];for(const e of m)(e.lockedByLocktime(u,l)||e.lockedBySequence(u,l))&&(y=e.getAddress())&&(b=e.getDepth(u),S=e.getHash("hex"),!n||S&&p.has(S))&&([w,x,k]=e.getLockStatus(),S=await s.getKey(S),_.push({txid:e.txid(),vout:e.index,address:y?y.toString(this.network):null,account:S?S.name:void 0,redeemScript:S&&S.script?S.script.toJSON():void 0,scriptPubKey:e.script.toJSON(),amount:v.btc(e.value,!0),confirmations:b,spendable:!1,solvable:!0,locktype:w,lockheight:x,locktime:k}));return _}async listOperUnspent(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,'coin.conserved.oper.list unlock ([{"txid":"txid","vout":n},...]) 保持/解除保持一组UTXO: true/false [{"txid": "交易id","vout": "输出序号"}]');const r=new g([e]);var[a]=await this.accessControl(i),s=r.bool(0,!1);if(!(t=r.array(1)))throw new h(c.TYPE_ERROR,"Invalid parameter.");for(const e of t){const t=new g([e]);var n=t.hash("txid"),o=t.u32("vout");if(null==n||null==o)throw new h(c.INVALID_PARAMETER,"Invalid parameter.");n=new j(n,o),s?a.unConserveCoin(n):a.conserveCoin(n)}return!0}async setTXFee(e,t,i){if(t||e.length<1||1<e.length)throw new h(c.MISC_ERROR,"sys.setfee rate");if(null==(t=new g([e]).ufixed(0,8)))throw new h(c.TYPE_ERROR,"Invalid parameter.");return this.wdb.feeRate=t,!0}async signMessage(e,t,i){if(t||2!==e.length)throw new h(c.MISC_ERROR,'sys.message.sign "address" "message"');t=new g([e]);var[e]=await this.accessControl(i);if(!e.master.key)throw new h(c.WALLET_UNLOCK_NEEDED,"Wallet is locked.");i=t.str(0,""),i=o.parseHash(i,this.network);if(e=await e.getKey(i))return i=t.str(1,""),e.sign(w.hash256(Buffer.from(u+i,"utf8"))).toString("base64");throw new h(c.WALLET_ERROR,"Address not found.")}async changePassphrase(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,'wallet.changepassphrase "oldpassphrase" "newpassphrase"');t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0,""),t=t.str(1,"");if(!e.master.encrypted)throw new h(c.WALLET_WRONG_ENC_STATE,"Wallet is not encrypted.");if(i.length<1||t.length<1)throw new h(c.INVALID_PARAMETER,"Invalid parameter");return await e.setPassphrase(i,t),null}async unlock(e,t,i){var r=new g([e]),[i]=await this.accessControl(i),a=r.str(0);r=r.u32(1,60);if(t||i.master.encrypted&&0==e.length)throw new h(c.MISC_ERROR,'wallet.unlock "passphrase" timeout');if(!i.master.encrypted)throw new h(c.WALLET_WRONG_ENC_STATE,"Wallet is not encrypted.");if(a.length<1)throw new h(c.INVALID_PARAMETER,"Invalid parameter");if(null==r)throw new h(c.TYPE_ERROR,"Invalid parameter");return await i.unlock(a,r),null}async decryptWallet(e,t,i){if(t||1!==e.length)throw new h(c.MISC_ERROR,'wallet.decrypt "passphrase"');t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0,"");if(!e.master.encrypted)throw new h(c.WALLET_WRONG_ENC_STATE,"Running with an decrypted wallet.");if(i.length<1)throw new h(c.MISC_ERROR,'wallet.decrypt "passphrase"');try{await e.setPassphrase(i)}catch(e){throw new h(c.WALLET_ENCRYPTION_FAILED,"Decryption failed.")}return"wallet decrypted"}async importPrunedFunds(e,t,i){if(t||e.length<2||3<e.length)throw new h(c.MISC_ERROR,'tx.importprunedfunds.admin "rawtransaction" "txoutproof" ( "label" )');if(e=(t=new g([e])).buf(0),t=t.buf(1),!e||!t)throw new h(c.TYPE_ERROR,"Invalid parameter.");e=A.fromRaw(e);var r=(t=_.fromRaw(t)).hash("hex");if(!t.verify())throw new h(c.VERIFY_ERROR,"Invalid proof.");if(!t.hasTX(e.hash("hex")))throw new h(c.VERIFY_ERROR,"Invalid proof.");var a=await this.client.getEntry(r);if(-1===a)throw new h(c.VERIFY_ERROR,"Invalid proof.");if(r={hash:r,time:t.time,mtp:t.mtp,height:a},await this.wdb.addTX(e,r))return null;throw new h(c.WALLET_ERROR,"No tracked address for TX.")}async removePrunedFunds(e,t,i){if(t||1!==e.length)throw new h(c.MISC_ERROR,'tx.removeprunedfunds.admin "txid"');t=new g([e]);var[e]=await this.accessControl(i);if(!(i=t.hash(0)))throw new h(c.TYPE_ERROR,"Invalid parameter.");if(await e.remove(i))return null;throw new h(c.WALLET_ERROR,"Transaction not in wallet.")}async getWallets(e,t,i){return this.wdb.getWallets()}async getWalletBlock(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"wallet.block height");t=new g([e]);var[e]=await this.accessControl(i);i=t.uint(0);return(t=await e.getBlock(i))?t.toJSON():null}async getWalletLayoutH(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"wallet.layouth height");return t=new g([e]).uint(0),(e=await this.wdb.getBlock(t))?e.toJSON():null}async getWalletInfo(e,t,i){if(t)throw new h(c.MISC_ERROR,"wallet.info");return((t=new g([e]).str(0,""))?await this.wdb.get(t):(await this.accessControl(i))[0]).toJSON(!1)}async scRegister(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"sc.register options (account): 发布合约 合约参数列表 (子账户)");t=new g([e]);var[r,a]=await this.accessControl(i,t.str(1,""));let s=t.obj(0);if(!s)throw new h(c.MISC_ERROR,"sc.register: options is null");let n=1e5;switch(s.oper){case"change":if(s.oper=O.scState,!s.dst||!s.state)throw new h(c.TYPE_ERROR,"sc.register: dst or state is null.");if(!this.wdb.$parent)throw new h(c.TYPE_ERROR,"sc.register: not support this operation.");var o=await this.wdb.$parent.chain.db.getSCList([["options.dst",s.dst]]);if(!o||0==o.list.length)throw new h(c.TYPE_ERROR,"sc.register: contract not exist.");switch(o.list[0].options.state){case C.Normal:if(s.state!=C.Frozen&&s.state!=C.Destroy)throw new h(c.TYPE_ERROR,"Contract State Error");break;case C.Frozen:if(s.state!=C.Normal&&s.state!=C.Destroy)throw new h(c.TYPE_ERROR,"Contract State Error");break;default:throw new h(c.TYPE_ERROR,"Contract State Error")}if(s.addr=o.list[0].options.addr,await r.belongToAccount(a,s.addr))break;throw new h(c.MISC_ERROR,"sc.register: Invald Account.");case"update":if(s.oper=O.scUpdate,!s.dst)throw new h(c.TYPE_ERROR,"sc.register: dst is null.");if(!this.wdb.$parent)throw new h(c.TYPE_ERROR,"sc.register: not support this operation.");if(!(o=await this.wdb.$parent.chain.db.getSCList([["options.dst",s.dst]]))||0==o.list.length)throw new h(c.TYPE_ERROR,"sc.register: contract not exist.");if(o.list[0].options.state!=C.Normal)throw new h(c.TYPE_ERROR,"sc.register: contract state error.");if(s.addr=o.list[0].options.addr,await r.belongToAccount(a,s.addr))break;throw new h(c.MISC_ERROR,"sc.register: Invald Account.");default:if(n=1e8,s.oper=O.scRegister,s.addr=(await r.createReceive(a)).getAddress("string"),s.dst=r.getSCAddress(d.hashInt(s.addr)).toString(),this.wdb.$parent&&(o=await this.wdb.$parent.chain.db.getSCList([["options.dst",s.dst]]))&&0<o.list.length)throw new h(c.TYPE_ERROR,"sc.register: contract address conflict.")}return(e=(await r.getPrivateKey(s.addr)).signData(s)).data.sig=e.sig,s=e.data,i=await r.send({subtractFee:!1,sort:!1,outputs:[{address:s.dst,value:n}],comment:JSON.stringify(s)},a),await this.wdb.logAudit({address:s.addr,oper:s.oper,hash:i.hash("hex"),index:0}),s.txid=i.rhash(),s}async scRun(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,'sc.run str options (account): 调用合约 逗分参数字符串("合约收款地址,转账金额") 参数对象 (子账户)');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0).split(","),a=(t=t.obj(1,{}),r.shift());if(!this.wdb.$parent)throw new h(c.TYPE_ERROR,"sc.run: not support this operation.");var s=await this.wdb.$parent.chain.db.getSCList([["options.dst",a]]);if(!s||0==s.list.length)throw new h(c.TYPE_ERROR,"sc.run: contract not exist.");if(1!=s.list[0].options.state)throw new h(c.TYPE_ERROR,`sc.run: contract execute disabled(state ${s.list[0].options.state}).`);if(t.ver&&t.ver!=s.list[0].options.ver)throw new h(c.TYPE_ERROR,"sc.run: contract version inconsistency.");return s=(0|parseInt(r.shift()))>>>0,o.parseAddress(a,this.network),r=await e.send({subtractFee:!1,sort:!1,outputs:[{address:a,value:s}],comment:JSON.stringify({oper:"scrun",params:t})},i),a=await e.getAccount(i),await this.wdb.logAudit({address:a.receive.getAddress("string"),oper:O.scRun,hash:r.hash("hex"),index:0}),(await e.getDetails(r.hash("hex"))).toJSON()}async cpRegister(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,'cp.create name "ip,addr,class,rate" (openid): 注册厂商 名称(不少于4个字符) "IP地址,注册地址,类别,媒体分成比例" (子账号)');return this.$cpRegister(e,i,!1)}async cpRegisterAsync(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,'cp.create.async name "ip,addr,class,rate" (openid): 注册厂商 名称(不少于4个字符) "IP地址,注册地址,类别,媒体分成比例" (子账号)');return this.$cpRegister(e,i,!0)}async $cpRegister(e,t,i){e=new g([e]);var r=decodeURIComponent(e.str(0)),a=(o=e.str(1,"").split(","))[0],s=o[1],n=o[2],o=o[3]?parseInt(o[3]):15,[t,e]=await this.accessControl(t,e.str(2,"")),u=f.verifyDataFormat({name:r,ip:a,grate:o,cls:n});if(u)throw new h(c.MISC_ERROR,u);return u={cid:z(),oper:O.cpRegister,name:r,ip:a,grate:o,cls:n},await t.cpRegister(d.isBech32(s)?s:null,u,e,i),u}async cpChange(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,'cp.change cid "newname,ip,addr,class,rate" "openid": 修改厂商信息 CP编号 "新的名称,IP,新的注册地址,类别,分成比例" 授权账号');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),a=t.str(0),s=(t=decodeURIComponent(t.str(1,"")).split(","))[0],n=t[1];let o=t[2];var u=t[3];t=parseInt(t[4])||null;if(l=f.verifyDataFormat({name:s,ip:n,grate:t,cls:u}))throw new h(c.MISC_ERROR,l);o&&(o=k.fromString(o),r(o instanceof k,"Not an address."));var l={cid:a,newName:s,ip:n,addr:o,grate:t,cls:u},[,,]=await e.cpChange(l,i);return l.addr=l.addr.toString(),l}async cpQuery(e,t,i){if(t)throw new h(c.MISC_ERROR,"cp.query (conditions account): 查询钱包中的厂商列表 (复合条件 子帐号)");t=new g([e]);var r,[a,s]=await this.accessControl(i,t.str(1,""));e=t.array(0,[]),i=a.db.cpList.query(e);for(r of i.list)r.owned=await a.belongToAccount(s,r.current.address);return i}async cpQueryRemote(e,t,i){if(t)throw new h(c.MISC_ERROR,"cp.query.remote conditions: 查询厂商列表 (复合条件)");t=new g([e]);var r,[a,s]=await this.accessControl(i,t.str(1,""));e=t.array(0,[]),i=await a.db.client.execute("cp.remoteQuery",[e]);for(r of i.list)r.owned=await a.belongToAccount(s,r.current.address);return i}async cpMine(e,t,i){if(t)throw new h(c.MISC_ERROR,"cp.mine (conditions account): 查询钱包中归属当前操作员/指定账户的厂商列表 (复合条件 子帐号)");t=new g([e]);let[r,a]=await this.accessControl(i,t.str(1,""));return(e=t.array(0,[])).push(["size",-1]),(await r.db.cpList.predict(async(e,t)=>r.belongToAccount(a,t.current.address))).query(e)}async htlcSuggest(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,"htlc.suggest params [account]: 发起HTLC 参数对象({alice, bob, amount, rate}) [子账户]");e=(t=new g([e])).obj(0,{});var r,[i,t]=await this.accessControl(i,t.str(1,""));if(!e.ab)throw new h(c.MISC_ERROR,"htlc.suggest: params.ab(alice bchain address) is null");if(!Number.isInteger(e.amount))throw new h(c.MISC_ERROR,"htlc.suggest: illegal params.amount");if(e.amount=parseInt(e.amount),e.amount<0||e.amount>1e4*b.COIN)throw new h(c.MISC_ERROR,"htlc.suggest: illegal params.amount");if(e.rate=parseFloat(e.rate),e.rate<0||e.amount*e.rate>b.MAX_MONEY)throw new h(c.MISC_ERROR,"htlc.suggest: illegal params.rate");if(e.target)return r=(await i.createReceive(t)).getAddress().toString(this.network),e={amount:e.amount,rate:e.rate,dst:e.target,aa:k.fromString(r).hash,ab:k.fromString(e.ab).hash,ba:k.fromString(e.ba).hash},[i]=await i.sendContracts([e],t,R),i?{txid:i.rhash(),aa:r}:null;throw new h(c.MISC_ERROR,"htlc.suggest: params.target is null")}async htlcAssent(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,"htlc.assent params({txid}) [account]: 响应HTLC 参数对象 [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));t=t.obj(0,{});if(!Number.isInteger(t.amount))throw new h(c.MISC_ERROR,"htlc.assent: illegal params.amount");if(t.amount=parseInt(t.amount),t.amount<0||t.amount>1e4*b.COIN)throw new h(c.MISC_ERROR,"htlc.assent: illegal params.amount");if(t.rate=parseFloat(t.rate),t.rate<0||t.amount*t.rate>b.MAX_MONEY)throw new h(c.MISC_ERROR,"htlc.assent: illegal params.rate");var r=(await e.createReceive(i)).getAddress().toString(this.network),[t]=(r={src:t.src,dst:t.dst,hash:t.hash,index:t.index,ab:Buffer.from(t.ab,"hex"),ba:Buffer.from(t.ba,"hex"),bb:k.fromString(r).hash,amount:t.amount*t.rate},await e.sendContracts([r],i,I));return t?{txid:t.rhash()}:null}async htlcSuggestDeal(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,"htlc.suggest.deal params({txid,index,sa}) [account]: 兑付HTLC 参数对象 [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,"")),[e,,]=(t=t.obj(0),t={suggest:!0,hash:d.revHex(t.txid),index:t.index,sa:t.sa},await e.htlcDeal(t,i));return e?{txid:e.rhash()}:null}async htlcQuery(e,t,i){if(t)throw new h(c.MISC_ERROR,"htlc.query query: 条件查询HTLC合约 条件数组");return(t=new g([e]).array(0,[])).push(["pst","!=",T.Cancel]),this.wdb.htlcList.query(t)}async htlcAssentDeal(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,"htlc.assent.deal params({txid,index,sa}) [account]: 兑付HTLC 参数对象 [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,"")),[e,,]=(t=t.obj(0),t={hash:d.revHex(t.txid),index:t.index,sa:t.sa},await e.htlcDeal(t,i));return e?{txid:e.rhash()}:null}async htlcAssentCancel(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,"htlc.assent.cancel params({txid, index, master}) [account]: 取消HTLC应答 参数对象 [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,"")),[e,,]=(t=t.obj(0),t={hash:d.revHex(t.txid),index:t.index,master:t.bb},await e.htlcCancel(t,i));return e?{txid:e.rhash()}:null}async htlcSuggestCancel(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,"htlc.suggest.cancel params({txid, index, sa, master}) [account]: 取消HTLC请求 参数对象 [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,"")),[e,,]=(t=t.obj(0),t={suggest:!0,hash:d.revHex(t.txid),index:t.index,sa:t.sa,master:t.aa},await e.htlcCancel(t,i));return e?{txid:e.rhash()}:null}async sendComment(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,"comm.comment params [account]: 发起附言交易 参数对象({body, bob}) [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));t=t.obj(0,{});if(!Number.isInteger(t.amount))throw new h(c.MISC_ERROR,"comm.comment: illegal params.amount");if(t.amount=parseInt(t.amount),t.amount<0||t.amount>1e4*b.COIN)throw new h(c.MISC_ERROR,"comm.comment: illegal params.amount");var r={bob:t.bob,body:t.body,amount:t.amount};t.alice||(t.alice=e.getAddress(),i&&(a=await e.createReceive(i),t.alice=a.getAddress()));var a=(await e.getPrivateKey(t.alice)).signData(r),[t]=(a.data.sig=a.sig,await e.sendContracts([a.data],i,B));return t?{txid:t.rhash()}:null}async commentQuery(e,t,i){if(t)throw new h(c.MISC_ERROR,"comm.comment.query query: 条件查询附言输出 条件数组");return t=new g([e]).array(0,[]),this.wdb.commentList.query(t)}async contractExecute(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,"contract.execute tid master: 执行交易对合约 交易编号 执行方(1-发起人,2-承兑人)");t=new g([e]);var[e]=await this.accessControl(i),[e,,]=(i=t.str(0),t=t.u32(1,2),await e.contractExecute(i,t));return e.toJSON()}async contractPromise(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,"contract.promise tid [openid]: 签署交易对合约 交易编号(type.address) [子账号]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,"")),[e,,]=(t=t.str(0),await e.contractPromise(t,i));return e.toJSON()}async contractOfMine(e,t,i){if(t||e.length<1||3<e.length)throw new h(c.MISC_ERROR,"contract.mine type page [openid]: 获取已签署交易对合约列表 交易对类型 页码 [子账号]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.uint(0,1);t=t.uint(1,1);return e.db.getContracts(r,t,i)}async contractCreate(e,t,i){if(t||e.length<4||5<e.length)throw new h(c.MISC_ERROR,"contract.create type src dst addr [openid] : 发布一个交易对合约 交易对类型 出让游戏金数值 换取兑换币数值 兑换币收款地址 [子账号]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(4,"")),r=t.u64(0),a=t.u64(1),s=t.u64(2),[e,,]=(t=t.str(3),await e.contractCreate(r,a,s,t,i));return e.toJSON()}async propGet(e,t,i){if(t)throw new h(c.MISC_ERROR,"prop.wallet.byid pid: 查询自己的物品 PID");return t=new g([e]).str(0,""),e=[],(t=await this.wdb.propList.getVp(t))&&t.pst!=P.Delete&&e.push(t),e}async propQuery(e,t,i){if(t)throw new h(c.MISC_ERROR,"prop.query query: 条件查询自己的物品 条件数组");t=new g([e]);var[e]=await this.accessControl(i,t.str(1,""));return(i=t.array(0,[])).push(["pst","!=",P.Delete]),(await e.getPropList()).query(i)}async mySaleList(e,t,i){if(t)throw new h(c.MISC_ERROR,"prop.query.auction (page acct): 查询自己拍卖的物品 (页码 账户)");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));t=t.uint(0,1);return e.mySaleList(t,i)}async onSaleList(e,t,i){e=new g([e]);var[i,r]=await this.accessControl(i,e.str(1,""));e=e.uint(0,1);return i.onSaleList(e,r)}async propBuy(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"prop.buy pid price [openid] : 竞拍道具 道具编号 出价 [子账号]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0),[e,,]=(t=t.u64(1),await e.propBuy(r,t,i));return e.toJSON()}async propFound(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"prop.found pid (openid): 熔铸道具 道具编号 (账号)");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));t=t.str(0);if(!(t=await e.db.propList.getVp(t))||t.pst==P.Delete)throw new h(c.MISC_ERROR,"prop.found prop not exist");if(!await e.ownedAddress(t.current.address))throw new h(c.MISC_ERROR,"prop.found: current account not owned prop.");if(t.pst!=P.Ready)throw new h(c.MISC_ERROR,"prop.found prop can not be found on current status");var[e,,t]=await e.propFound(t.current.hash,t.current.index,i);if(e&&t)return{hash:e.hash("hex"),txid:e.rhash(),index:0,cid:t.cid,pid:t.pid,oid:t.oid,gold:e.outputs[0].value}}async propSale(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"prop.sale pid fixedPrice [openid]: 拍卖道具 道具编号 一口价 [子帐号]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0);if(!(r=await e.db.propList.getVp(r))||r.pst==P.Delete)throw new h(c.MISC_ERROR,"prop.sale prop not exist");if(r.pst!=P.Ready)throw new h(c.MISC_ERROR,"prop.sale prop cannt be sent on current status");t=t.u64(1,0);var[e,,]=await e.propSale(r.current.hash,r.current.index,t,i);return e.toJSON()}async propSendListAdmin(e,t,i){return this.propSendList(e,t,i,!0)}async propSendList(e,t,i,r=!1){if(t||e.length<1)throw new h(c.MISC_ERROR,"prop.sendlist (addr|txid|index)(n,) [openid]: 批量转移道具 道具数组(地址|交易ID|输出索引) [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,"")),a=[];if((t=t.str(0).split(","))&&Array.isArray(t))for(var s of t){var n,o;3<=(s=s.split("|")).length&&(n=s[0],o=new j(d.revHex(s[1]),parseInt(s[2])),4<=s.length?a.push([o,k.fromString(n),s[3]]):a.push([o,k.fromString(n)]))}var[t,,e]=await e.propExchangeList(a,i,r);if(t&&e){let i=t.hash("hex"),r=t.rhash();return e.map(e=>({hash:i,txid:r,cid:e.cid,pid:e.pid,oid:e.oid,gold:e.gold,addr:e.addr}))}}async propReceive(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"prop.receive tx [account]: 捐赠接收函数 捐赠交易字符串 [接收账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));if(!(t=t.buf(0)))throw new h(c.TYPE_ERROR,"Invalid TX Info.");t=A.fromRaw(t);var[e,,t]=await e.propReceive(t,i);if(e&&t)return{hash:e.hash("hex"),txid:e.rhash(),cid:t.cid,pid:t.pid,oid:t.oid,gold:t.gold,addr:t.simAddr,gaddr:t.gaddr}}async propDonate(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"prop.donate pid [openid]: 捐赠道具函数 道具ID [发起账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));t=t.str(0);if(!(t=await e.db.propList.getVp(t))||t.pst==P.Delete)throw new h(c.MISC_ERROR,"prop not exist");if(t.pst!=P.Ready)throw new h(c.MISC_ERROR,"prop cannt be sent on current status");t=new j(t.current.hash,t.current.index);var[e,,t]=await e.propDonate(t,i);if(e&&t)return{hash:e.hash("hex"),txid:e.rhash(),cid:t.cid,pid:t.pid,oid:t.oid,gold:t.gold,raw:e.toRaw().toString("hex")}}async propExchange(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"prop.send addr pid [openid]: 转移道具函数 接收地址 物品编号 [发起账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0);t=t.str(1);if(!(t=await e.db.propList.getVp(t))||t.pst==P.Delete)throw new h(c.MISC_ERROR,"prop.send prop not exist");if(t.pst!=P.Ready)throw new h(c.MISC_ERROR,"prop.send prop cannt be sent on current status");var[e,,t]=await e.propExchange(new j(t.current.hash,t.current.index),k.fromString(r),i);if(e&&t)return{hash:e.hash("hex"),txid:e.rhash(),cid:t.cid,pid:t.pid,oid:t.oid,gold:t.gold,addr:r}}async propCreateList(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"prop.createlist (cid|oid|gold|pid)(n,) [openid]: 批量创建道具 道具信息数组 [发起账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));let r=[];if((t=t.str(0).split(","))&&Array.isArray(t))for(var a of t)if(3<=(a=a.split("|")).length){var s=a[0],n=a[1],o=parseInt(a[2]);let e=null;4<=a.length&&(e=a[3]),o<b.MINPROPVALUE||r.push([s,n,o,e])}r=r.map(e=>{var[e,t,i,r]=e;return{oper:O.propCreate,cid:e,oid:t,gold:i,pid:r}});var[t,,]=await e.propCreate(r,i);return t?r:null}readImageAsBlob(e,t){l.readFile(e).then(i=>{var r=M.getType(L.basename(e));t(null,{hex:i.toString("hex"),type:r})}).catch(e=>{t(e,null)})}async inscriptionCreate(e,t,i){if(!(t||e.length<2)){t=new g([e]);var[e,r]=await this.accessControl(i,t.str(4,"")),a=t.str(0);let u=t.str(1);if((t=t.u64(2,b.MINPROPVALUE))<b.MINPROPVALUE)throw new h(c.PROP_MINVALUE,"prop.create: not a valid value");if(0<=u.indexOf("file:")){const e=u.replace("file:","")||"docs/eth.jpg";u=await new Promise(t=>{this.readImageAsBlob(e,(e,i)=>{e?console.error("Error reading inscription:",e):t(i)})})}else{if(!(0<=u.indexOf("data:")))throw new h(c.MISC_ERROR,"inscription.create cid content gold (openid): 创建道具 厂商编码 素材(file:filename or data:{hex,type}) 含金量 [账户]");u=JSON.parse(u.replace("data:",""))}var s,n=await e.createReceive(r),o=w.sha256(Buffer.from(JSON.stringify(u))).toString("hex");if(o=await this.caIssuePublic([JSON.stringify({blob:u,hash:o,height:0}),n.getAddress("string"),"",r],null,i))return n={oper:O.propCreate,cid:a,gold:t,type:"inscription",oid:o.erid},[i,s]=await e.propCreate([n],r),i?n:null}throw new h(c.MISC_ERROR,"inscription.create cid content gold (openid): 创建道具 厂商编码 素材(file:filename or data:{hex,type}) 含金量 [账户]")}async propCreate(e,t,i){if(t||e.length<3)throw new h(c.MISC_ERROR,"prop.create cid oid gold pid (openid): 创建道具 厂商编码 道具类别码 含金量 道具编码(可填空) [账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(4,"")),r=t.str(0),a=t.str(1),s=t.u64(2,b.MINPROPVALUE);t=t.str(3,null);if(s<b.MINPROPVALUE)throw new h(c.PROP_MINVALUE,"prop.create: not a valid value");r={oper:O.propCreate,cid:r,oid:a,gold:s,pid:t};var[a,,]=await e.propCreate([r],i);return a?r:null}async attach(e,t,i){if(t||e.length<3)throw new h(c.MISC_ERROR,"tx.attach addr amount data (openid): 发送附言交易 地址 金额 附言结构 [账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(3,"")),r=t.str(0),a=t.u64(1),[a,,]=(r=((t=t.obj(2,{})).oper=O.attach,{address:r,value:a,data:t}),await e.attach([r],i));return a?r:null}async walletLock(e,t,i){if(t)throw new h(c.MISC_ERROR,"wallet.lock [passphrase]");var[t]=await this.accessControl(i);if(!t.master.encrypted){if((i=new g([e]).str(0,"")).length<1)throw new h(c.MISC_ERROR,"Wallet is not encrypted, please run wallet.lock passphrase");try{await t.setPassphrase(null,i)}catch(e){throw new h(c.WALLET_ENCRYPTION_FAILED,"Encryption failed.")}}return await t.lock(),null}async listMSTrans(e,t,i){if(t)throw new h(c.MISC_ERROR,"tx.mstrans");return t=new g([e]).str(0,""),this.wdb.listMSTrans(t)}async signMSTrans(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"tx.mstrans.sign txid");e=(t=new g([e])).str(0,"");var r=t.str(1,""),[i,t]=await this.accessControl(i,t.str(2,""));if(!(e=await this.wdb.db.get(s.ms(k.getHash(e,"hex"),r))))throw new h(c.MISC_ERROR,"tx.mstrans.sign txid");if(e=JSON.parse(e.toString()),!await i.belongToAccount(t,e.addr))throw new h(c.MISC_ERROR,"tx.mstrans.sign invalid account");var a,o=await this.wdb.get(e.addr);o&&o.account.type==n.types.MULTISIG&&((a=E.fromRaw(e.data,"hex")).view=await o.getCoinView(a),await o.sign(a),a.isSigned()?await o.sendMTX(a):await i.send({subtractFee:!1,sort:!1,outputs:[{address:e.contract,value:1e4}],comment:JSON.stringify({oper:"scrun",params:{oper:"sign",addr:e.addr,tx:a.toRaw().toString("hex")}})},t),await this.wdb.delMSTrans(e.addr,r))}async resendWalletTransactions(e,t,i){if(t||0!==e.length)throw new h(c.MISC_ERROR,"tx.resend.admin");var[t]=await this.accessControl(i),r=[];for(const e of await t.resend())r.push(e.txid());return r}async resend(e,t,i){if(t||0!==e.length)throw new h(c.MISC_ERROR,"tx.resendall.admin: 重发挂起交易");var r=await this.wdb.resend();if(r)for(var a of Object.keys(r))if(a)for(const e of r[a])await this.wdb.send(e);return!0}async rescan(e,t,i){if(t)throw new h(c.MISC_ERROR,'wallet.rescan ( "height" )');return t=new g([e]).u32(0),await this.wdb.rescan(t),this.logger.info("Rescanning..."),!0}async createAddress(e,t,i){if(t||2<e.length)throw new h(c.MISC_ERROR,'address.create ( "account" "uid" )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));t=t.u32(1,0);return(e=await e.createReceive(i,t))?e.toJSON():null}async calcAddress(e,t,i){if(t||e.length<3)throw new h(c.MISC_ERROR,"address.calc account(must be typeof number) branch index");t=new g([e]);let[a,s]=await this.accessControl(i,t.int(0,0));return e=t.u32(1,0),i=t.u32(2,0),"default"==s&&(s=0),t=(await a.deriveKey(s,e,i,a.master)).toJSON(),i=(e=await a.deriveKey(s,e,i))?e.toJSON():null,r(t.address==i.address,"address derived from prv not equals which derived from pub."),i}async createAddressAdmin(e,t,i){if(t||1<e.length)throw new h(c.MISC_ERROR,'address.create.admin ( "account" )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));return(t=await e.createReceive(i,0,e.master))?t.toJSON(!0):null}async createChange(e,t,i){if(t||1<e.length)throw new h(c.MISC_ERROR,'address.change.create ( "account" )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));return(t=await e.createChange(i))?t.toJSON():null}async createNested(e,t,i){if(t||1<e.length)throw new h(c.MISC_ERROR,'address.nested.create ( "account" )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));return(t=await e.createNested(i))?t.toJSON():null}async mkwallet(e,t,i){var r=(e=new g([e])).str(4);if(r)for(var a of await this.wdb.getWallets())if((await this.wdb.get(a)).master.mnemonic.getPhrase()===body.phrase)throw new h(c.MISC_ERROR,"wallet.create: 相同助记词已被使用");return(r=await this.wdb.ensure({id:z(),type:e.str(1),m:e.u32(2),n:e.u32(3),mnemonic:r,passphrase:e.str(5),master:e.str(6),witness:e.bool(7),watchOnly:e.bool(8),accountKey:e.str(9)}))?r.toJSON(!1):null}async accountGet(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"account.get account: 查询账户");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));return(t=await e.getAccount(i))?t.toJSON():null}async getPending(e,t,i){if(t)throw new h(c.MISC_ERROR,"tx.pending [account]: 查询挂起的交易");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=(t=await e.getPending(i),a.sortTX(t),[]);for(const i of await e.toDetails(t))r.push(i.toJSON());return r}async getPendingItem(e,t,i){var r,a=(e=new g([e])).hash(0,""),[s,i]=await this.accessControl(i,e.str(1,""));for(r of await s.getPending(i))if(r.hash==a)return(r=await s.toDetails(r)).toJSON()}async getPendingHash(e,t,i){e=new g([e]);var[i,e]=await this.accessControl(i,e.str(0,"")),r=(e=await i.getPending(e),a.sortTX(e),[]);for(const t of await i.toDetails(e))r.push(d.revHex(t.hash));return r}async getPendingCount(e,t,i){if(t)throw new h(c.MISC_ERROR,"tx.pending.count [account]: 查询挂起的交易数");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));t=await e.ensureIndex(i);return(await e.txdb.getPendingHashes(t)).length}async accountCreate(e,t,i){e=new g([e]);var r,[i]=await this.accessControl(i),a=e.obj(0);e=e.str(1),a={name:(a=new g([a])).str("name"),witness:a.bool("witness",!0),type:a.str("type","pubkeyhash"),m:a.u32("m",1),n:a.u32("n",1),watchOnly:a.bool("watch",!1),accountKey:a.str("key",null),lookahead:a.u32("lookahead",10)};try{let t=await i.getAccount(a.name);return t?t.toJSON():((r=(t=await i.createAccount(a,e)).toJSON()).isNew=!0,r)}catch(t){return null}}async getblocks(e,t,i){if(t)throw new h(c.MISC_ERROR,"wallet.blocks");var[t]=await this.accessControl(i);return await t.getBlocks()}async getKey(e,t,i){if(t||1!==e.length)throw new h(c.MISC_ERROR,"key.export.public address: 查询地址的密钥");t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0);return(t=(r(i,"Address is required."),await e.getKey(i)))?t.toJSON():null}async getPrivKey(e,t,i){if(t||1!==e.length)throw new h(c.MISC_ERROR,"address.key.admin address: 查询地址的密钥");t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0);return(t=(r(i,"Address is required."),await e.getKey(i)))?t.toJSON(!0):null}async getwif(e,t,i){if(t||1!=e.length)throw new h(c.MISC_ERROR,"address.wif.admin address: 查询地址对应的私钥 地址");t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0),t=t.str(1);return(e=(r(i,"Address is required."),await e.getPrivateKey(i,t)))?e.toSecret():null}async ownedAddress(e,t,i){if(t||1!=e.length)throw new h(c.MISC_ERROR,"address.has address: 查询钱包是否拥有一个地址 地址");t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0);return r(i,"Address is required."),e.ownedAddress(i)}async getCoin(e,t,i){e=new g([e]);var[i]=await this.accessControl(i),a=e.hash(0);e=e.u32(1);return(i=(r(a,"Hash is required."),r(null!=e,"Index is required."),await i.getCoin(a,e)))?i.getJSON(this.network):null}async getSpender(e,t,i){e=new g([e]);var[i]=await this.accessControl(i),a=e.hash(0);e=e.u32(1);return(i=(r(a,"Hash is required."),r(null!=e,"Index is required."),await i.txdb.getSpender(a,e)))?{hash:d.revHex(i.hash),index:i.index}:null}async getSpent(e,t,i){e=new g([e]);var[i]=await this.accessControl(i),a=e.hash(0);e=e.u32(1),r(a,"Hash is required."),r(null!=e,"Index is required."),i=await i.txdb.getSpentCoin({hash:a,index:e});return{hash:d.revHex(i.hash),index:i.index,value:i.value,height:i.height,version:i.version,time:i.time}}async getCoincacheSize(e,t,i){var[i]=await this.accessControl(i);return i.txdb.coinCache.size}async conserveCoin(e,t,i){if(t||2!=e.length)throw new h(c.MISC_ERROR,"coin.conserved.add txhash index: 新增需要保持的硬币: 交易Hash 输出序号");t=new g([e]);var[e]=await this.accessControl(i);i=t.hash(0),t=t.u32(1),r(i,"Hash is required."),r(null!=t,"Index is required."),i=new j(i,t);return e.conserveCoin(i),!0}async getConservedCoins(e,t,i){if(t||0<e.length)throw new h(c.MISC_ERROR,"coin.conserved.get: 查询已经保持的Coin列表");var[t]=await this.accessControl(i),r=[];for(const e of t.getConserved())r.push(e.toJSON());return r}async unConserveCoin(e,t,i){if(t||2!=e.length)throw new h(c.MISC_ERROR,"coin.conserved.del: 减少需要保持的硬币: 交易Hash 输出序号");t=new g([e]);var[e]=await this.accessControl(i);i=t.hash(0),t=t.u32(1),r(i,"Hash is required."),r(null!=t,"Index is required."),i=new j(i,t);return e.unConserveCoin(i),!0}async addShared(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"key.shared.add [account] key: 新增共享公钥 [账号] 公钥");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));t=t.str(1);return await e.addSharedKey(i,t),!0}async removeShared(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"key.shared.del [account] key: 删除共享公钥 [账号] 公钥");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));t=t.str(1);return await e.removeSharedKey(i,t),!0}async zap(e,t,i){if(t)throw new h(c.MISC_ERROR,"sys.zap [age]: 移除挂起交易 挂起时长(默认三天)");t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0),t=t.u32(1,259200);return r(t,"Age is required."),await e.zap(i,t),!0}async sendOracle(e,t,i){if(!(t||e.length<3||4<e.length)){t=new g([e]);var[e,i]=await this.accessControl(i,t.str(3,"")),r=t.str(0,null),a=t.str(1,null);if(null==(t=t.u64(2)))throw new h(c.TYPE_ERROR,"Invalid parameter.");if(r&&a)return t={subtractFee:!1,selection:"age",sort:!1,outputs:[{address:(await e.createReceive(i)).getAddress("string"),value:t}],comment:JSON.stringify({oper:O.vote,type:"oracle",k:r,v:a})},r=await e.send(t,i),(await e.getDetails(r.hash("hex"))).toJSON()}throw new h(c.MISC_ERROR,"oracle.send k v amount [openid]")}async sendVote(e,t,i){if(t||e.length<2||3<e.length)throw new h(c.MISC_ERROR,"vote.send addresses amount [openid]");t=new g([e]);var r,[e,i]=await this.accessControl(i,t.str(2,"")),a=t.str(0);if(null==(t=t.u64(1)))throw new h(c.TYPE_ERROR,"Invalid parameter.");for(r of a.split(","))if(!o.parseAddress(r,this.network))throw new h(c.TYPE_ERROR,"Invalid address.");return t={subtractFee:!1,selection:"age",sort:!1,outputs:[{address:(await e.createReceive(i)).getAddress("string"),value:t}],comment:`{"oper": "${O.vote}", "type": "mine", "ca": "${a}"}`},a=await e.send(t,i),(await e.getDetails(a.hash("hex"))).toJSON()}async sendVoteAsync(e,t,i){if(t||e.length<2||3<e.length)throw new h(c.MISC_ERROR,"vote.send.async addresses amount [openid]");t=new g([e]);var r,[e,i]=await this.accessControl(i,t.str(2,"")),a=t.str(0);if(null==(t=t.u64(1)))throw new h(c.TYPE_ERROR,"Invalid parameter.");for(r of a.split(","))if(!o.parseAddress(r,this.network))throw new h(c.TYPE_ERROR,"Invalid address.");t={subtractFee:!1,selection:"age",sort:!1,outputs:[{address:(await e.createReceive(i)).getAddress("string"),value:t}],comment:`{"oper": "${O.vote}", "type": "mine", "ca": "${a}"}`},e.send(t,i)}async sendTX(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"tx.send addr amount [openid]:发送交易 地址 金额 [发起账户]");if(this.wdb.$parent&&this.wdb.$parent.config.abandon)throw new h(c.MISC_ERROR,"Alliance Cert Invalid.");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0);t=t.u64(1),r=await e.send({outputs:[{address:r,value:t}]},i);return(await e.getDetails(r.hash("hex"))).toJSON()}async sendTXAsync(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"tx.send.async addr amount [openid]:发送交易 地址 金额 [发起账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0);t=t.u64(1);e.send({outputs:[{address:r,value:t}]},i)}async signTX(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"tx.sign.admin txdata [sendnow passphrase]: 对交易签名/发送 交易原始数据 [立即发送 解锁密码]");t=new g([e]);var[e]=await this.accessControl(i),a=(i=t.buf(0),r(i,"TX is required."),t.bool(1,!1));t=t.str(2);(i=E.fromRaw(i)).view=await e.getCoinView(i),await e.sign(i,t);let s=null;return s=(a&&i.isSigned()?await e.sendMTX(i):i).getJSON(this.network),e.account.type==n.types.MULTISIG&&(t=i.getMultisig(this.network),s.ms={m:t.m,n:t.n,c:t.c}),s}async createTX(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"tx.create options outputs [openid]: 创建交易 参数对象 输出数组 [子账号]");if(this.wdb.$parent&&this.wdb.$parent.config.abandon)throw new h(c.MISC_ERROR,"Alliance Cert Invalid.");t=new g([e]);var[r,e]=await this.accessControl(i,t.str(2,""));i=t.obj(0),t=t.array(1);if(Array.isArray(i.in))for(var a of i.in)a.hash=d.revHex(a.hash);var s={comment:(i=new g([i])).obj("comment",null),sendnow:i.bool("sendnow",!0),account:i.str("account"),rate:i.u64("rate"),blocks:i.u32("blocks"),maxFee:i.u64("maxFee"),selection:i.str("selection"),smart:i.bool("smart"),subtractFee:i.bool("subtractFee"),subtractIndex:i.get("subtractIndex"),depth:i.u32(["confirmations","depth"]),inputs:i.array("in",null),outputs:[]};for(const e of t){var o=new g([e]),u={value:o.u64("value")};if(u.address=o.str("address"),!u.address){var l=o.str("account");if(l){await r.ensureAccount({name:l,witness:!0});var p=await r.createReceive(l);if(!p)throw new h(c.MISC_ERROR,`tx.create: account ${l} not exist`);u.address=p.getAddress("string")}}if((l=o.buf("script"))&&(u.script=y.fromRaw(l)),(p=o.str("locktype"))&&(o=o.u64("locktime",0))){if("no"!=p&&"clb"!=p&&"clt"!=p&&"csb"!=p&&"cst"!=p)throw new h(c.MISC_ERROR,'locktype should be "no"-不锁定 or "clb"-绝对高度锁定 or clt(绝对时间锁定) or "csb"-相对高度锁定 or "cst"-相对时间锁定 !');if(p==y.outputLockType.CHECKABSOLUTETIME&&o<=b.LOCKTIME_THRESHOLD)throw new h(c.MISC_ERROR,"lock absolute time should not less than 500000000!");if(p==y.outputLockType.CHECKABSOLUTEBLOCK&&o>b.LOCKTIME_THRESHOLD)throw new h(c.MISC_ERROR,"lock absolute block should not more than 500000000!");if((p==y.outputLockType.CHECKRELATIVEBLOCK||p==y.outputLockType.CHECKRELATIVETIME)&&65535<o)throw new h(c.MISC_ERROR,"lock relative block/time should not more than 65535!");u.locktype=p,u.locktime=o}s.outputs.push(u)}e&&(s.account=e);let f=null;return s.sendnow?(i=await r.send(s),f=(t=await r.getDetails(i.hash("hex"))).toJSON()):(e=await r.createTX(s),await r.sign(e),f=e.getJSON(this.network),r.account.type==n.types.MULTISIG&&(i=e.getMultisig(this.network),f.ms={m:i.m,n:i.n,c:i.c})),f}async getLast(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"tx.last account [limit]: 最近的交易 账号 [最大记录数]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0)),r=(t=t.u32(1),[]);i=await e.getLast(i,t);for(const t of await e.toDetails(i))r.push(t.toJSON());return r}async getRange(e,t,i){if(t||e.length<4)throw new h(c.MISC_ERROR,"tx.range account start end limit [reserve]: 指定时限内的交易 账号 开始时间 结束时间 最大记录数 [反转]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=(t={start:t.u32(1),end:t.u32(2),limit:t.u32(3),reverse:t.bool(4)},i=await e.getRange(i,t),[]);for(const t of await e.toDetails(i))r.push(t.toJSON());return r}async caUserStatus(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"ca.user.status cid uid (query)");e=(t=new g([e])).str(0,"");var r=t.uint(1,0),a=t.array(2,[]);let s=null;for(let e=0;e<a.length;e++){var n=a[e];n&&Array.isArray(n)?"alliancename"==n[0]&&(s=n[1],delete a[e]):delete a[e]}var[t]=await this.accessControl(i);e=await this.$allianceUserCreate([e,r,s],i);return a.push(["pubkey",e.data.pubkey]),a.push(["merge",!0]),t.db.client.execute("ca.list",[a])}async caUserLog(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"ca.user.log cid uid (query)");e=(t=new g([e])).str(0,"");var r=t.uint(1,0),a=t.array(2,[]);let s=null;for(let e=0;e<a.length;e++){var n=a[e];n&&Array.isArray(n)?"alliancename"==n[0]&&(s=n[1],delete a[e]):delete a[e]}var[t,,]=await this.accessControl(i,e);e=await this.$allianceUserCreate([e,r,s],i);return a.push(["pubkey",e.data.pubkey]),t.db.client.execute("ca.list",[a])}async sysLog(e,t,i){if(t)throw new h(c.MISC_ERROR,"sys.log (query openid)");e=(t=new g([e])).array(0,[]);var r,[a,,]=await this.accessControl(i,t.str(1,"")),s=[];for(r of(await this.wdb.auditList.query(e)).list){var n=Object.assign({},r),u=o.parseHash(r.address,this.network);(u=await a.getPath(u))&&(n.account=u.name),n.time=new Date(1e3*r.time).toLocaleString(),s.push(n)}return s}async caIssuePublic(e,t,i){if(t||e.length<2||4<e.length)throw new h(c.MISC_ERROR,"ca.issue.public cert witness [pubkey openid]: 签发证书 证书对象 见证地址 [原始存证签名公钥 支付账户]");e=(t=new g([e])).obj(0,{});var r=t.str(1,""),a=t.str(2,""),[i,t]=await this.accessControl(i,t.str(3,""));if(64!=e.hash.length)throw new h(c.TYPE_ERROR,"err hash length");var s=await i.db.client.execute("ca.byId",[e.hash]);if(s)return s;if(s=await i.getPrivateKey(r))return e.height||(e.height=b.retargetInterval),await i.issueCreate({erid:e.hash,key:s.privateKey.toString("hex"),address:s.getAddress().toString(),witness:s.publicKey.toString("hex"),validHeight:this.wdb.curHeight+e.height,source:{subjectName:e.name||"",pubkey:a,subjectHash:e.hash,cluster:e.cluster,blob:e.blob}},t);throw new h(c.TYPE_ERROR,"Invalid witness.")}async caAbolishPublic(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"ca.abolish.public array[[erid height [openid]]]: 废止授信交易 废止交易信息数组");var r,a=[];for(r of new g([e]).array(0,[])){var[s,n]=await this.accessControl(i,r[3]),o=r[0],u=parseInt(r[1]),l=await this.wdb.erList.query([["erid",o]]),p=(l=k.fromWitnessPubkeyhash(w.hash160(Buffer.from(l.list[0].witness,"hex")),this.network.type).toString(),await s.getKey(l));if(!p)throw new h(c.TYPE_ERROR,"Invalid witness.");(s=await s.caAbolish({key:p.privateKey.toString("hex"),witness:p.publicKey.toString("hex"),address:l,erid:o,abolishHeight:u,cid:"",uid:0},n))&&a.push(s)}return a}async caIssue(e,t,i){if(t||e.length<3||4<e.length)throw new h(c.MISC_ERROR,"ca.issue cert uid cid [openid]: 签发证书 证书对象 见证人 见证人归属单位 [消费账户]");return this.$caIssue(e,i,!1)}async caIssueAsync(e,t,i){if(t||e.length<3||4<e.length)throw new h(c.MISC_ERROR,"ca.issue.async cert uid cid [openid]: 签发证书 证书对象 见证人 见证人归属单位 [消费账户]");return this.$caIssue(e,i,!0)}async $caIssue(e,t,i){var r=(e=new g([e])).obj(0,{}),a=e.uint(1,0),s=e.str(2,""),[e,n]=await this.accessControl(t,e.str(3,""));if(!(o=await e.ensureCp(s))||"forbidden"==o.cls)throw new h(c.MISC_ERROR,"Invalid Account");if(64!=r.hash.length)throw new h(c.TYPE_ERROR,"err hash length");var o=await this.$allianceUserCreate([s,a],t),u=[];if(u.push(["pubkey",o.data.pubkey]),u.push(["source.subjectHash",r.hash]),0<(await e.db.client.execute("ca.list",[u])).count)throw new h(c.TYPE_ERROR,"cert.hash conflicted");if(await e.db.client.execute("ca.byId",[r.hash]))throw new h(c.TYPE_ERROR,"cert.hash conflicted");return r.height||(r.height=b.retargetInterval),o=await this.$allianceUserCreate([s,a],t,!0),await e.issueCreate({erid:r.hash,key:o.prvkey,witness:o.data.pubkey,address:o.data.addr,validHeight:this.wdb.curHeight+r.height,source:{subjectName:r.name,pubkey:o.data.pubkey,subjectHash:r.hash,cluster:r.cluster,cid:s,uid:a}},n,i)}async caAbolish(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"ca.abolish [[uid cid erid height [openid]]]: 废止授信交易 废止交易信息数组");return this.$caAbolish(e,i,!1)}async caAbolishAsync(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"ca.abolish.async [[uid cid erid height [openid]]]: 废止授信交易 废止交易信息数组");return this.$caAbolish(e,i,!0)}async $caAbolish(e,t,i){var r,a=[];for(r of new g([e]).array(0,[])){var s,n=r[0],o=r[1],c=r[2],u=parseInt(r[3]),[s,h]=await this.accessControl(t,r[4]),l=await this.$allianceUserCreate([o,n],t,!0);(s=await s.caAbolish({cid:o,uid:n,key:l.prvkey,witness:l.data.pubkey,address:l.data.addr,erid:c,abolishHeight:u},h,i))&&a.push(s)}return a}async enchanceCp(e,t,i){if(t||e.length<2||4<e.length)throw new h(c.MISC_ERROR,"ca.enchance toCid fromCid height [openid]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(3)),r=t.str(0,0),a=t.str(1,0);let s=t.uint(2,0);(!s||s<this.wdb.curHeight)&&(s=this.wdb.curHeight+b.retargetInterval);var[t,e]=await e.enchanceCp({to:r,from:a,enchanceHeight:s},i);return t&&e?e:null}async queryErList(e,t,i){if(t)throw new h(c.MISC_ERROR,"ca.query.remote conditions: 查询存证列表 (复合条件)");t=new g([e]);var[e,,]=await this.accessControl(i,t.str(1,""));i=t.array(0,[]);return e.db.client.execute("ca.list",[i])}async queryMyErlist(e,t,i){if(t)throw new h(c.MISC_ERROR,"ca.list.me query: 条件查询自己的电子权利 条件数组");return t=new g([e]).array(0,[]),this.wdb.erList.query(t)}}},function(e,t,i){var r=i(31);const{ContractEnvType:a,ContractStatus:s}=i(5),n=i(6),o=i(108);e.exports=class extends r{constructor(e){super(),this.db=e}async loadHistory(){var e;for(e of await this.db.getContracts())e&&(e.period<this.db.curHeight&&e.transStatus==s.CreatedOnMem?await this.delTransContract(e,!0):(e.id=e.type+"."+e.addr,await this.saveContract(e),e.transStatus==s.Promised&&this.db.autoTaskMgr.addTask(new o(this.db.network.txcheckpoint,e),this.db.network.txchecktime[e.type])))}query(e,t){return(e=this.get(e+"."+t))?e.transStatus:s.None}async addTransContract(e,t,i=!1){t.id=t.type+"."+t.addr;var r=this.get(t.id);e===a.Mempool&&((t=r||t).transStatus||(t.transStatus=s.CreatedOnMem),await this.saveContract(t,i))}async saveContract(e,t=!1){e.id=e.id||e.type+"."+e.addr,this.set(e.id,e),t&&(t=n.hash256(Buffer.from(e.id)).toString("hex"),await this.db.batchPut(this.db.tidCreator(t),Buffer.from(JSON.stringify(e))))}async promiseContract(e,t=!1){let i=!1;var r=e.type+"."+e.addr;let a=this.get(r);return a&&a.oper==e.oper||(i=!0,a=e),(!a.transStatus||a.transStatus<s.Promised)&&(i=!0,a.transStatus=s.Promised),i&&await this.saveContract(a,t),i}async confirmContract(e,t,i){e=e.type+"."+e.addr,!(e=this.get(e))||e.transStatus!=s.Promised||t!=s.Confirmed&&t!=s.Expired||(e.transStatus=t,await this.saveContract(e,i))}async delTransContract(e,t){var i=e.type+"."+e.addr,r=this.get(i);r&&r.oper==e.oper&&(this.delete(i),t)&&(r=n.hash256(Buffer.from(i)).toString("hex"),await this.db.batchDel(this.db.tidCreator(r)))}}},function(e,t,i){const r=i(5).HtlcStatus;i=i(31);class a extends i{constructor(e){super(),this.db=e}async loadHistory(){var e,t;for(e of(this.clear(),await this.db.loadHtlcList()))this.set(e.id,e),e.wid&&e.account&&(t=e.wid+"."+e.account,this.account.get(t)||this.account.set(t,new Map),this.account.get(t).set(e.id,e))}setAccount(e,t,i){this.delAccount(e),t&&i&&(e.wid=t,e.account=i,t=e.wid+"."+e.account,this.account.get(t)||this.account.set(t,new Map),this.account.get(t).set(e.id,e))}delAccount(e){var t;e&&e.wid&&e.account&&(t=e.wid+"."+e.account,this.account.get(t))&&this.account.get(t).delete(e.id)}}a.vpItem=class e{constructor(e){this.fromOptions(e||{})}fromOptions(e){this.shash=e.shash,this.sidx=e.sidx,this.sheight=e.sheight,this.ahash=e.ahash,this.aidx=e.aidx,this.aheight=e.aheight,this.src=e.src,this.dst=e.dst,this.aa=e.aa,this.ab=e.ab,this.ba=e.ba,this.bb=e.bb,this.amount=e.amount,this.rate=e.rate,this.pst=e.pst}toRaw(){var e={};return e.shash=this.shash,e.sidx=this.sidx,e.sheight=this.sheight,e.ahash=this.ahash,e.aidx=this.aidx,e.aheight=this.aheight,e.src=this.src,e.dst=this.dst,e.amount=this.amount,e.rate=this.rate,e.pst=this.pst||r.Init,e.aa=this.aa||"",e.ab=this.ab||"",e.ba=this.ba||"",e.bb=this.bb||"",Buffer.from(JSON.stringify(e),"utf-8")}get id(){return""+this.shash+this.sidx}fromRaw(e){return e=JSON.parse(e.toString("utf8")),this.fromOptions(e),this}static fromRaw(t){return(new e).fromRaw(t)}},e.exports=a},,,,,,,,,,,,,,,function(e,t,i){"use strict";
|
|
851
|
+
*/const r=i(0),a=i(73);i(119);const s=i(85).walletdb,n=i(157),o=i(78),c=o.errors,u=o.MAGIC_STRING,h=i(77),l=i(59),p=i(107),d=i(2),f=i(193),m=i(3),g=i(80),v=i(33),y=i(17),b=i(7),w=i(6),x=i(26),k=i(13),S=i(38),_=i(131),E=i(68),j=i(46),A=i(20),R=i(135),I=i(136),{ContractType:O,ContractState:C,PropStatus:P,HtlcStatus:T}=i(5),B=i(137),N=i(123),z=i(141),F=i(19).opcodes,L=i(34),M=i(612);e.exports=class extends o{constructor(e){super(e),r(e,"RPC requires a WalletDB."),this.wdb=e,this.keys=e.keys,this.network=e.network,this.logger=e.logger.context("rpc"),this.client=e.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.admin",this.exportMnemonic),this.add("wallet.importmnemonic.admin",this.importMnemonic),this.add("wallet.export",this.dumpWallet),this.add("wallet.exports.admin",this.dumpWallets),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("wallet.rescan",this.rescan),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.map",this.mapAccounts),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("account.virtualadd.admin",this.accountVirtualAdd),this.add("account.checkamount",this.accountCheckAmount),this.add("balance.confirmed",this.getBalance),this.add("balance.all",this.getBalanceAll),this.add("balance.check",this.checkBalance),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.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.ownedAddress),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.query.remote",this.cpQueryRemote),this.add("cp.mine",this.cpMine),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.list.remote",this.queryErList),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("prop",this.routerOfProp),this.add("prop.create",this.propCreate),this.add("prop.createlist",this.propCreateList),this.add("prop.send",this.propExchange),this.add("prop.sendlist",this.propSendList),this.add("prop.sendlist.admin",this.propSendListAdmin),this.add("prop.found",this.propFound),this.add("inscription.create",this.inscriptionCreate),this.add("prop.wallet.byid",this.propGet),this.add("prop.wallet.byoid",this.listPropByOid),this.add("prop.wallet.byaddress",this.listProp),this.add("prop.sale",this.propSale),this.add("prop.buy",this.propBuy),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("tx.get.wallet",this.getTransaction),this.add("tx.list",this.listTransactions),this.add("tx.create",this.createTX),this.add("tx.attach",this.attach),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.spent",this.getSpent),this.add("coin.cache",this.getCoincacheSize),this.add("coin.check",this.checkUnspent),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(e){throw new h(c.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(e){throw new h(c.MISC_ERROR,"\n contract.create 发布交易对合约\n contract.promise 签署交易对合约\n contract.execute 执行交易对合约\n contract.mine 获取已签署交易对合约列表\n contract.list 查询并返回交易对\n ")}async routerOfHTLC(e){throw new h(c.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(e){throw new h(c.MISC_ERROR,"\n wallet.create 创建钱包\n wallet.list 列表钱包\n wallet.info 查询钱包概要\n wallet.block 查询区块信息\n wallet.exportmnemonic.admin 导出钱包助记词备份\n wallet.importmnemonic.admin 导入钱包助记词备份\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(e){throw new h(c.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(e){throw new h(c.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(e){throw new h(c.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(e){throw new h(c.MISC_ERROR,"\n cp.create 创建CP记录\n cp.change 修改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.user 生成用户令牌(钱包)\n ")}async routerOfSc(e){throw new h(c.MISC_ERROR,"\n sc.model 查询托管合约模板列表\n sc.register 指定托管合约模板,创建新的实例\n sc.query 查询托管合约实例列表\n sc.run 调用托管合约实例\n ")}async routerOfCa(e){throw new h(c.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 routerOfProp(e){throw new h(c.MISC_ERROR,"\n prop.create 创建道具\n prop.send 转移道具\n prop.createlist 批量创建道具\n prop.sendlist 批量转移道具\n prop.found 熔铸道具\n prop.byaddress 根据地址查询道具\n prop.byid 根据PID查询道具\n prop.wallet.byaddress 根据地址查询自己拥有的道具\n prop.wallet.byid 根据PID查询自己拥有的道具\n prop.wallet.byoid 根据OID查询自己拥有的道具\n ")}async allianceCreate(e,t,i){if(t||e.length<3)throw new h(c.MISC_ERROR,"sys.alliance.create password nodeid alliancename (host): 创建联盟节点证书 备份密码 节点编号 盟友名称 (节点地址)");e=(t=new g([e])).str(0);var r=t.uint(1,0),a=t.str(2,"").trim();t=t.str(3,"");if(!r||!e)throw new h(c.MISC_ERROR,"节点编号、备份密码都不能为空");if(a==this.wdb.$parent.config.allianceName)throw new h(c.MISC_ERROR,`子网名称不能和当前网络名称[${this.wdb.$parent.config.allianceName}]相同`);if(!this.wdb.$parent||!this.wdb.$parent.config.identityKey)throw new h(c.MISC_ERROR,"identityKey not set yet, please run sys.alliance.gettoken without params first");var[i,s]=await this.accessControl(i,""),n={body:{language:(n=await i.createAllianceInfo(a,r)).mnemonic.language,phrase:n.mnemonic.getPhrase(),passphrase:n.mnemonic.passphrase,alliancePrivateKey:n.alliancePrivateKey.toString("hex"),allianceName:a,allianceNodeId:r,awardAddress:n.awardAddress,allianceNodeToken:{network:this.network.type,alliancename:a,sn:r,prv:n.prv.toString("hex"),pub:n.pub.toString("hex"),address:n.address},notifyAddress:i.notifyAddress,authorized:""},password:e,network:this.network.type,file:this.network.type+`-${a}-${r}.keystore`};let o=N.encrypt(n);if(this.wdb.$parent){let i=!1;for(var u of this.wdb.$parent.config.alliances)if((u=u.split("|"))[0]==a&&u[1]==r){i=!0;break}i||(this.wdb.$parent.pool.authdb.addKnown(t,Buffer.from(n.body.allianceNodeToken.pub,"hex")),o=N.encrypt(n),this.wdb.$parent.config.alliances.push(`${a}|${r}|${o}|${e}|${n.body.awardAddress}|`+t),await this.wdb.$parent.saveConfigAsync())}e={host:t,an:n.body.allianceNodeToken.alliancename,ai:n.body.allianceNodeToken.sn,key:n.body.allianceNodeToken.pub};var d=p.signObj(e,i.notifyKey.privateKey);return await i.commNotify({dst:i.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:e,sig:d,pub:i.notifyKey.publicKey.toString("hex")})}),l.unsupported||await l.writeFile(n.file,o,"utf8"),e=(await i.getAccount(s)).getReceive().toString(),await this.wdb.logAudit({address:e,oper:"node.create",hash:a+"."+r,index:0}),{nodeid:r,alliancename:a,host:t,peerPubkey:n.body.allianceNodeToken.pub,awardAddress:n.body.awardAddress,file:n.file,notifyAddress:i.notifyAddress}}async allianceImport(e,t,i){if(t||e.length<3)throw new h(c.MISC_ERROR,"sys.alliance.import password nodeid alliancename key (host): 导入联盟节点 备份密码 节点编号 盟友名称 节点公钥 (节点地址)");if(!this.wdb.$parent||!this.wdb.$parent.config.identityKey)throw new h(c.MISC_ERROR,"identityKey not set yet, please run sys.alliance.gettoken without params first");e=(t=new g([e])).str(0);var r=t.uint(1,0),a=t.str(2,""),s=t.str(3,"");t=t.str(4,"");if(!r||!e||!s)throw new h(c.MISC_ERROR,"节点编号、备份密码、节点公钥都不能为空");var[i,n]=await this.accessControl(i,""),o={body:{alliancePrivateKey:(o=await i.createAllianceInfo(a,r,s)).alliancePrivateKey.toString("hex"),allianceName:a,allianceNodeId:r,allianceNodeToken:{network:this.network.type,alliancename:a,sn:r,pub:o.pub.toString("hex"),address:o.address},awardAddress:o.awardAddress,notifyAddress:i.notifyAddress,authorized:""},password:e,network:this.network.type,file:this.network.type+`-${a}-${r}.keystore`};let u;if(this.wdb.$parent){let i=!1;for(var d of this.wdb.$parent.config.alliances)if((d=d.split("|"))[0]==a&&d[1]==r){i=!0;break}i||(this.wdb.$parent.pool.authdb.addKnown(t,Buffer.from(s,"hex")),u=N.encrypt(o),this.wdb.$parent.config.alliances.push(`${a}|${r}|${u}|${e}|${o.body.awardAddress}|`+t),await this.wdb.$parent.saveConfigAsync())}else u=N.encrypt(o);return l.unsupported||await l.writeFile(o.file,u,"utf8"),s={host:t,key:o.body.allianceNodeToken.pub,an:o.body.allianceNodeToken.alliancename,ai:o.body.allianceNodeToken.sn},e=p.signObj(s,i.notifyKey.privateKey),await i.commNotify({dst:i.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:s,sig:e,pub:i.notifyKey.publicKey.toString("hex")})}),s=(await i.getAccount(n)).getReceive().toString(),await this.wdb.logAudit({address:s,oper:"node.create",hash:a+"."+r,index:0}),{nodeid:r,alliancename:a,host:t,peerPubkey:o.body.allianceNodeToken.pub,awardAddress:o.body.awardAddress,file:o.file,notifyAddress:i.notifyAddress}}async refreshAlliance(e,t,i){if(t)throw new h(c.MISC_ERROR,"sys.alliance.refresh amount: 为联盟成员批量充值 充值金额");var r=new g([e]).uint(0,0);if(r<1e4||5e9<r)throw new h(c.MISC_ERROR,"无效的充值金额(10000~5000000000)");var[a,s]=await this.accessControl(i);if(this.wdb.$parent)for(var n of this.wdb.$parent.config.alliances){n=n.split("|");var o=(k.fromString(n[4],this.network.type).isWitnessPubkeyhash()&&await a.send({outputs:[{address:n[4],value:r}]},s),N.decrypt({network:this.network.type,password:n[3],body:n[2]}));n=(this.wdb.$parent.rpc.addPeer&&await this.wdb.$parent.rpc.addPeer([n[5],o.allianceNodeToken.pub]),{host:n[5],key:o.allianceNodeToken.pub,an:o.allianceNodeToken.alliancename,ai:o.allianceNodeToken.sn}),o=p.signObj(n,a.notifyKey.privateKey);await a.commNotify({dst:a.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:n,sig:o,pub:a.notifyKey.publicKey.toString("hex")})})}}async refreshAllianceAsync(e,t,i){if(t)throw new h(c.MISC_ERROR,"sys.alliance.refresh.async amount: 为联盟成员批量充值 充值金额");var r=new g([e]).uint(0,0);if(r<1e4||5e9<r)throw new h(c.MISC_ERROR,"无效的充值金额(10000~5000000000)");var[a,s]=await this.accessControl(i);if(this.wdb.$parent)for(var n of this.wdb.$parent.config.alliances){n=n.split("|");var o=(k.fromString(n[4],this.network.type).isWitnessPubkeyhash()&&a.send({outputs:[{address:n[4],value:r}]},s),N.decrypt({network:this.network.type,password:n[3],body:n[2]}));n=(this.wdb.$parent.rpc.addPeer&&await this.wdb.$parent.rpc.addPeer([n[5],o.allianceNodeToken.pub]),{host:n[5],key:o.allianceNodeToken.pub,an:o.allianceNodeToken.alliancename,ai:o.allianceNodeToken.sn}),o=p.signObj(n,a.notifyKey.privateKey);a.commNotify({dst:a.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:n,sig:o,pub:a.notifyKey.publicKey.toString("hex")})})}}async allianceDelete(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"sys.alliance.delete nodeid alliancename: 删除联盟节点证书 节点编号 盟友名称");var r=(t=new g([e])).uint(0,0),a=t.str(1,""),[s,e]=await this.accessControl(i,"");if(!r||!a)throw new h(c.MISC_ERROR,"节点编号、节点名称都不能为空");if(this.wdb.$parent)for(let e=0;e<this.wdb.$parent.config.alliances.length;e++){var n,o=this.wdb.$parent.config.alliances[e].split("|");o[0]==a&&o[1]==r&&(this.wdb.$parent.config.alliances.splice(e,1),await this.wdb.$parent.config.saveAsync(),o[5])&&(o={host:o[5],an:a,ai:r},n=p.signObj(o,s.notifyKey.privateKey),await s.commNotify({dst:s.notifyAddress,content:JSON.stringify({cmd:"peerdel",payload:o,sig:n,pub:s.notifyKey.publicKey.toString("hex")})}))}return t=(await s.getAccount(e)).getReceive().toString(),await this.wdb.logAudit({address:t,oper:"node.delete",hash:a+"."+r,index:0}),!0}async getAllianceNodeToken(e,t,i){if(t)throw new h(c.MISC_ERROR,"sys.alliance.gettoken (nodeid alliancename pubkey): 创建联盟节点信道密钥 (节点编号 盟友名称)");e=(t=new g([e])).uint(0,0);var r=t.str(1);t=t.str(2);if(this.wdb.$parent)return[i]=await this.accessControl(i),i=await i.createAllianceInfo(r,e,t),r||(this.wdb.$parent.config.identityKey?(i.prv=Buffer.from(this.wdb.$parent.config.identityKey,"hex"),i.pub=x.publicKeyCreate(i.prv,!0),i.address=k.fromWitnessPubkeyhash(w.hash160(i.pub),this.network.type).toString()):(this.wdb.$parent.pool.options.identityKey=i.prv,this.wdb.$parent.config.identityKey=i.prv.toString("hex"),await this.wdb.$parent.saveConfigAsync())),{network:this.network.type,alliancename:r,sn:e,prv:i.prv.toString("hex"),pub:i.pub.toString("hex"),address:i.address};throw new h(c.MISC_ERROR,"this cmd can only run on fullnode.")}async allianceUserCreate(e,t,i){if(t)throw new h(c.MISC_ERROR,"sys.alliance.user cid uid (alliancename): 创建企业用户 企业编号 用户编号 (盟友名称)");return this.$allianceUserCreate(e,i)}async $allianceUserCreate(e,t,i){var r=(e=new g([e])).str(0),a=e.uint(1);let s=null,n=null;return n=(e=e.str(2,""))?([t]=await this.accessControl(t),w.hash256(Buffer.concat([Buffer.from(e),t.master.key.privateKey]))):Buffer.from(this.wdb.$parent.config.alliancePrivateKey,"hex"),e=S.fromPrivate(n,!0,this.network),(t=S.fromPrivate(w.hash256(Buffer.concat([Buffer.from(r+"-"+a),e.privateKey]),!0,this.network))).witness=!0,s=t.signData({cid:r,uid:a}),i&&(s.prvkey=t.privateKey.toString("hex")),s}async isReady(e){return this.wdb.isFull()}async shutdown(e,t){return this.wdb.$parent&&this.wdb.$parent.close().catch(e=>{setImmediate(()=>{throw e})}).finally(async()=>{await new Promise(e=>{setTimeout(e,1e4)}),process.exit(0)}),"Stopping."}async stop(e,t,i){if(t||0!==e.length)throw new h(c.MISC_ERROR,"sys.walletdb.stop");return this.wdb.close(),"Stopping walletdb..."}async destroyWalletDb(e,t,i){if(t||0!==e.length)throw new h(c.MISC_ERROR,"sys.walletdb.destroy: 删除钱包数据库");return await this.wdb.close(),await this.wdb.destroy(),"Destroyed."}async createWalletDb(e,t,i){if(t||0!==e.length)throw new h(c.MISC_ERROR,"sys.walletdb.create: 删除原有钱包数据库并重建");return await this.wdb.close(),await this.wdb.destroy(),await this.wdb.open(),"Created."}async fundRawTransaction(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,'tx.fund.admin "hexstring" ( options openid )');const r=new g([e]);var[t,e]=await this.accessControl(i,r.str(2,"")),a=(i=r.buf(0),r.obj(1));if(!i)throw new h(c.TYPE_ERROR,"Invalid hex string.");if(0===(i=E.fromRaw(i)).outputs.length)throw new h(c.INVALID_PARAMETER,"TX must have at least one output.");let s=null,n=null;if(a){const e=new g([a]);s=e.ufixed("feeRate",8),n=(n=e.str("changeAddress"))&&o.parseAddress(n,this.network)}return await t.fund(i,{rate:s,changeAddress:n,account:e}),{hex:i.toRaw().toString("hex"),changepos:i.changeIndex,fee:v.btc(i.getFee(),!0)}}async dumpPrivKey(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"key.export.private address [account]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));t=t.str(0,"");if(!await e.belongToAccount(i,t))throw new h(c.MISC_ERROR,"Invald Account.");if(i=o.parseHash(t,this.network),t=await e.getPrivateKey(i))return t.toSecret();throw new h(c.MISC_ERROR,"Key not found.")}async exportMnemonic(e,t,i){if(t||1!==e.length)throw new h(c.MISC_ERROR,"wallet.exportmnemonic.admin password: 备份钱包助记符 备份密码");t=new g([e]);var[e,i]=await this.accessControl(i);if(!(t=t.str(0)))throw new h(c.MISC_ERROR,"wallet.exportmnemonic.admin: Invalid password");if("primary"==e.id&&"default"!=i)throw new h(c.MISC_ERROR,"wallet.exportmnemonic.admin: Invalid Account");return i={body:{phrase:e.master.mnemonic.getPhrase(),language:e.master.mnemonic.language,passphrase:e.master.mnemonic.passphrase},password:t,network:this.network,file:`./${this.network.type}-wallet${e.db.options.spv?"-spv":""}.keystore`},this.wdb.$parent&&(i.body.awardAddress=this.wdb.$parent.config.coinbaseAddress),await N.writeEncryptFile(i),N.encrypt(i)}async importMnemonic(e,t,i){if(t||2!==e.length)throw new h(c.MISC_ERROR,"wallet.importmnemonic.admin encrypt password: 导入钱包助记符 备份文本 备份密码");var r;t=new g([e]);let a=N.decrypt({body:t.str(0),password:t.str(1),network:this.network});for(r of("string"==typeof a&&(a=JSON.parse(a)),this.wdb.$parent&&(a.awardAddress=this.wdb.$parent.config.coinbaseAddress),await this.wdb.getWallets()))if((await this.wdb.get(r)).master.mnemonic.getPhrase()===a.phrase)throw new h(c.MISC_ERROR,"wallet.importmnemonic.admin: 相同助记词已被使用");return(e=await this.wdb.ensure({id:z(),type:"pubkeyhash",m:1,n:1,mnemonic:a,passphrase:null,master:null,witness:!0,watchOnly:!1,accountKey:null}))?e.toJSON(!1):null}async dumpWallet(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"wallet.export filename (fragment): 导出钱包备份 备份文件全路径 (分片存储 true/false)");t=new g([e]);var[e,,]=await this.accessControl(i);if(i=t.str(0))return t=t.bool(1,!1),await e.exportToFile({file:i,fragment:t}),!0;throw new h(c.TYPE_ERROR,"Invalid filename.")}async dumpWallets(e,t,i){if(t)throw new h(c.MISC_ERROR,"wallet.exports.admin: 导出所有钱包备份");for(var r of await this.wdb.getWallets())await(await this.wdb.get(r)).exportToFile({file:`backup-${r}.txt`});return!0}async encryptWallet(e,t,i){if(t||1!==e.length)throw new h(c.MISC_ERROR,'wallet.encrypt "passphrase"');t=new g([e]);var[e,i]=await this.accessControl(i);t=t.str(0,"");if("primary"==e.id&&"default"!=i)throw new h(c.MISC_ERROR,"Invalid Account");if(e.master.encrypted)throw new h(c.WALLET_WRONG_ENC_STATE,"Already running with an encrypted wallet.");if(t.length<1)throw new h(c.MISC_ERROR,'wallet.encrypt "passphrase"');try{await e.setPassphrase(null,t)}catch(e){throw new h(c.WALLET_ENCRYPTION_FAILED,"Encryption failed.")}return"wallet encrypted"}async getAccount(e,t,i){if(t||1!==e.length)throw new h(c.MISC_ERROR,'address.account "address"');t=new g([e]);var[e,i]=await this.accessControl(i);return("primary"!=e.id||"default"==i)&&(i=t.str(0,""),t=o.parseHash(i,this.network),i=await e.getPath(t))?i.name:""}async getAddressesByIndex(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,'address.index "index"');t=new g([e]);var[e,i]=await this.accessControl(i);if("primary"!=e.id||"default"==i){var r=t.uint(0);for(const t of await e.getPaths("default")){var a=t.toAddress();if(0==t.branch&&t.index==r)return a.toString(this.network)}}}async accessControl(e,t){let i=await this.wdb.get("primary");if(this.wdb.options.acl.isRoot(e.options.cid))"primary"!==e.options.wid?(i=await this.wdb.get(e.options.wid),t=null):"*"===(t=t||"default")&&(t=null);else if("primary"!==e.options.wid){if(!await i.belongToAccount(e.options.cid,e.options.wid))throw new h(c.TYPE_ERROR,"Invalid wid.");i=await this.wdb.get(e.options.wid),t=null}else t=e.options.cid;return await i.ensureAccount({name:t,witness:!0}),[i,t]}async getAddressesByAccount(e,t,i){if(t)throw new h(c.MISC_ERROR,'address.list "account"');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=[],a=[],s=[];for(const t of await e.getPaths(i)){var n=t.toAddress();(0==t.branch?r:1==t.branch?a:s).push(n.toString(this.network))}return[r,a,s]}async getAccountAddress(e,t,i){if(t)throw new h(c.MISC_ERROR,'address.receive "account"');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));if(t=await e.getAccount(i))return t.receive.getAddress("string")}async getAccountChangeAddress(e,t,i){if(t)throw new h(c.MISC_ERROR,"address.change account");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));if(t=await e.getAccount(i))return t.change.getAddress("string")}async getAccountNestedAddress(e,t,i){if(t)throw new h(c.MISC_ERROR,'address.nested.list "account"');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));if(t=await e.getAccount(i))return t.nested.getAddress("string")}async getBalance(e,t,i){if(t||3<e.length)throw new h(c.MISC_ERROR,'balance.confirmed ( "account" minconf includeWatchonly )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=t.u32(1,0);t=t.bool(2,!1);if(e.watchOnly!==t)return 0;let a;return t=await e.getBalance(i),a=0<r?t.confirmed:t.unconfirmed,v.btc(a,!0)}async getBalanceLog(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,'balance.log "account" (height)');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0));t=t.uint(1,0);return e.queryBalanceLog(i,t)}async getBalanceAll(e,t,i){if(t||3<e.length)throw new h(c.MISC_ERROR,'balance.all ( "account" minconf includeWatchonly )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0));return(await e.getBalance(i)).toJSON()}async checkBalance(e,t,i){if(t)throw new h(c.MISC_ERROR,"balance.check");t=new g([e]);var[e,,]=await this.accessControl(i,t.str(0));return(await e.resetBalance()).toJSON()}async getUserToken(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"cp.user cid uid: 生成登录令牌 厂商编码 用户编码");e=(t=new g([e])).str(0),t=t.str(1);var[i]=await this.accessControl(i);return i.tokenCreate({cid:e,uid:t},t)}async masterkey(e,t,i){var[i,r]=await this.accessControl(i);if("primary"==i.id||"default"==r)return i.master.toJSON(!0)}async getHistory(e,t,i){if(t||1<e.length)throw new h(c.MISC_ERROR,"tx.history (page acct):查询交易历史记录 (页码 账号)");var r=(t=new g([e])).uint(0,1);if(r<1)throw new h(c.MISC_ERROR,"页面必须是大于0的数字");var[e,i]=await this.accessControl(i,t.str(1));t=await e.getHistory(i);a.sortTX(t);let s=0;var n,o=[];for(n of t){if(s<10*(r-1));else{if(s>=10*r)break;o.push(n)}s++}return i=await e.toDetails(o),(e={}).items=i,e.pageSize=10,e.pageNum=r,e.total=t.length,e}async sendSecret(e,t,i){if(t||e.length<3)throw new h(c.MISC_ERROR,"comm.secret dst message (openid): 安全通信消息 收信地址 信息内容 (玩家账号)");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(3,"")),r=t.str(0,"");t=t.str(1,"");if(o.parseAddress(r,this.network))return e.sendSecret(r,t,i);throw new h(c.TYPE_ERROR,"Invalid Destination Address.")}async calcHash(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"comm.hash content: 计算输入的哈希值");return t=new g([e]).str(0,""),w.hash256(Buffer.from(t)).toString("hex")}async commNotify(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"comm.notify addr content (openid): 发送点对点消息 地址 内容 (玩家账号)");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0,"");t=t.obj(1,{});return e.commNotify({dst:r,content:t,account:i})}async scanContact(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,'comm.scanContact "txid" ( index )');t=new g([e]);var[e,,]=await this.accessControl(i);i=t.hash(0),r(i,"Hash is required."),t=t.uint(1,-1);if(!i)throw new h(c.TYPE_ERROR,"Invalid parameter");if(e=await e.getTX(i))return this.wdb.scanContact(e.tx,t);throw new h(c.WALLET_ERROR,"TX not found.")}async listContact(e,t,i){if(t)throw new h(c.MISC_ERROR,"sys.listContact: 列表联系人");return t=new g([e]).array(0,[]),this.wdb.listContact(t,null,["address"])}async listNotify(e,t,i){if(t)throw new h(c.MISC_ERROR,"comm.listNotify (query): 通知列表 (查询条件,使用 account 参数可分账号查询)");return t=new g([e]).array(0,[]),this.wdb.listNotify(t)}async getReceivedByAccount(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,'account.received "account" ( minconf )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=t.u32(1,0),a=this.wdb.curHeight,s=(t=await e.getPaths(i),new Set);for(const e of t)s.add(e.hash);let n=0,o=-1;for(const t of await e.getHistory(i)){var u=t.getDepth(a);if(!(u<r)){(-1===o||u<o)&&(o=u);for(const e of t.tx.outputs){var l=e.getHash("hex");l&&s.has(l)&&(n+=e.value)}}}return v.btc(n,!0)}async getReceivedByAddress(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,'address.received "address" ( minconf )');t=new g([e]);var[e,,]=await this.accessControl(i),r=(i=t.str(0,""),t.u32(1,0)),a=this.wdb.curHeight,s=o.parseHash(i,this.network);let n=0;for(const t of await e.getHistory())if(!(t.getDepth(a)<r))for(const e of t.tx.outputs)e.getHash("hex")===s&&(n+=e.value);return v.btc(n,!0)}async _toWalletTX(e,t){var[e,,]=await this.accessControl(e),i=await e.toDetails(t);if(!i)throw new h(c.WALLET_ERROR,"TX not found.");let r=!0;for(const e of i.inputs)if(e.path){r=!1;break}var a=[];let s=0,n=0;for(let e=0;e<i.outputs.length;e++){var o=i.outputs[e];o.path?1!==o.path.branch&&(a.push({account:o.path.name,address:o.address.toString(this.network),category:"receive",amount:v.btc(o.value,!0),label:o.path.name,vout:e}),n+=o.value):r||(a.push({account:"",address:o.address?o.address.toString(this.network):null,category:"send",amount:-v.btc(o.value,!0),fee:-v.btc(i.getFee(),!0),vout:e}),s+=o.value)}return{amount:v.btc(r?n:-s,!0),confirmations:i.confirmations,blockhash:i.block?d.revHex(i.block):null,blockindex:i.index,blocktime:i.time,txid:d.revHex(i.hash),walletconflicts:[],time:i.mtime,timereceived:i.mtime,"bip125-replaceable":"no",details:a,hex:i.tx.toRaw().toString("hex")}}async getTransaction(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,'tx.get.wallet "txid" ( includeWatchonly )');t=new g([e]);var[e,,]=await this.accessControl(i),a=t.hash(0);r(a,"Hash is required."),t=t.bool(1,!1);if(!a)throw new h(c.TYPE_ERROR,"Invalid parameter");if(e=await e.getTX(a))return this._toWalletTX(i,e,t);throw new h(c.WALLET_ERROR,"TX not found.")}async abandonPending(e,t,i){if(t)throw new h(c.MISC_ERROR,"tx.abandonall.admin [account]: 废弃所有挂起的交易");t=new g([e]);var[r,e]=await this.accessControl(i,t.str(0,""));for(const t of await r.getPending(e))try{await r.abandon(t.hash)}catch(e){this.logger.warning(e.message)}return null}async abandonTransaction(e,t,i){if(t||1!==e.length)throw new h(c.MISC_ERROR,'tx.abandon.admin "txid"');t=new g([e]);var[e,,]=await this.accessControl(i);if(!(i=t.hash(0)))throw new h(c.TYPE_ERROR,"Invalid parameter.");if(await e.abandon(i))return null;throw new h(c.WALLET_ERROR,"Transaction not in wallet.")}async getUnconfirmedBalance(e,t,i){if(t||1<e.length)throw new h(c.MISC_ERROR,"balance.unconfirmed");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));t=await e.getBalance(i);return v.btc(t.unconfirmed,!0)}async importPrivKey(e,t,i){if(t||e.length<1||4<e.length)throw new h(c.MISC_ERROR,'key.import.private account "privatekey" passphrase [rescan]');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=t.str(1),a=t.str(2);t=t.bool(3,!1);return(r=o.parseSecret(r,this.network)).witness=!0,await e.importKey(i,r,a),t&&await this.wdb.rescan(0),!0}async walletAuth(e,t,i){return!0}async importWallet(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,'wallet.import "filename" ( rescan )');t=new g([e]);var[,]=await this.accessControl(i);e=t.str(0),i=t.bool(1,!1);return await this.wdb.loadBackup(e),i&&await this.wdb.rescan(0),!0}async importAddress(e,t,i){if(t||e.length<1||4<e.length)throw new h(c.MISC_ERROR,"address.import account address [rescan p2sh]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));let r=t.str(1,"");var a=t.bool(2,!1);if(t.bool(3,!1)){let e=t.buf(0);if(!e)throw new h(c.TYPE_ERROR,"Invalid parameters.");e=y.fromRaw(e),e=y.createScript(e.hash160(),y.types.SCRIPTHASH),r=k.fromScript(e)}else r=o.parseAddress(r,this.network);return await e.importAddress(i,r),a&&await this.wdb.rescan(0),!0}async importPubkey(e,t,i){if(t||e.length<1||4<e.length)throw new h(c.MISC_ERROR,"key.import.public account pubkey [rescan]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=t.buf(1);t=t.bool(2,!1);if(r)return r=S.fromPublic(r,this.network),await e.importKey(i,r),t&&await this.wdb.rescan(0),!0;throw new h(c.TYPE_ERROR,"Invalid parameter.")}async listAccounts(e,t,i){if(t||2<e.length)throw new h(c.MISC_ERROR,"account.list ( minconf includeWatchonly)");t=new g([e]);var[r]=await this.accessControl(i),a=t.u32(0,0),s=t.bool(1,!1),n={};for(const e of await r.getAccounts()){var o=await r.getBalance(e);let t=o.unconfirmed;0<a&&(t=o.confirmed),r.watchOnly!==s&&(t=0),n[e]=v.btc(t,!0)}return n}async mapAccounts(e,t,i){if(t||2<e.length)throw new h(c.MISC_ERROR,"account.list ( minconf includeWatchonly)");t=new g([e]);var[e]=await this.accessControl(i);return t.u32(0,0),t.bool(1,!1),e.getAccountMap()}async listConservedUnspent(e,t,i){if(t||0<e.length)throw new h(c.MISC_ERROR,"coin.conserved.list: 查询已经保持的Unspent列表");var[t]=await this.accessControl(i),r=[];for(const e of t.getConserved())r.push({txid:e.txid(),vout:e.index});return r}async accountVirtualAdd(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"account.virtualadd.admin account amount: 虚增账户余额 账户名称 金额");t=new g([e]);var[e]=await this.accessControl(i,t.str(2,""));i=t.str(0),t=t.u64(1),i=await e.ensureIndex(i);return e.txdb.addAccountAmount(i,t),!0}async accountCheckAmount(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"account.checkamount account: 验证账户余额 账户名称");t=new g([e]);var[e]=await this.accessControl(i,t.str(2,""));i=t.str(0),t=await e.ensureIndex(i);return e.txdb.checkAccountAmount(t),!0}async listReceivedByAccount(e,t,i){if(t||3<e.length)throw new h(c.MISC_ERROR,"account.listreceived ( minconf includeempty includeWatchonly )");e=(t=new g([e])).u32(0,0);var r=t.bool(1,!1);t=t.bool(2,!1);return this._listReceived(i,e,r,t,!0)}async listReceivedByAddress(e,t,i){if(t||3<e.length)throw new h(c.MISC_ERROR,"address.received.list ( minconf includeempty includeWatchonly )");e=(t=new g([e])).u32(0,0);var r=t.bool(1,!1);t=t.bool(2,!1);return this._listReceived(i,e,r,t,!1)}async _listReceived(e,t,i,r,a){var[s]=await this.accessControl(e),n=(e=await s.getPaths(),this.wdb.curHeight);const o=new Map;for(const t of e){var c=t.toAddress();o.set(t.hash,{involvesWatchonly:s.watchOnly,address:c.toString(this.network),account:t.name,amount:0,confirmations:-1,label:""})}for(const e of await s.getHistory()){var u=e.getDepth(n);if(!(u<t))for(const t of e.tx.outputs){var h,l=t.getAddress();l&&(h=l.getHash("hex"),h=o.get(h))&&((-1===h.confirmations||u<h.confirmations)&&(h.confirmations=u),h.address=l.toString(this.network),h.amount+=t.value)}}let p=[];for(const e of o.values())p.push(e);if(a){const e=new Map;for(const t of p){var d=e.get(t.account);d?d.amount+=t.amount:(e.set(t.account,t),t.address=void 0)}p=[];for(const t of e.values())p.push(t)}var f=[];for(const t of p)if(i||0!==t.amount){-1===t.confirmations&&(t.confirmations=0);try{t.amount=v.btc(t.amount,!0),f.push(t)}catch(e){this.logger.error("invalid amount:entry(%s) msg(%s)",JSON.stringify(t),e.message)}}return f}async listSinceBlock(e,t,i){if(t)throw new h(c.MISC_ERROR,'tx.history.since ( "blockhash" target-confirmations includeWatchonly account)');var r=this.wdb.curHeight,[e,a]=(t=new g([e]),await this.accessControl(i,t.str(3,""))),s=t.hash(0),n=t.u32(1,0);t=t.bool(2,!1);if(e.watchOnly!==t)return[];let o=-1;-1===(o=s&&(t=await this.client.getEntry(s))?t.height:o)&&(o=r);var u,l=[];let p;for(const t of await e.getHistory(a))t.height<o||t.getDepth(r)<n||((!p||t.height>p)&&(p=t),u=await this._toListTX(i,t),l.push(u));return{transactions:l,lastblock:p&&p.block?d.revHex(p.block):m.NULL_HASH}}async _toListTX(e,t){var[e]=await this.accessControl(e),i=await e.toDetails(t);if(!i)throw new h(c.WALLET_ERROR,"TX not found.");let a=!0;for(const e of i.inputs)if(e.path){a=!1;break}let s,n,o,u,l,p,f=0,m=0;for(let e=0;e<i.outputs.length;e++){const t=i.outputs[e];t.path?1!==t.path.branch&&(m+=t.value,n=t,u=e):(f+=t.value,s=t,o=e)}return p=a?(l=n,u):(l=s,o),l||(r(!a),a=!0,l=n,p=u),{account:l.path?l.path.name:"",address:l.address?l.address.toString(this.network):null,category:a?"receive":"send",amount:v.btc(a?m:-f,!0),label:l.path?l.path.name:void 0,vout:p,confirmations:i.getDepth(),blockhash:i.block?d.revHex(i.block):null,blockindex:i.index,blocktime:i.time,txid:d.revHex(i.hash),walletconflicts:[],time:i.mtime,timereceived:i.mtime,"bip125-replaceable":"no"}}async listTransactions(e,t,i){if(t||4<e.length)throw new h(c.MISC_ERROR,'tx.list ( "account" count from includeWatchonly)');t=new g([e]);var[e,r]=await this.accessControl(i,t.str(0,"")),s=t.u32(1,10),n=t.u32(2,0);t=t.bool(3,!1);if(e.watchOnly!==t)return[];var o=await e.getHistory(r),u=(t=(a.sortTX(o),n+s),Math.min(t,o.length)),l=[];for(let e=n;e<u;e++){var p=o[e];p=await this._toListTX(i,p);l.push(p)}return l}async selectone(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"coin.selectone options (account)");t=new g([e]);var[r,e]=await this.accessControl(i,t.str(1,"")),a=t.obj(0,{}),s=[];for(const t of await r.getCoins(e)){var n=t.getDepth(this.wdb.curHeight),o=t.getAddress();if(o){var u=t.getHash("hex");if(u&&!t.isColored&&!(a.value&&t.value<a.value||t.coinbase&&0<t.height&&this.wdb.curHeight<t.height+b.COINBASE_MATURITY)&&(u=await r.getKey(u),s.push({txid:t.txid(),vout:t.index,address:o?o.toString(this.network):null,account:u?u.name:void 0,redeemScript:u&&u.script?u.script.toJSON():void 0,scriptPubKey:t.script.toJSON(),amount:v.btc(t.value,!0),confirmations:n,spendable:!r.isConserved(t),solvable:!0}),a.len&&s.length>=a.len))break}}return s}async listUnspent(e,t,i){if(t||4<e.length)throw new h(c.MISC_ERROR,'coin.list ( minconf maxconf ["address", account] )');const r=new g([e]);var[s,t]=await this.accessControl(i,r.str(3,"")),n=r.u32(0,1),u=r.u32(1,9999999),l=r.array(2),p=this.wdb.curHeight,d=new Set;if(l&&0<l.length){const e=new g([l]);for(let t=0;t<l.length;t++){var f=e.str(t,"");f=o.parseHash(f,this.network);if(d.has(f))throw new h(c.INVALID_PARAMETER,"Duplicate address.");d.add(f)}}e=await s.getCoins(t);var m,y,b,w=(a.sortCoins(e),[]);for(const t of e)t.isColored||(m=t.getDepth(p))<n||u<m||((y=t.getAddress())?(b=t.getHash("hex"),l&&0<l.length&&(!b||!d.has(b))||(b=await s.getKey(b),w.push({txid:t.txid(),vout:t.index,address:y?y.toString(this.network):null,account:b?b.name:void 0,redeemScript:b&&b.script?b.script.toJSON():void 0,scriptPubKey:t.script.toJSON(),amount:v.btc(t.value,!0),confirmations:m,spendable:!s.isConserved(t),solvable:!0}))):this.logger.error("mistaken coin: miss address",t.hash,t.index));return w}async checkUnspent(e,t,i){if(t)throw new h(c.MISC_ERROR,"coin.check (account)");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=[];if(this.wdb.$parent)for(const t of await e.getCoins(i))await this.wdb.$parent.getCoin(t.hash,t.index)||r.push(t.txid(),t.index);return r}async listProp(e,t,i){if(t||4<e.length)throw new h(c.MISC_ERROR,"prop.wallet.byaddress ( minconf maxconf [address, account] )");const r=new g([e]);var[s,t]=await this.accessControl(i,r.str(3,"")),n=r.u32(0,1),u=r.u32(1,9999999),l=r.array(2),p=this.wdb.curHeight,d=new Set;if(l){const e=new g([l]);for(let t=0;t<l.length;t++){var f=e.str(t,"");f=o.parseHash(f,this.network);if(d.has(f))throw new h(c.INVALID_PARAMETER,"Duplicate address.");d.add(f)}}e=await s.getCoins(t);var m=(a.sortCoins(e),[]);for(const t of e){var y,b,w,x=t.getDepth(p);x<n||u<x||(y=t.getAddress())&&(b=t.getHash("hex"),!l||b&&d.has(b))&&(b=await s.getKey(b),w=t.getReturnData([F.OP_PROPCREATE,F.OP_PROPCREATE]))&&m.push({txid:t.txid(),vout:t.index,address:y?y.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 m}async listPropByOid(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"prop.wallet.byoid oid");t=new g([e]);var[r,e]=await this.accessControl(i,t.str(1,"")),s=t.str(0),n=this.wdb.curHeight,o=(i=await r.getCoins(e),a.sortCoins(i),[]);for(const e of i){var u,l,p,d=e.getDepth(n);d<0||9999999<d||(u=e.getAddress())&&(l=e.getHash("hex"),l=await r.getKey(l),p=e.getReturnData([F.OP_PROPCREATE,F.OP_PROPEXCHANGE]))&&p.oid==s&&o.push({txid:e.txid(),vout:e.index,address:u?u.toString(this.network):null,account:l?l.name:void 0,amount:v.btc(e.value,!0),confirmations:d,spendable:!r.isConserved(e),solvable:!0,nd:p})}return{list:o,count:o.length}}async listLockedUnspent(e,t,i){if(t||2<e.length)throw new h(c.MISC_ERROR,'coin.list.locked ["address", account]');const r=new g([e]);var[s,t]=await this.accessControl(i,r.str(1,"")),n=r.array(0),u=this.wdb.curHeight,l=d.now(),p=new Set;if(n){const e=new g([n]);for(let t=0;t<n.length;t++){var f=e.str(t,"");f=o.parseHash(f,this.network);if(p.has(f))throw new h(c.INVALID_PARAMETER,"Duplicate address.");p.add(f)}}let m;m=account?await s.getCoins(t):s.getLockedCoins(),a.sortCoins(m);var y,b,w,x,k,S,_=[];for(const e of m)(e.lockedByLocktime(u,l)||e.lockedBySequence(u,l))&&(y=e.getAddress())&&(b=e.getDepth(u),S=e.getHash("hex"),!n||S&&p.has(S))&&([w,x,k]=e.getLockStatus(),S=await s.getKey(S),_.push({txid:e.txid(),vout:e.index,address:y?y.toString(this.network):null,account:S?S.name:void 0,redeemScript:S&&S.script?S.script.toJSON():void 0,scriptPubKey:e.script.toJSON(),amount:v.btc(e.value,!0),confirmations:b,spendable:!1,solvable:!0,locktype:w,lockheight:x,locktime:k}));return _}async listOperUnspent(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,'coin.conserved.oper.list unlock ([{"txid":"txid","vout":n},...]) 保持/解除保持一组UTXO: true/false [{"txid": "交易id","vout": "输出序号"}]');const r=new g([e]);var[a]=await this.accessControl(i),s=r.bool(0,!1);if(!(t=r.array(1)))throw new h(c.TYPE_ERROR,"Invalid parameter.");for(const e of t){const t=new g([e]);var n=t.hash("txid"),o=t.u32("vout");if(null==n||null==o)throw new h(c.INVALID_PARAMETER,"Invalid parameter.");n=new j(n,o),s?a.unConserveCoin(n):a.conserveCoin(n)}return!0}async setTXFee(e,t,i){if(t||e.length<1||1<e.length)throw new h(c.MISC_ERROR,"sys.setfee rate");if(null==(t=new g([e]).ufixed(0,8)))throw new h(c.TYPE_ERROR,"Invalid parameter.");return this.wdb.feeRate=t,!0}async signMessage(e,t,i){if(t||2!==e.length)throw new h(c.MISC_ERROR,'sys.message.sign "address" "message"');t=new g([e]);var[e]=await this.accessControl(i);if(!e.master.key)throw new h(c.WALLET_UNLOCK_NEEDED,"Wallet is locked.");i=t.str(0,""),i=o.parseHash(i,this.network);if(e=await e.getKey(i))return i=t.str(1,""),e.sign(w.hash256(Buffer.from(u+i,"utf8"))).toString("base64");throw new h(c.WALLET_ERROR,"Address not found.")}async changePassphrase(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,'wallet.changepassphrase "oldpassphrase" "newpassphrase"');t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0,""),t=t.str(1,"");if(!e.master.encrypted)throw new h(c.WALLET_WRONG_ENC_STATE,"Wallet is not encrypted.");if(i.length<1||t.length<1)throw new h(c.INVALID_PARAMETER,"Invalid parameter");return await e.setPassphrase(i,t),null}async unlock(e,t,i){var r=new g([e]),[i]=await this.accessControl(i),a=r.str(0);r=r.u32(1,60);if(t||i.master.encrypted&&0==e.length)throw new h(c.MISC_ERROR,'wallet.unlock "passphrase" timeout');if(!i.master.encrypted)throw new h(c.WALLET_WRONG_ENC_STATE,"Wallet is not encrypted.");if(a.length<1)throw new h(c.INVALID_PARAMETER,"Invalid parameter");if(null==r)throw new h(c.TYPE_ERROR,"Invalid parameter");return await i.unlock(a,r),null}async decryptWallet(e,t,i){if(t||1!==e.length)throw new h(c.MISC_ERROR,'wallet.decrypt "passphrase"');t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0,"");if(!e.master.encrypted)throw new h(c.WALLET_WRONG_ENC_STATE,"Running with an decrypted wallet.");if(i.length<1)throw new h(c.MISC_ERROR,'wallet.decrypt "passphrase"');try{await e.setPassphrase(i)}catch(e){throw new h(c.WALLET_ENCRYPTION_FAILED,"Decryption failed.")}return"wallet decrypted"}async importPrunedFunds(e,t,i){if(t||e.length<2||3<e.length)throw new h(c.MISC_ERROR,'tx.importprunedfunds.admin "rawtransaction" "txoutproof" ( "label" )');if(e=(t=new g([e])).buf(0),t=t.buf(1),!e||!t)throw new h(c.TYPE_ERROR,"Invalid parameter.");e=A.fromRaw(e);var r=(t=_.fromRaw(t)).hash("hex");if(!t.verify())throw new h(c.VERIFY_ERROR,"Invalid proof.");if(!t.hasTX(e.hash("hex")))throw new h(c.VERIFY_ERROR,"Invalid proof.");var a=await this.client.getEntry(r);if(-1===a)throw new h(c.VERIFY_ERROR,"Invalid proof.");if(r={hash:r,time:t.time,mtp:t.mtp,height:a},await this.wdb.addTX(e,r))return null;throw new h(c.WALLET_ERROR,"No tracked address for TX.")}async removePrunedFunds(e,t,i){if(t||1!==e.length)throw new h(c.MISC_ERROR,'tx.removeprunedfunds.admin "txid"');t=new g([e]);var[e]=await this.accessControl(i);if(!(i=t.hash(0)))throw new h(c.TYPE_ERROR,"Invalid parameter.");if(await e.remove(i))return null;throw new h(c.WALLET_ERROR,"Transaction not in wallet.")}async getWallets(e,t,i){return this.wdb.getWallets()}async getWalletBlock(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"wallet.block height");t=new g([e]);var[e]=await this.accessControl(i);i=t.uint(0);return(t=await e.getBlock(i))?t.toJSON():null}async getWalletLayoutH(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"wallet.layouth height");return t=new g([e]).uint(0),(e=await this.wdb.getBlock(t))?e.toJSON():null}async getWalletInfo(e,t,i){if(t)throw new h(c.MISC_ERROR,"wallet.info");return((t=new g([e]).str(0,""))?await this.wdb.get(t):(await this.accessControl(i))[0]).toJSON(!1)}async scRegister(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"sc.register options (account): 发布合约 合约参数列表 (子账户)");t=new g([e]);var[r,a]=await this.accessControl(i,t.str(1,""));let s=t.obj(0);if(!s)throw new h(c.MISC_ERROR,"sc.register: options is null");let n=1e5;switch(s.oper){case"change":if(s.oper=O.scState,!s.dst||!s.state)throw new h(c.TYPE_ERROR,"sc.register: dst or state is null.");if(!this.wdb.$parent)throw new h(c.TYPE_ERROR,"sc.register: not support this operation.");var o=await this.wdb.$parent.chain.db.getSCList([["options.dst",s.dst]]);if(!o||0==o.list.length)throw new h(c.TYPE_ERROR,"sc.register: contract not exist.");switch(o.list[0].options.state){case C.Normal:if(s.state!=C.Frozen&&s.state!=C.Destroy)throw new h(c.TYPE_ERROR,"Contract State Error");break;case C.Frozen:if(s.state!=C.Normal&&s.state!=C.Destroy)throw new h(c.TYPE_ERROR,"Contract State Error");break;default:throw new h(c.TYPE_ERROR,"Contract State Error")}if(s.addr=o.list[0].options.addr,await r.belongToAccount(a,s.addr))break;throw new h(c.MISC_ERROR,"sc.register: Invald Account.");case"update":if(s.oper=O.scUpdate,!s.dst)throw new h(c.TYPE_ERROR,"sc.register: dst is null.");if(!this.wdb.$parent)throw new h(c.TYPE_ERROR,"sc.register: not support this operation.");if(!(o=await this.wdb.$parent.chain.db.getSCList([["options.dst",s.dst]]))||0==o.list.length)throw new h(c.TYPE_ERROR,"sc.register: contract not exist.");if(o.list[0].options.state!=C.Normal)throw new h(c.TYPE_ERROR,"sc.register: contract state error.");if(s.addr=o.list[0].options.addr,await r.belongToAccount(a,s.addr))break;throw new h(c.MISC_ERROR,"sc.register: Invald Account.");default:if(n=1e8,s.oper=O.scRegister,s.addr=(await r.createReceive(a)).getAddress("string"),s.dst=r.getSCAddress(d.hashInt(s.addr)).toString(),this.wdb.$parent&&(o=await this.wdb.$parent.chain.db.getSCList([["options.dst",s.dst]]))&&0<o.list.length)throw new h(c.TYPE_ERROR,"sc.register: contract address conflict.")}return(e=(await r.getPrivateKey(s.addr)).signData(s)).data.sig=e.sig,s=e.data,i=await r.send({subtractFee:!1,sort:!1,outputs:[{address:s.dst,value:n}],comment:JSON.stringify(s)},a),await this.wdb.logAudit({address:s.addr,oper:s.oper,hash:i.hash("hex"),index:0}),s.txid=i.rhash(),s}async scRun(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,'sc.run str options (account): 调用合约 逗分参数字符串("合约收款地址,转账金额") 参数对象 (子账户)');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0).split(","),a=(t=t.obj(1,{}),r.shift());if(!this.wdb.$parent)throw new h(c.TYPE_ERROR,"sc.run: not support this operation.");var s=await this.wdb.$parent.chain.db.getSCList([["options.dst",a]]);if(!s||0==s.list.length)throw new h(c.TYPE_ERROR,"sc.run: contract not exist.");if(1!=s.list[0].options.state)throw new h(c.TYPE_ERROR,`sc.run: contract execute disabled(state ${s.list[0].options.state}).`);if(t.ver&&t.ver!=s.list[0].options.ver)throw new h(c.TYPE_ERROR,"sc.run: contract version inconsistency.");return s=(0|parseInt(r.shift()))>>>0,o.parseAddress(a,this.network),r=await e.send({subtractFee:!1,sort:!1,outputs:[{address:a,value:s}],comment:JSON.stringify({oper:"scrun",params:t})},i),a=await e.getAccount(i),await this.wdb.logAudit({address:a.receive.getAddress("string"),oper:O.scRun,hash:r.hash("hex"),index:0}),(await e.getDetails(r.hash("hex"))).toJSON()}async cpRegister(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,'cp.create name "ip,addr,class,rate" (openid): 注册厂商 名称(不少于4个字符) "IP地址,注册地址,类别,媒体分成比例" (子账号)');return this.$cpRegister(e,i,!1)}async cpRegisterAsync(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,'cp.create.async name "ip,addr,class,rate" (openid): 注册厂商 名称(不少于4个字符) "IP地址,注册地址,类别,媒体分成比例" (子账号)');return this.$cpRegister(e,i,!0)}async $cpRegister(e,t,i){e=new g([e]);var r=decodeURIComponent(e.str(0)),a=(o=e.str(1,"").split(","))[0],s=o[1],n=o[2],o=o[3]?parseInt(o[3]):15,[t,e]=await this.accessControl(t,e.str(2,"")),u=f.verifyDataFormat({name:r,ip:a,grate:o,cls:n});if(u)throw new h(c.MISC_ERROR,u);return u={cid:z(),oper:O.cpRegister,name:r,ip:a,grate:o,cls:n},await t.cpRegister(d.isBech32(s)?s:null,u,e,i),u}async cpChange(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,'cp.change cid "newname,ip,addr,class,rate" "openid": 修改厂商信息 CP编号 "新的名称,IP,新的注册地址,类别,分成比例" 授权账号');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),a=t.str(0),s=(t=decodeURIComponent(t.str(1,"")).split(","))[0],n=t[1];let o=t[2];var u=t[3];t=parseInt(t[4])||null;if(l=f.verifyDataFormat({name:s,ip:n,grate:t,cls:u}))throw new h(c.MISC_ERROR,l);o&&(o=k.fromString(o),r(o instanceof k,"Not an address."));var l={cid:a,newName:s,ip:n,addr:o,grate:t,cls:u},[,,]=await e.cpChange(l,i);return l.addr=l.addr.toString(),l}async cpQuery(e,t,i){if(t)throw new h(c.MISC_ERROR,"cp.query (conditions account): 查询钱包中的厂商列表 (复合条件 子帐号)");t=new g([e]);var r,[a,s]=await this.accessControl(i,t.str(1,""));e=t.array(0,[]),i=a.db.cpList.query(e);for(r of i.list)r.owned=await a.belongToAccount(s,r.current.address);return i}async cpQueryRemote(e,t,i){if(t)throw new h(c.MISC_ERROR,"cp.query.remote conditions: 查询厂商列表 (复合条件)");t=new g([e]);var r,[a,s]=await this.accessControl(i,t.str(1,""));e=t.array(0,[]),i=await a.db.client.execute("cp.remoteQuery",[e]);for(r of i.list)r.owned=await a.belongToAccount(s,r.current.address);return i}async cpMine(e,t,i){if(t)throw new h(c.MISC_ERROR,"cp.mine (conditions account): 查询钱包中归属当前操作员/指定账户的厂商列表 (复合条件 子帐号)");t=new g([e]);let[r,a]=await this.accessControl(i,t.str(1,""));return(e=t.array(0,[])).push(["size",-1]),(await r.db.cpList.predict(async(e,t)=>r.belongToAccount(a,t.current.address))).query(e)}async htlcSuggest(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,"htlc.suggest params [account]: 发起HTLC 参数对象({alice, bob, amount, rate}) [子账户]");e=(t=new g([e])).obj(0,{});var r,[i,t]=await this.accessControl(i,t.str(1,""));if(!e.ab)throw new h(c.MISC_ERROR,"htlc.suggest: params.ab(alice bchain address) is null");if(!Number.isInteger(e.amount))throw new h(c.MISC_ERROR,"htlc.suggest: illegal params.amount");if(e.amount=parseInt(e.amount),e.amount<0||e.amount>1e4*b.COIN)throw new h(c.MISC_ERROR,"htlc.suggest: illegal params.amount");if(e.rate=parseFloat(e.rate),e.rate<0||e.amount*e.rate>b.MAX_MONEY)throw new h(c.MISC_ERROR,"htlc.suggest: illegal params.rate");if(e.target)return r=(await i.createReceive(t)).getAddress().toString(this.network),e={amount:e.amount,rate:e.rate,dst:e.target,aa:k.fromString(r).hash,ab:k.fromString(e.ab).hash,ba:k.fromString(e.ba).hash},[i]=await i.sendContracts([e],t,R),i?{txid:i.rhash(),aa:r}:null;throw new h(c.MISC_ERROR,"htlc.suggest: params.target is null")}async htlcAssent(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,"htlc.assent params({txid}) [account]: 响应HTLC 参数对象 [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));t=t.obj(0,{});if(!Number.isInteger(t.amount))throw new h(c.MISC_ERROR,"htlc.assent: illegal params.amount");if(t.amount=parseInt(t.amount),t.amount<0||t.amount>1e4*b.COIN)throw new h(c.MISC_ERROR,"htlc.assent: illegal params.amount");if(t.rate=parseFloat(t.rate),t.rate<0||t.amount*t.rate>b.MAX_MONEY)throw new h(c.MISC_ERROR,"htlc.assent: illegal params.rate");var r=(await e.createReceive(i)).getAddress().toString(this.network),[t]=(r={src:t.src,dst:t.dst,hash:t.hash,index:t.index,ab:Buffer.from(t.ab,"hex"),ba:Buffer.from(t.ba,"hex"),bb:k.fromString(r).hash,amount:t.amount*t.rate},await e.sendContracts([r],i,I));return t?{txid:t.rhash()}:null}async htlcSuggestDeal(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,"htlc.suggest.deal params({txid,index,sa}) [account]: 兑付HTLC 参数对象 [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,"")),[e,,]=(t=t.obj(0),t={suggest:!0,hash:d.revHex(t.txid),index:t.index,sa:t.sa},await e.htlcDeal(t,i));return e?{txid:e.rhash()}:null}async htlcQuery(e,t,i){if(t)throw new h(c.MISC_ERROR,"htlc.query query: 条件查询HTLC合约 条件数组");return(t=new g([e]).array(0,[])).push(["pst","!=",T.Cancel]),this.wdb.htlcList.query(t)}async htlcAssentDeal(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,"htlc.assent.deal params({txid,index,sa}) [account]: 兑付HTLC 参数对象 [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,"")),[e,,]=(t=t.obj(0),t={hash:d.revHex(t.txid),index:t.index,sa:t.sa},await e.htlcDeal(t,i));return e?{txid:e.rhash()}:null}async htlcAssentCancel(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,"htlc.assent.cancel params({txid, index, master}) [account]: 取消HTLC应答 参数对象 [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,"")),[e,,]=(t=t.obj(0),t={hash:d.revHex(t.txid),index:t.index,master:t.bb},await e.htlcCancel(t,i));return e?{txid:e.rhash()}:null}async htlcSuggestCancel(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,"htlc.suggest.cancel params({txid, index, sa, master}) [account]: 取消HTLC请求 参数对象 [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,"")),[e,,]=(t=t.obj(0),t={suggest:!0,hash:d.revHex(t.txid),index:t.index,sa:t.sa,master:t.aa},await e.htlcCancel(t,i));return e?{txid:e.rhash()}:null}async sendComment(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,"comm.comment params [account]: 发起附言交易 参数对象({body, bob}) [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));t=t.obj(0,{});if(!Number.isInteger(t.amount))throw new h(c.MISC_ERROR,"comm.comment: illegal params.amount");if(t.amount=parseInt(t.amount),t.amount<0||t.amount>1e4*b.COIN)throw new h(c.MISC_ERROR,"comm.comment: illegal params.amount");var r={bob:t.bob,body:t.body,amount:t.amount};t.alice||(t.alice=e.getAddress(),i&&(a=await e.createReceive(i),t.alice=a.getAddress()));var a=(await e.getPrivateKey(t.alice)).signData(r),[t]=(a.data.sig=a.sig,await e.sendContracts([a.data],i,B));return t?{txid:t.rhash()}:null}async commentQuery(e,t,i){if(t)throw new h(c.MISC_ERROR,"comm.comment.query query: 条件查询附言输出 条件数组");return t=new g([e]).array(0,[]),this.wdb.commentList.query(t)}async contractExecute(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,"contract.execute tid master: 执行交易对合约 交易编号 执行方(1-发起人,2-承兑人)");t=new g([e]);var[e]=await this.accessControl(i),[e,,]=(i=t.str(0),t=t.u32(1,2),await e.contractExecute(i,t));return e.toJSON()}async contractPromise(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,"contract.promise tid [openid]: 签署交易对合约 交易编号(type.address) [子账号]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,"")),[e,,]=(t=t.str(0),await e.contractPromise(t,i));return e.toJSON()}async contractOfMine(e,t,i){if(t||e.length<1||3<e.length)throw new h(c.MISC_ERROR,"contract.mine type page [openid]: 获取已签署交易对合约列表 交易对类型 页码 [子账号]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.uint(0,1);t=t.uint(1,1);return e.db.getContracts(r,t,i)}async contractCreate(e,t,i){if(t||e.length<4||5<e.length)throw new h(c.MISC_ERROR,"contract.create type src dst addr [openid] : 发布一个交易对合约 交易对类型 出让游戏金数值 换取兑换币数值 兑换币收款地址 [子账号]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(4,"")),r=t.u64(0),a=t.u64(1),s=t.u64(2),[e,,]=(t=t.str(3),await e.contractCreate(r,a,s,t,i));return e.toJSON()}async propGet(e,t,i){if(t)throw new h(c.MISC_ERROR,"prop.wallet.byid pid: 查询自己的物品 PID");return t=new g([e]).str(0,""),e=[],(t=await this.wdb.propList.getVp(t))&&t.pst!=P.Delete&&e.push(t),e}async propQuery(e,t,i){if(t)throw new h(c.MISC_ERROR,"prop.query query: 条件查询自己的物品 条件数组");t=new g([e]);var[e]=await this.accessControl(i,t.str(1,""));return(i=t.array(0,[])).push(["pst","!=",P.Delete]),(await e.getPropList()).query(i)}async mySaleList(e,t,i){if(t)throw new h(c.MISC_ERROR,"prop.query.auction (page acct): 查询自己拍卖的物品 (页码 账户)");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));t=t.uint(0,1);return e.mySaleList(t,i)}async onSaleList(e,t,i){e=new g([e]);var[i,r]=await this.accessControl(i,e.str(1,""));e=e.uint(0,1);return i.onSaleList(e,r)}async propBuy(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"prop.buy pid price [openid] : 竞拍道具 道具编号 出价 [子账号]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0),[e,,]=(t=t.u64(1),await e.propBuy(r,t,i));return e.toJSON()}async propFound(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"prop.found pid (openid): 熔铸道具 道具编号 (账号)");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));t=t.str(0);if(!(t=await e.db.propList.getVp(t))||t.pst==P.Delete)throw new h(c.MISC_ERROR,"prop.found prop not exist");if(!await e.ownedAddress(t.current.address))throw new h(c.MISC_ERROR,"prop.found: current account not owned prop.");if(t.pst!=P.Ready)throw new h(c.MISC_ERROR,"prop.found prop can not be found on current status");var[e,,t]=await e.propFound(t.current.hash,t.current.index,i);if(e&&t)return{hash:e.hash("hex"),txid:e.rhash(),index:0,cid:t.cid,pid:t.pid,oid:t.oid,gold:e.outputs[0].value}}async propSale(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"prop.sale pid fixedPrice [openid]: 拍卖道具 道具编号 一口价 [子帐号]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0);if(!(r=await e.db.propList.getVp(r))||r.pst==P.Delete)throw new h(c.MISC_ERROR,"prop.sale prop not exist");if(r.pst!=P.Ready)throw new h(c.MISC_ERROR,"prop.sale prop cannt be sent on current status");t=t.u64(1,0);var[e,,]=await e.propSale(r.current.hash,r.current.index,t,i);return e.toJSON()}async propSendListAdmin(e,t,i){return this.propSendList(e,t,i,!0)}async propSendList(e,t,i,r=!1){if(t||e.length<1)throw new h(c.MISC_ERROR,"prop.sendlist (addr|txid|index)(n,) [openid]: 批量转移道具 道具数组(地址|交易ID|输出索引) [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,"")),a=[];if((t=t.str(0).split(","))&&Array.isArray(t))for(var s of t){var n,o;3<=(s=s.split("|")).length&&(n=s[0],o=new j(d.revHex(s[1]),parseInt(s[2])),4<=s.length?a.push([o,k.fromString(n),s[3]]):a.push([o,k.fromString(n)]))}var[t,,e]=await e.propExchangeList(a,i,r);if(t&&e){let i=t.hash("hex"),r=t.rhash();return e.map(e=>({hash:i,txid:r,cid:e.cid,pid:e.pid,oid:e.oid,gold:e.gold,addr:e.addr}))}}async propReceive(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"prop.receive tx [account]: 捐赠接收函数 捐赠交易字符串 [接收账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));if(!(t=t.buf(0)))throw new h(c.TYPE_ERROR,"Invalid TX Info.");t=A.fromRaw(t);var[e,,t]=await e.propReceive(t,i);if(e&&t)return{hash:e.hash("hex"),txid:e.rhash(),cid:t.cid,pid:t.pid,oid:t.oid,gold:t.gold,addr:t.simAddr,gaddr:t.gaddr}}async propDonate(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"prop.donate pid [openid]: 捐赠道具函数 道具ID [发起账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));t=t.str(0);if(!(t=await e.db.propList.getVp(t))||t.pst==P.Delete)throw new h(c.MISC_ERROR,"prop not exist");if(t.pst!=P.Ready)throw new h(c.MISC_ERROR,"prop cannt be sent on current status");t=new j(t.current.hash,t.current.index);var[e,,t]=await e.propDonate(t,i);if(e&&t)return{hash:e.hash("hex"),txid:e.rhash(),cid:t.cid,pid:t.pid,oid:t.oid,gold:t.gold,raw:e.toRaw().toString("hex")}}async propExchange(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"prop.send addr pid [openid]: 转移道具函数 接收地址 物品编号 [发起账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0);t=t.str(1);if(!(t=await e.db.propList.getVp(t))||t.pst==P.Delete)throw new h(c.MISC_ERROR,"prop.send prop not exist");if(t.pst!=P.Ready)throw new h(c.MISC_ERROR,"prop.send prop cannt be sent on current status");var[e,,t]=await e.propExchange(new j(t.current.hash,t.current.index),k.fromString(r),i);if(e&&t)return{hash:e.hash("hex"),txid:e.rhash(),cid:t.cid,pid:t.pid,oid:t.oid,gold:t.gold,addr:r}}async propCreateList(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"prop.createlist (cid|oid|gold|pid)(n,) [openid]: 批量创建道具 道具信息数组 [发起账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));let r=[];if((t=t.str(0).split(","))&&Array.isArray(t))for(var a of t)if(3<=(a=a.split("|")).length){var s=a[0],n=a[1],o=parseInt(a[2]);let e=null;4<=a.length&&(e=a[3]),o<b.MINPROPVALUE||r.push([s,n,o,e])}r=r.map(e=>{var[e,t,i,r]=e;return{oper:O.propCreate,cid:e,oid:t,gold:i,pid:r}});var[t,,]=await e.propCreate(r,i);return t?r:null}readImageAsBlob(e,t){l.readFile(e).then(i=>{var r=M.getType(L.basename(e));t(null,{hex:i.toString("hex"),type:r})}).catch(e=>{t(e,null)})}async inscriptionCreate(e,t,i){if(!(t||e.length<2)){t=new g([e]);var[e,r]=await this.accessControl(i,t.str(4,"")),a=t.str(0);let u=t.str(1);if((t=t.u64(2,b.MINPROPVALUE))<b.MINPROPVALUE)throw new h(c.PROP_MINVALUE,"prop.create: not a valid value");if(0<=u.indexOf("file:")){const e=u.replace("file:","")||"docs/eth.jpg";u=await new Promise(t=>{this.readImageAsBlob(e,(e,i)=>{e?console.error("Error reading inscription:",e):t(i)})})}else{if(!(0<=u.indexOf("data:")))throw new h(c.MISC_ERROR,"inscription.create cid content gold (openid): 创建道具 厂商编码 素材(file:filename or data:{hex,type}) 含金量 [账户]");u=JSON.parse(u.replace("data:",""))}var s,n=await e.createReceive(r),o=w.sha256(Buffer.from(JSON.stringify(u))).toString("hex");if(o=await this.caIssuePublic([JSON.stringify({blob:u,hash:o,height:0}),n.getAddress("string"),"",r],null,i))return n={oper:O.propCreate,cid:a,gold:t,type:"inscription",oid:o.erid},[i,s]=await e.propCreate([n],r),i?n:null}throw new h(c.MISC_ERROR,"inscription.create cid content gold (openid): 创建道具 厂商编码 素材(file:filename or data:{hex,type}) 含金量 [账户]")}async propCreate(e,t,i){if(t||e.length<3)throw new h(c.MISC_ERROR,"prop.create cid oid gold pid (openid): 创建道具 厂商编码 道具类别码 含金量 道具编码(可填空) [账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(4,"")),r=t.str(0),a=t.str(1),s=t.u64(2,b.MINPROPVALUE);t=t.str(3,null);if(s<b.MINPROPVALUE)throw new h(c.PROP_MINVALUE,"prop.create: not a valid value");r={oper:O.propCreate,cid:r,oid:a,gold:s,pid:t};var[a,,]=await e.propCreate([r],i);return a?r:null}async attach(e,t,i){if(t||e.length<3)throw new h(c.MISC_ERROR,"tx.attach addr amount data (openid): 发送附言交易 地址 金额 附言结构 [账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(3,"")),r=t.str(0),a=t.u64(1),[a,,]=(r=((t=t.obj(2,{})).oper=O.attach,{address:r,value:a,data:t}),await e.attach([r],i));return a?r:null}async walletLock(e,t,i){if(t)throw new h(c.MISC_ERROR,"wallet.lock [passphrase]");var[t]=await this.accessControl(i);if(!t.master.encrypted){if((i=new g([e]).str(0,"")).length<1)throw new h(c.MISC_ERROR,"Wallet is not encrypted, please run wallet.lock passphrase");try{await t.setPassphrase(null,i)}catch(e){throw new h(c.WALLET_ENCRYPTION_FAILED,"Encryption failed.")}}return await t.lock(),null}async listMSTrans(e,t,i){if(t)throw new h(c.MISC_ERROR,"tx.mstrans");return t=new g([e]).str(0,""),this.wdb.listMSTrans(t)}async signMSTrans(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"tx.mstrans.sign txid");e=(t=new g([e])).str(0,"");var r=t.str(1,""),[i,t]=await this.accessControl(i,t.str(2,""));if(!(e=await this.wdb.db.get(s.ms(k.getHash(e,"hex"),r))))throw new h(c.MISC_ERROR,"tx.mstrans.sign txid");if(e=JSON.parse(e.toString()),!await i.belongToAccount(t,e.addr))throw new h(c.MISC_ERROR,"tx.mstrans.sign invalid account");var a,o=await this.wdb.get(e.addr);o&&o.account.type==n.types.MULTISIG&&((a=E.fromRaw(e.data,"hex")).view=await o.getCoinView(a),await o.sign(a),a.isSigned()?await o.sendMTX(a):await i.send({subtractFee:!1,sort:!1,outputs:[{address:e.contract,value:1e4}],comment:JSON.stringify({oper:"scrun",params:{oper:"sign",addr:e.addr,tx:a.toRaw().toString("hex")}})},t),await this.wdb.delMSTrans(e.addr,r))}async resendWalletTransactions(e,t,i){if(t||0!==e.length)throw new h(c.MISC_ERROR,"tx.resend.admin");var[t]=await this.accessControl(i),r=[];for(const e of await t.resend())r.push(e.txid());return r}async resend(e,t,i){if(t||0!==e.length)throw new h(c.MISC_ERROR,"tx.resendall.admin: 重发挂起交易");var r=await this.wdb.resend();if(r)for(var a of Object.keys(r))if(a)for(const e of r[a])await this.wdb.send(e);return!0}async rescan(e,t,i){if(t)throw new h(c.MISC_ERROR,'wallet.rescan ( "height" )');return t=new g([e]).u32(0),await this.wdb.rescan(t),this.logger.info("Rescanning..."),!0}async createAddress(e,t,i){if(t||2<e.length)throw new h(c.MISC_ERROR,'address.create ( "account" "uid" )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));t=t.u32(1,0);return(e=await e.createReceive(i,t))?e.toJSON():null}async calcAddress(e,t,i){if(t||e.length<3)throw new h(c.MISC_ERROR,"address.calc account(must be typeof number) branch index");t=new g([e]);let[a,s]=await this.accessControl(i,t.int(0,0));return e=t.u32(1,0),i=t.u32(2,0),"default"==s&&(s=0),t=(await a.deriveKey(s,e,i,a.master)).toJSON(),i=(e=await a.deriveKey(s,e,i))?e.toJSON():null,r(t.address==i.address,"address derived from prv not equals which derived from pub."),i}async createAddressAdmin(e,t,i){if(t||1<e.length)throw new h(c.MISC_ERROR,'address.create.admin ( "account" )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));return(t=await e.createReceive(i,0,e.master))?t.toJSON(!0):null}async createChange(e,t,i){if(t||1<e.length)throw new h(c.MISC_ERROR,'address.change.create ( "account" )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));return(t=await e.createChange(i))?t.toJSON():null}async createNested(e,t,i){if(t||1<e.length)throw new h(c.MISC_ERROR,'address.nested.create ( "account" )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));return(t=await e.createNested(i))?t.toJSON():null}async mkwallet(e,t,i){var r=(e=new g([e])).str(4);if(r)for(var a of await this.wdb.getWallets())if((await this.wdb.get(a)).master.mnemonic.getPhrase()===body.phrase)throw new h(c.MISC_ERROR,"wallet.create: 相同助记词已被使用");return(r=await this.wdb.ensure({id:z(),type:e.str(1),m:e.u32(2),n:e.u32(3),mnemonic:r,passphrase:e.str(5),master:e.str(6),witness:e.bool(7),watchOnly:e.bool(8),accountKey:e.str(9)}))?r.toJSON(!1):null}async accountGet(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"account.get account: 查询账户");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));return(t=await e.getAccount(i))?t.toJSON():null}async getPending(e,t,i){if(t)throw new h(c.MISC_ERROR,"tx.pending [account]: 查询挂起的交易");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=(t=await e.getPending(i),a.sortTX(t),[]);for(const i of await e.toDetails(t))r.push(i.toJSON());return r}async getPendingItem(e,t,i){var r,a=(e=new g([e])).hash(0,""),[s,i]=await this.accessControl(i,e.str(1,""));for(r of await s.getPending(i))if(r.hash==a)return(r=await s.toDetails(r)).toJSON()}async getPendingHash(e,t,i){e=new g([e]);var[i,e]=await this.accessControl(i,e.str(0,"")),r=(e=await i.getPending(e),a.sortTX(e),[]);for(const t of await i.toDetails(e))r.push(d.revHex(t.hash));return r}async getPendingCount(e,t,i){if(t)throw new h(c.MISC_ERROR,"tx.pending.count [account]: 查询挂起的交易数");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));t=await e.ensureIndex(i);return(await e.txdb.getPendingHashes(t)).length}async accountCreate(e,t,i){e=new g([e]);var r,[i]=await this.accessControl(i),a=e.obj(0);e=e.str(1),a={name:(a=new g([a])).str("name"),witness:a.bool("witness",!0),type:a.str("type","pubkeyhash"),m:a.u32("m",1),n:a.u32("n",1),watchOnly:a.bool("watch",!1),accountKey:a.str("key",null),lookahead:a.u32("lookahead",10)};try{let t=await i.getAccount(a.name);return t?t.toJSON():((r=(t=await i.createAccount(a,e)).toJSON()).isNew=!0,r)}catch(t){return null}}async getblocks(e,t,i){if(t)throw new h(c.MISC_ERROR,"wallet.blocks");var[t]=await this.accessControl(i);return await t.getBlocks()}async getKey(e,t,i){if(t||1!==e.length)throw new h(c.MISC_ERROR,"key.export.public address: 查询地址的密钥");t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0);return(t=(r(i,"Address is required."),await e.getKey(i)))?t.toJSON():null}async getPrivKey(e,t,i){if(t||1!==e.length)throw new h(c.MISC_ERROR,"address.key.admin address: 查询地址的密钥");t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0);return(t=(r(i,"Address is required."),await e.getKey(i)))?t.toJSON(!0):null}async getwif(e,t,i){if(t||1!=e.length)throw new h(c.MISC_ERROR,"address.wif.admin address: 查询地址对应的私钥 地址");t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0),t=t.str(1);return(e=(r(i,"Address is required."),await e.getPrivateKey(i,t)))?e.toSecret():null}async ownedAddress(e,t,i){if(t||1!=e.length)throw new h(c.MISC_ERROR,"address.has address: 查询钱包是否拥有一个地址 地址");t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0);return r(i,"Address is required."),e.ownedAddress(i)}async getCoin(e,t,i){e=new g([e]);var[i]=await this.accessControl(i),a=e.hash(0);e=e.u32(1);return(i=(r(a,"Hash is required."),r(null!=e,"Index is required."),await i.getCoin(a,e)))?i.getJSON(this.network):null}async getSpender(e,t,i){e=new g([e]);var[i]=await this.accessControl(i),a=e.hash(0);e=e.u32(1);return(i=(r(a,"Hash is required."),r(null!=e,"Index is required."),await i.txdb.getSpender(a,e)))?{hash:d.revHex(i.hash),index:i.index}:null}async getSpent(e,t,i){e=new g([e]);var[i]=await this.accessControl(i),a=e.hash(0);e=e.u32(1),r(a,"Hash is required."),r(null!=e,"Index is required."),i=await i.txdb.getSpentCoin({hash:a,index:e});return{hash:d.revHex(i.hash),index:i.index,value:i.value,height:i.height,version:i.version,time:i.time}}async getCoincacheSize(e,t,i){var[i]=await this.accessControl(i);return i.txdb.coinCache.size}async conserveCoin(e,t,i){if(t||2!=e.length)throw new h(c.MISC_ERROR,"coin.conserved.add txhash index: 新增需要保持的硬币: 交易Hash 输出序号");t=new g([e]);var[e]=await this.accessControl(i);i=t.hash(0),t=t.u32(1),r(i,"Hash is required."),r(null!=t,"Index is required."),i=new j(i,t);return e.conserveCoin(i),!0}async getConservedCoins(e,t,i){if(t||0<e.length)throw new h(c.MISC_ERROR,"coin.conserved.get: 查询已经保持的Coin列表");var[t]=await this.accessControl(i),r=[];for(const e of t.getConserved())r.push(e.toJSON());return r}async unConserveCoin(e,t,i){if(t||2!=e.length)throw new h(c.MISC_ERROR,"coin.conserved.del: 减少需要保持的硬币: 交易Hash 输出序号");t=new g([e]);var[e]=await this.accessControl(i);i=t.hash(0),t=t.u32(1),r(i,"Hash is required."),r(null!=t,"Index is required."),i=new j(i,t);return e.unConserveCoin(i),!0}async addShared(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"key.shared.add [account] key: 新增共享公钥 [账号] 公钥");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));t=t.str(1);return await e.addSharedKey(i,t),!0}async removeShared(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"key.shared.del [account] key: 删除共享公钥 [账号] 公钥");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));t=t.str(1);return await e.removeSharedKey(i,t),!0}async zap(e,t,i){if(t)throw new h(c.MISC_ERROR,"sys.zap [age]: 移除挂起交易 挂起时长(默认三天)");t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0),t=t.u32(1,259200);return r(t,"Age is required."),await e.zap(i,t),!0}async sendOracle(e,t,i){if(!(t||e.length<3||4<e.length)){t=new g([e]);var[e,i]=await this.accessControl(i,t.str(3,"")),r=t.str(0,null),a=t.str(1,null);if(null==(t=t.u64(2)))throw new h(c.TYPE_ERROR,"Invalid parameter.");if(r&&a)return t={subtractFee:!1,selection:"age",sort:!1,outputs:[{address:(await e.createReceive(i)).getAddress("string"),value:t}],comment:JSON.stringify({oper:O.vote,type:"oracle",k:r,v:a})},r=await e.send(t,i),(await e.getDetails(r.hash("hex"))).toJSON()}throw new h(c.MISC_ERROR,"oracle.send k v amount [openid]")}async sendVote(e,t,i){if(t||e.length<2||3<e.length)throw new h(c.MISC_ERROR,"vote.send addresses amount [openid]");t=new g([e]);var r,[e,i]=await this.accessControl(i,t.str(2,"")),a=t.str(0);if(null==(t=t.u64(1)))throw new h(c.TYPE_ERROR,"Invalid parameter.");for(r of a.split(","))if(!o.parseAddress(r,this.network))throw new h(c.TYPE_ERROR,"Invalid address.");return t={subtractFee:!1,selection:"age",sort:!1,outputs:[{address:(await e.createReceive(i)).getAddress("string"),value:t}],comment:`{"oper": "${O.vote}", "type": "mine", "ca": "${a}"}`},a=await e.send(t,i),(await e.getDetails(a.hash("hex"))).toJSON()}async sendVoteAsync(e,t,i){if(t||e.length<2||3<e.length)throw new h(c.MISC_ERROR,"vote.send.async addresses amount [openid]");t=new g([e]);var r,[e,i]=await this.accessControl(i,t.str(2,"")),a=t.str(0);if(null==(t=t.u64(1)))throw new h(c.TYPE_ERROR,"Invalid parameter.");for(r of a.split(","))if(!o.parseAddress(r,this.network))throw new h(c.TYPE_ERROR,"Invalid address.");t={subtractFee:!1,selection:"age",sort:!1,outputs:[{address:(await e.createReceive(i)).getAddress("string"),value:t}],comment:`{"oper": "${O.vote}", "type": "mine", "ca": "${a}"}`},e.send(t,i)}async sendTX(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"tx.send addr amount [openid]:发送交易 地址 金额 [发起账户]");if(this.wdb.$parent&&this.wdb.$parent.config.abandon)throw new h(c.MISC_ERROR,"Alliance Cert Invalid.");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0);t=t.u64(1),r=await e.send({outputs:[{address:r,value:t}]},i);return(await e.getDetails(r.hash("hex"))).toJSON()}async sendTXAsync(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"tx.send.async addr amount [openid]:发送交易 地址 金额 [发起账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0);t=t.u64(1);e.send({outputs:[{address:r,value:t}]},i)}async signTX(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"tx.sign.admin txdata [sendnow passphrase]: 对交易签名/发送 交易原始数据 [立即发送 解锁密码]");t=new g([e]);var[e]=await this.accessControl(i),a=(i=t.buf(0),r(i,"TX is required."),t.bool(1,!1));t=t.str(2);(i=E.fromRaw(i)).view=await e.getCoinView(i),await e.sign(i,t);let s=null;return s=(a&&i.isSigned()?await e.sendMTX(i):i).getJSON(this.network),e.account.type==n.types.MULTISIG&&(t=i.getMultisig(this.network),s.ms={m:t.m,n:t.n,c:t.c}),s}async createTX(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"tx.create options outputs [openid]: 创建交易 参数对象 输出数组 [子账号]");if(this.wdb.$parent&&this.wdb.$parent.config.abandon)throw new h(c.MISC_ERROR,"Alliance Cert Invalid.");t=new g([e]);var[r,e]=await this.accessControl(i,t.str(2,""));i=t.obj(0),t=t.array(1);if(Array.isArray(i.in))for(var a of i.in)a.hash=d.revHex(a.hash);var s={comment:(i=new g([i])).obj("comment",null),sendnow:i.bool("sendnow",!0),account:i.str("account"),rate:i.u64("rate"),blocks:i.u32("blocks"),maxFee:i.u64("maxFee"),selection:i.str("selection"),smart:i.bool("smart"),subtractFee:i.bool("subtractFee"),subtractIndex:i.get("subtractIndex"),depth:i.u32(["confirmations","depth"]),inputs:i.array("in",null),outputs:[]};for(const e of t){var o=new g([e]),u={value:o.u64("value")};if(u.address=o.str("address"),!u.address){var l=o.str("account");if(l){await r.ensureAccount({name:l,witness:!0});var p=await r.createReceive(l);if(!p)throw new h(c.MISC_ERROR,`tx.create: account ${l} not exist`);u.address=p.getAddress("string")}}if((l=o.buf("script"))&&(u.script=y.fromRaw(l)),(p=o.str("locktype"))&&(o=o.u64("locktime",0))){if("no"!=p&&"clb"!=p&&"clt"!=p&&"csb"!=p&&"cst"!=p)throw new h(c.MISC_ERROR,'locktype should be "no"-不锁定 or "clb"-绝对高度锁定 or clt(绝对时间锁定) or "csb"-相对高度锁定 or "cst"-相对时间锁定 !');if(p==y.outputLockType.CHECKABSOLUTETIME&&o<=b.LOCKTIME_THRESHOLD)throw new h(c.MISC_ERROR,"lock absolute time should not less than 500000000!");if(p==y.outputLockType.CHECKABSOLUTEBLOCK&&o>b.LOCKTIME_THRESHOLD)throw new h(c.MISC_ERROR,"lock absolute block should not more than 500000000!");if((p==y.outputLockType.CHECKRELATIVEBLOCK||p==y.outputLockType.CHECKRELATIVETIME)&&65535<o)throw new h(c.MISC_ERROR,"lock relative block/time should not more than 65535!");u.locktype=p,u.locktime=o}s.outputs.push(u)}e&&(s.account=e);let f=null;return s.sendnow?(i=await r.send(s),f=(t=await r.getDetails(i.hash("hex"))).toJSON()):(e=await r.createTX(s),await r.sign(e),f=e.getJSON(this.network),r.account.type==n.types.MULTISIG&&(i=e.getMultisig(this.network),f.ms={m:i.m,n:i.n,c:i.c})),f}async getLast(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"tx.last account [limit]: 最近的交易 账号 [最大记录数]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0)),r=(t=t.u32(1),[]);i=await e.getLast(i,t);for(const t of await e.toDetails(i))r.push(t.toJSON());return r}async getRange(e,t,i){if(t||e.length<4)throw new h(c.MISC_ERROR,"tx.range account start end limit [reserve]: 指定时限内的交易 账号 开始时间 结束时间 最大记录数 [反转]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=(t={start:t.u32(1),end:t.u32(2),limit:t.u32(3),reverse:t.bool(4)},i=await e.getRange(i,t),[]);for(const t of await e.toDetails(i))r.push(t.toJSON());return r}async caUserStatus(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"ca.user.status cid uid (query)");e=(t=new g([e])).str(0,"");var r=t.uint(1,0),a=t.array(2,[]);let s=null;for(let e=0;e<a.length;e++){var n=a[e];n&&Array.isArray(n)?"alliancename"==n[0]&&(s=n[1],delete a[e]):delete a[e]}var[t]=await this.accessControl(i);e=await this.$allianceUserCreate([e,r,s],i);return a.push(["pubkey",e.data.pubkey]),a.push(["merge",!0]),t.db.client.execute("ca.list",[a])}async caUserLog(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"ca.user.log cid uid (query)");e=(t=new g([e])).str(0,"");var r=t.uint(1,0),a=t.array(2,[]);let s=null;for(let e=0;e<a.length;e++){var n=a[e];n&&Array.isArray(n)?"alliancename"==n[0]&&(s=n[1],delete a[e]):delete a[e]}var[t,,]=await this.accessControl(i,e);e=await this.$allianceUserCreate([e,r,s],i);return a.push(["pubkey",e.data.pubkey]),t.db.client.execute("ca.list",[a])}async sysLog(e,t,i){if(t)throw new h(c.MISC_ERROR,"sys.log (query openid)");e=(t=new g([e])).array(0,[]);var r,[a,,]=await this.accessControl(i,t.str(1,"")),s=[];for(r of(await this.wdb.auditList.query(e)).list){var n=Object.assign({},r),u=o.parseHash(r.address,this.network);(u=await a.getPath(u))&&(n.account=u.name),n.time=new Date(1e3*r.time).toLocaleString(),s.push(n)}return s}async caIssuePublic(e,t,i){if(t||e.length<2||4<e.length)throw new h(c.MISC_ERROR,"ca.issue.public cert witness [pubkey openid]: 签发证书 证书对象 见证地址 [原始存证签名公钥 支付账户]");e=(t=new g([e])).obj(0,{});var r=t.str(1,""),a=t.str(2,""),[i,t]=await this.accessControl(i,t.str(3,""));if(64!=e.hash.length)throw new h(c.TYPE_ERROR,"err hash length");var s=await i.db.client.execute("ca.byId",[e.hash]);if(s)return s;if(s=await i.getPrivateKey(r))return e.height||(e.height=b.retargetInterval),await i.issueCreate({erid:e.hash,key:s.privateKey.toString("hex"),address:s.getAddress().toString(),witness:s.publicKey.toString("hex"),validHeight:this.wdb.curHeight+e.height,source:{subjectName:e.name||"",pubkey:a,subjectHash:e.hash,cluster:e.cluster,blob:e.blob}},t);throw new h(c.TYPE_ERROR,"Invalid witness.")}async caAbolishPublic(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"ca.abolish.public array[[erid height [openid]]]: 废止授信交易 废止交易信息数组");var r,a=[];for(r of new g([e]).array(0,[])){var[s,n]=await this.accessControl(i,r[3]),o=r[0],u=parseInt(r[1]),l=await this.wdb.erList.query([["erid",o]]),p=(l=k.fromWitnessPubkeyhash(w.hash160(Buffer.from(l.list[0].witness,"hex")),this.network.type).toString(),await s.getKey(l));if(!p)throw new h(c.TYPE_ERROR,"Invalid witness.");(s=await s.caAbolish({key:p.privateKey.toString("hex"),witness:p.publicKey.toString("hex"),address:l,erid:o,abolishHeight:u,cid:"",uid:0},n))&&a.push(s)}return a}async caIssue(e,t,i){if(t||e.length<3||4<e.length)throw new h(c.MISC_ERROR,"ca.issue cert uid cid [openid]: 签发证书 证书对象 见证人 见证人归属单位 [消费账户]");return this.$caIssue(e,i,!1)}async caIssueAsync(e,t,i){if(t||e.length<3||4<e.length)throw new h(c.MISC_ERROR,"ca.issue.async cert uid cid [openid]: 签发证书 证书对象 见证人 见证人归属单位 [消费账户]");return this.$caIssue(e,i,!0)}async $caIssue(e,t,i){var r=(e=new g([e])).obj(0,{}),a=e.uint(1,0),s=e.str(2,""),[e,n]=await this.accessControl(t,e.str(3,""));if(!(o=await e.ensureCp(s))||"forbidden"==o.cls)throw new h(c.MISC_ERROR,"Invalid Account");if(64!=r.hash.length)throw new h(c.TYPE_ERROR,"err hash length");var o=await this.$allianceUserCreate([s,a],t),u=[];if(u.push(["pubkey",o.data.pubkey]),u.push(["source.subjectHash",r.hash]),0<(await e.db.client.execute("ca.list",[u])).count)throw new h(c.TYPE_ERROR,"cert.hash conflicted");if(await e.db.client.execute("ca.byId",[r.hash]))throw new h(c.TYPE_ERROR,"cert.hash conflicted");return r.height||(r.height=b.retargetInterval),o=await this.$allianceUserCreate([s,a],t,!0),await e.issueCreate({erid:r.hash,key:o.prvkey,witness:o.data.pubkey,address:o.data.addr,validHeight:this.wdb.curHeight+r.height,source:{subjectName:r.name,pubkey:o.data.pubkey,subjectHash:r.hash,cluster:r.cluster,cid:s,uid:a}},n,i)}async caAbolish(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"ca.abolish [[uid cid erid height [openid]]]: 废止授信交易 废止交易信息数组");return this.$caAbolish(e,i,!1)}async caAbolishAsync(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"ca.abolish.async [[uid cid erid height [openid]]]: 废止授信交易 废止交易信息数组");return this.$caAbolish(e,i,!0)}async $caAbolish(e,t,i){var r,a=[];for(r of new g([e]).array(0,[])){var s,n=r[0],o=r[1],c=r[2],u=parseInt(r[3]),[s,h]=await this.accessControl(t,r[4]),l=await this.$allianceUserCreate([o,n],t,!0);(s=await s.caAbolish({cid:o,uid:n,key:l.prvkey,witness:l.data.pubkey,address:l.data.addr,erid:c,abolishHeight:u},h,i))&&a.push(s)}return a}async enchanceCp(e,t,i){if(t||e.length<2||4<e.length)throw new h(c.MISC_ERROR,"ca.enchance toCid fromCid height [openid]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(3)),r=t.str(0,0),a=t.str(1,0);let s=t.uint(2,0);(!s||s<this.wdb.curHeight)&&(s=this.wdb.curHeight+b.retargetInterval);var[t,e]=await e.enchanceCp({to:r,from:a,enchanceHeight:s},i);return t&&e?e:null}async queryErList(e,t,i){if(t)throw new h(c.MISC_ERROR,"ca.query.remote conditions: 查询存证列表 (复合条件)");t=new g([e]);var[e,,]=await this.accessControl(i,t.str(1,""));i=t.array(0,[]);return e.db.client.execute("ca.list",[i])}async queryMyErlist(e,t,i){if(t)throw new h(c.MISC_ERROR,"ca.list.me query: 条件查询自己的电子权利 条件数组");return t=new g([e]).array(0,[]),this.wdb.erList.query(t)}}},function(e,t,i){var r=i(31);const{ContractEnvType:a,ContractStatus:s}=i(5),n=i(6),o=i(108);e.exports=class extends r{constructor(e){super(),this.db=e}async loadHistory(){var e;for(e of await this.db.getContracts())e&&(e.period<this.db.curHeight&&e.transStatus==s.CreatedOnMem?await this.delTransContract(e,!0):(e.id=e.type+"."+e.addr,await this.saveContract(e),e.transStatus==s.Promised&&this.db.autoTaskMgr.addTask(new o(this.db.network.txcheckpoint,e),this.db.network.txchecktime[e.type])))}query(e,t){return(e=this.get(e+"."+t))?e.transStatus:s.None}async addTransContract(e,t,i=!1){t.id=t.type+"."+t.addr;var r=this.get(t.id);e===a.Mempool&&((t=r||t).transStatus||(t.transStatus=s.CreatedOnMem),await this.saveContract(t,i))}async saveContract(e,t=!1){e.id=e.id||e.type+"."+e.addr,this.set(e.id,e),t&&(t=n.hash256(Buffer.from(e.id)).toString("hex"),await this.db.batchPut(this.db.tidCreator(t),Buffer.from(JSON.stringify(e))))}async promiseContract(e,t=!1){let i=!1;var r=e.type+"."+e.addr;let a=this.get(r);return a&&a.oper==e.oper||(i=!0,a=e),(!a.transStatus||a.transStatus<s.Promised)&&(i=!0,a.transStatus=s.Promised),i&&await this.saveContract(a,t),i}async confirmContract(e,t,i){e=e.type+"."+e.addr,!(e=this.get(e))||e.transStatus!=s.Promised||t!=s.Confirmed&&t!=s.Expired||(e.transStatus=t,await this.saveContract(e,i))}async delTransContract(e,t){var i=e.type+"."+e.addr,r=this.get(i);r&&r.oper==e.oper&&(this.delete(i),t)&&(r=n.hash256(Buffer.from(i)).toString("hex"),await this.db.batchDel(this.db.tidCreator(r)))}}},function(e,t,i){const r=i(5).HtlcStatus;i=i(31);class a extends i{constructor(e){super(),this.db=e}async loadHistory(){var e,t;for(e of(this.clear(),await this.db.loadHtlcList()))this.set(e.id,e),e.wid&&e.account&&(t=e.wid+"."+e.account,this.account.get(t)||this.account.set(t,new Map),this.account.get(t).set(e.id,e))}setAccount(e,t,i){this.delAccount(e),t&&i&&(e.wid=t,e.account=i,t=e.wid+"."+e.account,this.account.get(t)||this.account.set(t,new Map),this.account.get(t).set(e.id,e))}delAccount(e){var t;e&&e.wid&&e.account&&(t=e.wid+"."+e.account,this.account.get(t))&&this.account.get(t).delete(e.id)}}a.vpItem=class e{constructor(e){this.fromOptions(e||{})}fromOptions(e){this.shash=e.shash,this.sidx=e.sidx,this.sheight=e.sheight,this.ahash=e.ahash,this.aidx=e.aidx,this.aheight=e.aheight,this.src=e.src,this.dst=e.dst,this.aa=e.aa,this.ab=e.ab,this.ba=e.ba,this.bb=e.bb,this.amount=e.amount,this.rate=e.rate,this.pst=e.pst}toRaw(){var e={};return e.shash=this.shash,e.sidx=this.sidx,e.sheight=this.sheight,e.ahash=this.ahash,e.aidx=this.aidx,e.aheight=this.aheight,e.src=this.src,e.dst=this.dst,e.amount=this.amount,e.rate=this.rate,e.pst=this.pst||r.Init,e.aa=this.aa||"",e.ab=this.ab||"",e.ba=this.ba||"",e.bb=this.bb||"",Buffer.from(JSON.stringify(e),"utf-8")}get id(){return""+this.shash+this.sidx}fromRaw(e){return e=JSON.parse(e.toString("utf8")),this.fromOptions(e),this}static fromRaw(t){return(new e).fromRaw(t)}},e.exports=a},,,,,,,,,,,,,,,function(e,t,i){"use strict";
|
|
852
852
|
/*!
|
|
853
853
|
* int64.js - int64 object for javascript.
|
|
854
854
|
* Copyright (c) 2017, Christopher Jeffrey (MIT License).
|
|
@@ -936,7 +936,7 @@ e.exports=function(e){return null!=e&&null!=e.constructor&&"function"==typeof e.
|
|
|
936
936
|
* See the License for the specific language governing permissions and
|
|
937
937
|
* limitations under the License.
|
|
938
938
|
*/
|
|
939
|
-
var r=i(8),a=i(43).parse,s=["acl","location","logging","notification","partNumber","policy","requestPayment","torrent","uploadId","uploads","versionId","versioning","versions","website"];function n(e){return"AWS "+e.key+":"+c(e)}function o(e){return r.createHmac("sha1",e.secret).update(e.message).digest("base64")}function c(e){return e.message=u(e),o(e)}function u(e){var t=e.amazonHeaders||"";return t&&(t+="\n"),[e.verb,e.md5,e.contentType,e.date?e.date.toUTCString():"",t+e.resource].join("\n")}function h(e){return"GET\n\n\n"+e.date+"\n"+e.resource}e.exports=n,e.exports.authorization=n,e.exports.hmacSha1=o,e.exports.sign=c,e.exports.signQuery=function(e){return e.message=h(e),o(e)},e.exports.stringToSign=u,e.exports.queryStringToSign=h,e.exports.canonicalizeHeaders=function(e){for(var t=[],i=Object.keys(e),r=0,a=i.length;r<a;++r){var s=i[r],n=e[s];0===(s=s.toLowerCase()).indexOf("x-amz")&&t.push(s+":"+n)}return t.sort().join("\n")},e.exports.canonicalizeResource=function(e){var t=a(e,!0),i=(e=t.pathname,[]);return Object.keys(t.query).forEach((function(e){var r;~s.indexOf(e)&&(r=""==t.query[e]?"":"="+encodeURIComponent(t.query[e]),i.push(e+r))})),e+(i.length?"?"+i.sort().join("&"):"")}},function(e,t,i){var r=i(43),a=i(116),s=i(8),n=i(462)(1e3);function o(e,t,i){return s.createHmac("sha256",e).update(t,"utf8").digest(i)}function c(e,t){return s.createHash("sha256").update(e,"utf8").digest(t)}function u(e){return e.replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}function h(e){return u(encodeURIComponent(e))}var l={authorization:!0,connection:!0,"x-amzn-trace-id":!0,"user-agent":!0,expect:!0,"presigned-expires":!0,range:!0};function p(e,t){var i=(e="string"==typeof e?r.parse(e):e).headers=e.headers||{},a=(!this.service||!this.region)&&this.matchHost(e.hostname||e.host||i.Host||i.host);this.request=e,this.credentials=t||this.defaultCredentials(),this.service=e.service||a[0]||"",this.region=e.region||a[1]||"us-east-1","email"===this.service&&(this.service="ses"),!e.method&&e.body&&(e.method="POST"),i.Host||i.host||(i.Host=e.hostname||e.host||this.createHost(),e.port&&(i.Host+=":"+e.port)),e.hostname||e.host||(e.hostname=i.Host||i.host),this.isCodeCommitGit="codecommit"===this.service&&"GIT"===e.method}p.prototype.matchHost=function(e){var t=((e||"").match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)||[]).slice(1,3);if("s3"==(t="es"===t[1]?t.reverse():t)[1])t[0]="s3",t[1]="us-east-1";else for(var i=0;i<2;i++)if(/^s3-/.test(t[i])){t[1]=t[i].slice(3),t[0]="s3";break}return t},p.prototype.isSingleRegion=function(){return 0<=["s3","sdb"].indexOf(this.service)&&"us-east-1"===this.region||0<=["cloudfront","ls","route53","iam","importexport","sts"].indexOf(this.service)},p.prototype.createHost=function(){var e=this.isSingleRegion()?"":"."+this.region;return("ses"===this.service?"email":this.service)+e+".amazonaws.com"},p.prototype.prepareRequest=function(){this.parsePath();var e,t=this.request,i=t.headers;t.signQuery?(this.parsedPath.query=e=this.parsedPath.query||{},this.credentials.sessionToken&&(e["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||e["X-Amz-Expires"]||(e["X-Amz-Expires"]=86400),e["X-Amz-Date"]?this.datetime=e["X-Amz-Date"]:e["X-Amz-Date"]=this.getDateTime(),e["X-Amz-Algorithm"]="AWS4-HMAC-SHA256",e["X-Amz-Credential"]=this.credentials.accessKeyId+"/"+this.credentialString(),e["X-Amz-SignedHeaders"]=this.signedHeaders()):(t.doNotModifyHeaders||this.isCodeCommitGit||(!t.body||i["Content-Type"]||i["content-type"]||(i["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8"),!t.body||i["Content-Length"]||i["content-length"]||(i["Content-Length"]=Buffer.byteLength(t.body)),!this.credentials.sessionToken||i["X-Amz-Security-Token"]||i["x-amz-security-token"]||(i["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||i["X-Amz-Content-Sha256"]||i["x-amz-content-sha256"]||(i["X-Amz-Content-Sha256"]=c(this.request.body||"","hex")),i["X-Amz-Date"]||i["x-amz-date"]?this.datetime=i["X-Amz-Date"]||i["x-amz-date"]:i["X-Amz-Date"]=this.getDateTime()),delete i.Authorization,delete i.authorization)},p.prototype.sign=function(){return this.parsedPath||this.prepareRequest(),this.request.signQuery?this.parsedPath.query["X-Amz-Signature"]=this.signature():this.request.headers.Authorization=this.authHeader(),this.request.path=this.formatPath(),this.request},p.prototype.getDateTime=function(){var e;return this.datetime||(e=this.request.headers,e=new Date(e.Date||e.date||new Date),this.datetime=e.toISOString().replace(/[:\-]|\.\d{3}/g,""),this.isCodeCommitGit&&(this.datetime=this.datetime.slice(0,-1))),this.datetime},p.prototype.getDate=function(){return this.getDateTime().substr(0,8)},p.prototype.authHeader=function(){return["AWS4-HMAC-SHA256 Credential="+this.credentials.accessKeyId+"/"+this.credentialString(),"SignedHeaders="+this.signedHeaders(),"Signature="+this.signature()].join(", ")},p.prototype.signature=function(){var e=this.getDate(),t=[this.credentials.secretAccessKey,e,this.region,this.service].join(),i=n.get(t);return i||(e=o("AWS4"+this.credentials.secretAccessKey,e),e=o(e,this.region),e=o(e,this.service),i=o(e,"aws4_request"),n.set(t,i)),o(i,this.stringToSign(),"hex")},p.prototype.stringToSign=function(){return["AWS4-HMAC-SHA256",this.getDateTime(),this.credentialString(),c(this.canonicalString(),"hex")].join("\n")},p.prototype.canonicalString=function(){this.parsedPath||this.prepareRequest();var e,t,i=this.parsedPath.path,r=this.parsedPath.query,a=this.request.headers,s="",n="s3"!==this.service,o="s3"===this.service||this.request.doNotEncodePath,u="s3"===this.service,l="s3"===this.service;a="s3"===this.service&&this.request.signQuery?"UNSIGNED-PAYLOAD":this.isCodeCommitGit?"":a["X-Amz-Content-Sha256"]||a["x-amz-content-sha256"]||c(this.request.body||"","hex");return r&&(e=Object.keys(r).reduce((function(e,t){return t&&(e[h(t)]=Array.isArray(r[t])&&l?r[t][0]:r[t]),e}),{}),t=[],Object.keys(e).sort().forEach((function(i){Array.isArray(e[i])?e[i].map(h).sort().forEach((function(e){t.push(i+"="+e)})):t.push(i+"="+h(e[i]))})),s=t.join("&")),"/"!==i&&("/"!==(i=(i=n?i.replace(/\/{2,}/g,"/"):i).split("/").reduce((function(e,t){return n&&".."===t?e.pop():n&&"."===t||(o&&(t=decodeURIComponent(t.replace(/\+/g," "))),e.push(h(t))),e}),[]).join("/"))[0]&&(i="/"+i),u)&&(i=i.replace(/%2F/g,"/")),[this.request.method||"GET",i,s,this.canonicalHeaders()+"\n",this.signedHeaders(),a].join("\n")},p.prototype.canonicalHeaders=function(){var e=this.request.headers;return Object.keys(e).filter((function(e){return null==l[e.toLowerCase()]})).sort((function(e,t){return e.toLowerCase()<t.toLowerCase()?-1:1})).map((function(t){return t.toLowerCase()+":"+e[t].toString().trim().replace(/\s+/g," ")})).join("\n")},p.prototype.signedHeaders=function(){return Object.keys(this.request.headers).map((function(e){return e.toLowerCase()})).filter((function(e){return null==l[e]})).sort().join(";")},p.prototype.credentialString=function(){return[this.getDate(),this.region,this.service,"aws4_request"].join("/")},p.prototype.defaultCredentials=function(){var e=process.env;return{accessKeyId:e.AWS_ACCESS_KEY_ID||e.AWS_ACCESS_KEY,secretAccessKey:e.AWS_SECRET_ACCESS_KEY||e.AWS_SECRET_KEY,sessionToken:e.AWS_SESSION_TOKEN}},p.prototype.parsePath=function(){var e=this.request.path||"/",t=(e=/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(e)?encodeURI(decodeURI(e)):e).indexOf("?"),i=null;0<=t&&(i=a.parse(e.slice(t+1)),e=e.slice(0,t)),this.parsedPath={path:e,query:i}},p.prototype.formatPath=function(){var e=this.parsedPath.path,t=this.parsedPath.query;return t?(null!=t[""]&&delete t[""],e+"?"+u(a.stringify(t))):e},t.RequestSigner=p,t.sign=function(e,t){return new p(e,t).sign()}},function(e,t){function i(e){this.capacity=0|e,this.map=Object.create(null),this.list=new r}function r(){this.firstNode=null,this.lastNode=null}function a(e,t){this.key=e,this.val=t,this.prev=null,this.next=null}e.exports=function(e){return new i(e)},i.prototype.get=function(e){if(null!=(e=this.map[e]))return this.used(e),e.val},i.prototype.set=function(e,t){var i=this.map[e];if(null!=i)i.val=t;else{if(this.capacity||this.prune(),!this.capacity)return!1;i=new a(e,t),this.map[e]=i,this.capacity--}return this.used(i),!0},i.prototype.used=function(e){this.list.moveToFront(e)},i.prototype.prune=function(){var e=this.list.pop();null!=e&&(delete this.map[e.key],this.capacity++)},r.prototype.moveToFront=function(e){this.firstNode!=e&&(this.remove(e),null==this.firstNode?(this.firstNode=e,(this.lastNode=e).prev=null,e.next=null):(e.prev=null,e.next=this.firstNode,e.next.prev=e,this.firstNode=e))},r.prototype.pop=function(){var e=this.lastNode;return null!=e&&this.remove(e),e},r.prototype.remove=function(e){this.firstNode==e?this.firstNode=e.next:null!=e.prev&&(e.prev.next=e.next),this.lastNode==e?this.lastNode=e.prev:null!=e.next&&(e.next.prev=e.prev)}},function(e,t,i){var r=i(464),a=i(472),s=i(476);i=i(133);e.exports={parse:r.parseRequest,parseRequest:r.parseRequest,sign:a.signRequest,signRequest:a.signRequest,createSigner:a.createSigner,isSigner:a.isSigner,sshKeyToPEM:i.sshKeyToPEM,sshKeyFingerprint:i.fingerprint,pemToRsaSSHKey:i.pemToRsaSSHKey,verify:s.verifySignature,verifySignature:s.verifySignature,verifyHMAC:s.verifyHMAC}},function(e,t,i){var r=i(10),a=i(9),s=((i=i(133)).HASH_ALGOS,i.PK_ALGOS,i.HttpSignatureError),n=i.InvalidAlgorithmError,o=i.validateAlgorithm;function c(e){s.call(this,e,c)}function u(e){s.call(this,e,u)}function h(e){s.call(this,e,h)}function l(e){s.call(this,e,l)}function p(e){s.call(this,e,p)}a.inherits(c,s),a.inherits(u,s),a.inherits(h,s),a.inherits(l,s),a.inherits(p,s),e.exports={parseRequest:function(e,t){r.object(e,"request"),r.object(e.headers,"request.headers"),void 0===(t=void 0===t?{}:t).headers&&(t.headers=[e.headers["x-date"]?"x-date":"date"]),r.object(t,"options"),r.arrayOfString(t.headers,"options.headers"),r.optionalFinite(t.clockSkew,"options.clockSkew");var i=t.authorizationHeaderName||"authorization";if(!e.headers[i])throw new l("no "+i+" header present in the request");t.clockSkew=t.clockSkew||300;var a=0,s=0,d=0,f="",m="",g={scheme:"",params:{},signingString:""},v=e.headers[i];for(a=0;a<v.length;a++){var y=v.charAt(a);switch(Number(s)){case 0:" "!==y?g.scheme+=y:s=1;break;case 1:switch(Number(d)){case 0:var b=y.charCodeAt(0);if(65<=b&&b<=90||97<=b&&b<=122)f+=y;else{if("="!==y)throw new u("bad param format");if(0===f.length)throw new u("bad param format");d=1}break;case 1:if('"'!==y)throw new u("bad param format");m="",d=2;break;case 2:'"'===y?(g.params[f]=m,d=3):m+=y;break;case 3:if(","!==y)throw new u("bad param format");f="",d=0;break;default:throw new Error("Invalid substate")}break;default:throw new Error("Invalid substate")}}if(g.params.headers&&""!==g.params.headers?g.params.headers=g.params.headers.split(" "):e.headers["x-date"]?g.params.headers=["x-date"]:g.params.headers=["date"],!g.scheme||"Signature"!==g.scheme)throw new u('scheme was not "Signature"');if(!g.params.keyId)throw new u("keyId was not specified");if(!g.params.algorithm)throw new u("algorithm was not specified");if(!g.params.signature)throw new u("signature was not specified");g.params.algorithm=g.params.algorithm.toLowerCase();try{o(g.params.algorithm)}catch(e){throw e instanceof n?new h(g.params.algorithm+" is not supported"):e}for(a=0;a<g.params.headers.length;a++){var w=g.params.headers[a].toLowerCase();if("request-line"===(g.params.headers[a]=w)){if(t.strict)throw new p("request-line is not a valid header with strict parsing enabled.");g.signingString+=e.method+" "+e.url+" HTTP/"+e.httpVersion}else if("(request-target)"===w)g.signingString+="(request-target): "+e.method.toLowerCase()+" "+e.url;else{var x=e.headers[w];if(void 0===x)throw new l(w+" was not in the request");g.signingString+=w+": "+x}a+1<g.params.headers.length&&(g.signingString+="\n")}if(e.headers.date||e.headers["x-date"]){i=e.headers["x-date"]?new Date(e.headers["x-date"]):new Date(e.headers.date);var k=new Date;if((k=Math.abs(k.getTime()-i.getTime()))>1e3*t.clockSkew)throw new c("clock skew of "+k/1e3+"s was greater than "+t.clockSkew+"s")}if(t.headers.forEach((function(e){if(g.params.headers.indexOf(e.toLowerCase())<0)throw new l(e+" was not a signed header")})),t.algorithms&&-1===t.algorithms.indexOf(g.params.algorithm))throw new h(g.params.algorithm+" is not a supported algorithm");return g.algorithm=g.params.algorithm.toUpperCase(),g.keyId=g.params.keyId,g}}},function(e,t,i){var r,a,s=i(176),n=i(177),o=i(466);i=i(467);for(r in e.exports={Reader:o,Writer:i},n)n.hasOwnProperty(r)&&(e.exports[r]=n[r]);for(a in s)s.hasOwnProperty(a)&&(e.exports[a]=s[a])},function(e,t,i){var r=i(0),a=i(12).Buffer,s=i(177),n=i(176).newInvalidAsn1Error;function o(e){if(!e||!a.isBuffer(e))throw new TypeError("data must be a node Buffer");this._buf=e,this._size=e.length,this._len=0,this._offset=0}Object.defineProperty(o.prototype,"length",{enumerable:!0,get:function(){return this._len}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){return this._offset}}),Object.defineProperty(o.prototype,"remain",{get:function(){return this._size-this._offset}}),Object.defineProperty(o.prototype,"buffer",{get:function(){return this._buf.slice(this._offset)}}),o.prototype.readByte=function(e){var t;return this._size-this._offset<1?null:(t=255&this._buf[this._offset],e||(this._offset+=1),t)},o.prototype.peek=function(){return this.readByte(!0)},o.prototype.readLength=function(e){if((e=void 0===e?this._offset:e)>=this._size)return null;var t=255&this._buf[e++];if(null===t)return null;if(128==(128&t)){if(0==(t&=127))throw n("Indefinite length not supported");if(4<t)throw n("encoding too long");if(this._size-e<t)return null;for(var i=this._len=0;i<t;i++)this._len=(this._len<<8)+(255&this._buf[e++])}else this._len=t;return e},o.prototype.readSequence=function(e){var t=this.peek();if(null===t)return null;if(void 0!==e&&e!==t)throw n("Expected 0x"+e.toString(16)+": got 0x"+t.toString(16));return null===(e=this.readLength(this._offset+1))?null:(this._offset=e,t)},o.prototype.readInt=function(){return this._readTag(s.Integer)},o.prototype.readBoolean=function(){return 0!==this._readTag(s.Boolean)},o.prototype.readEnumeration=function(){return this._readTag(s.Enumeration)},o.prototype.readString=function(e,t){e=e||s.OctetString;var i=this.peek();if(null===i)return null;if(i!==e)throw n("Expected 0x"+e.toString(16)+": got 0x"+i.toString(16));return null===(e=this.readLength(this._offset+1))||this.length>this._size-e?null:(this._offset=e,0===this.length?t?a.alloc(0):"":(i=this._buf.slice(this._offset,this._offset+this.length),this._offset+=this.length,t?i:i.toString("utf8")))},o.prototype.readOID=function(e){e=e||s.OID;var t=this.readString(e,!0);if(null===t)return null;for(var i=[],r=0,a=0;a<t.length;a++){var n=255&t[a];r=(r<<7)+(127&n);0==(128&n)&&(i.push(r),r=0)}return r=i.shift(),i.unshift(r%40),i.unshift(r/40>>0),i.join(".")},o.prototype._readTag=function(e){if(r.ok(void 0!==e),null===(t=this.peek()))return null;if(t!==e)throw n("Expected 0x"+e.toString(16)+": got 0x"+t.toString(16));if(null===(e=this.readLength(this._offset+1)))return null;if(4<this.length)throw n("Integer too long: "+this.length);if(this.length>this._size-e)return null;this._offset=e;for(var t=this._buf[this._offset],i=0,a=0;a<this.length;a++)i=(i<<=8)|255&this._buf[this._offset++];return 128==(128&t)&&4!==a&&(i-=1<<8*a),i>>0},e.exports=o},function(e,t,i){var r=i(0),a=i(12).Buffer,s=i(177),n=i(176).newInvalidAsn1Error,o={size:1024,growthFactor:8};function c(e){var t,i;t=o,i=e||{},r.ok(t),r.equal(typeof t,"object"),r.ok(i),r.equal(typeof i,"object"),Object.getOwnPropertyNames(t).forEach((function(e){var r;i[e]||(r=Object.getOwnPropertyDescriptor(t,e),Object.defineProperty(i,e,r))})),e=i,this._buf=a.alloc(e.size||1024),this._size=this._buf.length,this._offset=0,this._options=e,this._seq=[]}Object.defineProperty(c.prototype,"buffer",{get:function(){if(this._seq.length)throw n(this._seq.length+" unended sequence(s)");return this._buf.slice(0,this._offset)}}),c.prototype.writeByte=function(e){if("number"!=typeof e)throw new TypeError("argument must be a Number");this._ensure(1),this._buf[this._offset++]=e},c.prototype.writeInt=function(e,t){if("number"!=typeof e)throw new TypeError("argument must be a Number");"number"!=typeof t&&(t=s.Integer);for(var i=4;(0==(4286578688&e)||-8388608==(4286578688&e))&&1<i;)i--,e<<=8;if(4<i)throw n("BER ints cannot be > 0xffffffff");for(this._ensure(2+i),this._buf[this._offset++]=t,this._buf[this._offset++]=i;0<i--;)this._buf[this._offset++]=(4278190080&e)>>>24,e<<=8},c.prototype.writeNull=function(){this.writeByte(s.Null),this.writeByte(0)},c.prototype.writeEnumeration=function(e,t){if("number"!=typeof e)throw new TypeError("argument must be a Number");return"number"!=typeof t&&(t=s.Enumeration),this.writeInt(e,t)},c.prototype.writeBoolean=function(e,t){if("boolean"!=typeof e)throw new TypeError("argument must be a Boolean");"number"!=typeof t&&(t=s.Boolean),this._ensure(3),this._buf[this._offset++]=t,this._buf[this._offset++]=1,this._buf[this._offset++]=e?255:0},c.prototype.writeString=function(e,t){if("string"!=typeof e)throw new TypeError("argument must be a string (was: "+typeof e+")");"number"!=typeof t&&(t=s.OctetString);var i=a.byteLength(e);this.writeByte(t),this.writeLength(i),i&&(this._ensure(i),this._buf.write(e,this._offset),this._offset+=i)},c.prototype.writeBuffer=function(e,t){if("number"!=typeof t)throw new TypeError("tag must be a number");if(!a.isBuffer(e))throw new TypeError("argument must be a buffer");this.writeByte(t),this.writeLength(e.length),this._ensure(e.length),e.copy(this._buf,this._offset,0,e.length),this._offset+=e.length},c.prototype.writeStringArray=function(e){if(!e instanceof Array)throw new TypeError("argument must be an Array[String]");var t=this;e.forEach((function(e){t.writeString(e)}))},c.prototype.writeOID=function(e,t){if("string"!=typeof e)throw new TypeError("argument must be a string");if("number"!=typeof t&&(t=s.OID),!/^([0-9]+\.){3,}[0-9]+$/.test(e))throw new Error("argument is not a valid OID string");e=e.split(".");var i=[],r=(i.push(40*parseInt(e[0],10)+parseInt(e[1],10)),e.slice(2).forEach((function(e){var t;t=i,(e=parseInt(e,10))<128?t.push(e):(e<16384?t.push(e>>>7|128):(e<2097152?t.push(e>>>14|128):(e<268435456?t.push(e>>>21|128):(t.push(255&(e>>>28|128)),t.push(255&(e>>>21|128))),t.push(255&(e>>>14|128))),t.push(255&(e>>>7|128))),t.push(127&e))})),this);this._ensure(2+i.length),this.writeByte(t),this.writeLength(i.length),i.forEach((function(e){r.writeByte(e)}))},c.prototype.writeLength=function(e){if("number"!=typeof e)throw new TypeError("argument must be a Number");if(this._ensure(4),!(e<=127))if(e<=255)this._buf[this._offset++]=129;else{if(e<=65535)this._buf[this._offset++]=130;else{if(!(e<=16777215))throw n("Length too long (> 4 bytes)");this._buf[this._offset++]=131,this._buf[this._offset++]=e>>16}this._buf[this._offset++]=e>>8}this._buf[this._offset++]=e},c.prototype.startSequence=function(e){"number"!=typeof e&&(e=s.Sequence|s.Constructor),this.writeByte(e),this._seq.push(this._offset),this._ensure(3),this._offset+=3},c.prototype.endSequence=function(){var e=this._seq.pop(),t=e+3,i=this._offset-t;if(i<=127)this._shift(t,i,-2),this._buf[e]=i;else if(i<=255)this._shift(t,i,-1),this._buf[e]=129,this._buf[e+1]=i;else if(i<=65535)this._buf[e]=130,this._buf[e+1]=i>>8,this._buf[e+2]=i;else{if(!(i<=16777215))throw n("Sequence too long");this._shift(t,i,1),this._buf[e]=131,this._buf[e+1]=i>>16,this._buf[e+2]=i>>8,this._buf[e+3]=i}},c.prototype._shift=function(e,t,i){r.ok(void 0!==e),r.ok(void 0!==t),r.ok(i),this._buf.copy(this._buf,e+i,e,e+t),this._offset+=i},c.prototype._ensure=function(e){var t;r.ok(e),this._size-this._offset<e&&((t=this._size*this._options.growthFactor)-this._offset<e&&(t+=e),e=a.alloc(t),this._buf.copy(e,0,0,this._offset),this._buf=e,this._size=t)},e.exports=c},function(e,t,i){var r=i(8),a=i(102).BigInteger,s=(i(134).ECPointFp,i(12).Buffer);function n(e,t){return e.length>=t?e:n("0"+e,t)}t.ECCurves=i(469),t.ECKey=function(e,t,i){var o=e(),c=o.getN(),u=Math.floor(c.bitLength()/8);if(t)if(i)e=o.getCurve(),this.P=e.decodePointHex(t.toString("hex"));else{if(t.length!=u)return!1;h=new a(t.toString("hex"),16)}else{i=c.subtract(a.ONE);var h=new a(r.randomBytes(c.bitLength())).mod(i).add(a.ONE);this.P=o.getG().multiply(h)}this.P&&(this.PublicKey=s.from(o.getCurve().encodeCompressedPointHex(this.P),"hex")),h&&(this.PrivateKey=s.from(n(h.toString(16),2*u),"hex"),this.deriveSharedSecret=function(e){return!(!e||!e.P)&&(e=e.P.multiply(h),s.from(n(e.getX().toBigInteger().toString(16),2*u),"hex"))})}},function(e,t,i){var r=i(102).BigInteger,a=i(134).ECCurveFp;function s(e,t,i,r){this.curve=e,this.g=t,this.n=i,this.h=r}function n(e){return new r(e,16)}s.prototype.getCurve=function(){return this.curve},s.prototype.getG=function(){return this.g},s.prototype.getN=function(){return this.n},s.prototype.getH=function(){return this.h},e.exports={secp128r1:function(){var e=n("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF"),t=n("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC"),i=n("E87579C11079F43DD824993C2CEE5ED3"),o=n("FFFFFFFE0000000075A30D1B9038A115"),c=r.ONE;return t=(e=new a(e,t,i)).decodePointHex("04161FF7528B899B2D0C28607CA52C5B86CF5AC8395BAFEB13C02DA292DDED7A83"),new s(e,t,o,c)},secp160k1:function(){var e=n("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73"),t=r.ZERO,i=n("7"),o=n("0100000000000000000001B8FA16DFAB9ACA16B6B3"),c=r.ONE;return t=(e=new a(e,t,i)).decodePointHex("043B4C382CE37AA192A4019E763036F4F5DD4D7EBB938CF935318FDCED6BC28286531733C3F03C4FEE"),new s(e,t,o,c)},secp160r1:function(){var e=n("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF"),t=n("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC"),i=n("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45"),o=n("0100000000000000000001F4C8F927AED3CA752257"),c=r.ONE;return t=(e=new a(e,t,i)).decodePointHex("044A96B5688EF573284664698968C38BB913CBFC8223A628553168947D59DCC912042351377AC5FB32"),new s(e,t,o,c)},secp192k1:function(){var e=n("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37"),t=r.ZERO,i=n("3"),o=n("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D"),c=r.ONE;return t=(e=new a(e,t,i)).decodePointHex("04DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D"),new s(e,t,o,c)},secp192r1:function(){var e=n("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF"),t=n("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC"),i=n("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1"),o=n("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831"),c=r.ONE;return t=(e=new a(e,t,i)).decodePointHex("04188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF101207192B95FFC8DA78631011ED6B24CDD573F977A11E794811"),new s(e,t,o,c)},secp224r1:function(){var e=n("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001"),t=n("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE"),i=n("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4"),o=n("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D"),c=r.ONE;return t=(e=new a(e,t,i)).decodePointHex("04B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34"),new s(e,t,o,c)},secp256r1:function(){var e=n("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF"),t=n("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC"),i=n("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B"),o=n("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"),c=r.ONE;return t=(e=new a(e,t,i)).decodePointHex("046B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C2964FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"),new s(e,t,o,c)}}},function(e,t,i){e.exports={read:function(e,t){if(n.isBuffer(e)&&(e=e.toString("ascii")),(e=e.trim().split(/[ \t\n]+/g)).length<2||3<e.length)throw new Error("Not a valid SSH certificate line");var i=e[0];e=e[1];return g(e=n.from(e,"base64"),i)},verify:function(e,t){return!1},sign:function(e,t){void 0===e.signatures.openssh&&(e.signatures.openssh={});try{var i=b(e,!0)}catch(t){return delete e.signatures.openssh,!1}e=e.signatures.openssh;var r=void 0;return"rsa"!==t.type&&"dsa"!==t.type||(r="sha1"),(t=t.createSign(r)).write(i),e.signature=t.sign(),!0},signAsync:function(e,t,i){void 0===e.signatures.openssh&&(e.signatures.openssh={});try{var r=b(e,!0)}catch(t){return delete e.signatures.openssh,void i(t)}var a=e.signatures.openssh;t(r,(function(e,t){if(e)i(e);else{try{t.toBuffer("ssh")}catch(e){return void i(e)}a.signature=t,i()}}))},write:function(e,t){void 0===t&&(t={});var i=b(e);e=w(e.subjectKey)+" "+i.toString("base64");return t.comment&&(e=e+" "+t.comment),e},fromBuffer:g,toBuffer:b};var r=i(10),a=i(91),s=i(8),n=i(12).Buffer,o=i(30),c=i(23),u=(i(24),i(106)),h=i(66),l=i(57),p=i(25),d=i(105),f={user:1,host:2},m=(Object.keys(f).forEach((function(e){f[f[e]]=e})),/^ecdsa-sha2-([^@-]+)-cert-v01@openssh.com$/);function g(e,t,i){var s=new a({buffer:e});e=s.readString();if(void 0!==t&&e!==t)throw new Error("SSH certificate algorithm mismatch");void 0===t&&(t=e),(e={signatures:{}}).signatures.openssh={},e.signatures.openssh.nonce=s.readBuffer();for(var n={},g=n.parts=[],y=(n.type=function(e){if("ssh-rsa-cert-v01@openssh.com"===e)return"rsa";if("ssh-dss-cert-v01@openssh.com"===e)return"dsa";if(e.match(m))return"ecdsa";if("ssh-ed25519-cert-v01@openssh.com"===e)return"ed25519";throw new Error("Unsupported cert type "+e)}(t),o.info[n.type].parts.length);g.length<y;)g.push(s.readPart());r.ok(1<=g.length,"key must have at least one part");var b=o.info[n.type];"ecdsa"===n.type&&(t=m.exec(t),r.ok(null!==t),r.strictEqual(t[1],g[0].data.toString()));for(var w,x=0;x<b.parts.length;++x)g[x].name=b.parts[x],"curve"!==g[x].name&&!1!==b.normalize&&((w=g[x]).data=p.mpNormalize(w.data));e.subjectKey=new c(n),e.serial=s.readInt64();for(var k=f[s.readInt()],S=(r.string(k,"valid cert type"),e.signatures.openssh.keyId=s.readString(),[]),_=(t=s.readBuffer(),new a({buffer:t}));!_.atEnd();)S.push(_.readString());0===S.length&&(S=["*"]),e.subjects=S.map((function(e){if("user"===k)return u.forUser(e);if("host"===k)return u.forHost(e);throw new Error("Unknown identity type "+k)})),e.validFrom=v(s.readInt64()),e.validUntil=v(s.readInt64());for(var E,j=[],A=new a({buffer:s.readBuffer()});!A.atEnd();)(E={critical:!0}).name=A.readString(),E.data=A.readBuffer(),j.push(E);for(A=new a({buffer:s.readBuffer()});!A.atEnd();)(E={critical:!1}).name=A.readString(),E.data=A.readBuffer(),j.push(E);return e.signatures.openssh.exts=j,s.readBuffer(),n=s.readBuffer(),e.issuerKey=h.read(n),e.issuer=u.forHost("**"),t=s.readBuffer(),e.signatures.openssh.signature=l.parse(t,e.issuerKey.type,"ssh"),void 0!==i&&(i.remainder=s.remainder(),i.consumed=s._offset),new d(e)}function v(e){var t=4294967296*e.readUInt32BE(0),i=(t+=e.readUInt32BE(4),new Date);return i.setTime(1e3*t),i.sourceInt64=e,i}function y(e){var t,i;return void 0!==e.sourceInt64?e.sourceInt64:(e=Math.round(e.getTime()/1e3),t=Math.floor(e/4294967296),e=Math.floor(e%4294967296),(i=n.alloc(8)).writeUInt32BE(t,0),i.writeUInt32BE(e,4),i)}function b(e,t){r.object(e.signatures.openssh,"signature for openssh format");var i=e.signatures.openssh,c=(void 0===i.nonce&&(i.nonce=s.randomBytes(16)),new a({})),u=(c.writeString(w(e.subjectKey)),c.writeBuffer(i.nonce),e.subjectKey),l=(o.info[u.type].parts.forEach((function(e){c.writePart(u.part[e])})),c.writeInt64(e.serial),e.subjects[0].type),p=(r.notStrictEqual(l,"unknown"),e.subjects.forEach((function(e){r.strictEqual(e.type,l)})),l=f[l],c.writeInt(l),void 0===i.keyId&&(i.keyId=e.subjects[0].type+"_"+(e.subjects[0].uid||e.subjects[0].hostname)),c.writeString(i.keyId),new a({})),d=(e.subjects.forEach((function(e){l===f.host?p.writeString(e.hostname):l===f.user&&p.writeString(e.uid)})),c.writeBuffer(p.toBuffer()),c.writeInt64(y(e.validFrom)),c.writeInt64(y(e.validUntil)),i.exts),m=(void 0===d&&(d=[]),new a({}));return d.forEach((function(e){!0===e.critical&&(m.writeString(e.name),m.writeBuffer(e.data))})),c.writeBuffer(m.toBuffer()),m=new a({}),d.forEach((function(e){!0!==e.critical&&(m.writeString(e.name),m.writeBuffer(e.data))})),c.writeBuffer(m.toBuffer()),c.writeBuffer(n.alloc(0)),p=h.write(e.issuerKey),c.writeBuffer(p),t||c.writeBuffer(i.signature.toBuffer("ssh")),c.toBuffer()}function w(e){if("rsa"===e.type)return"ssh-rsa-cert-v01@openssh.com";if("dsa"===e.type)return"ssh-dss-cert-v01@openssh.com";if("ecdsa"===e.type)return"ecdsa-sha2-"+e.curve+"-cert-v01@openssh.com";if("ed25519"===e.type)return"ssh-ed25519-cert-v01@openssh.com";throw new Error("Unsupported key type "+e.type)}},function(e,t,i){var r=i(278),a=(e.exports={read:function(e,t){"string"!=typeof e&&(a.buffer(e,"buf"),e=e.toString("ascii"));for(var i,n,o=e.trim().split(/[\r\n]+/g),c=-1;!i&&c<o.length;)i=o[++c].match(/[-]+[ ]*BEGIN CERTIFICATE[ ]*[-]+/);a.ok(i,"invalid PEM header");for(var u=o.length;!n&&0<u;)n=o[--u].match(/[-]+[ ]*END CERTIFICATE[ ]*[-]+/);for(a.ok(n,"invalid PEM footer"),o=o.slice(c,u+1);i=(o=o.slice(1))[0].match(/^([A-Za-z0-9-]+): (.+)$/);)i[1].toLowerCase(),i[2];return o=o.slice(0,-1).join(""),e=s.from(o,"base64"),r.read(e,t)},verify:r.verify,sign:r.sign,write:function(e,t){e=r.write(e,t),t="CERTIFICATE";var i=e.toString("base64"),a=(e=i.length+i.length/64+18+16+2*t.length+10,s.alloc(e)),n=0;n+=a.write("-----BEGIN "+t+"-----\n",n);for(var o=0;o<i.length;){var c=o+64;c>i.length&&(c=i.length),n+=a.write(i.slice(o,c),n),a[n++]=10,o=c}return n+=a.write("-----END "+t+"-----\n",n),a.slice(0,n)}},i(10)),s=(i(58),i(12).Buffer);i(30),i(25),i(23),i(24),i(65),i(106),i(57),i(105)},function(e,t,i){var r=i(10),a=i(8),s=(i(61),i(9)),n=i(175),o=i(473),c=i(133),u=i(9).format,h=c.HASH_ALGOS,l=c.PK_ALGOS,p=c.InvalidAlgorithmError,d=c.HttpSignatureError,f=c.validateAlgorithm,m='Signature keyId="%s",algorithm="%s",headers="%s",signature="%s"';function g(e){d.call(this,e,g)}function v(e){d.call(this,e,v)}function y(e){r.object(e,"options");var t=[];if(void 0!==e.algorithm&&(r.string(e.algorithm,"options.algorithm"),t=f(e.algorithm)),this.rs_alg=t,void 0!==e.sign)r.func(e.sign,"options.sign"),this.rs_signFunc=e.sign;else if("hmac"===t[0]&&void 0!==e.key){if(r.string(e.keyId,"options.keyId"),this.rs_keyId=e.keyId,"string"!=typeof e.key&&!Buffer.isBuffer(e.key))throw new TypeError("options.key for HMAC must be a string or Buffer");this.rs_signer=a.createHmac(t[1].toUpperCase(),e.key),this.rs_signer.sign=function(){var e=this.digest("base64");return{hashAlgorithm:t[1],toString:function(){return e}}}}else{if(void 0===e.key)throw new TypeError("options.sign (func) or options.key is required");var i=e.key;if("string"!=typeof i&&!Buffer.isBuffer(i)||(i=n.parsePrivateKey(i)),r.ok(n.PrivateKey.isPrivateKey(i,[1,2]),"options.key must be a sshpk.PrivateKey"),this.rs_key=i,r.string(e.keyId,"options.keyId"),this.rs_keyId=e.keyId,!l[i.type])throw new p(i.type.toUpperCase()+" type keys are not supported");if(void 0!==t[0]&&i.type!==t[0])throw new p("options.key must be a "+t[0].toUpperCase()+" key, was given a "+i.type.toUpperCase()+" key instead");this.rs_signer=i.createSign(t[1])}this.rs_headers=[],this.rs_lines=[]}s.inherits(g,d),s.inherits(v,d),y.prototype.writeHeader=function(e,t){return r.string(e,"header"),e=e.toLowerCase(),r.string(t,"value"),this.rs_headers.push(e),this.rs_signFunc?this.rs_lines.push(e+": "+t):(e=e+": "+t,0<this.rs_headers.length&&(e="\n"+e),this.rs_signer.update(e)),t},y.prototype.writeDateHeader=function(){return this.writeHeader("date",o.rfc1123(new Date))},y.prototype.writeTarget=function(e,t){r.string(e,"method"),r.string(t,"path"),e=e.toLowerCase(),this.writeHeader("(request-target)",e+" "+t)},y.prototype.sign=function(e){if(r.func(e,"callback"),this.rs_headers.length<1)throw new Error("At least one header must be signed");if(this.rs_signFunc){var t=this.rs_lines.join("\n"),i=this;this.rs_signFunc(t,(function(t,a){if(t)e(t);else{try{r.object(a,"signature"),r.string(a.keyId,"signature.keyId"),r.string(a.algorithm,"signature.algorithm"),r.string(a.signature,"signature.signature"),s=f(a.algorithm),n=u(m,a.keyId,a.algorithm,i.rs_headers.join(" "),a.signature)}catch(t){return void e(t)}e(null,n)}}))}else{try{var a=this.rs_signer.sign()}catch(t){return void e(t)}var s=(this.rs_alg[0]||this.rs_key.type)+"-"+a.hashAlgorithm,n=(t=a.toString(),u(m,this.rs_keyId,s,this.rs_headers.join(" "),t));e(null,n)}},e.exports={isSigner:function(e){return"object"==typeof e&&e instanceof y},createSigner:function(e){return new y(e)},signRequest:function(e,t){r.object(e,"request"),r.object(t,"options"),r.optionalString(t.algorithm,"options.algorithm"),r.string(t.keyId,"options.keyId"),r.optionalArrayOfString(t.headers,"options.headers"),r.optionalString(t.httpVersion,"options.httpVersion"),e.getHeader("Date")||e.setHeader("Date",o.rfc1123(new Date)),t.headers||(t.headers=["date"]),t.httpVersion||(t.httpVersion="1.1");for(var i=[],s=(t.algorithm&&(t.algorithm=t.algorithm.toLowerCase(),i=f(t.algorithm)),""),c=0;c<t.headers.length;c++){if("string"!=typeof t.headers[c])throw new TypeError("options.headers must be an array of Strings");var d=t.headers[c].toLowerCase();if("request-line"===d){if(t.strict)throw new v("request-line is not a valid header with strict parsing enabled.");s+=e.method+" "+e.path+" HTTP/"+t.httpVersion}else if("(request-target)"===d)s+="(request-target): "+e.method.toLowerCase()+" "+e.path;else{var y=e.getHeader(d);if(void 0===y||""===y)throw new g(d+" was not in the request");s+=d+": "+y}c+1<t.headers.length&&(s+="\n")}if(e.hasOwnProperty("_stringToSign")&&(e._stringToSign=s),"hmac"===i[0]){if("string"!=typeof t.key&&!Buffer.isBuffer(t.key))throw new TypeError("options.key must be a string or Buffer");var b=a.createHmac(i[1].toUpperCase(),t.key);b.update(s),b=b.digest("base64")}else{var w=t.key;if("string"!=typeof w&&!Buffer.isBuffer(w)||(w=n.parsePrivateKey(t.key)),r.ok(n.PrivateKey.isPrivateKey(w,[1,2]),"options.key must be a sshpk.PrivateKey"),!l[w.type])throw new p(w.type.toUpperCase()+" type keys are not supported");if(void 0!==i[0]&&w.type!==i[0])throw new p("options.key must be a "+i[0].toUpperCase()+" key, was given a "+w.type.toUpperCase()+" key instead");if((i=w.createSign(i[1])).update(s),i=i.sign(),!h[i.hashAlgorithm])throw new p(i.hashAlgorithm.toUpperCase()+" is not a supported hash algorithm");t.algorithm=w.type+"-"+i.hashAlgorithm,b=i.toString(),r.notStrictEqual(b,"","empty signature produced")}return w=t.authorizationHeaderName||"Authorization",e.setHeader(w,u(m,t.keyId,t.algorithm,t.headers.join(" "),b)),!0}}},function(e,t,i){var r=i(10),a=(i(9),i(279)),s=i(474),n=i(475);function o(e,t){return r.equal(typeof t,"string"),Object.prototype.hasOwnProperty.call(e,t)}t.deepCopy=function e(t){var i,r,a="__deepCopy";if(t&&t[a])throw new Error("attempted deep copy of cyclic object");if(t&&t.constructor==Object){for(r in i={},t[a]=!0,t)r!=a&&(i[r]=e(t[r]));return delete t[a],i}if(t&&t.constructor==Array){for(i=[],t[a]=!0,r=0;r<t.length;r++)i.push(e(t[r]));return delete t[a],i}return t},t.deepEqual=function e(t,i){if(typeof t!=typeof i)return!1;if(null===t||null===i||"object"!=typeof t)return t===i;if(t.constructor!=i.constructor)return!1;for(var r in t){if(!i.hasOwnProperty(r))return!1;if(!e(t[r],i[r]))return!1}for(r in i)if(!t.hasOwnProperty(r))return!1;return!0},t.isEmpty=function(e){for(var t in e)return!1;return!0},t.hasKey=o,t.forEachKey=function(e,t){for(var i in e)o(e,i)&&t(i,e[i])},t.pluck=function(e,t){return r.equal(typeof t,"string"),function e(t,i){if(null!==t&&"object"==typeof t){if(t.hasOwnProperty(i))return t[i];var r=i.indexOf(".");if(-1!=r){var a=i.substr(0,r);if(t.hasOwnProperty(a))return e(t[a],i.substr(r+1))}}}(e,t)},t.flattenObject=function e(t,i){if(0===i)return[t];r.ok(null!==t),r.equal(typeof t,"object"),r.equal(typeof i,"number"),r.ok(0<=i);var a=[];for(var s in t)e(t[s],i-1).forEach((function(e){a.push([s].concat(e))}));return a},t.flattenIter=function(e,t,i){!function e(t,i,a,s){var n;if(0===i)return(n=a.slice(0)).push(t),void s(n);for(var o in r.ok(null!==t),r.equal(typeof t,"object"),r.equal(typeof i,"number"),r.ok(0<=i),t)(n=a.slice(0)).push(o),e(t[o],i-1,n,s)}(e,t,[],i)},t.validateJsonObject=C,t.validateJsonObjectJS=C,t.randElt=function(e){return r.ok(Array.isArray(e)&&0<e.length,"randElt argument must be a non-empty array"),e[Math.floor(Math.random()*e.length)]},t.extraProperties=function(e,t){r.ok("object"==typeof e&&null!==e,"obj argument must be a non-null object"),r.ok(Array.isArray(t),"allowed argument must be an array of strings");for(var i=0;i<t.length;i++)r.ok("string"==typeof t[i],"allowed argument must be an array of strings");return Object.keys(e).filter((function(e){return-1===t.indexOf(e)}))},t.mergeObjects=N,t.startsWith=function(e,t){return e.substr(0,t.length)==t},t.endsWith=function(e,t){return e.substr(e.length-t.length,t.length)==t},t.parseInteger=function(e,t){r.string(e,"str"),r.optionalObject(t,"options");var i,a=!1,s=p;t&&(a=o(t,"base"),s=N(s,t),r.number(s.base,"options.base"),r.ok(2<=s.base,"options.base >= 2"),r.ok(s.base<=36,"options.base <= 36"),r.bool(s.allowSign,"options.allowSign"),r.bool(s.allowPrefix,"options.allowPrefix"),r.bool(s.allowTrailing,"options.allowTrailing"),r.bool(s.allowImprecise,"options.allowImprecise"),r.bool(s.trimWhitespace,"options.trimWhitespace"),r.bool(s.leadingZeroIsOctal,"options.leadingZeroIsOctal"),s.leadingZeroIsOctal)&&r.ok(!a,'"base" and "leadingZeroIsOctal" are mutually exclusive');t=-1;var n=s.base,c=1,u=0,C=0,P=e.length;if(s.trimWhitespace)for(;C<P&&O(e.charCodeAt(C));)++C;for(s.allowSign&&("-"===e[C]?(C+=1,c=-1):"+"===e[C]&&(C+=1)),"0"===e[C]&&(!s.allowPrefix||-1===(t=function(e){return e===k||e===g?2:e===S||e===v?8:e===_||e===y?10:e===E||e===b?16:-1}(e.charCodeAt(C+1)))||a&&t!==n||(n=t,C+=2),-1===t)&&s.leadingZeroIsOctal&&(n=8),a=C;C<P&&-1!==(i=function(e){return d<=e&&e<=f?e-A:m<=e&&e<=w?e-R:x<=e&&e<=j?e-I:-1}(e.charCodeAt(C)))&&i<n;++C)u=u*n+i;if(a===C)return new Error("invalid number: "+JSON.stringify(e));if(s.trimWhitespace)for(;C<P&&O(e.charCodeAt(C));)++C;return C<P&&!s.allowTrailing?new Error("trailing characters after number: "+JSON.stringify(e.slice(C))):0===u?0:(t=u*c,s.allowImprecise||!(h<u||t<l)?t:new Error("number is outside of the supported range: "+JSON.stringify(e.slice(a,C))))},t.iso8601=function(e){return"number"==typeof e&&(e=new Date(e)),r.ok(e.constructor===Date),a.sprintf("%4d-%02d-%02dT%02d:%02d:%02d.%03dZ",e.getUTCFullYear(),e.getUTCMonth()+1,e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds())},t.rfc1123=function(e){return a.sprintf("%s, %02d %s %04d %02d:%02d:%02d GMT",u[e.getUTCDay()],e.getUTCDate(),c[e.getUTCMonth()],e.getUTCFullYear(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds())},t.parseDateTime=function(e){var t=+e;return isNaN(t)?new Date(e):new Date(t)},t.hrtimediff=T,t.hrtimeDiff=T,t.hrtimeAccum=B,t.hrtimeAdd=function(e,t){return P(e),B([e[0],e[1]],t)},t.hrtimeNanosec=function(e){return P(e),Math.floor(1e9*e[0]+e[1])},t.hrtimeMicrosec=function(e){return P(e),Math.floor(1e6*e[0]+e[1]/1e3)},t.hrtimeMillisec=function(e){return P(e),Math.floor(1e3*e[0]+e[1]/1e6)};var c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],u=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],h=Number.MAX_SAFE_INTEGER||9007199254740991,l=Number.MIN_SAFE_INTEGER||-9007199254740991,p={base:10,allowSign:!0,allowPrefix:!1,allowTrailing:!1,allowImprecise:!1,trimWhitespace:!1,leadingZeroIsOctal:!1},d=48,f=57,m=65,g=66,v=79,y=84,b=88,w=90,x=97,k=98,S=111,_=116,E=120,j=122,A=48,R=55,I=87;function O(e){return 32===e||9<=e&&e<=13||160===e||5760===e||6158===e||8192<=e&&e<=8202||8232===e||8233===e||8239===e||8287===e||12288===e||65279===e}function C(e,t){var i,r,a;return 0===(t=n.validate(t,e)).errors.length?null:(t=(e=t.errors[0]).property,-1!=(r=(i=e.message.toLowerCase()).indexOf("the property "))&&-1!=(a=i.indexOf(" is not defined in the schema and the schema does not allow additional properties"))&&(r+="the property ".length,t=""===t?i.substr(r,a-r):t+"."+i.substr(r,a-r),i="unsupported property"),(a=new s.VError('property "%s": %s',t,i)).jsv_details=e,a)}function P(e){r.ok(0<=e[0]&&0<=e[1],"negative numbers not allowed in hrtimes"),r.ok(e[1]<1e9,"nanoseconds column overflow")}function T(e,t){P(e),P(t),r.ok(e[0]>t[0]||e[0]==t[0]&&e[1]>=t[1],"negative differences not allowed");var i=[e[0]-t[0],0];return e[1]>=t[1]?i[1]=e[1]-t[1]:(i[0]--,i[1]=1e9-(t[1]-e[1])),i}function B(e,t){return P(e),P(t),e[1]+=t[1],1e9<=e[1]&&(e[0]++,e[1]-=1e9),e[0]+=t[0],e}function N(e,t,i){var r,a={};if(i)for(r in i)a[r]=i[r];if(e)for(r in e)a[r]=e[r];if(t)for(r in t)a[r]=t[r];return a}},function(e,t,i){var r=i(10),a=i(9),s=i(279),n=i(86).isError,o=s.sprintf;function c(e){var t,i,a,s;if(r.object(e,"args"),r.bool(e.strict,"args.strict"),r.array(e.argv,"args.argv"),0===(t=e.argv).length)i={},a=[];else if(n(t[0]))i={cause:t[0]},a=t.slice(1);else if("object"==typeof t[0]){for(s in i={},t[0])i[s]=t[0][s];a=t.slice(1)}else r.string(t[0],"first argument to VError, SError, or WError constructor must be a string, object, or Error"),i={},a=t;return r.object(i),{options:i,shortmessage:0===(a=i.strict||e.strict?a:a.map((function(e){return null===e?"null":void 0===e?"undefined":e}))).length?"":o.apply(null,a)}}function u(){var e,t,i,a=Array.prototype.slice.call(arguments,0);if(!(this instanceof u))return t=Object.create(u.prototype),u.apply(t,arguments),t;if((e=c({argv:a,strict:!1})).options.name&&(r.string(e.options.name,'error\'s "name" must be a string'),this.name=e.options.name),this.jse_shortmsg=e.shortmessage,t=e.shortmessage,(a=e.options.cause)&&(r.ok(n(a),"cause is not an Error"),this.jse_cause=a,e.options.skipCauseMessage||(t+=": "+a.message)),this.jse_info={},e.options.info)for(i in e.options.info)this.jse_info[i]=e.options.info[i];return this.message=t,Error.call(this,t),Error.captureStackTrace&&(a=e.options.constructorOpt||this.constructor,Error.captureStackTrace(this,a)),this}function h(){var e,t=Array.prototype.slice.call(arguments,0);return this instanceof h?(e=(t=c({argv:t,strict:!0})).options,u.call(this,e,"%s",t.shortmessage),this):(e=Object.create(h.prototype),h.apply(e,arguments),e)}function l(e){r.array(e,"list of errors"),r.ok(0<e.length,"must be at least one error"),this.ase_errors=e,u.call(this,{cause:e[0]},"first of %d error%s",e.length,1==e.length?"":"s")}function p(){var e,t,i=Array.prototype.slice.call(arguments,0);return this instanceof p?((t=(e=c({argv:i,strict:!1})).options).skipCauseMessage=!0,u.call(this,t,"%s",e.shortmessage),this):(t=Object.create(p.prototype),p.apply(t,i),t)}((e.exports=u).VError=u).SError=h,u.WError=p,u.MultiError=l,a.inherits(u,Error),u.prototype.name="VError",u.prototype.toString=function(){var e=this.hasOwnProperty("name")&&this.name||this.constructor.name||this.constructor.prototype.name;return this.message&&(e+=": "+this.message),e},u.prototype.cause=function(){var e=u.cause(this);return null===e?void 0:e},u.cause=function(e){return r.ok(n(e),"err must be an Error"),n(e.jse_cause)?e.jse_cause:null},u.info=function(e){var t,i,a;if(r.ok(n(e),"err must be an Error"),t=null!==(i=u.cause(e))?u.info(i):{},"object"==typeof e.jse_info&&null!==e.jse_info)for(a in e.jse_info)t[a]=e.jse_info[a];return t},u.findCauseByName=function(e,t){var i;for(r.ok(n(e),"err must be an Error"),r.string(t,"name"),r.ok(0<t.length,"name cannot be empty"),i=e;null!==i;i=u.cause(i))if(r.ok(n(i)),i.name==t)return i;return null},u.hasCauseWithName=function(e,t){return null!==u.findCauseByName(e,t)},u.fullStack=function(e){r.ok(n(e),"err must be an Error");var t=u.cause(e);return t?e.stack+"\ncaused by: "+u.fullStack(t):e.stack},u.errorFromList=function(e){return r.arrayOfObject(e,"errors"),0===e.length?null:(e.forEach((function(e){r.ok(n(e))})),1==e.length?e[0]:new l(e))},u.errorForEach=function(e,t){r.ok(n(e),"err must be an Error"),r.func(t,"func"),e instanceof l?e.errors().forEach((function(e){t(e)})):t(e)},a.inherits(h,u),a.inherits(l,u),l.prototype.name="MultiError",l.prototype.errors=function(){return this.ase_errors.slice(0)},a.inherits(p,u),p.prototype.name="WError",p.prototype.toString=function(){var e=this.hasOwnProperty("name")&&this.name||this.constructor.name||this.constructor.prototype.name;return this.message&&(e+=": "+this.message),this.jse_cause&&this.jse_cause.message&&(e+="; caused by "+this.jse_cause.toString()),e},p.prototype.cause=function(e){return n(e)&&(this.jse_cause=e),this.jse_cause}},function(e,t,i){void 0!==(t=function(){return(t=e).Integer={type:"integer"},i={String:String,Boolean:Boolean,Number:Number,Object:Object,Array:Array,Date:Date},t.validate=e,t.checkPropertyChange=function(t,i,r){return e(t,i,{changing:r||"property"})},e=t._validate=function(e,t,r){var a=(r=r||{}).changing;function s(e){return e.type||i[e.name]==e&&e.name.toLowerCase()}var n=[];function o(e,t,i,c){function u(e){n.push({property:i,message:e})}if(i+=i?"number"==typeof c?"["+c+"]":void 0===c?"":"."+c:c,!("object"!=typeof t||t instanceof Array)||!i&&"function"==typeof t||t&&s(t)){if(a&&t.readonly&&u("is a readonly field, it can not be changed"),t.extends&&o(e,t.extends,i,c),void 0===e)t.required&&u("is missing and it is required");else if(n=n.concat(g(s(t),e)),t.disallow&&!g(t.disallow,e).length&&u(" disallowed value was matched"),null!==e){if(e instanceof Array){if(t.items){var h=t.items instanceof Array,l=t.items;for(c=0,f=e.length;c<f;c+=1)h&&(l=t.items[c]),r.coerce&&(e[c]=r.coerce(e[c],l)),n.concat(o(e[c],l,i,c))}t.minItems&&e.length<t.minItems&&u("There must be a minimum of "+t.minItems+" in the array"),t.maxItems&&e.length>t.maxItems&&u("There must be a maximum of "+t.maxItems+" in the array")}else(t.properties||t.additionalProperties)&&n.concat(function(e,t,i,s){if("object"==typeof t)for(var c in("object"!=typeof e||e instanceof Array)&&n.push({property:i,message:"an object is required"}),t){var u,h;!t.hasOwnProperty(c)||"__proto__"==c||"constructor"==c||void 0===(u=e.hasOwnProperty(c)?e[c]:void 0)&&r.existingOnly||(h=t[c],void 0===u&&h.default&&(u=e[c]=h.default),o(u=r.coerce&&c in e?e[c]=r.coerce(u,h):u,h,i,c))}for(c in e){if(e.hasOwnProperty(c)&&("_"!=c.charAt(0)||"_"!=c.charAt(1))&&t&&!t[c]&&!1===s){if(r.filter){delete e[c];continue}n.push({property:i,message:"The property "+c+" is not defined in the schema and the schema does not allow additional properties"})}var l=t&&t[c]&&t[c].requires;!l||l in e||n.push({property:i,message:"the presence of the property "+c+" requires that "+l+" also be present"}),u=e[c],!s||t&&"object"==typeof t&&c in t||o(u=r.coerce?e[c]=r.coerce(u,s):u,s,i,c),!a&&u&&u.$schema&&(n=n.concat(o(u,u.$schema,i,c)))}return n}(e,t.properties,i,t.additionalProperties));if(t.pattern&&"string"==typeof e&&!e.match(t.pattern)&&u("does not match the regex pattern "+t.pattern),t.maxLength&&"string"==typeof e&&e.length>t.maxLength&&u("may only be "+t.maxLength+" characters long"),t.minLength&&"string"==typeof e&&e.length<t.minLength&&u("must be at least "+t.minLength+" characters long"),void 0!==t.minimum&&typeof e==typeof t.minimum&&t.minimum>e&&u("must have a minimum value of "+t.minimum),void 0!==t.maximum&&typeof e==typeof t.maximum&&t.maximum<e&&u("must have a maximum value of "+t.maximum),t.enum){for(var p,d=t.enum,f=d.length,m=0;m<f;m++)if(d[m]===e){p=1;break}p||u("does not have a value in the enumeration "+d.join(", "))}"number"==typeof t.maxDecimal&&e.toString().match(new RegExp("\\.[0-9]{"+(t.maxDecimal+1)+",}"))&&u("may only have "+t.maxDecimal+" digits of decimal places")}}else"function"==typeof t?e instanceof t||u("is not an instance of the class/constructor "+t.name):t&&u("Invalid schema/property definition "+t);return null;function g(e,t){if(e){if(!("string"!=typeof e||"any"==e||("null"==e?null===t:typeof t==e)||t instanceof Array&&"array"==e||t instanceof Date&&"date"==e||"integer"==e&&t%1==0))return[{property:i,message:t+" - "+typeof t+" value found, but a "+e+" is required"}];if(e instanceof Array){for(var r=[],a=0;a<e.length&&(r=g(e[a],t)).length;a++);if(r.length)return r}else{var s,c;if("object"==typeof e)return s=n,n=[],o(t,e,i),c=n,n=s,c}}return[]}}return t&&o(e,t,"",a||""),!a&&e&&e.$schema&&o(e,e.$schema,"",""),{valid:!n.length,errors:n}},t.mustBeValid=function(e){if(!e.valid)throw new TypeError(e.errors.map((function(e){return"for property "+e.property+": "+e.message})).join(", \n"))},t;function e(t,i){return e(t,i,{changing:!1})}var t,i}.apply(t,[]))&&(e.exports=t)},function(e,t,i){var r=i(10),a=i(8),s=i(175),n=((i=i(133)).HASH_ALGOS,i.PK_ALGOS,i.InvalidAlgorithmError,i.HttpSignatureError,i.validateAlgorithm);e.exports={verifySignature:function(e,t){r.object(e,"parsedSignature"),"string"!=typeof t&&!Buffer.isBuffer(t)||(t=s.parseKey(t)),r.ok(s.Key.isKey(t,[1,1]),"pubkey must be a sshpk.Key");var i=n(e.algorithm);return"hmac"!==i[0]&&i[0]===t.type&&((t=t.createVerify(i[1])).update(e.signingString),t.verify(e.params.signature,"base64"))},verifyHMAC:function(e,t){r.object(e,"parsedHMAC"),r.string(t,"secret");var i,s,o=n(e.algorithm);return"hmac"===o[0]&&(o=o[1].toUpperCase(),(s=a.createHmac(o,t)).update(e.signingString),(i=a.createHmac(o,t)).update(s.digest()),i=i.digest(),(s=a.createHmac(o,t)).update(new Buffer(e.params.signature,"base64")),s=s.digest(),"string"==typeof i?i===s:Buffer.isBuffer(i)&&!i.equals?i.toString("binary")===s.toString("binary"):i.equals(s))}}},function(e,t,i){
|
|
939
|
+
var r=i(8),a=i(43).parse,s=["acl","location","logging","notification","partNumber","policy","requestPayment","torrent","uploadId","uploads","versionId","versioning","versions","website"];function n(e){return"AWS "+e.key+":"+c(e)}function o(e){return r.createHmac("sha1",e.secret).update(e.message).digest("base64")}function c(e){return e.message=u(e),o(e)}function u(e){var t=e.amazonHeaders||"";return t&&(t+="\n"),[e.verb,e.md5,e.contentType,e.date?e.date.toUTCString():"",t+e.resource].join("\n")}function h(e){return"GET\n\n\n"+e.date+"\n"+e.resource}e.exports=n,e.exports.authorization=n,e.exports.hmacSha1=o,e.exports.sign=c,e.exports.signQuery=function(e){return e.message=h(e),o(e)},e.exports.stringToSign=u,e.exports.queryStringToSign=h,e.exports.canonicalizeHeaders=function(e){for(var t=[],i=Object.keys(e),r=0,a=i.length;r<a;++r){var s=i[r],n=e[s];0===(s=s.toLowerCase()).indexOf("x-amz")&&t.push(s+":"+n)}return t.sort().join("\n")},e.exports.canonicalizeResource=function(e){var t=a(e,!0),i=(e=t.pathname,[]);return Object.keys(t.query).forEach((function(e){var r;~s.indexOf(e)&&(r=""==t.query[e]?"":"="+encodeURIComponent(t.query[e]),i.push(e+r))})),e+(i.length?"?"+i.sort().join("&"):"")}},function(e,t,i){var r=i(43),a=i(116),s=i(8),n=i(462)(1e3);function o(e,t,i){return s.createHmac("sha256",e).update(t,"utf8").digest(i)}function c(e,t){return s.createHash("sha256").update(e,"utf8").digest(t)}function u(e){return e.replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}function h(e){return u(encodeURIComponent(e))}var l={authorization:!0,connection:!0,"x-amzn-trace-id":!0,"user-agent":!0,expect:!0,"presigned-expires":!0,range:!0};function p(e,t){var i=(e="string"==typeof e?r.parse(e):e).headers=e.headers||{},a=(!this.service||!this.region)&&this.matchHost(e.hostname||e.host||i.Host||i.host);this.request=e,this.credentials=t||this.defaultCredentials(),this.service=e.service||a[0]||"",this.region=e.region||a[1]||"us-east-1","email"===this.service&&(this.service="ses"),!e.method&&e.body&&(e.method="POST"),i.Host||i.host||(i.Host=e.hostname||e.host||this.createHost(),e.port&&(i.Host+=":"+e.port)),e.hostname||e.host||(e.hostname=i.Host||i.host),this.isCodeCommitGit="codecommit"===this.service&&"GIT"===e.method}p.prototype.matchHost=function(e){var t=((e||"").match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)||[]).slice(1,3);if("s3"==(t="es"===t[1]?t.reverse():t)[1])t[0]="s3",t[1]="us-east-1";else for(var i=0;i<2;i++)if(/^s3-/.test(t[i])){t[1]=t[i].slice(3),t[0]="s3";break}return t},p.prototype.isSingleRegion=function(){return 0<=["s3","sdb"].indexOf(this.service)&&"us-east-1"===this.region||0<=["cloudfront","ls","route53","iam","importexport","sts"].indexOf(this.service)},p.prototype.createHost=function(){var e=this.isSingleRegion()?"":"."+this.region;return("ses"===this.service?"email":this.service)+e+".amazonaws.com"},p.prototype.prepareRequest=function(){this.parsePath();var e,t=this.request,i=t.headers;t.signQuery?(this.parsedPath.query=e=this.parsedPath.query||{},this.credentials.sessionToken&&(e["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||e["X-Amz-Expires"]||(e["X-Amz-Expires"]=86400),e["X-Amz-Date"]?this.datetime=e["X-Amz-Date"]:e["X-Amz-Date"]=this.getDateTime(),e["X-Amz-Algorithm"]="AWS4-HMAC-SHA256",e["X-Amz-Credential"]=this.credentials.accessKeyId+"/"+this.credentialString(),e["X-Amz-SignedHeaders"]=this.signedHeaders()):(t.doNotModifyHeaders||this.isCodeCommitGit||(!t.body||i["Content-Type"]||i["content-type"]||(i["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8"),!t.body||i["Content-Length"]||i["content-length"]||(i["Content-Length"]=Buffer.byteLength(t.body)),!this.credentials.sessionToken||i["X-Amz-Security-Token"]||i["x-amz-security-token"]||(i["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||i["X-Amz-Content-Sha256"]||i["x-amz-content-sha256"]||(i["X-Amz-Content-Sha256"]=c(this.request.body||"","hex")),i["X-Amz-Date"]||i["x-amz-date"]?this.datetime=i["X-Amz-Date"]||i["x-amz-date"]:i["X-Amz-Date"]=this.getDateTime()),delete i.Authorization,delete i.authorization)},p.prototype.sign=function(){return this.parsedPath||this.prepareRequest(),this.request.signQuery?this.parsedPath.query["X-Amz-Signature"]=this.signature():this.request.headers.Authorization=this.authHeader(),this.request.path=this.formatPath(),this.request},p.prototype.getDateTime=function(){var e;return this.datetime||(e=this.request.headers,e=new Date(e.Date||e.date||new Date),this.datetime=e.toISOString().replace(/[:\-]|\.\d{3}/g,""),this.isCodeCommitGit&&(this.datetime=this.datetime.slice(0,-1))),this.datetime},p.prototype.getDate=function(){return this.getDateTime().substr(0,8)},p.prototype.authHeader=function(){return["AWS4-HMAC-SHA256 Credential="+this.credentials.accessKeyId+"/"+this.credentialString(),"SignedHeaders="+this.signedHeaders(),"Signature="+this.signature()].join(", ")},p.prototype.signature=function(){var e=this.getDate(),t=[this.credentials.secretAccessKey,e,this.region,this.service].join(),i=n.get(t);return i||(e=o("AWS4"+this.credentials.secretAccessKey,e),e=o(e,this.region),e=o(e,this.service),i=o(e,"aws4_request"),n.set(t,i)),o(i,this.stringToSign(),"hex")},p.prototype.stringToSign=function(){return["AWS4-HMAC-SHA256",this.getDateTime(),this.credentialString(),c(this.canonicalString(),"hex")].join("\n")},p.prototype.canonicalString=function(){this.parsedPath||this.prepareRequest();var e,t,i=this.parsedPath.path,r=this.parsedPath.query,a=this.request.headers,s="",n="s3"!==this.service,o="s3"===this.service||this.request.doNotEncodePath,u="s3"===this.service,l="s3"===this.service;a="s3"===this.service&&this.request.signQuery?"UNSIGNED-PAYLOAD":this.isCodeCommitGit?"":a["X-Amz-Content-Sha256"]||a["x-amz-content-sha256"]||c(this.request.body||"","hex");return r&&(e=Object.keys(r).reduce((function(e,t){return t&&(e[h(t)]=Array.isArray(r[t])&&l?r[t][0]:r[t]),e}),{}),t=[],Object.keys(e).sort().forEach((function(i){Array.isArray(e[i])?e[i].map(h).sort().forEach((function(e){t.push(i+"="+e)})):t.push(i+"="+h(e[i]))})),s=t.join("&")),"/"!==i&&("/"!==(i=(i=n?i.replace(/\/{2,}/g,"/"):i).split("/").reduce((function(e,t){return n&&".."===t?e.pop():n&&"."===t||(o&&(t=decodeURIComponent(t.replace(/\+/g," "))),e.push(h(t))),e}),[]).join("/"))[0]&&(i="/"+i),u)&&(i=i.replace(/%2F/g,"/")),[this.request.method||"GET",i,s,this.canonicalHeaders()+"\n",this.signedHeaders(),a].join("\n")},p.prototype.canonicalHeaders=function(){var e=this.request.headers;return Object.keys(e).filter((function(e){return null==l[e.toLowerCase()]})).sort((function(e,t){return e.toLowerCase()<t.toLowerCase()?-1:1})).map((function(t){return t.toLowerCase()+":"+e[t].toString().trim().replace(/\s+/g," ")})).join("\n")},p.prototype.signedHeaders=function(){return Object.keys(this.request.headers).map((function(e){return e.toLowerCase()})).filter((function(e){return null==l[e]})).sort().join(";")},p.prototype.credentialString=function(){return[this.getDate(),this.region,this.service,"aws4_request"].join("/")},p.prototype.defaultCredentials=function(){var e=process.env;return{accessKeyId:e.AWS_ACCESS_KEY_ID||e.AWS_ACCESS_KEY,secretAccessKey:e.AWS_SECRET_ACCESS_KEY||e.AWS_SECRET_KEY,sessionToken:e.AWS_SESSION_TOKEN}},p.prototype.parsePath=function(){var e=this.request.path||"/",t=(e=/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(e)?encodeURI(decodeURI(e)):e).indexOf("?"),i=null;0<=t&&(i=a.parse(e.slice(t+1)),e=e.slice(0,t)),this.parsedPath={path:e,query:i}},p.prototype.formatPath=function(){var e=this.parsedPath.path,t=this.parsedPath.query;return t?(null!=t[""]&&delete t[""],e+"?"+u(a.stringify(t))):e},t.RequestSigner=p,t.sign=function(e,t){return new p(e,t).sign()}},function(e,t){function i(e){this.capacity=0|e,this.map=Object.create(null),this.list=new r}function r(){this.firstNode=null,this.lastNode=null}function a(e,t){this.key=e,this.val=t,this.prev=null,this.next=null}e.exports=function(e){return new i(e)},i.prototype.get=function(e){if(null!=(e=this.map[e]))return this.used(e),e.val},i.prototype.set=function(e,t){var i=this.map[e];if(null!=i)i.val=t;else{if(this.capacity||this.prune(),!this.capacity)return!1;i=new a(e,t),this.map[e]=i,this.capacity--}return this.used(i),!0},i.prototype.used=function(e){this.list.moveToFront(e)},i.prototype.prune=function(){var e=this.list.pop();null!=e&&(delete this.map[e.key],this.capacity++)},r.prototype.moveToFront=function(e){this.firstNode!=e&&(this.remove(e),null==this.firstNode?(this.firstNode=e,(this.lastNode=e).prev=null,e.next=null):(e.prev=null,e.next=this.firstNode,e.next.prev=e,this.firstNode=e))},r.prototype.pop=function(){var e=this.lastNode;return null!=e&&this.remove(e),e},r.prototype.remove=function(e){this.firstNode==e?this.firstNode=e.next:null!=e.prev&&(e.prev.next=e.next),this.lastNode==e?this.lastNode=e.prev:null!=e.next&&(e.next.prev=e.prev)}},function(e,t,i){var r=i(464),a=i(472),s=i(476);i=i(132);e.exports={parse:r.parseRequest,parseRequest:r.parseRequest,sign:a.signRequest,signRequest:a.signRequest,createSigner:a.createSigner,isSigner:a.isSigner,sshKeyToPEM:i.sshKeyToPEM,sshKeyFingerprint:i.fingerprint,pemToRsaSSHKey:i.pemToRsaSSHKey,verify:s.verifySignature,verifySignature:s.verifySignature,verifyHMAC:s.verifyHMAC}},function(e,t,i){var r=i(10),a=i(9),s=((i=i(132)).HASH_ALGOS,i.PK_ALGOS,i.HttpSignatureError),n=i.InvalidAlgorithmError,o=i.validateAlgorithm;function c(e){s.call(this,e,c)}function u(e){s.call(this,e,u)}function h(e){s.call(this,e,h)}function l(e){s.call(this,e,l)}function p(e){s.call(this,e,p)}a.inherits(c,s),a.inherits(u,s),a.inherits(h,s),a.inherits(l,s),a.inherits(p,s),e.exports={parseRequest:function(e,t){r.object(e,"request"),r.object(e.headers,"request.headers"),void 0===(t=void 0===t?{}:t).headers&&(t.headers=[e.headers["x-date"]?"x-date":"date"]),r.object(t,"options"),r.arrayOfString(t.headers,"options.headers"),r.optionalFinite(t.clockSkew,"options.clockSkew");var i=t.authorizationHeaderName||"authorization";if(!e.headers[i])throw new l("no "+i+" header present in the request");t.clockSkew=t.clockSkew||300;var a=0,s=0,d=0,f="",m="",g={scheme:"",params:{},signingString:""},v=e.headers[i];for(a=0;a<v.length;a++){var y=v.charAt(a);switch(Number(s)){case 0:" "!==y?g.scheme+=y:s=1;break;case 1:switch(Number(d)){case 0:var b=y.charCodeAt(0);if(65<=b&&b<=90||97<=b&&b<=122)f+=y;else{if("="!==y)throw new u("bad param format");if(0===f.length)throw new u("bad param format");d=1}break;case 1:if('"'!==y)throw new u("bad param format");m="",d=2;break;case 2:'"'===y?(g.params[f]=m,d=3):m+=y;break;case 3:if(","!==y)throw new u("bad param format");f="",d=0;break;default:throw new Error("Invalid substate")}break;default:throw new Error("Invalid substate")}}if(g.params.headers&&""!==g.params.headers?g.params.headers=g.params.headers.split(" "):e.headers["x-date"]?g.params.headers=["x-date"]:g.params.headers=["date"],!g.scheme||"Signature"!==g.scheme)throw new u('scheme was not "Signature"');if(!g.params.keyId)throw new u("keyId was not specified");if(!g.params.algorithm)throw new u("algorithm was not specified");if(!g.params.signature)throw new u("signature was not specified");g.params.algorithm=g.params.algorithm.toLowerCase();try{o(g.params.algorithm)}catch(e){throw e instanceof n?new h(g.params.algorithm+" is not supported"):e}for(a=0;a<g.params.headers.length;a++){var w=g.params.headers[a].toLowerCase();if("request-line"===(g.params.headers[a]=w)){if(t.strict)throw new p("request-line is not a valid header with strict parsing enabled.");g.signingString+=e.method+" "+e.url+" HTTP/"+e.httpVersion}else if("(request-target)"===w)g.signingString+="(request-target): "+e.method.toLowerCase()+" "+e.url;else{var x=e.headers[w];if(void 0===x)throw new l(w+" was not in the request");g.signingString+=w+": "+x}a+1<g.params.headers.length&&(g.signingString+="\n")}if(e.headers.date||e.headers["x-date"]){i=e.headers["x-date"]?new Date(e.headers["x-date"]):new Date(e.headers.date);var k=new Date;if((k=Math.abs(k.getTime()-i.getTime()))>1e3*t.clockSkew)throw new c("clock skew of "+k/1e3+"s was greater than "+t.clockSkew+"s")}if(t.headers.forEach((function(e){if(g.params.headers.indexOf(e.toLowerCase())<0)throw new l(e+" was not a signed header")})),t.algorithms&&-1===t.algorithms.indexOf(g.params.algorithm))throw new h(g.params.algorithm+" is not a supported algorithm");return g.algorithm=g.params.algorithm.toUpperCase(),g.keyId=g.params.keyId,g}}},function(e,t,i){var r,a,s=i(176),n=i(177),o=i(466);i=i(467);for(r in e.exports={Reader:o,Writer:i},n)n.hasOwnProperty(r)&&(e.exports[r]=n[r]);for(a in s)s.hasOwnProperty(a)&&(e.exports[a]=s[a])},function(e,t,i){var r=i(0),a=i(12).Buffer,s=i(177),n=i(176).newInvalidAsn1Error;function o(e){if(!e||!a.isBuffer(e))throw new TypeError("data must be a node Buffer");this._buf=e,this._size=e.length,this._len=0,this._offset=0}Object.defineProperty(o.prototype,"length",{enumerable:!0,get:function(){return this._len}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){return this._offset}}),Object.defineProperty(o.prototype,"remain",{get:function(){return this._size-this._offset}}),Object.defineProperty(o.prototype,"buffer",{get:function(){return this._buf.slice(this._offset)}}),o.prototype.readByte=function(e){var t;return this._size-this._offset<1?null:(t=255&this._buf[this._offset],e||(this._offset+=1),t)},o.prototype.peek=function(){return this.readByte(!0)},o.prototype.readLength=function(e){if((e=void 0===e?this._offset:e)>=this._size)return null;var t=255&this._buf[e++];if(null===t)return null;if(128==(128&t)){if(0==(t&=127))throw n("Indefinite length not supported");if(4<t)throw n("encoding too long");if(this._size-e<t)return null;for(var i=this._len=0;i<t;i++)this._len=(this._len<<8)+(255&this._buf[e++])}else this._len=t;return e},o.prototype.readSequence=function(e){var t=this.peek();if(null===t)return null;if(void 0!==e&&e!==t)throw n("Expected 0x"+e.toString(16)+": got 0x"+t.toString(16));return null===(e=this.readLength(this._offset+1))?null:(this._offset=e,t)},o.prototype.readInt=function(){return this._readTag(s.Integer)},o.prototype.readBoolean=function(){return 0!==this._readTag(s.Boolean)},o.prototype.readEnumeration=function(){return this._readTag(s.Enumeration)},o.prototype.readString=function(e,t){e=e||s.OctetString;var i=this.peek();if(null===i)return null;if(i!==e)throw n("Expected 0x"+e.toString(16)+": got 0x"+i.toString(16));return null===(e=this.readLength(this._offset+1))||this.length>this._size-e?null:(this._offset=e,0===this.length?t?a.alloc(0):"":(i=this._buf.slice(this._offset,this._offset+this.length),this._offset+=this.length,t?i:i.toString("utf8")))},o.prototype.readOID=function(e){e=e||s.OID;var t=this.readString(e,!0);if(null===t)return null;for(var i=[],r=0,a=0;a<t.length;a++){var n=255&t[a];r=(r<<7)+(127&n);0==(128&n)&&(i.push(r),r=0)}return r=i.shift(),i.unshift(r%40),i.unshift(r/40>>0),i.join(".")},o.prototype._readTag=function(e){if(r.ok(void 0!==e),null===(t=this.peek()))return null;if(t!==e)throw n("Expected 0x"+e.toString(16)+": got 0x"+t.toString(16));if(null===(e=this.readLength(this._offset+1)))return null;if(4<this.length)throw n("Integer too long: "+this.length);if(this.length>this._size-e)return null;this._offset=e;for(var t=this._buf[this._offset],i=0,a=0;a<this.length;a++)i=(i<<=8)|255&this._buf[this._offset++];return 128==(128&t)&&4!==a&&(i-=1<<8*a),i>>0},e.exports=o},function(e,t,i){var r=i(0),a=i(12).Buffer,s=i(177),n=i(176).newInvalidAsn1Error,o={size:1024,growthFactor:8};function c(e){var t,i;t=o,i=e||{},r.ok(t),r.equal(typeof t,"object"),r.ok(i),r.equal(typeof i,"object"),Object.getOwnPropertyNames(t).forEach((function(e){var r;i[e]||(r=Object.getOwnPropertyDescriptor(t,e),Object.defineProperty(i,e,r))})),e=i,this._buf=a.alloc(e.size||1024),this._size=this._buf.length,this._offset=0,this._options=e,this._seq=[]}Object.defineProperty(c.prototype,"buffer",{get:function(){if(this._seq.length)throw n(this._seq.length+" unended sequence(s)");return this._buf.slice(0,this._offset)}}),c.prototype.writeByte=function(e){if("number"!=typeof e)throw new TypeError("argument must be a Number");this._ensure(1),this._buf[this._offset++]=e},c.prototype.writeInt=function(e,t){if("number"!=typeof e)throw new TypeError("argument must be a Number");"number"!=typeof t&&(t=s.Integer);for(var i=4;(0==(4286578688&e)||-8388608==(4286578688&e))&&1<i;)i--,e<<=8;if(4<i)throw n("BER ints cannot be > 0xffffffff");for(this._ensure(2+i),this._buf[this._offset++]=t,this._buf[this._offset++]=i;0<i--;)this._buf[this._offset++]=(4278190080&e)>>>24,e<<=8},c.prototype.writeNull=function(){this.writeByte(s.Null),this.writeByte(0)},c.prototype.writeEnumeration=function(e,t){if("number"!=typeof e)throw new TypeError("argument must be a Number");return"number"!=typeof t&&(t=s.Enumeration),this.writeInt(e,t)},c.prototype.writeBoolean=function(e,t){if("boolean"!=typeof e)throw new TypeError("argument must be a Boolean");"number"!=typeof t&&(t=s.Boolean),this._ensure(3),this._buf[this._offset++]=t,this._buf[this._offset++]=1,this._buf[this._offset++]=e?255:0},c.prototype.writeString=function(e,t){if("string"!=typeof e)throw new TypeError("argument must be a string (was: "+typeof e+")");"number"!=typeof t&&(t=s.OctetString);var i=a.byteLength(e);this.writeByte(t),this.writeLength(i),i&&(this._ensure(i),this._buf.write(e,this._offset),this._offset+=i)},c.prototype.writeBuffer=function(e,t){if("number"!=typeof t)throw new TypeError("tag must be a number");if(!a.isBuffer(e))throw new TypeError("argument must be a buffer");this.writeByte(t),this.writeLength(e.length),this._ensure(e.length),e.copy(this._buf,this._offset,0,e.length),this._offset+=e.length},c.prototype.writeStringArray=function(e){if(!e instanceof Array)throw new TypeError("argument must be an Array[String]");var t=this;e.forEach((function(e){t.writeString(e)}))},c.prototype.writeOID=function(e,t){if("string"!=typeof e)throw new TypeError("argument must be a string");if("number"!=typeof t&&(t=s.OID),!/^([0-9]+\.){3,}[0-9]+$/.test(e))throw new Error("argument is not a valid OID string");e=e.split(".");var i=[],r=(i.push(40*parseInt(e[0],10)+parseInt(e[1],10)),e.slice(2).forEach((function(e){var t;t=i,(e=parseInt(e,10))<128?t.push(e):(e<16384?t.push(e>>>7|128):(e<2097152?t.push(e>>>14|128):(e<268435456?t.push(e>>>21|128):(t.push(255&(e>>>28|128)),t.push(255&(e>>>21|128))),t.push(255&(e>>>14|128))),t.push(255&(e>>>7|128))),t.push(127&e))})),this);this._ensure(2+i.length),this.writeByte(t),this.writeLength(i.length),i.forEach((function(e){r.writeByte(e)}))},c.prototype.writeLength=function(e){if("number"!=typeof e)throw new TypeError("argument must be a Number");if(this._ensure(4),!(e<=127))if(e<=255)this._buf[this._offset++]=129;else{if(e<=65535)this._buf[this._offset++]=130;else{if(!(e<=16777215))throw n("Length too long (> 4 bytes)");this._buf[this._offset++]=131,this._buf[this._offset++]=e>>16}this._buf[this._offset++]=e>>8}this._buf[this._offset++]=e},c.prototype.startSequence=function(e){"number"!=typeof e&&(e=s.Sequence|s.Constructor),this.writeByte(e),this._seq.push(this._offset),this._ensure(3),this._offset+=3},c.prototype.endSequence=function(){var e=this._seq.pop(),t=e+3,i=this._offset-t;if(i<=127)this._shift(t,i,-2),this._buf[e]=i;else if(i<=255)this._shift(t,i,-1),this._buf[e]=129,this._buf[e+1]=i;else if(i<=65535)this._buf[e]=130,this._buf[e+1]=i>>8,this._buf[e+2]=i;else{if(!(i<=16777215))throw n("Sequence too long");this._shift(t,i,1),this._buf[e]=131,this._buf[e+1]=i>>16,this._buf[e+2]=i>>8,this._buf[e+3]=i}},c.prototype._shift=function(e,t,i){r.ok(void 0!==e),r.ok(void 0!==t),r.ok(i),this._buf.copy(this._buf,e+i,e,e+t),this._offset+=i},c.prototype._ensure=function(e){var t;r.ok(e),this._size-this._offset<e&&((t=this._size*this._options.growthFactor)-this._offset<e&&(t+=e),e=a.alloc(t),this._buf.copy(e,0,0,this._offset),this._buf=e,this._size=t)},e.exports=c},function(e,t,i){var r=i(8),a=i(102).BigInteger,s=(i(133).ECPointFp,i(12).Buffer);function n(e,t){return e.length>=t?e:n("0"+e,t)}t.ECCurves=i(469),t.ECKey=function(e,t,i){var o=e(),c=o.getN(),u=Math.floor(c.bitLength()/8);if(t)if(i)e=o.getCurve(),this.P=e.decodePointHex(t.toString("hex"));else{if(t.length!=u)return!1;h=new a(t.toString("hex"),16)}else{i=c.subtract(a.ONE);var h=new a(r.randomBytes(c.bitLength())).mod(i).add(a.ONE);this.P=o.getG().multiply(h)}this.P&&(this.PublicKey=s.from(o.getCurve().encodeCompressedPointHex(this.P),"hex")),h&&(this.PrivateKey=s.from(n(h.toString(16),2*u),"hex"),this.deriveSharedSecret=function(e){return!(!e||!e.P)&&(e=e.P.multiply(h),s.from(n(e.getX().toBigInteger().toString(16),2*u),"hex"))})}},function(e,t,i){var r=i(102).BigInteger,a=i(133).ECCurveFp;function s(e,t,i,r){this.curve=e,this.g=t,this.n=i,this.h=r}function n(e){return new r(e,16)}s.prototype.getCurve=function(){return this.curve},s.prototype.getG=function(){return this.g},s.prototype.getN=function(){return this.n},s.prototype.getH=function(){return this.h},e.exports={secp128r1:function(){var e=n("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF"),t=n("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC"),i=n("E87579C11079F43DD824993C2CEE5ED3"),o=n("FFFFFFFE0000000075A30D1B9038A115"),c=r.ONE;return t=(e=new a(e,t,i)).decodePointHex("04161FF7528B899B2D0C28607CA52C5B86CF5AC8395BAFEB13C02DA292DDED7A83"),new s(e,t,o,c)},secp160k1:function(){var e=n("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73"),t=r.ZERO,i=n("7"),o=n("0100000000000000000001B8FA16DFAB9ACA16B6B3"),c=r.ONE;return t=(e=new a(e,t,i)).decodePointHex("043B4C382CE37AA192A4019E763036F4F5DD4D7EBB938CF935318FDCED6BC28286531733C3F03C4FEE"),new s(e,t,o,c)},secp160r1:function(){var e=n("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF"),t=n("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC"),i=n("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45"),o=n("0100000000000000000001F4C8F927AED3CA752257"),c=r.ONE;return t=(e=new a(e,t,i)).decodePointHex("044A96B5688EF573284664698968C38BB913CBFC8223A628553168947D59DCC912042351377AC5FB32"),new s(e,t,o,c)},secp192k1:function(){var e=n("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37"),t=r.ZERO,i=n("3"),o=n("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D"),c=r.ONE;return t=(e=new a(e,t,i)).decodePointHex("04DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D"),new s(e,t,o,c)},secp192r1:function(){var e=n("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF"),t=n("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC"),i=n("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1"),o=n("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831"),c=r.ONE;return t=(e=new a(e,t,i)).decodePointHex("04188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF101207192B95FFC8DA78631011ED6B24CDD573F977A11E794811"),new s(e,t,o,c)},secp224r1:function(){var e=n("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001"),t=n("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE"),i=n("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4"),o=n("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D"),c=r.ONE;return t=(e=new a(e,t,i)).decodePointHex("04B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34"),new s(e,t,o,c)},secp256r1:function(){var e=n("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF"),t=n("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC"),i=n("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B"),o=n("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"),c=r.ONE;return t=(e=new a(e,t,i)).decodePointHex("046B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C2964FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"),new s(e,t,o,c)}}},function(e,t,i){e.exports={read:function(e,t){if(n.isBuffer(e)&&(e=e.toString("ascii")),(e=e.trim().split(/[ \t\n]+/g)).length<2||3<e.length)throw new Error("Not a valid SSH certificate line");var i=e[0];e=e[1];return g(e=n.from(e,"base64"),i)},verify:function(e,t){return!1},sign:function(e,t){void 0===e.signatures.openssh&&(e.signatures.openssh={});try{var i=b(e,!0)}catch(t){return delete e.signatures.openssh,!1}e=e.signatures.openssh;var r=void 0;return"rsa"!==t.type&&"dsa"!==t.type||(r="sha1"),(t=t.createSign(r)).write(i),e.signature=t.sign(),!0},signAsync:function(e,t,i){void 0===e.signatures.openssh&&(e.signatures.openssh={});try{var r=b(e,!0)}catch(t){return delete e.signatures.openssh,void i(t)}var a=e.signatures.openssh;t(r,(function(e,t){if(e)i(e);else{try{t.toBuffer("ssh")}catch(e){return void i(e)}a.signature=t,i()}}))},write:function(e,t){void 0===t&&(t={});var i=b(e);e=w(e.subjectKey)+" "+i.toString("base64");return t.comment&&(e=e+" "+t.comment),e},fromBuffer:g,toBuffer:b};var r=i(10),a=i(91),s=i(8),n=i(12).Buffer,o=i(30),c=i(23),u=(i(24),i(106)),h=i(66),l=i(57),p=i(25),d=i(105),f={user:1,host:2},m=(Object.keys(f).forEach((function(e){f[f[e]]=e})),/^ecdsa-sha2-([^@-]+)-cert-v01@openssh.com$/);function g(e,t,i){var s=new a({buffer:e});e=s.readString();if(void 0!==t&&e!==t)throw new Error("SSH certificate algorithm mismatch");void 0===t&&(t=e),(e={signatures:{}}).signatures.openssh={},e.signatures.openssh.nonce=s.readBuffer();for(var n={},g=n.parts=[],y=(n.type=function(e){if("ssh-rsa-cert-v01@openssh.com"===e)return"rsa";if("ssh-dss-cert-v01@openssh.com"===e)return"dsa";if(e.match(m))return"ecdsa";if("ssh-ed25519-cert-v01@openssh.com"===e)return"ed25519";throw new Error("Unsupported cert type "+e)}(t),o.info[n.type].parts.length);g.length<y;)g.push(s.readPart());r.ok(1<=g.length,"key must have at least one part");var b=o.info[n.type];"ecdsa"===n.type&&(t=m.exec(t),r.ok(null!==t),r.strictEqual(t[1],g[0].data.toString()));for(var w,x=0;x<b.parts.length;++x)g[x].name=b.parts[x],"curve"!==g[x].name&&!1!==b.normalize&&((w=g[x]).data=p.mpNormalize(w.data));e.subjectKey=new c(n),e.serial=s.readInt64();for(var k=f[s.readInt()],S=(r.string(k,"valid cert type"),e.signatures.openssh.keyId=s.readString(),[]),_=(t=s.readBuffer(),new a({buffer:t}));!_.atEnd();)S.push(_.readString());0===S.length&&(S=["*"]),e.subjects=S.map((function(e){if("user"===k)return u.forUser(e);if("host"===k)return u.forHost(e);throw new Error("Unknown identity type "+k)})),e.validFrom=v(s.readInt64()),e.validUntil=v(s.readInt64());for(var E,j=[],A=new a({buffer:s.readBuffer()});!A.atEnd();)(E={critical:!0}).name=A.readString(),E.data=A.readBuffer(),j.push(E);for(A=new a({buffer:s.readBuffer()});!A.atEnd();)(E={critical:!1}).name=A.readString(),E.data=A.readBuffer(),j.push(E);return e.signatures.openssh.exts=j,s.readBuffer(),n=s.readBuffer(),e.issuerKey=h.read(n),e.issuer=u.forHost("**"),t=s.readBuffer(),e.signatures.openssh.signature=l.parse(t,e.issuerKey.type,"ssh"),void 0!==i&&(i.remainder=s.remainder(),i.consumed=s._offset),new d(e)}function v(e){var t=4294967296*e.readUInt32BE(0),i=(t+=e.readUInt32BE(4),new Date);return i.setTime(1e3*t),i.sourceInt64=e,i}function y(e){var t,i;return void 0!==e.sourceInt64?e.sourceInt64:(e=Math.round(e.getTime()/1e3),t=Math.floor(e/4294967296),e=Math.floor(e%4294967296),(i=n.alloc(8)).writeUInt32BE(t,0),i.writeUInt32BE(e,4),i)}function b(e,t){r.object(e.signatures.openssh,"signature for openssh format");var i=e.signatures.openssh,c=(void 0===i.nonce&&(i.nonce=s.randomBytes(16)),new a({})),u=(c.writeString(w(e.subjectKey)),c.writeBuffer(i.nonce),e.subjectKey),l=(o.info[u.type].parts.forEach((function(e){c.writePart(u.part[e])})),c.writeInt64(e.serial),e.subjects[0].type),p=(r.notStrictEqual(l,"unknown"),e.subjects.forEach((function(e){r.strictEqual(e.type,l)})),l=f[l],c.writeInt(l),void 0===i.keyId&&(i.keyId=e.subjects[0].type+"_"+(e.subjects[0].uid||e.subjects[0].hostname)),c.writeString(i.keyId),new a({})),d=(e.subjects.forEach((function(e){l===f.host?p.writeString(e.hostname):l===f.user&&p.writeString(e.uid)})),c.writeBuffer(p.toBuffer()),c.writeInt64(y(e.validFrom)),c.writeInt64(y(e.validUntil)),i.exts),m=(void 0===d&&(d=[]),new a({}));return d.forEach((function(e){!0===e.critical&&(m.writeString(e.name),m.writeBuffer(e.data))})),c.writeBuffer(m.toBuffer()),m=new a({}),d.forEach((function(e){!0!==e.critical&&(m.writeString(e.name),m.writeBuffer(e.data))})),c.writeBuffer(m.toBuffer()),c.writeBuffer(n.alloc(0)),p=h.write(e.issuerKey),c.writeBuffer(p),t||c.writeBuffer(i.signature.toBuffer("ssh")),c.toBuffer()}function w(e){if("rsa"===e.type)return"ssh-rsa-cert-v01@openssh.com";if("dsa"===e.type)return"ssh-dss-cert-v01@openssh.com";if("ecdsa"===e.type)return"ecdsa-sha2-"+e.curve+"-cert-v01@openssh.com";if("ed25519"===e.type)return"ssh-ed25519-cert-v01@openssh.com";throw new Error("Unsupported key type "+e.type)}},function(e,t,i){var r=i(278),a=(e.exports={read:function(e,t){"string"!=typeof e&&(a.buffer(e,"buf"),e=e.toString("ascii"));for(var i,n,o=e.trim().split(/[\r\n]+/g),c=-1;!i&&c<o.length;)i=o[++c].match(/[-]+[ ]*BEGIN CERTIFICATE[ ]*[-]+/);a.ok(i,"invalid PEM header");for(var u=o.length;!n&&0<u;)n=o[--u].match(/[-]+[ ]*END CERTIFICATE[ ]*[-]+/);for(a.ok(n,"invalid PEM footer"),o=o.slice(c,u+1);i=(o=o.slice(1))[0].match(/^([A-Za-z0-9-]+): (.+)$/);)i[1].toLowerCase(),i[2];return o=o.slice(0,-1).join(""),e=s.from(o,"base64"),r.read(e,t)},verify:r.verify,sign:r.sign,write:function(e,t){e=r.write(e,t),t="CERTIFICATE";var i=e.toString("base64"),a=(e=i.length+i.length/64+18+16+2*t.length+10,s.alloc(e)),n=0;n+=a.write("-----BEGIN "+t+"-----\n",n);for(var o=0;o<i.length;){var c=o+64;c>i.length&&(c=i.length),n+=a.write(i.slice(o,c),n),a[n++]=10,o=c}return n+=a.write("-----END "+t+"-----\n",n),a.slice(0,n)}},i(10)),s=(i(58),i(12).Buffer);i(30),i(25),i(23),i(24),i(65),i(106),i(57),i(105)},function(e,t,i){var r=i(10),a=i(8),s=(i(61),i(9)),n=i(175),o=i(473),c=i(132),u=i(9).format,h=c.HASH_ALGOS,l=c.PK_ALGOS,p=c.InvalidAlgorithmError,d=c.HttpSignatureError,f=c.validateAlgorithm,m='Signature keyId="%s",algorithm="%s",headers="%s",signature="%s"';function g(e){d.call(this,e,g)}function v(e){d.call(this,e,v)}function y(e){r.object(e,"options");var t=[];if(void 0!==e.algorithm&&(r.string(e.algorithm,"options.algorithm"),t=f(e.algorithm)),this.rs_alg=t,void 0!==e.sign)r.func(e.sign,"options.sign"),this.rs_signFunc=e.sign;else if("hmac"===t[0]&&void 0!==e.key){if(r.string(e.keyId,"options.keyId"),this.rs_keyId=e.keyId,"string"!=typeof e.key&&!Buffer.isBuffer(e.key))throw new TypeError("options.key for HMAC must be a string or Buffer");this.rs_signer=a.createHmac(t[1].toUpperCase(),e.key),this.rs_signer.sign=function(){var e=this.digest("base64");return{hashAlgorithm:t[1],toString:function(){return e}}}}else{if(void 0===e.key)throw new TypeError("options.sign (func) or options.key is required");var i=e.key;if("string"!=typeof i&&!Buffer.isBuffer(i)||(i=n.parsePrivateKey(i)),r.ok(n.PrivateKey.isPrivateKey(i,[1,2]),"options.key must be a sshpk.PrivateKey"),this.rs_key=i,r.string(e.keyId,"options.keyId"),this.rs_keyId=e.keyId,!l[i.type])throw new p(i.type.toUpperCase()+" type keys are not supported");if(void 0!==t[0]&&i.type!==t[0])throw new p("options.key must be a "+t[0].toUpperCase()+" key, was given a "+i.type.toUpperCase()+" key instead");this.rs_signer=i.createSign(t[1])}this.rs_headers=[],this.rs_lines=[]}s.inherits(g,d),s.inherits(v,d),y.prototype.writeHeader=function(e,t){return r.string(e,"header"),e=e.toLowerCase(),r.string(t,"value"),this.rs_headers.push(e),this.rs_signFunc?this.rs_lines.push(e+": "+t):(e=e+": "+t,0<this.rs_headers.length&&(e="\n"+e),this.rs_signer.update(e)),t},y.prototype.writeDateHeader=function(){return this.writeHeader("date",o.rfc1123(new Date))},y.prototype.writeTarget=function(e,t){r.string(e,"method"),r.string(t,"path"),e=e.toLowerCase(),this.writeHeader("(request-target)",e+" "+t)},y.prototype.sign=function(e){if(r.func(e,"callback"),this.rs_headers.length<1)throw new Error("At least one header must be signed");if(this.rs_signFunc){var t=this.rs_lines.join("\n"),i=this;this.rs_signFunc(t,(function(t,a){if(t)e(t);else{try{r.object(a,"signature"),r.string(a.keyId,"signature.keyId"),r.string(a.algorithm,"signature.algorithm"),r.string(a.signature,"signature.signature"),s=f(a.algorithm),n=u(m,a.keyId,a.algorithm,i.rs_headers.join(" "),a.signature)}catch(t){return void e(t)}e(null,n)}}))}else{try{var a=this.rs_signer.sign()}catch(t){return void e(t)}var s=(this.rs_alg[0]||this.rs_key.type)+"-"+a.hashAlgorithm,n=(t=a.toString(),u(m,this.rs_keyId,s,this.rs_headers.join(" "),t));e(null,n)}},e.exports={isSigner:function(e){return"object"==typeof e&&e instanceof y},createSigner:function(e){return new y(e)},signRequest:function(e,t){r.object(e,"request"),r.object(t,"options"),r.optionalString(t.algorithm,"options.algorithm"),r.string(t.keyId,"options.keyId"),r.optionalArrayOfString(t.headers,"options.headers"),r.optionalString(t.httpVersion,"options.httpVersion"),e.getHeader("Date")||e.setHeader("Date",o.rfc1123(new Date)),t.headers||(t.headers=["date"]),t.httpVersion||(t.httpVersion="1.1");for(var i=[],s=(t.algorithm&&(t.algorithm=t.algorithm.toLowerCase(),i=f(t.algorithm)),""),c=0;c<t.headers.length;c++){if("string"!=typeof t.headers[c])throw new TypeError("options.headers must be an array of Strings");var d=t.headers[c].toLowerCase();if("request-line"===d){if(t.strict)throw new v("request-line is not a valid header with strict parsing enabled.");s+=e.method+" "+e.path+" HTTP/"+t.httpVersion}else if("(request-target)"===d)s+="(request-target): "+e.method.toLowerCase()+" "+e.path;else{var y=e.getHeader(d);if(void 0===y||""===y)throw new g(d+" was not in the request");s+=d+": "+y}c+1<t.headers.length&&(s+="\n")}if(e.hasOwnProperty("_stringToSign")&&(e._stringToSign=s),"hmac"===i[0]){if("string"!=typeof t.key&&!Buffer.isBuffer(t.key))throw new TypeError("options.key must be a string or Buffer");var b=a.createHmac(i[1].toUpperCase(),t.key);b.update(s),b=b.digest("base64")}else{var w=t.key;if("string"!=typeof w&&!Buffer.isBuffer(w)||(w=n.parsePrivateKey(t.key)),r.ok(n.PrivateKey.isPrivateKey(w,[1,2]),"options.key must be a sshpk.PrivateKey"),!l[w.type])throw new p(w.type.toUpperCase()+" type keys are not supported");if(void 0!==i[0]&&w.type!==i[0])throw new p("options.key must be a "+i[0].toUpperCase()+" key, was given a "+w.type.toUpperCase()+" key instead");if((i=w.createSign(i[1])).update(s),i=i.sign(),!h[i.hashAlgorithm])throw new p(i.hashAlgorithm.toUpperCase()+" is not a supported hash algorithm");t.algorithm=w.type+"-"+i.hashAlgorithm,b=i.toString(),r.notStrictEqual(b,"","empty signature produced")}return w=t.authorizationHeaderName||"Authorization",e.setHeader(w,u(m,t.keyId,t.algorithm,t.headers.join(" "),b)),!0}}},function(e,t,i){var r=i(10),a=(i(9),i(279)),s=i(474),n=i(475);function o(e,t){return r.equal(typeof t,"string"),Object.prototype.hasOwnProperty.call(e,t)}t.deepCopy=function e(t){var i,r,a="__deepCopy";if(t&&t[a])throw new Error("attempted deep copy of cyclic object");if(t&&t.constructor==Object){for(r in i={},t[a]=!0,t)r!=a&&(i[r]=e(t[r]));return delete t[a],i}if(t&&t.constructor==Array){for(i=[],t[a]=!0,r=0;r<t.length;r++)i.push(e(t[r]));return delete t[a],i}return t},t.deepEqual=function e(t,i){if(typeof t!=typeof i)return!1;if(null===t||null===i||"object"!=typeof t)return t===i;if(t.constructor!=i.constructor)return!1;for(var r in t){if(!i.hasOwnProperty(r))return!1;if(!e(t[r],i[r]))return!1}for(r in i)if(!t.hasOwnProperty(r))return!1;return!0},t.isEmpty=function(e){for(var t in e)return!1;return!0},t.hasKey=o,t.forEachKey=function(e,t){for(var i in e)o(e,i)&&t(i,e[i])},t.pluck=function(e,t){return r.equal(typeof t,"string"),function e(t,i){if(null!==t&&"object"==typeof t){if(t.hasOwnProperty(i))return t[i];var r=i.indexOf(".");if(-1!=r){var a=i.substr(0,r);if(t.hasOwnProperty(a))return e(t[a],i.substr(r+1))}}}(e,t)},t.flattenObject=function e(t,i){if(0===i)return[t];r.ok(null!==t),r.equal(typeof t,"object"),r.equal(typeof i,"number"),r.ok(0<=i);var a=[];for(var s in t)e(t[s],i-1).forEach((function(e){a.push([s].concat(e))}));return a},t.flattenIter=function(e,t,i){!function e(t,i,a,s){var n;if(0===i)return(n=a.slice(0)).push(t),void s(n);for(var o in r.ok(null!==t),r.equal(typeof t,"object"),r.equal(typeof i,"number"),r.ok(0<=i),t)(n=a.slice(0)).push(o),e(t[o],i-1,n,s)}(e,t,[],i)},t.validateJsonObject=C,t.validateJsonObjectJS=C,t.randElt=function(e){return r.ok(Array.isArray(e)&&0<e.length,"randElt argument must be a non-empty array"),e[Math.floor(Math.random()*e.length)]},t.extraProperties=function(e,t){r.ok("object"==typeof e&&null!==e,"obj argument must be a non-null object"),r.ok(Array.isArray(t),"allowed argument must be an array of strings");for(var i=0;i<t.length;i++)r.ok("string"==typeof t[i],"allowed argument must be an array of strings");return Object.keys(e).filter((function(e){return-1===t.indexOf(e)}))},t.mergeObjects=N,t.startsWith=function(e,t){return e.substr(0,t.length)==t},t.endsWith=function(e,t){return e.substr(e.length-t.length,t.length)==t},t.parseInteger=function(e,t){r.string(e,"str"),r.optionalObject(t,"options");var i,a=!1,s=p;t&&(a=o(t,"base"),s=N(s,t),r.number(s.base,"options.base"),r.ok(2<=s.base,"options.base >= 2"),r.ok(s.base<=36,"options.base <= 36"),r.bool(s.allowSign,"options.allowSign"),r.bool(s.allowPrefix,"options.allowPrefix"),r.bool(s.allowTrailing,"options.allowTrailing"),r.bool(s.allowImprecise,"options.allowImprecise"),r.bool(s.trimWhitespace,"options.trimWhitespace"),r.bool(s.leadingZeroIsOctal,"options.leadingZeroIsOctal"),s.leadingZeroIsOctal)&&r.ok(!a,'"base" and "leadingZeroIsOctal" are mutually exclusive');t=-1;var n=s.base,c=1,u=0,C=0,P=e.length;if(s.trimWhitespace)for(;C<P&&O(e.charCodeAt(C));)++C;for(s.allowSign&&("-"===e[C]?(C+=1,c=-1):"+"===e[C]&&(C+=1)),"0"===e[C]&&(!s.allowPrefix||-1===(t=function(e){return e===k||e===g?2:e===S||e===v?8:e===_||e===y?10:e===E||e===b?16:-1}(e.charCodeAt(C+1)))||a&&t!==n||(n=t,C+=2),-1===t)&&s.leadingZeroIsOctal&&(n=8),a=C;C<P&&-1!==(i=function(e){return d<=e&&e<=f?e-A:m<=e&&e<=w?e-R:x<=e&&e<=j?e-I:-1}(e.charCodeAt(C)))&&i<n;++C)u=u*n+i;if(a===C)return new Error("invalid number: "+JSON.stringify(e));if(s.trimWhitespace)for(;C<P&&O(e.charCodeAt(C));)++C;return C<P&&!s.allowTrailing?new Error("trailing characters after number: "+JSON.stringify(e.slice(C))):0===u?0:(t=u*c,s.allowImprecise||!(h<u||t<l)?t:new Error("number is outside of the supported range: "+JSON.stringify(e.slice(a,C))))},t.iso8601=function(e){return"number"==typeof e&&(e=new Date(e)),r.ok(e.constructor===Date),a.sprintf("%4d-%02d-%02dT%02d:%02d:%02d.%03dZ",e.getUTCFullYear(),e.getUTCMonth()+1,e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds())},t.rfc1123=function(e){return a.sprintf("%s, %02d %s %04d %02d:%02d:%02d GMT",u[e.getUTCDay()],e.getUTCDate(),c[e.getUTCMonth()],e.getUTCFullYear(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds())},t.parseDateTime=function(e){var t=+e;return isNaN(t)?new Date(e):new Date(t)},t.hrtimediff=T,t.hrtimeDiff=T,t.hrtimeAccum=B,t.hrtimeAdd=function(e,t){return P(e),B([e[0],e[1]],t)},t.hrtimeNanosec=function(e){return P(e),Math.floor(1e9*e[0]+e[1])},t.hrtimeMicrosec=function(e){return P(e),Math.floor(1e6*e[0]+e[1]/1e3)},t.hrtimeMillisec=function(e){return P(e),Math.floor(1e3*e[0]+e[1]/1e6)};var c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],u=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],h=Number.MAX_SAFE_INTEGER||9007199254740991,l=Number.MIN_SAFE_INTEGER||-9007199254740991,p={base:10,allowSign:!0,allowPrefix:!1,allowTrailing:!1,allowImprecise:!1,trimWhitespace:!1,leadingZeroIsOctal:!1},d=48,f=57,m=65,g=66,v=79,y=84,b=88,w=90,x=97,k=98,S=111,_=116,E=120,j=122,A=48,R=55,I=87;function O(e){return 32===e||9<=e&&e<=13||160===e||5760===e||6158===e||8192<=e&&e<=8202||8232===e||8233===e||8239===e||8287===e||12288===e||65279===e}function C(e,t){var i,r,a;return 0===(t=n.validate(t,e)).errors.length?null:(t=(e=t.errors[0]).property,-1!=(r=(i=e.message.toLowerCase()).indexOf("the property "))&&-1!=(a=i.indexOf(" is not defined in the schema and the schema does not allow additional properties"))&&(r+="the property ".length,t=""===t?i.substr(r,a-r):t+"."+i.substr(r,a-r),i="unsupported property"),(a=new s.VError('property "%s": %s',t,i)).jsv_details=e,a)}function P(e){r.ok(0<=e[0]&&0<=e[1],"negative numbers not allowed in hrtimes"),r.ok(e[1]<1e9,"nanoseconds column overflow")}function T(e,t){P(e),P(t),r.ok(e[0]>t[0]||e[0]==t[0]&&e[1]>=t[1],"negative differences not allowed");var i=[e[0]-t[0],0];return e[1]>=t[1]?i[1]=e[1]-t[1]:(i[0]--,i[1]=1e9-(t[1]-e[1])),i}function B(e,t){return P(e),P(t),e[1]+=t[1],1e9<=e[1]&&(e[0]++,e[1]-=1e9),e[0]+=t[0],e}function N(e,t,i){var r,a={};if(i)for(r in i)a[r]=i[r];if(e)for(r in e)a[r]=e[r];if(t)for(r in t)a[r]=t[r];return a}},function(e,t,i){var r=i(10),a=i(9),s=i(279),n=i(86).isError,o=s.sprintf;function c(e){var t,i,a,s;if(r.object(e,"args"),r.bool(e.strict,"args.strict"),r.array(e.argv,"args.argv"),0===(t=e.argv).length)i={},a=[];else if(n(t[0]))i={cause:t[0]},a=t.slice(1);else if("object"==typeof t[0]){for(s in i={},t[0])i[s]=t[0][s];a=t.slice(1)}else r.string(t[0],"first argument to VError, SError, or WError constructor must be a string, object, or Error"),i={},a=t;return r.object(i),{options:i,shortmessage:0===(a=i.strict||e.strict?a:a.map((function(e){return null===e?"null":void 0===e?"undefined":e}))).length?"":o.apply(null,a)}}function u(){var e,t,i,a=Array.prototype.slice.call(arguments,0);if(!(this instanceof u))return t=Object.create(u.prototype),u.apply(t,arguments),t;if((e=c({argv:a,strict:!1})).options.name&&(r.string(e.options.name,'error\'s "name" must be a string'),this.name=e.options.name),this.jse_shortmsg=e.shortmessage,t=e.shortmessage,(a=e.options.cause)&&(r.ok(n(a),"cause is not an Error"),this.jse_cause=a,e.options.skipCauseMessage||(t+=": "+a.message)),this.jse_info={},e.options.info)for(i in e.options.info)this.jse_info[i]=e.options.info[i];return this.message=t,Error.call(this,t),Error.captureStackTrace&&(a=e.options.constructorOpt||this.constructor,Error.captureStackTrace(this,a)),this}function h(){var e,t=Array.prototype.slice.call(arguments,0);return this instanceof h?(e=(t=c({argv:t,strict:!0})).options,u.call(this,e,"%s",t.shortmessage),this):(e=Object.create(h.prototype),h.apply(e,arguments),e)}function l(e){r.array(e,"list of errors"),r.ok(0<e.length,"must be at least one error"),this.ase_errors=e,u.call(this,{cause:e[0]},"first of %d error%s",e.length,1==e.length?"":"s")}function p(){var e,t,i=Array.prototype.slice.call(arguments,0);return this instanceof p?((t=(e=c({argv:i,strict:!1})).options).skipCauseMessage=!0,u.call(this,t,"%s",e.shortmessage),this):(t=Object.create(p.prototype),p.apply(t,i),t)}((e.exports=u).VError=u).SError=h,u.WError=p,u.MultiError=l,a.inherits(u,Error),u.prototype.name="VError",u.prototype.toString=function(){var e=this.hasOwnProperty("name")&&this.name||this.constructor.name||this.constructor.prototype.name;return this.message&&(e+=": "+this.message),e},u.prototype.cause=function(){var e=u.cause(this);return null===e?void 0:e},u.cause=function(e){return r.ok(n(e),"err must be an Error"),n(e.jse_cause)?e.jse_cause:null},u.info=function(e){var t,i,a;if(r.ok(n(e),"err must be an Error"),t=null!==(i=u.cause(e))?u.info(i):{},"object"==typeof e.jse_info&&null!==e.jse_info)for(a in e.jse_info)t[a]=e.jse_info[a];return t},u.findCauseByName=function(e,t){var i;for(r.ok(n(e),"err must be an Error"),r.string(t,"name"),r.ok(0<t.length,"name cannot be empty"),i=e;null!==i;i=u.cause(i))if(r.ok(n(i)),i.name==t)return i;return null},u.hasCauseWithName=function(e,t){return null!==u.findCauseByName(e,t)},u.fullStack=function(e){r.ok(n(e),"err must be an Error");var t=u.cause(e);return t?e.stack+"\ncaused by: "+u.fullStack(t):e.stack},u.errorFromList=function(e){return r.arrayOfObject(e,"errors"),0===e.length?null:(e.forEach((function(e){r.ok(n(e))})),1==e.length?e[0]:new l(e))},u.errorForEach=function(e,t){r.ok(n(e),"err must be an Error"),r.func(t,"func"),e instanceof l?e.errors().forEach((function(e){t(e)})):t(e)},a.inherits(h,u),a.inherits(l,u),l.prototype.name="MultiError",l.prototype.errors=function(){return this.ase_errors.slice(0)},a.inherits(p,u),p.prototype.name="WError",p.prototype.toString=function(){var e=this.hasOwnProperty("name")&&this.name||this.constructor.name||this.constructor.prototype.name;return this.message&&(e+=": "+this.message),this.jse_cause&&this.jse_cause.message&&(e+="; caused by "+this.jse_cause.toString()),e},p.prototype.cause=function(e){return n(e)&&(this.jse_cause=e),this.jse_cause}},function(e,t,i){void 0!==(t=function(){return(t=e).Integer={type:"integer"},i={String:String,Boolean:Boolean,Number:Number,Object:Object,Array:Array,Date:Date},t.validate=e,t.checkPropertyChange=function(t,i,r){return e(t,i,{changing:r||"property"})},e=t._validate=function(e,t,r){var a=(r=r||{}).changing;function s(e){return e.type||i[e.name]==e&&e.name.toLowerCase()}var n=[];function o(e,t,i,c){function u(e){n.push({property:i,message:e})}if(i+=i?"number"==typeof c?"["+c+"]":void 0===c?"":"."+c:c,!("object"!=typeof t||t instanceof Array)||!i&&"function"==typeof t||t&&s(t)){if(a&&t.readonly&&u("is a readonly field, it can not be changed"),t.extends&&o(e,t.extends,i,c),void 0===e)t.required&&u("is missing and it is required");else if(n=n.concat(g(s(t),e)),t.disallow&&!g(t.disallow,e).length&&u(" disallowed value was matched"),null!==e){if(e instanceof Array){if(t.items){var h=t.items instanceof Array,l=t.items;for(c=0,f=e.length;c<f;c+=1)h&&(l=t.items[c]),r.coerce&&(e[c]=r.coerce(e[c],l)),n.concat(o(e[c],l,i,c))}t.minItems&&e.length<t.minItems&&u("There must be a minimum of "+t.minItems+" in the array"),t.maxItems&&e.length>t.maxItems&&u("There must be a maximum of "+t.maxItems+" in the array")}else(t.properties||t.additionalProperties)&&n.concat(function(e,t,i,s){if("object"==typeof t)for(var c in("object"!=typeof e||e instanceof Array)&&n.push({property:i,message:"an object is required"}),t){var u,h;!t.hasOwnProperty(c)||"__proto__"==c||"constructor"==c||void 0===(u=e.hasOwnProperty(c)?e[c]:void 0)&&r.existingOnly||(h=t[c],void 0===u&&h.default&&(u=e[c]=h.default),o(u=r.coerce&&c in e?e[c]=r.coerce(u,h):u,h,i,c))}for(c in e){if(e.hasOwnProperty(c)&&("_"!=c.charAt(0)||"_"!=c.charAt(1))&&t&&!t[c]&&!1===s){if(r.filter){delete e[c];continue}n.push({property:i,message:"The property "+c+" is not defined in the schema and the schema does not allow additional properties"})}var l=t&&t[c]&&t[c].requires;!l||l in e||n.push({property:i,message:"the presence of the property "+c+" requires that "+l+" also be present"}),u=e[c],!s||t&&"object"==typeof t&&c in t||o(u=r.coerce?e[c]=r.coerce(u,s):u,s,i,c),!a&&u&&u.$schema&&(n=n.concat(o(u,u.$schema,i,c)))}return n}(e,t.properties,i,t.additionalProperties));if(t.pattern&&"string"==typeof e&&!e.match(t.pattern)&&u("does not match the regex pattern "+t.pattern),t.maxLength&&"string"==typeof e&&e.length>t.maxLength&&u("may only be "+t.maxLength+" characters long"),t.minLength&&"string"==typeof e&&e.length<t.minLength&&u("must be at least "+t.minLength+" characters long"),void 0!==t.minimum&&typeof e==typeof t.minimum&&t.minimum>e&&u("must have a minimum value of "+t.minimum),void 0!==t.maximum&&typeof e==typeof t.maximum&&t.maximum<e&&u("must have a maximum value of "+t.maximum),t.enum){for(var p,d=t.enum,f=d.length,m=0;m<f;m++)if(d[m]===e){p=1;break}p||u("does not have a value in the enumeration "+d.join(", "))}"number"==typeof t.maxDecimal&&e.toString().match(new RegExp("\\.[0-9]{"+(t.maxDecimal+1)+",}"))&&u("may only have "+t.maxDecimal+" digits of decimal places")}}else"function"==typeof t?e instanceof t||u("is not an instance of the class/constructor "+t.name):t&&u("Invalid schema/property definition "+t);return null;function g(e,t){if(e){if(!("string"!=typeof e||"any"==e||("null"==e?null===t:typeof t==e)||t instanceof Array&&"array"==e||t instanceof Date&&"date"==e||"integer"==e&&t%1==0))return[{property:i,message:t+" - "+typeof t+" value found, but a "+e+" is required"}];if(e instanceof Array){for(var r=[],a=0;a<e.length&&(r=g(e[a],t)).length;a++);if(r.length)return r}else{var s,c;if("object"==typeof e)return s=n,n=[],o(t,e,i),c=n,n=s,c}}return[]}}return t&&o(e,t,"",a||""),!a&&e&&e.$schema&&o(e,e.$schema,"",""),{valid:!n.length,errors:n}},t.mustBeValid=function(e){if(!e.valid)throw new TypeError(e.errors.map((function(e){return"for property "+e.property+": "+e.message})).join(", \n"))},t;function e(t,i){return e(t,i,{changing:!1})}var t,i}.apply(t,[]))&&(e.exports=t)},function(e,t,i){var r=i(10),a=i(8),s=i(175),n=((i=i(132)).HASH_ALGOS,i.PK_ALGOS,i.InvalidAlgorithmError,i.HttpSignatureError,i.validateAlgorithm);e.exports={verifySignature:function(e,t){r.object(e,"parsedSignature"),"string"!=typeof t&&!Buffer.isBuffer(t)||(t=s.parseKey(t)),r.ok(s.Key.isKey(t,[1,1]),"pubkey must be a sshpk.Key");var i=n(e.algorithm);return"hmac"!==i[0]&&i[0]===t.type&&((t=t.createVerify(i[1])).update(e.signingString),t.verify(e.params.signature,"base64"))},verifyHMAC:function(e,t){r.object(e,"parsedHMAC"),r.string(t,"secret");var i,s,o=n(e.algorithm);return"hmac"===o[0]&&(o=o[1].toUpperCase(),(s=a.createHmac(o,t)).update(e.signingString),(i=a.createHmac(o,t)).update(s.digest()),i=i.digest(),(s=a.createHmac(o,t)).update(new Buffer(e.params.signature,"base64")),s=s.digest(),"string"==typeof i?i===s:Buffer.isBuffer(i)&&!i.equals?i.toString("binary")===s.toString("binary"):i.equals(s))}}},function(e,t,i){
|
|
940
940
|
/*!
|
|
941
941
|
* mime-db
|
|
942
942
|
* Copyright(c) 2014 Jonathan Ong
|
|
@@ -955,7 +955,7 @@ e.exports=i(478)},function(e){e.exports=JSON.parse('{"application/1d-interleaved
|
|
|
955
955
|
* gcs.js - gcs filters for vallnet
|
|
956
956
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
957
957
|
* https://github.com/bookmansoft/gamegold
|
|
958
|
-
*/const r=i(0),a=i(110).U64,s=i(6),n=i(305),o=Buffer.alloc(0),c=new a(-1);function u(){this.n=0,this.p=0,this.m=new a(0),this.data=o}function h(){this.stream=[],this.remain=0}function l(e){this.stream=e,this.pos=0,this.remain=8}function p(e,t){return e.cmp(t)}function d(e,t){var[e,t]=n(e,t);return a.fromBits(e,t)}function f(e,t){for(const i of t.code)i.data&&0!==i.data.length&&e.push(i.data)}u.prototype.hash=function(e){var t=s.hash256(this.data);return"hex"===e?t.toString("hex"):t},u.prototype.header=function(e){return s.root256(this.hash(),e)},u.prototype.match=function(e,t){var i=new l(this.data),r=d(t,e).imod(this.m);let s=new a(0);for(;s.lt(r);){var n=this.readU64(i);if(n===c)return!1;if(n.iadd(s),n.eq(r))return!0;s=n}return!1},u.prototype.matchAny=function(e,t){r(0<t.length);var i=new l(this.data),s=new a(0),n=[];for(const i of t){var o=d(i,e).imod(this.m);n.push(o)}n.sort(p);let u=n[0],h=1;for(;;){var f=s.cmp(u);if(0===f)break;if(0<f){if(h<n.length){u=n[h],h+=1;continue}return!1}if((f=this.readU64(i))===c)return!1;s.iadd(f)}return!0},u.prototype.readU64=function(e){try{return this._readU64(e)}catch(e){if("EOF"===e.message)return c;throw e}},u.prototype._readU64=function(e){for(var t=new a(0);e.readBit();)t.iaddn(1);var i=e.readBits64(this.p);return t.ishln(this.p).ior(i)},u.prototype.toBytes=function(){return this.data},u.prototype.toNBytes=function(){var e=Buffer.allocUnsafe(4+this.data.length);return e.writeUInt32BE(this.n,0,!0),this.data.copy(e,4),e},u.prototype.toPBytes=function(){var e=Buffer.allocUnsafe(1+this.data.length);return e.writeUInt8(this.p,0,!0),this.data.copy(e,1),e},u.prototype.toNPBytes=function(){var e=Buffer.allocUnsafe(5+this.data.length);return e.writeUInt32BE(this.n,0,!0),e.writeUInt8(this.p,4,!0),this.data.copy(e,5),e},u.prototype.toRaw=function(){return r(20===this.p),this.toNBytes()},u.prototype.fromItems=function(e,t,i){r("number"==typeof e&&isFinite(e)),r(0<=e&&e<=32),r(Buffer.isBuffer(t)),r(16===t.length),r(Array.isArray(i)),r(0<i.length),r(i.length<=4294967295),this.n=i.length,this.p=e,this.m=a(this.n).ishln(this.p);var s=[];for(const e of i){r(Buffer.isBuffer(e));var n=d(e,t).imod(this.m);s.push(n)}s.sort(p);var o=new h;let c=new a(0);for(const e of s){var u=e.sub(c).imaskn(this.p),l=e.sub(c).isub(u).ishrn(this.p);for(c=e;!l.isZero();)o.writeBit(1),l.isubn(1);o.writeBit(0),o.writeBits64(u,this.p)}return this.data=o.render(),this},u.prototype.fromBytes=function(e,t,i){return r("number"==typeof e&&isFinite(e)),r("number"==typeof t&&isFinite(t)),r(0<=t&&t<=32),r(Buffer.isBuffer(i)),this.n=e,this.p=t,this.m=a(this.n).ishln(this.p),this.data=i,this},u.prototype.fromNBytes=function(e,t){r("number"==typeof e&&isFinite(e)),r(Buffer.isBuffer(t)),r(4<=t.length);var i=t.readUInt32BE(0,!0);return this.fromBytes(i,e,t.slice(4))},u.prototype.fromPBytes=function(e,t){r("number"==typeof e&&isFinite(e)),r(Buffer.isBuffer(t)),r(1<=t.length);var i=t.readUInt8(0,!0);return this.fromBytes(e,i,t.slice(1))},u.prototype.fromNPBytes=function(e){r(Buffer.isBuffer(e)),r(5<=e.length);var t=e.readUInt32BE(0,!0),i=e.readUInt8(4,!0);return this.fromBytes(t,i,e.slice(5))},u.prototype.fromRaw=function(e){return this.fromNBytes(20,e)},u.prototype.fromBlock=function(e){var t=e.hash().slice(0,16),i=[];for(let t=0;t<e.txs.length;t++){var r=e.txs[t];if(0<t)for(const e of r.inputs)i.push(e.prevout.toRaw());for(const e of r.outputs)f(i,e.script)}return this.fromItems(20,t,i)},u.prototype.fromExtended=function(e){var t=e.hash().slice(0,16),i=[];for(let t=0;t<e.txs.length;t++){var r=e.txs[t];if(i.push(r.hash()),0<t)for(const e of r.inputs){a=void 0;var a=i,s=e.witness;for(const e of s.items)0!==e.length&&a.push(e);f(i,e.script)}}return this.fromItems(20,t,i)},u.fromItems=function(e,t,i){return(new u).fromItems(e,t,i)},u.fromBytes=function(e,t,i){return(new u).fromBytes(e,t,i)},u.fromNBytes=function(e,t){return(new u).fromNBytes(e,t)},u.fromPBytes=function(e,t){return(new u).fromPBytes(e,t)},u.fromNPBytes=function(e){return(new u).fromNPBytes(e)},u.fromRaw=function(e){return(new u).fromRaw(e)},u.fromBlock=function(e){return(new u).fromBlock(e)},u.fromExtended=function(e){return(new u).fromExtended(e)},h.prototype.writeBit=function(e){0===this.remain&&(this.stream.push(0),this.remain=8),e&&(e=this.stream.length-1,this.stream[e]|=1<<this.remain-1),this.remain--},h.prototype.writeByte=function(e){0===this.remain&&(this.stream.push(0),this.remain=8);var t=this.stream.length-1;this.stream[t]|=e>>8-this.remain&255,this.stream.push(0),this.stream[1+t]=e<<this.remain&255},h.prototype.writeBits=function(e,t){for(r(0<=t),r(t<=32),e<<=32-t;8<=t;)this.writeByte(e>>>24),e<<=8,t-=8;for(;0<t;)this.writeBit(e>>>31),e<<=1,--t},h.prototype.writeBits64=function(e,t){r(0<=t),r(t<=64),32<t?(this.writeBits(e.hi,t-32),this.writeBits(e.lo,32)):this.writeBits(e.lo,t)},h.prototype.render=function(){var e=Buffer.allocUnsafe(this.stream.length);for(let t=0;t<this.stream.length;t++)e[t]=this.stream[t];return e},l.prototype.readBit=function(){if(this.pos>=this.stream.length)throw new Error("EOF");if(0===this.remain){if(this.pos+=1,this.pos>=this.stream.length)throw new Error("EOF");this.remain=8}return--this.remain,this.stream[this.pos]>>this.remain&1},l.prototype.readByte=function(){if(this.pos>=this.stream.length)throw new Error("EOF");if(0===this.remain){if(this.pos+=1,this.pos>=this.stream.length)throw new Error("EOF");this.remain=8}if(8===this.remain){const e=this.stream[this.pos];return this.pos+=1,e}let e=this.stream[this.pos]&(1<<this.remain)-1;if(e<<=8-this.remain,this.pos+=1,this.pos>=this.stream.length)throw new Error("EOF");return e|this.stream[this.pos]>>this.remain},l.prototype.readBits=function(e){r(0<=e),r(e<=32);let t=0;for(;8<=e;)t=(t<<=8)|this.readByte(),e-=8;for(;0<e;)t=(t<<=1)|this.readBit(),--e;return t},l.prototype.readBits64=function(e){r(0<=e),r(e<=64);var t=new a;return 32<e?(t.hi=this.readBits(e-32),t.lo=this.readBits(32)):t.lo=this.readBits(e),t},e.exports=u},function(e,t,i){var r={"./ConvertScript":166,"./ConvertScript.js":166,"./checkContract":108,"./checkContract.js":108,"./coinbase":195,"./coinbase.js":195,"./comm":5,"./comm.js":5,"./contractcreate":213,"./contractcreate.js":213,"./contractexecute":214,"./contractexecute.js":214,"./contractpromise":196,"./contractpromise.js":196,"./cpchange":194,"./cpchange.js":194,"./cpregister":192,"./cpregister.js":192,"./electronicright/enchancecp":217,"./electronicright/enchancecp.js":217,"./electronicright/erAbolish":216,"./electronicright/erAbolish.js":216,"./electronicright/erIssue":215,"./electronicright/erIssue.js":215,"./facade":42,"./facade.js":42,"./model/base":81,"./model/base.js":81,"./model/example":205,"./model/example.js":205,"./model/issue":206,"./model/issue.js":206,"./model/multisig":207,"./model/multisig.js":207,"./model/relay":203,"./model/relay.js":203,"./model/selector":152,"./model/selector.js":152,"./model/vem":204,"./model/vem.js":204,"./nesting":188,"./nesting.js":188,"./nesting/attach":190,"./nesting/attach.js":190,"./nesting/comment":
|
|
958
|
+
*/const r=i(0),a=i(110).U64,s=i(6),n=i(305),o=Buffer.alloc(0),c=new a(-1);function u(){this.n=0,this.p=0,this.m=new a(0),this.data=o}function h(){this.stream=[],this.remain=0}function l(e){this.stream=e,this.pos=0,this.remain=8}function p(e,t){return e.cmp(t)}function d(e,t){var[e,t]=n(e,t);return a.fromBits(e,t)}function f(e,t){for(const i of t.code)i.data&&0!==i.data.length&&e.push(i.data)}u.prototype.hash=function(e){var t=s.hash256(this.data);return"hex"===e?t.toString("hex"):t},u.prototype.header=function(e){return s.root256(this.hash(),e)},u.prototype.match=function(e,t){var i=new l(this.data),r=d(t,e).imod(this.m);let s=new a(0);for(;s.lt(r);){var n=this.readU64(i);if(n===c)return!1;if(n.iadd(s),n.eq(r))return!0;s=n}return!1},u.prototype.matchAny=function(e,t){r(0<t.length);var i=new l(this.data),s=new a(0),n=[];for(const i of t){var o=d(i,e).imod(this.m);n.push(o)}n.sort(p);let u=n[0],h=1;for(;;){var f=s.cmp(u);if(0===f)break;if(0<f){if(h<n.length){u=n[h],h+=1;continue}return!1}if((f=this.readU64(i))===c)return!1;s.iadd(f)}return!0},u.prototype.readU64=function(e){try{return this._readU64(e)}catch(e){if("EOF"===e.message)return c;throw e}},u.prototype._readU64=function(e){for(var t=new a(0);e.readBit();)t.iaddn(1);var i=e.readBits64(this.p);return t.ishln(this.p).ior(i)},u.prototype.toBytes=function(){return this.data},u.prototype.toNBytes=function(){var e=Buffer.allocUnsafe(4+this.data.length);return e.writeUInt32BE(this.n,0,!0),this.data.copy(e,4),e},u.prototype.toPBytes=function(){var e=Buffer.allocUnsafe(1+this.data.length);return e.writeUInt8(this.p,0,!0),this.data.copy(e,1),e},u.prototype.toNPBytes=function(){var e=Buffer.allocUnsafe(5+this.data.length);return e.writeUInt32BE(this.n,0,!0),e.writeUInt8(this.p,4,!0),this.data.copy(e,5),e},u.prototype.toRaw=function(){return r(20===this.p),this.toNBytes()},u.prototype.fromItems=function(e,t,i){r("number"==typeof e&&isFinite(e)),r(0<=e&&e<=32),r(Buffer.isBuffer(t)),r(16===t.length),r(Array.isArray(i)),r(0<i.length),r(i.length<=4294967295),this.n=i.length,this.p=e,this.m=a(this.n).ishln(this.p);var s=[];for(const e of i){r(Buffer.isBuffer(e));var n=d(e,t).imod(this.m);s.push(n)}s.sort(p);var o=new h;let c=new a(0);for(const e of s){var u=e.sub(c).imaskn(this.p),l=e.sub(c).isub(u).ishrn(this.p);for(c=e;!l.isZero();)o.writeBit(1),l.isubn(1);o.writeBit(0),o.writeBits64(u,this.p)}return this.data=o.render(),this},u.prototype.fromBytes=function(e,t,i){return r("number"==typeof e&&isFinite(e)),r("number"==typeof t&&isFinite(t)),r(0<=t&&t<=32),r(Buffer.isBuffer(i)),this.n=e,this.p=t,this.m=a(this.n).ishln(this.p),this.data=i,this},u.prototype.fromNBytes=function(e,t){r("number"==typeof e&&isFinite(e)),r(Buffer.isBuffer(t)),r(4<=t.length);var i=t.readUInt32BE(0,!0);return this.fromBytes(i,e,t.slice(4))},u.prototype.fromPBytes=function(e,t){r("number"==typeof e&&isFinite(e)),r(Buffer.isBuffer(t)),r(1<=t.length);var i=t.readUInt8(0,!0);return this.fromBytes(e,i,t.slice(1))},u.prototype.fromNPBytes=function(e){r(Buffer.isBuffer(e)),r(5<=e.length);var t=e.readUInt32BE(0,!0),i=e.readUInt8(4,!0);return this.fromBytes(t,i,e.slice(5))},u.prototype.fromRaw=function(e){return this.fromNBytes(20,e)},u.prototype.fromBlock=function(e){var t=e.hash().slice(0,16),i=[];for(let t=0;t<e.txs.length;t++){var r=e.txs[t];if(0<t)for(const e of r.inputs)i.push(e.prevout.toRaw());for(const e of r.outputs)f(i,e.script)}return this.fromItems(20,t,i)},u.prototype.fromExtended=function(e){var t=e.hash().slice(0,16),i=[];for(let t=0;t<e.txs.length;t++){var r=e.txs[t];if(i.push(r.hash()),0<t)for(const e of r.inputs){a=void 0;var a=i,s=e.witness;for(const e of s.items)0!==e.length&&a.push(e);f(i,e.script)}}return this.fromItems(20,t,i)},u.fromItems=function(e,t,i){return(new u).fromItems(e,t,i)},u.fromBytes=function(e,t,i){return(new u).fromBytes(e,t,i)},u.fromNBytes=function(e,t){return(new u).fromNBytes(e,t)},u.fromPBytes=function(e,t){return(new u).fromPBytes(e,t)},u.fromNPBytes=function(e){return(new u).fromNPBytes(e)},u.fromRaw=function(e){return(new u).fromRaw(e)},u.fromBlock=function(e){return(new u).fromBlock(e)},u.fromExtended=function(e){return(new u).fromExtended(e)},h.prototype.writeBit=function(e){0===this.remain&&(this.stream.push(0),this.remain=8),e&&(e=this.stream.length-1,this.stream[e]|=1<<this.remain-1),this.remain--},h.prototype.writeByte=function(e){0===this.remain&&(this.stream.push(0),this.remain=8);var t=this.stream.length-1;this.stream[t]|=e>>8-this.remain&255,this.stream.push(0),this.stream[1+t]=e<<this.remain&255},h.prototype.writeBits=function(e,t){for(r(0<=t),r(t<=32),e<<=32-t;8<=t;)this.writeByte(e>>>24),e<<=8,t-=8;for(;0<t;)this.writeBit(e>>>31),e<<=1,--t},h.prototype.writeBits64=function(e,t){r(0<=t),r(t<=64),32<t?(this.writeBits(e.hi,t-32),this.writeBits(e.lo,32)):this.writeBits(e.lo,t)},h.prototype.render=function(){var e=Buffer.allocUnsafe(this.stream.length);for(let t=0;t<this.stream.length;t++)e[t]=this.stream[t];return e},l.prototype.readBit=function(){if(this.pos>=this.stream.length)throw new Error("EOF");if(0===this.remain){if(this.pos+=1,this.pos>=this.stream.length)throw new Error("EOF");this.remain=8}return--this.remain,this.stream[this.pos]>>this.remain&1},l.prototype.readByte=function(){if(this.pos>=this.stream.length)throw new Error("EOF");if(0===this.remain){if(this.pos+=1,this.pos>=this.stream.length)throw new Error("EOF");this.remain=8}if(8===this.remain){const e=this.stream[this.pos];return this.pos+=1,e}let e=this.stream[this.pos]&(1<<this.remain)-1;if(e<<=8-this.remain,this.pos+=1,this.pos>=this.stream.length)throw new Error("EOF");return e|this.stream[this.pos]>>this.remain},l.prototype.readBits=function(e){r(0<=e),r(e<=32);let t=0;for(;8<=e;)t=(t<<=8)|this.readByte(),e-=8;for(;0<e;)t=(t<<=1)|this.readBit(),--e;return t},l.prototype.readBits64=function(e){r(0<=e),r(e<=64);var t=new a;return 32<e?(t.hi=this.readBits(e-32),t.lo=this.readBits(32)):t.lo=this.readBits(e),t},e.exports=u},function(e,t,i){var r={"./ConvertScript":166,"./ConvertScript.js":166,"./checkContract":108,"./checkContract.js":108,"./coinbase":195,"./coinbase.js":195,"./comm":5,"./comm.js":5,"./contractcreate":213,"./contractcreate.js":213,"./contractexecute":214,"./contractexecute.js":214,"./contractpromise":196,"./contractpromise.js":196,"./cpchange":194,"./cpchange.js":194,"./cpregister":192,"./cpregister.js":192,"./electronicright/enchancecp":217,"./electronicright/enchancecp.js":217,"./electronicright/erAbolish":216,"./electronicright/erAbolish.js":216,"./electronicright/erIssue":215,"./electronicright/erIssue.js":215,"./facade":42,"./facade.js":42,"./model/base":81,"./model/base.js":81,"./model/example":205,"./model/example.js":205,"./model/issue":206,"./model/issue.js":206,"./model/multisig":207,"./model/multisig.js":207,"./model/relay":203,"./model/relay.js":203,"./model/selector":152,"./model/selector.js":152,"./model/vem":204,"./model/vem.js":204,"./nesting":188,"./nesting.js":188,"./nesting/attach":190,"./nesting/attach.js":190,"./nesting/comment":137,"./nesting/comment.js":137,"./nesting/default":52,"./nesting/default.js":52,"./nesting/htlcassent":136,"./nesting/htlcassent.js":136,"./nesting/htlcsuggest":135,"./nesting/htlcsuggest.js":135,"./nesting/propcreate":189,"./nesting/propcreate.js":189,"./nesting/propexchange":191,"./nesting/propexchange.js":191,"./nesting/selector":117,"./nesting/selector.js":117,"./notify":212,"./notify.js":212,"./plugin":229,"./plugin.js":229,"./propfound":209,"./propfound.js":209,"./propsale":211,"./propsale.js":211,"./scnotify":208,"./scnotify.js":208,"./scregister":199,"./scregister.js":199,"./scrun":202,"./scrun.js":202,"./scstate":201,"./scstate.js":201,"./scupdate":200,"./scupdate.js":200,"./selector":187,"./selector.js":187,"./taskManager":159,"./taskManager.js":159,"./transaction":14,"./transaction.js":14,"./vote":210,"./vote.js":210};function a(e){return e=s(e),i(e)}function s(e){if(i.o(r,e))return r[e];throw(e=new Error("Cannot find module '"+e+"'")).code="MODULE_NOT_FOUND",e}a.keys=function(){return Object.keys(r)},a.resolve=s,(e.exports=a).id=581},function(e,t,i){"use strict";
|
|
959
959
|
/*!
|
|
960
960
|
* contractdb.js - storage for SmartContract account management
|
|
961
961
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|