gamegold 4.2.1 → 4.2.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.
@@ -196,7 +196,7 @@ var i=r(128),s=i.Buffer;function n(e,t){for(var r in e)t[r]=e[r]}function a(e,t,
196
196
  * pkg.js - package constants
197
197
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
198
198
  * https://github.com/bookmansoft/gamegold
199
- */t.protocol="vallnet",t.version="v4.2.1",t.url="https://github.com/bookmansoft/gamegold"},function(e,t,r){"use strict";
199
+ */t.protocol="vallnet",t.version="v4.2.3",t.url="https://github.com/bookmansoft/gamegold"},function(e,t,r){"use strict";
200
200
  /*!
201
201
  * common.js - p2p constants for vallnet
202
202
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -358,7 +358,7 @@ const i=r(21).opcodes;function s(e){let t=null;var r=s.list[e.type];return new(r
358
358
  /*!
359
359
  * layout.js - blockchain data layout for vallnet
360
360
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
361
- */const i=r(0),s={binary:!0,C:function(e,t,r){let s,a=e.length;return i("number"==typeof r),"string"==typeof e&&(a/=2),32===a?((s=Buffer.allocUnsafe(69))[0]=154,n(s,e,1),n(s,t,33),s.writeUInt32BE(r,65,!0)):20===a?((s=Buffer.allocUnsafe(57))[0]=67,n(s,e,1),n(s,t,21),s.writeUInt32BE(r,53,!0)):i(!1),s},Cc:function(e){let t,r;return i(Buffer.isBuffer(e)),69===e.length?(t=e.toString("hex",33,65),r=e.readUInt32BE(65,0)):57===e.length?(t=e.toString("hex",21,53),r=e.readUInt32BE(53,0)):i(!1),[t,r]},CP:function(e,t="ascii"){return e=s.s2b(e,t),(t=Buffer.allocUnsafe(37))[0]=147,n(t,e,1),t},CPc:function(e){let t;return i(Buffer.isBuffer(e)),i.strictEqual(e[0],147),37===e.length?t=e.slice(1,37):i(!1),s.b2s(t)},CV:Buffer.from([118]),EN2:function(e,t,r="ascii"){i("string"==typeof e),i("string"==typeof t);var s=Buffer.allocUnsafe(73);return s[0]=226,s.write(e,1,r),s.write(t,37,r),s},ER:function(e){e=s.s2b(e,"hex");var t=Buffer.allocUnsafe(33);return t[0]=152,n(t,e,1),t},ERR:function(e,t,r){return i("string"==typeof e),i("string"==typeof t),i("string"==typeof r),(r=Buffer.allocUnsafe(98))[0]=217,r.write(e,1,"hex"),r.write(t,34,"hex"),r.write(t,66,"hex"),r},ERRR:function(e){return i(Buffer.isBuffer(e)),[(e=e.slice(1)).toString("hex",0,33),e.toString("hex",33,65),e.toString("hex",65,97)]},ERA:function(e){i("string"==typeof e);var t=Buffer.allocUnsafe(33);return t[0]=216,t.write(e,1,"hex"),t},H:function(e){return o(72,e)},HL:Buffer.from([148]),O:Buffer.from([79]),R:Buffer.from([82]),SC:function(e,t="ascii"){return e=s.s2b(e,t),(t=Buffer.allocUnsafe(37))[0]=150,n(t,e,1),t},SR:function(e,t,r,a,o,c){var u=Buffer.allocUnsafe(117);return u.fill(0),Buffer.isBuffer(t)||(i("string"==typeof t),t=s.s2b(t)),u[0]=165,u.writeUInt32BE(e,1,!0),n(u,t,5),u.writeUInt32BE(r,41,!0),n(u,a,45),u.writeUInt32BE(o,109,!0),u.writeUInt32BE(c,113,!0),u},SRR:function(e){return i(Buffer.isBuffer(e)),[(e=e.slice(1)).readUInt32BE(0,!0),e.toString("ascii",4,40),e.readUInt32BE(40,!0),e.toString("hex",44,108),e.readUInt32BE(109,!0),e.readUInt32BE(109,!0)]},SN:function(e,t){var r=Buffer.allocUnsafe(37+t.length);return r.fill(0),Buffer.isBuffer(e)||(i("string"==typeof e),e=s.s2b(e)),r[0]=161,n(r,e,1),n(r,t,37),r},SNN:function(e){return i(Buffer.isBuffer(e)),[(e=e.slice(1)).toString("ascii",0,36),e.toString("hex",36,e.length)]},SS:function(e,t){var r=Buffer.allocUnsafe(41);return r.fill(0),Buffer.isBuffer(e)||(i("string"==typeof e),e=s.s2b(e)),r[0]=167,n(r,e,1),r.writeUInt32BE(t,37,!0),r},SSS:function(e){return i(Buffer.isBuffer(e)),i.strictEqual(e[0],167),[(e=e.slice(1)).toString("ascii",0,36),e.readUInt32BE(36,!0)]},T:function(e,t){let r,s=e.length;return"string"==typeof e&&(s/=2),32===s?((r=Buffer.allocUnsafe(65))[0]=171,n(r,e,1),n(r,t,33)):20===s?((r=Buffer.allocUnsafe(53))[0]=84,n(r,e,1),n(r,t,21)):i(!1),r},TI:function(e,t){let r,s=e.length;return"string"==typeof e&&(s/=2),32===s?((r=Buffer.allocUnsafe(65))[0]=244,n(r,e,1),n(r,t,33)):20===s?((r=Buffer.allocUnsafe(53))[0]=157,n(r,e,1),n(r,t,21)):i(!1),r},TO:function(e,t){let r,s=e.length;return"string"==typeof e&&(s/=2),32===s?((r=Buffer.allocUnsafe(65))[0]=250,n(r,e,1),n(r,t,33)):20===s?((r=Buffer.allocUnsafe(53))[0]=163,n(r,e,1),n(r,t,21)):i(!1),r},Tt:function(e){return i(Buffer.isBuffer(e)),65===e.length?e.toString("hex",33,65):(i(53===e.length),e.toString("hex",21,53))},V:Buffer.from([86]),VM:function(e){return o(164,e)},VO:function(e){return o(162,e)},VP:function(e,t="utf8"){return e=s.s2b(e,t),(t=Buffer.allocUnsafe(37))[0]=166,n(t,e,1),t},VPc:function(e){let t;return i(Buffer.isBuffer(e)),i.strictEqual(e[0],166),37===e.length?t=e.slice(1,37):i(!1),s.b2s(t)},VH:function(e,t){return this.hi(158,e,t)},b:function(e){return a(98,e)},c:function(e,t){return 99,e=e,t=t,r=Buffer.allocUnsafe(37),i("number"==typeof t),r[0]=99,n(r,e,1),r.writeUInt32BE(t,33,!0),r;var r},e:function(e){return a(101,e)},g:function(e){i("string"==typeof e);var t=Buffer.allocUnsafe(1+e.length/2);return t[0]=103,t.write(e,1,"hex"),t},gs:function(e,t,r){i("string"==typeof e),i("string"==typeof t),i("string"==typeof r);var s=Buffer.allocUnsafe(77);return s[0]=218,s.write(e,1,"hex"),s.write(t,21,"hex"),s.write(r,57,"hex"),s},h:function(e){return a(104,e)},hi:function(e,t,r){i("string"==typeof t),i("number"==typeof r);var s=Buffer.allocUnsafe(37);return s[0]=e,s.write(t,1,"hex"),s.writeUInt32BE(r,33,!0),s},hii:function(e){return i(Buffer.isBuffer(e)),i(37===e.length),[(e=e.slice(1)).toString("hex",0,32),e.readUInt32BE(32,!0)]},n:function(e){return a(110,e)},o:function(e,t){i("string"==typeof e),i("string"==typeof t);var r=Buffer.allocUnsafe(73);return r.fill(0),r[0]=111,r.write(e,1,"ascii"),r.write(t,37,"ascii"),r},oo:function(e){return i(Buffer.isBuffer(e)),i(73===e.length),[e.toString("ascii",1,37),e.toString("ascii",38,73)]},p:function(e){return a(112,e)},pp:function(e){return i(Buffer.isBuffer(e)),i(33===e.length),e.toString("hex",1,33)},s:function(e,t){return this.hi(115,e,t)},ss:function(e){return this.hii(e)},t:function(e){return a(116,e)},th:function(e,t){i("number"==typeof e);var r=Buffer.allocUnsafe(37);return r.fill(0),r[0]=220,r.writeUInt32BE(e,1,!0),n(r,t,5),r},thh:function(e){return i(Buffer.isBuffer(e)),i(220==e[0]),{time:e.readUInt32BE(1,!0),hash:e.slice(5,37).toString("hex")}},tx:function(e){return Buffer.concat([Buffer.from([236]),Buffer.from(e,"hex")])},u:function(e){return a(117,e)},v:function(e,t){var r=Buffer.allocUnsafe(34);return i("number"==typeof e),r[0]=118,r[1]=e,n(r,t,2),r},vv:function(e){return i(Buffer.isBuffer(e)),i(34===e.length),[e[1],e.toString("hex",2,34)]},version:function(e){var t=Buffer.allocUnsafe(4);return t.writeUInt32LE(e,0,!0),t},equalVersion:function(e,t){return i(Buffer.isBuffer(e)),e.readUInt32LE(0,!0)==t},s2b:function(e,t="ascii"){return Buffer.from(e,t)},b2s:(e,t="ascii")=>(i(Buffer.isBuffer(e)),e.toString(t))};function n(e,t,r){if(Buffer.isBuffer(t))return t.copy(e,r);i("string"==typeof t),e.write(t,r,"hex")}function a(e,t){var r=Buffer.allocUnsafe(33);return r[0]=e,n(r,t,1),r}function o(e,t){var r=Buffer.allocUnsafe(5);return i("number"==typeof t),r[0]=e,r.writeUInt32BE(t,1,!0),r}e.exports=s},function(e,t){e.exports=require("tls")},function(e,t,r){"use strict";
361
+ */const i=r(0),s={binary:!0,C:function(e,t,r){let s,a=e.length;return i("number"==typeof r),"string"==typeof e&&(a/=2),32===a?((s=Buffer.allocUnsafe(69))[0]=154,n(s,e,1),n(s,t,33),s.writeUInt32BE(r,65,!0)):20===a?((s=Buffer.allocUnsafe(57))[0]=67,n(s,e,1),n(s,t,21),s.writeUInt32BE(r,53,!0)):i(!1),s},Cc:function(e){let t,r;return i(Buffer.isBuffer(e)),69===e.length?(t=e.toString("hex",33,65),r=e.readUInt32BE(65,0)):57===e.length?(t=e.toString("hex",21,53),r=e.readUInt32BE(53,0)):i(!1),[t,r]},CP:function(e,t="ascii"){return e=s.s2b(e,t),(t=Buffer.allocUnsafe(37))[0]=147,n(t,e,1),t},CPc:function(e){let t;return i(Buffer.isBuffer(e)),i.strictEqual(e[0],147),37===e.length?t=e.slice(1,37):i(!1),s.b2s(t)},CV:Buffer.from([118]),EN2:function(e,t,r="ascii"){i("string"==typeof e),i("string"==typeof t);var s=Buffer.allocUnsafe(73);return s[0]=226,s.write(e,1,r),s.write(t,37,r),s},ER:function(e){e=s.s2b(e,"hex");var t=Buffer.allocUnsafe(33);return t[0]=152,n(t,e,1),t},ERR:function(e,t,r){i("string"==typeof e),i("string"==typeof t),i("string"==typeof r);var s=Buffer.allocUnsafe(98);return s[0]=217,s.write(e,1,"hex"),s.write(t,34,"hex"),s.write(r,66,"hex"),s},ERRR:function(e){return i(Buffer.isBuffer(e)),[(e=e.slice(1)).toString("hex",0,33),e.toString("hex",33,65),e.toString("hex",65,97)]},ERA:function(e){i("string"==typeof e);var t=Buffer.allocUnsafe(33);return t[0]=216,t.write(e,1,"hex"),t},H:function(e){return o(72,e)},HL:Buffer.from([148]),O:Buffer.from([79]),R:Buffer.from([82]),SC:function(e,t="ascii"){return e=s.s2b(e,t),(t=Buffer.allocUnsafe(37))[0]=150,n(t,e,1),t},SR:function(e,t,r,a,o,c){var u=Buffer.allocUnsafe(117);return u.fill(0),Buffer.isBuffer(t)||(i("string"==typeof t),t=s.s2b(t)),u[0]=165,u.writeUInt32BE(e,1,!0),n(u,t,5),u.writeUInt32BE(r,41,!0),n(u,a,45),u.writeUInt32BE(o,109,!0),u.writeUInt32BE(c,113,!0),u},SRR:function(e){return i(Buffer.isBuffer(e)),[(e=e.slice(1)).readUInt32BE(0,!0),e.toString("ascii",4,40),e.readUInt32BE(40,!0),e.toString("hex",44,108),e.readUInt32BE(109,!0),e.readUInt32BE(109,!0)]},SN:function(e,t){var r=Buffer.allocUnsafe(37+t.length);return r.fill(0),Buffer.isBuffer(e)||(i("string"==typeof e),e=s.s2b(e)),r[0]=161,n(r,e,1),n(r,t,37),r},SNN:function(e){return i(Buffer.isBuffer(e)),[(e=e.slice(1)).toString("ascii",0,36),e.toString("hex",36,e.length)]},SS:function(e,t){var r=Buffer.allocUnsafe(41);return r.fill(0),Buffer.isBuffer(e)||(i("string"==typeof e),e=s.s2b(e)),r[0]=167,n(r,e,1),r.writeUInt32BE(t,37,!0),r},SSS:function(e){return i(Buffer.isBuffer(e)),i.strictEqual(e[0],167),[(e=e.slice(1)).toString("ascii",0,36),e.readUInt32BE(36,!0)]},T:function(e,t){let r,s=e.length;return"string"==typeof e&&(s/=2),32===s?((r=Buffer.allocUnsafe(65))[0]=171,n(r,e,1),n(r,t,33)):20===s?((r=Buffer.allocUnsafe(53))[0]=84,n(r,e,1),n(r,t,21)):i(!1),r},TI:function(e,t){let r,s=e.length;return"string"==typeof e&&(s/=2),32===s?((r=Buffer.allocUnsafe(65))[0]=244,n(r,e,1),n(r,t,33)):20===s?((r=Buffer.allocUnsafe(53))[0]=157,n(r,e,1),n(r,t,21)):i(!1),r},TO:function(e,t){let r,s=e.length;return"string"==typeof e&&(s/=2),32===s?((r=Buffer.allocUnsafe(65))[0]=250,n(r,e,1),n(r,t,33)):20===s?((r=Buffer.allocUnsafe(53))[0]=163,n(r,e,1),n(r,t,21)):i(!1),r},Tt:function(e){return i(Buffer.isBuffer(e)),65===e.length?e.toString("hex",33,65):(i(53===e.length),e.toString("hex",21,53))},V:Buffer.from([86]),VM:function(e){return o(164,e)},VO:function(e){return o(162,e)},VP:function(e,t="utf8"){return e=s.s2b(e,t),(t=Buffer.allocUnsafe(37))[0]=166,n(t,e,1),t},VPc:function(e){let t;return i(Buffer.isBuffer(e)),i.strictEqual(e[0],166),37===e.length?t=e.slice(1,37):i(!1),s.b2s(t)},VH:function(e,t){return this.hi(158,e,t)},b:function(e){return a(98,e)},c:function(e,t){return 99,e=e,t=t,r=Buffer.allocUnsafe(37),i("number"==typeof t),r[0]=99,n(r,e,1),r.writeUInt32BE(t,33,!0),r;var r},e:function(e){return a(101,e)},g:function(e){i("string"==typeof e);var t=Buffer.allocUnsafe(1+e.length/2);return t[0]=103,t.write(e,1,"hex"),t},gs:function(e,t,r){i("string"==typeof e),i("string"==typeof t),i("string"==typeof r);var s=Buffer.allocUnsafe(77);return s[0]=218,s.write(e,1,"hex"),s.write(t,21,"hex"),s.write(r,57,"hex"),s},h:function(e){return a(104,e)},hi:function(e,t,r){i("string"==typeof t),i("number"==typeof r);var s=Buffer.allocUnsafe(37);return s[0]=e,s.write(t,1,"hex"),s.writeUInt32BE(r,33,!0),s},hii:function(e){return i(Buffer.isBuffer(e)),i(37===e.length),[(e=e.slice(1)).toString("hex",0,32),e.readUInt32BE(32,!0)]},n:function(e){return a(110,e)},o:function(e,t){i("string"==typeof e),i("string"==typeof t);var r=Buffer.allocUnsafe(73);return r.fill(0),r[0]=111,r.write(e,1,"ascii"),r.write(t,37,"ascii"),r},oo:function(e){return i(Buffer.isBuffer(e)),i(73===e.length),[e.toString("ascii",1,37),e.toString("ascii",38,73)]},p:function(e){return a(112,e)},pp:function(e){return i(Buffer.isBuffer(e)),i(33===e.length),e.toString("hex",1,33)},s:function(e,t){return this.hi(115,e,t)},ss:function(e){return this.hii(e)},t:function(e){return a(116,e)},th:function(e,t){i("number"==typeof e);var r=Buffer.allocUnsafe(37);return r.fill(0),r[0]=220,r.writeUInt32BE(e,1,!0),n(r,t,5),r},thh:function(e){return i(Buffer.isBuffer(e)),i(220==e[0]),{time:e.readUInt32BE(1,!0),hash:e.slice(5,37).toString("hex")}},tx:function(e){return Buffer.concat([Buffer.from([236]),Buffer.from(e,"hex")])},u:function(e){return a(117,e)},v:function(e,t){var r=Buffer.allocUnsafe(34);return i("number"==typeof e),r[0]=118,r[1]=e,n(r,t,2),r},vv:function(e){return i(Buffer.isBuffer(e)),i(34===e.length),[e[1],e.toString("hex",2,34)]},version:function(e){var t=Buffer.allocUnsafe(4);return t.writeUInt32LE(e,0,!0),t},equalVersion:function(e,t){return i(Buffer.isBuffer(e)),e.readUInt32LE(0,!0)==t},s2b:function(e,t="ascii"){return Buffer.from(e,t)},b2s:(e,t="ascii")=>(i(Buffer.isBuffer(e)),e.toString(t))};function n(e,t,r){if(Buffer.isBuffer(t))return t.copy(e,r);i("string"==typeof t),e.write(t,r,"hex")}function a(e,t){var r=Buffer.allocUnsafe(33);return r[0]=e,n(r,t,1),r}function o(e,t){var r=Buffer.allocUnsafe(5);return i("number"==typeof t),r[0]=e,r.writeUInt32BE(t,1,!0),r}e.exports=s},function(e,t){e.exports=require("tls")},function(e,t,r){"use strict";
362
362
  /*!
363
363
  * general.js - bitcoin constants for vallnet
364
364
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -838,7 +838,7 @@ const i=r(5).ContractType;e.exports=function(e){if(!e)return r(190);switch(e.ope
838
838
  /*!
839
839
  * accountdb.js - storage for account management
840
840
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
841
- */const i=r(8),s=r(0),n=r(73),a=r(122),o=r(159),c=r(612),u=r(95),h=u.walletdb,l=r(7),p=r(160),d=r(127),f=r(169),m=r(6),g=r(37).VerifyError,y=r(46),v=r(12);r(19);const b=r(60),w=r(198),x=r(69),k=r(43),{getVerifyMsg:S,BlockFinalType:E,ContractEnvType:_}=r(5),A=r(161),R=r(614),I=r(31);var j=r(72);const C=r(1),P=r(119).sortWithSeq,O=r(34),T=r(199),F=r(65),B=r(101),N=r(3),D=N.U32,L=r(341),H=r(342),z=r(343),M=z.vpItem,U=r(616),q=U.vpItem,V=r(85),K=r(617),W=V.cpItem,G=V.stockItem,$=r(158),Y=$.ErAbolishItem,X=r(36).broadcast,J=r(134),Z=J.vpItem,Q=r(232),ee=Q.stockAccount,te=r(157),re=te.ErItem,ie=r(618),se=ie.AuditItem,ne=r(315),ae=r(110),oe=r(619),ce=r(316),ue=r(123),he=r(620),le=r(222),pe=r(39),de=r(35),fe=r(59),me=r(78).errors,ge=r(77);class ye extends j{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:N.DefaultChainCode},e.keys&&e.keys.hmacSalt&&(s(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 L(this),this.primary=null,this.state=new oe,this.wallets=new Map,this.depth=0,this.rescanning=!1,this.bound=!1,this.newRecord=!0,this.readLock=new T,this.writeLock=new O,this.txLock=new O,this.scanLock=new O,this.widCache=new F(1e4),this.pathMapCache=new F(1e5),this.filter=new B,this.middleHashMem=new Set,this.middleHashChain=new Set,this.autoTaskMgr=new A(this),this.transactionList=new H(this),this.htlcList=new z(this),this.commentList=new U(this),this.NotifyList=new I,this.propList=new J(this),this.accountList=new Q(this),this.$contacts=new I,this.cpList=new V(this),this.cpMemList=new V(this),this.accountCoinList=new K(this),this.auditList=new ie(this),this.erList=new te(this),this.erAbList=new $(this),this.hmacConnection=[],this._init()}async logAudit(e){e.height=this.curHeight,e.time=C.now(),e.erid=l.sha256(C.stringify(e)).toString("hex"),e=new se(e),await this.auditList.setAudit(e)}async getAccountByAddress(e,t){if(e){let s=null;if(s=t?await this.getWalletsByTX(t):await this.getWallets())for(const t of s){var r=await this.get(t);if(r){var i=await r.getPath(e);if(i)return[r.wid,i.name,r.id]}}}return[0,"",""]}_init(){let e=1e6,t=-1;this.spv&&(e=2e4,t=B.flags.ALL),this.filter=B.fromRate(e,.001,t)}async getCpSnap(){return{}}get mode(){return _.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 w(e),{code:0}}catch(e){return{code:-1,msg:e.message}}}async getContracts(e){var t=await this.db.values({gte:u.txdb.tx(N.NULL_HASH),lte:u.txdb.tx(N.HIGH_HASH),parse:e=>C.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 r=e.body.content;if("string"==typeof r)try{r=JSON.parse(e.body.content)}catch(e){return}"object"==typeof r&&"secret"===r.type&&(t={contact:e.body.src,messenger:e.body.dst},r.init&&(t.init=Buffer.from(r.init,"hex")),r.packet&&(t.packet=Buffer.from(r.packet)),await this.handleSecret(t))}}async handleSecret(e){if(e.contact&&e.messenger&&e.contact!=e.messenger){try{v.fromString(e.contact,this.network.type),v.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 r=async e=>{var t;e.witness&&"witnesspubkeyhash"==e.getType()&&(t=e.witness.getPubkeyhashInput()[1],e=v.fromWitness(e.witness).toString(),t)&&e&&await this.ensureContact({contact:e,publicKey:t})};if(0<=t&&t<e.inputs.length)await r(e.inputs[t]);else for(var i of e.inputs)await r(i)}async ensureContact(e){if(!e.contact||e.contact==e.messenger)return null;try{v.fromString(e.contact,this.network.type),e.messenger&&v.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 R(e));var t=this.$contacts.get(e.contact);if(e.messenger&&!(e=t.ensureMessenger(e)).wallet){var r,[r,i]=await this.getAccountByAddress(e.address);if(!(r=await this.get(r)))return;e.wallet=r,e.account=i}return t}getCps(){return this.db.values({gte:u.txdb.cp(N.ZERO_CID,"hex"),lte:u.txdb.cp(N.MAX_CID,"hex"),parse:e=>W.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}),r=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{r()}setTimeout(()=>{this.resend()},5e3)}}bind(){!this.client||this.bound||(this.bound=!0,this.client.hook("htlcassent.cancel",e=>{this.setAssent(e),this.emit("htlcassent.cancel",e)}),this.client.hook("htlcassent.deal",e=>{this.setAssent(e),this.emit("htlcassent.deal",e)}),this.client.hook("htlcassent.receive",e=>{this.setAssent(e),this.emit("htlcassent.receive",e)}),this.client.hook("htlcsuggest.cancel",e=>{this.setSuggest(e),this.emit("htlcsuggest.cancel",e)}),this.client.hook("htlcsuggest.deal",e=>{this.setSuggest(e),this.emit("htlcsuggest.deal",e)}),this.client.hook("htlcsuggest.receive",e=>{this.setSuggest(e),this.emit("htlcsuggest.receive",e)}),this.on("mssendpubk/receive",async e=>{let t=await this.get(e.addr);var r,i,s;if(!t&&(t=await this.ensure({id:e.addr,type:"multisig",m:e.m,n:e.n,witness:!0}),[s,i]=await this.getAccountByAddress(e.addr),s=await this.get(s))&&await s.send({subtractFee:!1,sort:!1,outputs:[{address:e.contract,value:1e4}],comment:JSON.stringify({oper:"scrun",params:{oper:"pubk",addr:e.addr,puba:t.account.accountKey}})},i),t.account.keys.length<t.account.n-1){for(r of e.data.split(","))try{await t.addSharedKey(r)}catch(e){}t.account.keys.length==t.account.n-1&&([s,i]=await this.getAccountByAddress(e.addr),s=await this.get(s))&&await s.send({subtractFee:!1,sort:!1,outputs:[{address:e.contract,value:1e4}],comment:JSON.stringify({oper:"scrun",params:{oper:"puba",addr:e.addr,puba:t.account.receive.getAddress().toString()}})},i)}}),this.on("mssendtx/receive",async e=>{var t,r=await this.get(e.addr);r&&r.account.type==o.types.MULTISIG&&((t=b.fromRaw(e.data,"hex")).view=await r.getCoinView(t),t.isSigned()||(e.txid=t.txid(),await this.saveMSTrans(e)))}),this.client.hook("onConnect",async()=>{await this.load()}),this.client.hook("error",e=>{this.emit("error",e)}),this.client.hook("block.connect",async(e,t)=>{try{await this.addBlock(e,t)}catch(e){this.emit("error",e)}}),this.client.hook("block.disconnect",async(e,t)=>{try{await this.removeBlock(e,t)}catch(e){this.emit("error",e)}}),this.client.hook("chain.full",()=>{this.synced=!0}),this.client.hook("block.rescan",async(e,t)=>{try{await this.rescanBlock(e,t)}catch(e){this.emit("error",e)}}),this.client.on("tx",async(e,t,r)=>{try{await this.addTX(e,null,r)}catch(e){this.emit("error",e)}}),this.client.on("entry.remove",async(e,t)=>{try{if(t){var r=e.tx.hash("hex"),i=await this.getWalletsByTX(e.tx);if(i)for(const t of i){var n=await this.get(t);s(n),await n.remove(r),(await k.FactoryOfContract({tx:e.tx,env:this})).erase()}}}catch(e){this.emit("error",e)}}),this.client.hook("chain.reset",async e=>{try{await this.resetChain(e)}catch(e){this.emit("error",e)}}),this.jsonp&&this.jsonp.hook("error",e=>{this.emit("error",e)}))}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(N.NULL_HASH),lte:h.p(N.HIGH_HASH)}),t=0,r=0;for(;;){var i=await e.next();if(!i)break;try{var s=h.pp(i.key);this.filter.add(s,"hex")}catch(t){throw await e.end(),t}t++}for(e=this.db.iterator({gte:h.o(N.NULL_HASH,0),lte:h.o(N.HIGH_HASH,4294967295)});;){var n=await e.next();if(!n)break;try{var[a,o]=h.oo(n.key),c=new y(a,o).toRaw();this.filter.add(c)}catch(t){throw await e.end(),t}r++}this.logger.info("Filter: Added %d hashes to AccountDB filter.",t),this.logger.info("Filter: Added %d outpoints to AccountDB filter.",r),await this.setFilter()}async sync(){if(this.client){let t,r=this.curHeight;for(;0<=r;){var e=await this.getBlock(r);if(!e)break;if(t=await this.client.getEntry(e.hash))break;r--}t||(r=this.state.startHeight,t=await this.client.getEntry(this.state.startHash))||(r=0),await this.cpList.loadHistory(),await this.cpMemList.loadHistory(),await this.propList.loadHistory(),await this.htlcList.loadHistory(),await this.commentList.loadHistory(),await this.accountList.loadHistory(),await this.transactionList.loadHistory(),await this.loadContact(),await this.erList.loadHistory(),await this.auditList.loadHistory(),await this.erAbList.loadHistory(),await this.accountCoinList.loadHistory(),await this.scan(r,!1)}}async scan(e,t=!0){if(this.client){null==e&&(e=this.state.startHeight),s(e>>>0===e,"WDB: Must pass in a height.");var r=this.curHeight;t=(await this.rollback(e,t),this.logger.info("AccountDB is scanning %d blocks.",r-e+1),await this.getTip());try{this.rescanning=!0,await this.client.rescan(t.hash)}finally{this.rescanning=!1}}}async rescan(e){var t=await this.txLock.lock();try{return await this.scan(e,!1)}finally{t()}}async send(e){if(this.client)return this.client.send(e);this.emit("send",e)}async getTX(e){for(const r of this.wallets.values()){var t=await r.getTX(e);if(t)return t.tx}return null}async getTXFromDb(e){for(const r of this.wallets.values()){var t=await r.getTX(e);if(t)return t.tx}return null}async getExtendTX(e){for(const r of this.wallets.values()){var t=await r.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())}addFilter(e){return this.client?this.client.addFilter(e):(this.emit("filter.add",e),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 r=0;for(;;){var i=await e.next();if(!i)break;try{switch(i.key[0]){case 98:case 99:case 101:case 116:case 111:case 104:case 82:t.del(i.key),r++}}catch(t){throw await e.end(),t}}this.logger.warning("Wiped %d txdb records.",r),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 s(!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 s(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){return this.filter.add(e,"hex"),this.addFilter(e)}addOutpoint(e,t){e=new y(e,t),this.filter.add(e.toRaw())}dump(){return this.db.dump()}register(e){s(!this.wallets.has(e.wid)),this.wallets.set(e.wid,e)}unregister(e){s(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=a.fromRaw(this,t)).open(),this.register(e),e):null)}async loadBackup(e){if(fe.unsupported)throw new ge(me.INTERNAL_ERROR,"FS not available.");let t=await this.get("primary");var r;for(r of(await fe.readFile(e,"utf8")).split(/\n+/))if(0!==(r=r.trim()).length&&!/^\s*#/.test(r)){var i=r.split(/\s+/);if(i.length<4)throw new ge(me.DESERIALIZATION_ERROR,"Malformed wallet Data File.");switch(i[0]){case"W":var n=Buffer.from(i[1],"base64");n=a.fromRaw(t.db,n);if(t.wid!=n.wid)throw new ge(me.DESERIALIZATION_ERROR,"Malformed wallet Key");await this.replace(n),t=await this.get("primary"),this.logger.info("Import Wallet %s(%s)",t.id,t.wid);break;case"C":n=Buffer.from(i[1],"base64");(c=((u=o.fromRaw(t.db,n)).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")&&s(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=parseInt(i[5]),u=parseInt(i[7]),h=parseInt(i[9]),l=i[11].trim(),p=await t.deriveKey(c,u,h),d=await t.deriveKey(c,u,h,t.master);p.getAddress("string")!==d.getAddress("string")&&s(p.getAddress("string")==d.getAddress("string")),p.getAddress("string")!==l&&s(p.getAddress("string")==l),this.logger.info("Import Address %s %s %s %s",c,u,h,p.getAddress("string"))}}return t.accountCache.reset(),t}save(e){var t=e.wid,r=e.id,i=this.batch(e);this.widCache.set(r,t),i.put(h.w(t),e.toRaw()),i.put(h.l(r),D(t))}async rename(e,t){var r=await this.writeLock.lock();try{return await this._rename(e,t)}finally{r()}}async _rename(e,t){var r=e.id;if(!n.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(r)),e.id=t,this.save(e),await this.commit(e),this.widCache.remove(r),r=e.pathCache.values();for(const e of r)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 r=e.wallet;this.batch(r).del(h.i(e.wid,e.name)),e.name=t,this.saveAccount(e)}async auth(e,t){if("string"==typeof t){if(!C.isHex256(t))throw new Error("WDB Authentication: Invalid Token.");t=Buffer.from(t,"hex")}e=x.getHmac(e.toString(),this.keys.hmacSalt);var r=i.createHmac("sha256",e.random);r=Buffer.from(r.update(e.token).digest("hex"),"hex");if(!p(t,r))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=a.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 getAccountIndex(e,t){return(e=await this.db.get(h.i(e,t)))?e.readUInt32LE(0,!0):-1}async getGuider(e){return e=v.fromString(e,this.network.type).getHash("hex"),(e=await this.db.get(h.g(e)))?v.fromRaw(e).toString():null}async setGuider(e,t,r){var i;r=v.fromString(r,this.network.type).getHash("hex"),await this.db.has(h.g(r))||(e=v.fromString(e,this.network.type),(i=this.db.batch()).put(h.g(r),e.toRaw()),i.put(h.gs(e.getHash("hex"),Buffer.from(t,"ascii").toString("hex"),r),null),await i.write())}async unsetGuider(e,t,r){e=v.fromString(e,this.network.type).getHash("hex"),r=v.fromString(r,this.network.type).getHash("hex");var i=this.db.batch();i.del(h.g(r)),i.del(h.gs(e,Buffer.from(t,"ascii").toString("hex"),r)),await i.write()}async getAccountName(e,t){return(e=await this.db.get(h.n(e,t)))?e.toString("ascii"):null}saveAccount(e){var t=e.wid,r=e.wallet,i=e.accountIndex,s=e.name,n=this.batch(r);n.put(h.a(t,i),e.toRaw()),n.put(h.i(t,s),D(i)),n.put(h.n(t,i),Buffer.from(s,"ascii")),r.accountCache.push(i,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=he.fromRaw(e,t),this.pathMapCache.set(e,t),t):null)}saveKey(e,t){return this.savePath(e,t.toPath())}async savePath(e,t){var r=e.wid,i=t.hash,s=this.batch(e);await this.addHash(i);let n=await this.getPathMap(i);(n=n||new he(i)).add(r)&&(this.pathMapCache.set(i,n),e.pathCache.push(i,t),s.put(h.p(i),n.toRaw()),s.put(h.P(r,i),t.toRaw()),s.put(h.r(r,t.account,i),null))}async getPath(e,t){var r=await this.db.get(h.P(e,t));return r?((r=ae.fromRaw(r)).wid=e,r.hash=t,r):null}hasPath(e,t){return this.db.has(h.P(e,t))}getHashes(){return this.db.keys({gte:h.p(N.NULL_HASH),lte:h.p(N.HIGH_HASH),parse:h.pp})}getOutpoints(){return this.db.keys({gte:h.o(N.NULL_HASH,0),lte:h.o(N.HIGH_HASH,4294967295),parse:e=>{var[e,t]=h.oo(e);return new y(e,t)}})}getWalletHashes(e){return this.db.keys({gte:h.P(e,N.NULL_HASH),lte:h.P(e,N.HIGH_HASH),parse:h.Pp})}getAccountHashes(e,t){return this.db.keys({gte:h.r(e,t,N.NULL_HASH),lte:h.r(e,t,N.HIGH_HASH),parse:h.rr})}async getWalletPaths(e){var t=[];for(const s of await this.db.range({gte:h.P(e,N.NULL_HASH),lte:h.P(e,N.HIGH_HASH)})){var r=h.Pp(s.key),i=ae.fromRaw(s.value);i.hash=r,i.wid=e,t.push(i)}return t}async encryptKeys(e,t){var r,i,n=e.wid,a=await e.getPaths(),o=this.batch(e);for(r of a)r.data&&(s(!r.encrypted),i=Buffer.from(r.hash,"hex").slice(0,16),(r=r.clone()).data=d.encipher(r.data,t,i),r.encrypted=!0,e.pathCache.push(r.hash,r),o.put(h.P(n,r.hash),r.toRaw()))}async decryptKeys(e,t){var r,i,n=e.wid,a=await e.getPaths(),o=this.batch(e);for(r of a)r.data&&(s(r.encrypted),i=Buffer.from(r.hash,"hex").slice(0,16),(r=r.clone()).data=d.decipher(r.data,t,i),r.encrypted=!1,e.pathCache.push(r.hash,r),o.put(h.P(n,r.hash),r.toRaw()))}async resend(){var e,t={};for(const e of await this.db.keys({gte:h.w(0),lte:h.w(4294967295)})){var r,i=h.ww(e);i&&(r=await this.resendPending(i))&&Array.isArray(r)&&(t[i]=r)}for(e of Object.keys(t)){var s=await this.get(parseInt(e));if(s)for(const r of t[e]){try{await this.send(r)}catch(e){this.logger.warning("wdb resend:",e.message);try{await s.abandon(r.hash("hex"))}catch(e){this.logger.warning("wdb abandon:",e.message)}}await de.timeout(50)}}}async resendPending(e){var t=await this.get(e),r=await this.db.keys({gte:u.txdb.prefix(e,u.txdb.p(N.NULL_HASH)),lte:u.txdb.prefix(e,u.txdb.p(N.HIGH_HASH))});if(0!==r.length){this.logger.info("Rebroadcasting %d transactions for %d.",r.length,e);var i=[];for(const o of r){var s=u.txdb.pp(o),n=u.txdb.prefix(e,u.txdb.t(s));if((n=await this.db.get(n))&&!(n=le.fromRaw(n)).tx.isCoinbase())try{var a=await k.FactoryOfContract({tx:n.tx,env:this});await a.isBlockFinal()==E.Expired?t&&(await this.removeTX(n.tx),await t.remove(s),await a.erase()):"notify"!=a.oper&&i.push(n.tx)}catch(e){this.logger.error("TX(%s) Smart Contract Error: %s",n.tx.txid(),e.message)}}return await P(i,this)}}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 i of e.inputs){var r=i.prevout;if(this.testFilter(r.toRaw())&&(r=await this.getOutpointMap(r.hash,r.index)))for(const e of r.wids)t.add(e)}for(const r of e.getOutputHashes("hex"))if(this.testFilter(r)){var i=await this.getPathMap(r);if(i)for(const e of i.wids)t.add(e)}return 0===t.size?null:t}async getState(){var e=await this.db.get(h.R);return e?oe.fromRaw(e):null}async init(e){var t=this.options.startHeight;let r;if(this.client){if(null!=t){if(!(r=await this.client.getEntry(t)))throw new Error("WDB: Could not find start block.")}else r=await this.client.getTip();r=ue.fromEntry(r)}else r=ue.fromEntry(this.network.genesis);this.logger.info("Initializing AccountDB chain state (height %d).",r.height),(t=await this.getState())?this.state=t:await this.resetState(r,!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 r=this.state.clone(),i=(r.startHeight=e.height,r.startHash=e.hash,r.height=e.height,r.marked=t,this.db.batch()),s=this.db.iterator({gte:h.h(e.height),lte:h.h(4294967295),values:!1});;){var n=await s.next();if(!n)break;try{i.del(n.key)}catch(e){throw await s.end(),e}}i.put(h.h(e.height),e.toHash()),i.put(h.R,r.toRaw()),await i.write(),this.state=r}async syncState(e){var t=this.state.clone(),r=this.db.batch();if(e.height<t.height){let s=t.height;var i=s-e.height;for(let e=0;e<i;e++)r.del(h.h(s--))}else e.height>t.height&&s(e.height===t.height+1,`Bad chain sync tip ${e.height} while state `+t.height);t.height=e.height,r.put(h.h(e.height),e.toHash()),r.put(h.R,t.toRaw()),await r.write(),this.state=t,X("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?ce.fromRaw(e,t):null}writeBlockMap(e,t,r){this.batch(e).put(h.b(t),r.toRaw())}unwriteBlockMap(e,t){this.batch(e).del(h.b(t))}async getOutpointMap(e,t){var r=await this.db.get(h.o(e,t));return r?ne.fromRaw(e,t,r):null}writeOutpointMap(e,t,r,i){e=this.batch(e),this.addOutpoint(t,r),e.put(h.o(t,r),i.toRaw())}unwriteOutpointMap(e,t,r){this.batch(e).del(h.o(t,r))}async writeBalanceLog(e,t){var r=h.log(e.wid,t.aidx,t.height,t.hash),i=(t=Buffer.from(JSON.stringify(t)),await this.writeLock.lock());try{this.start(e).put(r,t),await this.commit(e)}finally{i()}}async queryBalanceLog(e,t,r=0){return this.db.values({gte:h.log(e,t,r,N.NULL_HASH),lte:h.log(e,t,this.curHeight,N.HIGH_HASH),parse:e=>JSON.parse(e.toString())})}async getBlock(e){var t,r=await this.db.get(h.h(e));return r?((t=new ue).hash=r.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 r=await this.getBlock(e);let i=!1;return r?(await this.revert(r.height),await this.syncState(r),t):(r=new ue,e>=this.state.startHeight?(r.height=this.state.startHeight,r.hash=this.state.startHash,i=this.state.marked,this.logger.warning("Rolling back AccountDB to start block (%d).",r.height)):(r.height=0,r.hash=this.network.genesis.hash,i=!1,this.logger.warning("Rolling back AccountDB to genesis block.")),await this.revert(r.height),await this.resetState(r,i),!1)}async revert(e){var t=this.db.iterator({gte:h.b(e+1),lte:h.b(4294967295),reverse:!0,values:!0});let r=0;for(;;){var i=await t.next();if(!i)break;try{var s=h.bb(i.key),n=ce.fromRaw(s,i.value).toArray();r+=n.length;for(let e=n.length-1;0<=e;e--)await this._unconfirm(n[e])}catch(e){throw await t.end(),e}}this.logger.info("Rolled back %d AccountDB transactions.",r)}async addBlock(e,t){var r=await this.txLock.lock();try{return await this._addBlock(e,t)}finally{r()}}async _addBlock(e,t){var r=ue.fromEntry(e);let i=0;if(r.height<this.curHeight)this.logger.warning("AccountDB is connecting low blocks (%d).",r.height);else{if(r.height===this.curHeight)this.logger.warning("Already saw AccountDB block (%d).",r.height);else if(r.height!==this.curHeight+1)throw new Error(`WDB(addBlock): Bad disconnection (height mismatch, tip ${r.height} while state ${this.curHeight})`);if(await this.syncState(r),!(this.options.checkpoints&&r.height<=this.network.lastCheckpoint)){for(const e of t)await this._insert(e,r)&&i++;0<i&&this.logger.info("Connected AccountDB block %s (tx=%d).",C.revHex(r.hash),i)}}return i}async removeBlock(e,t){var r=await this.txLock.lock();try{return await this._removeBlock(e,t)}finally{r()}}async _removeBlock(e,t){if((e=ue.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} / ${C.revHex(e.hash)} while state ${this.curHeight})`);var r=await this.getBlock(e.height-1);if(!r)throw new Error(`WDB(removeBlock): Bad disconnection (no previous block of ${e.height} / ${C.revHex(e.hash)}).`);var i=await this.getBlockMap(e.height);if(i){for(let e=t.length-1;0<=e;e--){var s=t[e];await this._unconfirm(s,i)}this.logger.warning("Disconnected wallet block %s (tx=%d).",C.revHex(e.hash),i.txs.size)}return await this.syncState(r),i?i.txs.size:0}async rescanBlock(e,t){if(this.rescanning){var r=await this.scanLock.lock();try{await this._addBlock(e,t)}catch(e){throw this.emit("error",e),e}finally{r()}}else this.logger.warning("Unsolicited rescan block: %s.",e.height)}async addTX(e,t,r){var i=await this.txLock.lock();try{return await this._insert(e,t,r)}finally{i()}}listNotify(e){return this.NotifyList.deletes([["h","<",this.curHeight-12]]),this.NotifyList.query(e)}listContact(e,t,r){return this.$contacts.query(e,t,r)}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 r=this.db.batch();r.put(u.txdb.VP(e.pid),e.toRaw()),await r.write()}async getVp(e){return(e=await this.db.get(u.txdb.VP(e)))?Z.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(N.ZERO_CID,"hex"),lte:u.txdb.VP(N.MAX_CID,"hex"),parse:e=>Z.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(N.ZERO_HASH160_HEX),lte:u.txdb.CT(N.MAX_HASH160_HEX),parse:e=>R.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 M(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 M(e);var t,[t,r]=(this.htlcList.set(e.id,e),await this.getAccountByAddress(e.aa)),[t,r]=(t&&this.htlcList.setAccount(e,t,r),await this.getAccountByAddress(e.ba));(t=(t&&this.htlcList.setAccount(e,t,r),this.db.batch())).put(u.txdb.VH(e.shash,e.sidx),e.toRaw()),await t.write()}async setAssent(e){e=new M(e);var t,[t,r]=(this.htlcList.set(e.id,e),await this.getAccountByAddress(e.ab)),[t,r]=(t&&this.htlcList.setAccount(e,t,r),await this.getAccountByAddress(e.bb));(t=(t&&this.htlcList.setAccount(e,t,r),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(N.ZERO_CID,0),lte:u.txdb.VH(N.MAX_CID,4294967295),parse:e=>M.fromRaw(e)})}async delComment(e){var t;(e=new q(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 q(e);var t,[t,r]=(this.commentList.set(e.id,e),await this.getAccountByAddress(e.bob));(t=(t&&(this.commentList.setAccount(e,t,r),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(N.ZERO_CID,0),lte:u.txdb.VC(N.MAX_CID,4294967295),parse:e=>q.fromRaw(e)})}async setStockRecord(e){var t=this.db.batch();switch(t.put(e.itemNo,e.toRaw()),e.type){case G.RecordType.Offer:break;case G.RecordType.Bid:var r=this.accountList.getStockAccount(e.cid,e.addr);r&&(r.stock.sum=e.sum,r.stock.price=e.price,r.stock.period=this.curHeight+10*m.BLOCK_DAY,r.seq=e.seq,t.put(r.getItemNo(),r.toRaw()));break;case G.RecordType.Auction:{let s=this.accountList.getStockAccount(e.cid,e.addr);if(s?(r=s.sum+e.sum,s.price=(e.sum*e.price+s.sum*s.price)/r|0,s.sum=r,s.seq=e.seq):((s=new ee(e.cid,e.addr,e.sum,e.price,0)).seq=e.seq,this.accountList.setStockAccount(s)),t.put(s.getItemNo(),s.toRaw()),!(r=this.accountList.getStockAccount(e.cid,e.to)))break;var i=r.sum-e.sum;r.sum=i,r.stock.sum-=e.sum,t.put(r.getItemNo(),r.toRaw());break}case G.RecordType.Purchase:{let r=this.accountList.getStockAccount(e.cid,e.addr);r?(i=r.sum+e.sum,r.price=(e.sum*e.price+r.sum*r.price)/i,r.sum=i,r.seq=e.seq):((r=new ee(e.cid,e.addr,e.sum,e.price,0)).seq=e.seq,this.accountList.setStockAccount(r)),t.put(r.getItemNo(),r.toRaw());break}case G.RecordType.Send:if(r=this.accountList.getStockAccount(e.cid,e.addr)){r.sum-=e.sum,r.seq=e.seq;let s=this.accountList.getStockAccount(e.cid,e.to);s||(s=new ee(e.cid,e.to,0,0,0),this.accountList.setStockAccount(s)),i=s.sum+e.sum,s.price=(e.sum*r.price+s.sum*s.price)/i,s.sum=i,t.put(r.getItemNo(),r.toRaw()),t.put(s.getItemNo(),s.toRaw())}break;case G.RecordType.Bonus:case G.RecordType.Ads:}await t.write()}async unsetStockRecord(e){var t=this.db.batch();switch(t.del(e.itemNo),e.type){case G.RecordType.Offer:break;case G.RecordType.Bid:(s=this.accountList.getStockAccount(e.cid,e.addr))&&(s.stock.sum=0,s.stock.price=0,s.stock.period=0,s.seq=e.seq-1,t.put(s.getItemNo(),s.toRaw()));break;case G.RecordType.Auction:(s=this.accountList.getStockAccount(e.cid,e.addr))&&(r=s.sum-e.sum,s.price=(s.sum*s.price-e.sum*e.price)/r|0,s.sum=r,s.seq=e.seq-1,t.put(s.getItemNo(),s.toRaw()),s=this.accountList.getStockAccount(e.cid,e.to))&&(r=s.sum+e.sum,s.sum=r,s.stock.sum+=e.sum,t.put(s.getItemNo(),s.toRaw()));break;case G.RecordType.Purchase:var r=this.accountList.getStockAccount(e.cid,e.addr);r&&(s=r.sum-e.sum,r.price=(r.sum*r.price-e.sum*e.price)/s,r.sum=s,r.seq=e.seq-1,t.put(r.getItemNo(),r.toRaw()));break;case G.RecordType.Send:var i,s;(s=this.accountList.getStockAccount(e.cid,e.addr))&&(s.sum+=e.sum,s.seq=e.seq-1,t.put(s.getItemNo(),s.toRaw()),r=this.accountList.getStockAccount(e.cid,e.to))&&(i=r.sum-e.sum,r.price=(r.sum*r.price-e.sum*s.price)/i|0,r.sum=i,t.put(r.getItemNo(),r.toRaw()));break;case G.RecordType.Bonus:}await t.write()}async getStockRecordById(e){return(e=await this.db.get(e))?G.fromRaw(e):null}async verifyClsTx(e,t){if(!this.spv&&1!=(t=await(await k.FactoryOfContract({env:this,block:t,tx:e})).verify()))throw new g(e,S(t),"bad-contract-verify",100);return!0}async getStockRecord(e,t,r){let i=6,s=N.ZERO_CID_BUF,n=N.MAX_CID_BUF,a=0;return e&&(i=e,t)&&(s=t,n=t,a=r||0),e=new I,(await this.db.values({gte:G.itemNo(i,s,a,N.NULL_HASH,0),lte:G.itemNo(i,n,4294967295,N.HIGH_HASH,4294967295),parse:G.fromRaw})).reduce((e,t)=>(e.set(t.itemNo,t),e),e),e}async getStockRecordByCid(e,t){var r,i=new I;for(r of Object.keys(G.RecordType)){var s=await this.getStockRecord(G.RecordType[r],e,t);i.merge(s)}return i}async getStockAccountList(e){var t;return e?(t=ee.SN(e,N.NULL_HASH),e=ee.SN(e,N.HIGH_HASH),this.db.values({gte:t,lte:e,parse:ee.fromRaw})):this.db.values({gte:ee.SN(N.ZERO_CID_BUF,N.NULL_HASH),lte:ee.SN(N.MAX_CID_BUF,N.HIGH_HASH),parse:ee.fromRaw})}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&&(r=v.fromWitnessPubkeyhash(l.hash160(Buffer.from(e.source.pubkey,"hex")),this.network),[r,t]=await this.getAccountByAddress(r,t),e.wid=r,e.account=t);var r=this.db.batch();t=u.txdb.ERR(e.witness,e.erid,e.txid);r.put(t,e.toRaw()),r.put(u.txdb.ER(e.erid),t),await r.write()}async getEr(e){return(e=(e=await this.db.get(u.txdb.ER(e)))&&await this.db.get(e))?re.fromRaw(e):null}async byPubkey(e,t,r=!1){var i,s=new I;e=await this.db.values({gte:u.txdb.ERR(e,N.NULL_HASH,N.NULL_HASH),lte:u.txdb.ERR(e,N.HIGH_HASH,N.HIGH_HASH),parse:e=>re.fromRaw(e)});let n=[],a=new Map;if(r){for(var o of e)(!a.get(o.source.cluster)||o.startHeight>a.get(o.source.cluster).startHeight)&&a.set(o.source.cluster,await this.caVerifyObj(o));n=a.values()}else n=e;for(i of n)s.set(i.erid,i);return s.query(t)}async caVerifyObj(e){var t={verify:!1};if(!e||e.validHeight<=this.curHeight)return t;var r=await this.erAbList.getErAb(e.erid);return r&&r.abolishHeight<this.curHeight?t:(r=pe.fromPublic(Buffer.from(e.witness,"hex"),this.network.type),e.verify(r)?(e.verify=!0,0<(r=this.cpList.query([["pubKey",e.witness]])).list.length&&(e.cpid=r.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)))?Y.fromRaw(e):null}loadErAbolishList(){return this.db.values({gte:u.txdb.ERA(N.ZERO_CID),lte:u.txdb.ERA(N.MAX_CID),parse:e=>Y.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)))?se.fromRaw(e):null}async loadAuditList(){return this.db.values({gte:u.txdb.AU(N.NULL_HASH),lte:u.txdb.AU(N.HIGH_HASH),parse:e=>se.fromRaw(e)})}async batchPut(e,t){var r=this.db.batch();r.put(e,t),await r.write()}async batchDel(e){var t=this.db.batch();t.del(e),await t.write()}async _insert(e,t,r){s(!e.mutable,"WDB: Cannot add mutable TX.");let i=await this.getWalletsByTX(e);if(i){this.logger.info("Incoming transaction for %d wallets in AccountDB (%s).",i.size,e.txid()),!t||this.state.marked||(this.logger.info("Marking AccountDB start block at %s (%d).",C.revHex(t.hash),t.height),await this.resetState(t,!0));let a=!1;for(const o of i){var n=await this.get(o);s(n),await n.add(e,t,r)&&(this.logger.info("Added transaction to wallet in AccountDB: %s (%d).",n.id,o),a=!0)}a||(i=null)}try{var a=await k.FactoryOfContract({env:this,block:t,tx:e});t?await a.confirm():await a.insert()}catch(a){t?this.logger.error("TX(%s) Smart Contract Confirm Error: %s",e.txid(),a.message):this.logger.error("TX(%s) Smart Contract Insert Error: %s",e.txid(),a.message)}return i}async _unconfirm(e,t){if(t)try{await(await k.FactoryOfContract({env:this,block:t,tx:e})).unconfirm()}catch(t){this.logger.error("TX(%s) Smart Contract Unconfirm Error: %s",e.txid(),t.message)}let r,i=null;if(r=e.wids?(i=e.wids,e.hash):(i=await this.getWalletsByTX(e),e.hash("hex")),!i)return null;for(const e of i){var n=await this.get(e);s(n),await n.unconfirm(r)}for(const e of i){var a=await this.get(e);s(a),await a.abandon(r)}}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.scan(),await this.getWallets())){var r=await this.get(t);for(const t of await r.getPending())try{await r.abandon(t.hash)}catch(e){}await r.resetBalance()}}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(v.getHash(e.addr,"hex"),e.txid),Buffer.from(JSON.stringify(e))),await t.write()}async listMSTrans(e){return e=v.getHash(e,"hex"),this.db.values({gte:h.ms(e,N.NULL_HASH),lte:h.ms(e,N.HIGH_HASH),parse:e=>JSON.parse(e.toString())})}async delMSTrans(e,t){var r=await this.writeLock.lock();try{return await this._delMSTrans(e,t)}finally{r()}}async _delMSTrans(e,t){e=v.getHash(e,"hex");var r=this.db.batch();r.del(h.ms(e,t)),await r.write()}}ye.layout=h,e.exports=ye},function(e,t,r){"use strict";
841
+ */const i=r(8),s=r(0),n=r(73),a=r(122),o=r(159),c=r(612),u=r(95),h=u.walletdb,l=r(7),p=r(160),d=r(127),f=r(169),m=r(6),g=r(37).VerifyError,y=r(46),v=r(12);r(19);const b=r(60),w=r(198),x=r(69),k=r(43),{getVerifyMsg:S,BlockFinalType:E,ContractEnvType:_}=r(5),A=r(161),R=r(614),I=r(31);var j=r(72);const C=r(1),P=r(119).sortWithSeq,O=r(34),T=r(199),F=r(65),B=r(101),N=r(3),D=N.U32,L=r(341),H=r(342),z=r(343),M=z.vpItem,U=r(616),q=U.vpItem,V=r(85),K=r(617),W=V.cpItem,G=V.stockItem,$=r(158),Y=$.ErAbolishItem,X=r(36).broadcast,J=r(134),Z=J.vpItem,Q=r(232),ee=Q.stockAccount,te=r(157),re=te.ErItem,ie=r(618),se=ie.AuditItem,ne=r(315),ae=r(110),oe=r(619),ce=r(316),ue=r(123),he=r(620),le=r(222),pe=r(39),de=r(35),fe=r(59),me=r(78).errors,ge=r(77);class ye extends j{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:N.DefaultChainCode},e.keys&&e.keys.hmacSalt&&(s(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 L(this),this.primary=null,this.state=new oe,this.wallets=new Map,this.depth=0,this.rescanning=!1,this.bound=!1,this.newRecord=!0,this.readLock=new T,this.writeLock=new O,this.txLock=new O,this.scanLock=new O,this.widCache=new F(1e4),this.pathMapCache=new F(1e5),this.filter=new B,this.middleHashMem=new Set,this.middleHashChain=new Set,this.autoTaskMgr=new A(this),this.transactionList=new H(this),this.htlcList=new z(this),this.commentList=new U(this),this.NotifyList=new I,this.propList=new J(this),this.accountList=new Q(this),this.$contacts=new I,this.cpList=new V(this),this.cpMemList=new V(this),this.accountCoinList=new K(this),this.auditList=new ie(this),this.erList=new te(this),this.erAbList=new $(this),this.hmacConnection=[],this._init()}async logAudit(e){e.height=this.curHeight,e.time=C.now(),e.erid=l.sha256(C.stringify(e)).toString("hex"),e=new se(e),await this.auditList.setAudit(e)}async getAccountByAddress(e,t){if(e){let s=null;if(s=t?await this.getWalletsByTX(t):await this.getWallets())for(const t of s){var r=await this.get(t);if(r){var i=await r.getPath(e);if(i)return[r.wid,i.name,r.id]}}}return[0,"",""]}_init(){let e=1e6,t=-1;this.spv&&(e=2e4,t=B.flags.ALL),this.filter=B.fromRate(e,.001,t)}async getCpSnap(){return{}}get mode(){return _.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 w(e),{code:0}}catch(e){return{code:-1,msg:e.message}}}async getContracts(e){var t=await this.db.values({gte:u.txdb.tx(N.NULL_HASH),lte:u.txdb.tx(N.HIGH_HASH),parse:e=>C.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 r=e.body.content;if("string"==typeof r)try{r=JSON.parse(e.body.content)}catch(e){return}"object"==typeof r&&"secret"===r.type&&(t={contact:e.body.src,messenger:e.body.dst},r.init&&(t.init=Buffer.from(r.init,"hex")),r.packet&&(t.packet=Buffer.from(r.packet)),await this.handleSecret(t))}}async handleSecret(e){if(e.contact&&e.messenger&&e.contact!=e.messenger){try{v.fromString(e.contact,this.network.type),v.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 r=async e=>{var t;e.witness&&"witnesspubkeyhash"==e.getType()&&(t=e.witness.getPubkeyhashInput()[1],e=v.fromWitness(e.witness).toString(),t)&&e&&await this.ensureContact({contact:e,publicKey:t})};if(0<=t&&t<e.inputs.length)await r(e.inputs[t]);else for(var i of e.inputs)await r(i)}async ensureContact(e){if(!e.contact||e.contact==e.messenger)return null;try{v.fromString(e.contact,this.network.type),e.messenger&&v.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 R(e));var t=this.$contacts.get(e.contact);if(e.messenger&&!(e=t.ensureMessenger(e)).wallet){var r,[r,i]=await this.getAccountByAddress(e.address);if(!(r=await this.get(r)))return;e.wallet=r,e.account=i}return t}getCps(){return this.db.values({gte:u.txdb.cp(N.ZERO_CID,"hex"),lte:u.txdb.cp(N.MAX_CID,"hex"),parse:e=>W.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}),r=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{r()}setTimeout(()=>{this.resend()},5e3)}}bind(){!this.client||this.bound||(this.bound=!0,this.client.hook("htlcassent.cancel",e=>{this.setAssent(e),this.emit("htlcassent.cancel",e)}),this.client.hook("htlcassent.deal",e=>{this.setAssent(e),this.emit("htlcassent.deal",e)}),this.client.hook("htlcassent.receive",e=>{this.setAssent(e),this.emit("htlcassent.receive",e)}),this.client.hook("htlcsuggest.cancel",e=>{this.setSuggest(e),this.emit("htlcsuggest.cancel",e)}),this.client.hook("htlcsuggest.deal",e=>{this.setSuggest(e),this.emit("htlcsuggest.deal",e)}),this.client.hook("htlcsuggest.receive",e=>{this.setSuggest(e),this.emit("htlcsuggest.receive",e)}),this.on("mssendpubk/receive",async e=>{let t=await this.get(e.addr);var r,i,s;if(!t&&(t=await this.ensure({id:e.addr,type:"multisig",m:e.m,n:e.n,witness:!0}),[s,i]=await this.getAccountByAddress(e.addr),s=await this.get(s))&&await s.send({subtractFee:!1,sort:!1,outputs:[{address:e.contract,value:1e4}],comment:JSON.stringify({oper:"scrun",params:{oper:"pubk",addr:e.addr,puba:t.account.accountKey}})},i),t.account.keys.length<t.account.n-1){for(r of e.data.split(","))try{await t.addSharedKey(r)}catch(e){}t.account.keys.length==t.account.n-1&&([s,i]=await this.getAccountByAddress(e.addr),s=await this.get(s))&&await s.send({subtractFee:!1,sort:!1,outputs:[{address:e.contract,value:1e4}],comment:JSON.stringify({oper:"scrun",params:{oper:"puba",addr:e.addr,puba:t.account.receive.getAddress().toString()}})},i)}}),this.on("mssendtx/receive",async e=>{var t,r=await this.get(e.addr);r&&r.account.type==o.types.MULTISIG&&((t=b.fromRaw(e.data,"hex")).view=await r.getCoinView(t),t.isSigned()||(e.txid=t.txid(),await this.saveMSTrans(e)))}),this.client.hook("onConnect",async()=>{await this.load()}),this.client.hook("error",e=>{this.emit("error",e)}),this.client.hook("block.connect",async(e,t)=>{try{await this.addBlock(e,t)}catch(e){this.emit("error",e)}}),this.client.hook("block.disconnect",async(e,t)=>{try{await this.removeBlock(e,t)}catch(e){this.emit("error",e)}}),this.client.hook("chain.full",()=>{this.synced=!0}),this.client.hook("block.rescan",async(e,t)=>{try{await this.rescanBlock(e,t)}catch(e){this.emit("error",e)}}),this.client.on("tx",async(e,t,r)=>{try{await this.addTX(e,null,r)}catch(e){this.emit("error",e)}}),this.client.on("entry.remove",async(e,t)=>{try{if(t){var r=e.tx.hash("hex"),i=await this.getWalletsByTX(e.tx);if(i)for(const t of i){var n=await this.get(t);s(n),await n.remove(r),(await k.FactoryOfContract({tx:e.tx,env:this})).erase()}}}catch(e){this.emit("error",e)}}),this.client.hook("chain.reset",async e=>{try{await this.resetChain(e)}catch(e){this.emit("error",e)}}),this.jsonp&&this.jsonp.hook("error",e=>{this.emit("error",e)}))}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(N.NULL_HASH),lte:h.p(N.HIGH_HASH)}),t=0,r=0;for(;;){var i=await e.next();if(!i)break;try{var s=h.pp(i.key);this.filter.add(s,"hex")}catch(t){throw await e.end(),t}t++}for(e=this.db.iterator({gte:h.o(N.NULL_HASH,0),lte:h.o(N.HIGH_HASH,4294967295)});;){var n=await e.next();if(!n)break;try{var[a,o]=h.oo(n.key),c=new y(a,o).toRaw();this.filter.add(c)}catch(t){throw await e.end(),t}r++}this.logger.info("Filter: Added %d hashes to AccountDB filter.",t),this.logger.info("Filter: Added %d outpoints to AccountDB filter.",r),await this.setFilter()}async sync(){if(this.client){let t,r=this.curHeight;for(;0<=r;){var e=await this.getBlock(r);if(!e)break;if(t=await this.client.getEntry(e.hash))break;r--}t||(r=this.state.startHeight,t=await this.client.getEntry(this.state.startHash))||(r=0),await this.cpList.loadHistory(),await this.cpMemList.loadHistory(),await this.propList.loadHistory(),await this.htlcList.loadHistory(),await this.commentList.loadHistory(),await this.accountList.loadHistory(),await this.transactionList.loadHistory(),await this.loadContact(),await this.erList.loadHistory(),await this.auditList.loadHistory(),await this.erAbList.loadHistory(),await this.accountCoinList.loadHistory(),await this.scan(r,!1)}}async scan(e,t=!0){if(this.client){null==e&&(e=this.state.startHeight),s(e>>>0===e,"WDB: Must pass in a height.");var r=this.curHeight;t=(await this.rollback(e,t),this.logger.info("AccountDB is scanning %d blocks.",r-e+1),await this.getTip());try{this.rescanning=!0,await this.client.rescan(t.hash)}finally{this.rescanning=!1}}}async rescan(e){var t=await this.txLock.lock();try{return await this.scan(e,!1)}finally{t()}}async send(e){if(this.client)return this.client.send(e);this.emit("send",e)}async getTX(e){for(const r of this.wallets.values()){var t=await r.getTX(e);if(t)return t.tx}return null}async getTXFromDb(e){for(const r of this.wallets.values()){var t=await r.getTX(e);if(t)return t.tx}return null}async getExtendTX(e){for(const r of this.wallets.values()){var t=await r.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())}addFilter(e){return this.client?this.client.addFilter(e):(this.emit("filter.add",e),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 r=0;for(;;){var i=await e.next();if(!i)break;try{switch(i.key[0]){case 98:case 99:case 101:case 116:case 111:case 104:case 82:t.del(i.key),r++}}catch(t){throw await e.end(),t}}this.logger.warning("Wiped %d txdb records.",r),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 s(!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 s(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){return this.filter.add(e,"hex"),this.addFilter(e)}addOutpoint(e,t){e=new y(e,t),this.filter.add(e.toRaw())}dump(){return this.db.dump()}register(e){s(!this.wallets.has(e.wid)),this.wallets.set(e.wid,e)}unregister(e){s(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=a.fromRaw(this,t)).open(),this.register(e),e):null)}async loadBackup(e){if(fe.unsupported)throw new ge(me.INTERNAL_ERROR,"FS not available.");let t=await this.get("primary");var r;for(r of(await fe.readFile(e,"utf8")).split(/\n+/))if(0!==(r=r.trim()).length&&!/^\s*#/.test(r)){var i=r.split(/\s+/);if(i.length<4)throw new ge(me.DESERIALIZATION_ERROR,"Malformed wallet Data File.");switch(i[0]){case"W":var n=Buffer.from(i[1],"base64");n=a.fromRaw(t.db,n);if(t.wid!=n.wid)throw new ge(me.DESERIALIZATION_ERROR,"Malformed wallet Key");await this.replace(n),t=await this.get("primary"),this.logger.info("Import Wallet %s(%s)",t.id,t.wid);break;case"C":n=Buffer.from(i[1],"base64");(c=((u=o.fromRaw(t.db,n)).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")&&s(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=parseInt(i[5]),u=parseInt(i[7]),h=parseInt(i[9]),l=i[11].trim(),p=await t.deriveKey(c,u,h),d=await t.deriveKey(c,u,h,t.master);p.getAddress("string")!==d.getAddress("string")&&s(p.getAddress("string")==d.getAddress("string")),p.getAddress("string")!==l&&s(p.getAddress("string")==l),this.logger.info("Import Address %s %s %s %s",c,u,h,p.getAddress("string"))}}return t.accountCache.reset(),t}save(e){var t=e.wid,r=e.id,i=this.batch(e);this.widCache.set(r,t),i.put(h.w(t),e.toRaw()),i.put(h.l(r),D(t))}async rename(e,t){var r=await this.writeLock.lock();try{return await this._rename(e,t)}finally{r()}}async _rename(e,t){var r=e.id;if(!n.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(r)),e.id=t,this.save(e),await this.commit(e),this.widCache.remove(r),r=e.pathCache.values();for(const e of r)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 r=e.wallet;this.batch(r).del(h.i(e.wid,e.name)),e.name=t,this.saveAccount(e)}async auth(e,t){if("string"==typeof t){if(!C.isHex256(t))throw new Error("WDB Authentication: Invalid Token.");t=Buffer.from(t,"hex")}e=x.getHmac(e.toString(),this.keys.hmacSalt);var r=i.createHmac("sha256",e.random);r=Buffer.from(r.update(e.token).digest("hex"),"hex");if(!p(t,r))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=a.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 getAccountIndex(e,t){return(e=await this.db.get(h.i(e,t)))?e.readUInt32LE(0,!0):-1}async getGuider(e){return e=v.fromString(e,this.network.type).getHash("hex"),(e=await this.db.get(h.g(e)))?v.fromRaw(e).toString():null}async setGuider(e,t,r){var i;r=v.fromString(r,this.network.type).getHash("hex"),await this.db.has(h.g(r))||(e=v.fromString(e,this.network.type),(i=this.db.batch()).put(h.g(r),e.toRaw()),i.put(h.gs(e.getHash("hex"),Buffer.from(t,"ascii").toString("hex"),r),null),await i.write())}async unsetGuider(e,t,r){e=v.fromString(e,this.network.type).getHash("hex"),r=v.fromString(r,this.network.type).getHash("hex");var i=this.db.batch();i.del(h.g(r)),i.del(h.gs(e,Buffer.from(t,"ascii").toString("hex"),r)),await i.write()}async getAccountName(e,t){return(e=await this.db.get(h.n(e,t)))?e.toString("ascii"):null}saveAccount(e){var t=e.wid,r=e.wallet,i=e.accountIndex,s=e.name,n=this.batch(r);n.put(h.a(t,i),e.toRaw()),n.put(h.i(t,s),D(i)),n.put(h.n(t,i),Buffer.from(s,"ascii")),r.accountCache.push(i,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=he.fromRaw(e,t),this.pathMapCache.set(e,t),t):null)}saveKey(e,t){return this.savePath(e,t.toPath())}async savePath(e,t){var r=e.wid,i=t.hash,s=this.batch(e);await this.addHash(i);let n=await this.getPathMap(i);(n=n||new he(i)).add(r)&&(this.pathMapCache.set(i,n),e.pathCache.push(i,t),s.put(h.p(i),n.toRaw()),s.put(h.P(r,i),t.toRaw()),s.put(h.r(r,t.account,i),null))}async getPath(e,t){var r=await this.db.get(h.P(e,t));return r?((r=ae.fromRaw(r)).wid=e,r.hash=t,r):null}hasPath(e,t){return this.db.has(h.P(e,t))}getHashes(){return this.db.keys({gte:h.p(N.NULL_HASH),lte:h.p(N.HIGH_HASH),parse:h.pp})}getOutpoints(){return this.db.keys({gte:h.o(N.NULL_HASH,0),lte:h.o(N.HIGH_HASH,4294967295),parse:e=>{var[e,t]=h.oo(e);return new y(e,t)}})}getWalletHashes(e){return this.db.keys({gte:h.P(e,N.NULL_HASH),lte:h.P(e,N.HIGH_HASH),parse:h.Pp})}getAccountHashes(e,t){return this.db.keys({gte:h.r(e,t,N.NULL_HASH),lte:h.r(e,t,N.HIGH_HASH),parse:h.rr})}async getWalletPaths(e){var t=[];for(const s of await this.db.range({gte:h.P(e,N.NULL_HASH),lte:h.P(e,N.HIGH_HASH)})){var r=h.Pp(s.key),i=ae.fromRaw(s.value);i.hash=r,i.wid=e,t.push(i)}return t}async encryptKeys(e,t){var r,i,n=e.wid,a=await e.getPaths(),o=this.batch(e);for(r of a)r.data&&(s(!r.encrypted),i=Buffer.from(r.hash,"hex").slice(0,16),(r=r.clone()).data=d.encipher(r.data,t,i),r.encrypted=!0,e.pathCache.push(r.hash,r),o.put(h.P(n,r.hash),r.toRaw()))}async decryptKeys(e,t){var r,i,n=e.wid,a=await e.getPaths(),o=this.batch(e);for(r of a)r.data&&(s(r.encrypted),i=Buffer.from(r.hash,"hex").slice(0,16),(r=r.clone()).data=d.decipher(r.data,t,i),r.encrypted=!1,e.pathCache.push(r.hash,r),o.put(h.P(n,r.hash),r.toRaw()))}async resend(){var e,t={};for(const e of await this.db.keys({gte:h.w(0),lte:h.w(4294967295)})){var r,i=h.ww(e);i&&(r=await this.resendPending(i))&&Array.isArray(r)&&(t[i]=r)}for(e of Object.keys(t)){var s=await this.get(parseInt(e));if(s)for(const r of t[e]){try{await this.send(r)}catch(e){this.logger.warning("wdb resend:",e.message);try{await s.abandon(r.hash("hex"))}catch(e){this.logger.warning("wdb abandon:",e.message)}}await de.timeout(50)}}}async resendPending(e){var t=await this.get(e),r=await this.db.keys({gte:u.txdb.prefix(e,u.txdb.p(N.NULL_HASH)),lte:u.txdb.prefix(e,u.txdb.p(N.HIGH_HASH))});if(0!==r.length){this.logger.info("Rebroadcasting %d transactions for %d.",r.length,e);var i=[];for(const o of r){var s=u.txdb.pp(o),n=u.txdb.prefix(e,u.txdb.t(s));if((n=await this.db.get(n))&&!(n=le.fromRaw(n)).tx.isCoinbase())try{var a=await k.FactoryOfContract({tx:n.tx,env:this});await a.isBlockFinal()==E.Expired?t&&(await this.removeTX(n.tx),await t.remove(s),await a.erase()):"notify"!=a.oper&&i.push(n.tx)}catch(e){this.logger.error("TX(%s) Smart Contract Error: %s",n.tx.txid(),e.message)}}return await P(i,this)}}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 i of e.inputs){var r=i.prevout;if(this.testFilter(r.toRaw())&&(r=await this.getOutpointMap(r.hash,r.index)))for(const e of r.wids)t.add(e)}for(const r of e.getOutputHashes("hex"))if(this.testFilter(r)){var i=await this.getPathMap(r);if(i)for(const e of i.wids)t.add(e)}return 0===t.size?null:t}async getState(){var e=await this.db.get(h.R);return e?oe.fromRaw(e):null}async init(e){var t=this.options.startHeight;let r;if(this.client){if(null!=t){if(!(r=await this.client.getEntry(t)))throw new Error("WDB: Could not find start block.")}else r=await this.client.getTip();r=ue.fromEntry(r)}else r=ue.fromEntry(this.network.genesis);this.logger.info("Initializing AccountDB chain state (height %d).",r.height),(t=await this.getState())?this.state=t:await this.resetState(r,!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 r=this.state.clone(),i=(r.startHeight=e.height,r.startHash=e.hash,r.height=e.height,r.marked=t,this.db.batch()),s=this.db.iterator({gte:h.h(e.height),lte:h.h(4294967295),values:!1});;){var n=await s.next();if(!n)break;try{i.del(n.key)}catch(e){throw await s.end(),e}}i.put(h.h(e.height),e.toHash()),i.put(h.R,r.toRaw()),await i.write(),this.state=r}async syncState(e){var t=this.state.clone(),r=this.db.batch();if(e.height<t.height){let s=t.height;var i=s-e.height;for(let e=0;e<i;e++)r.del(h.h(s--))}else e.height>t.height&&s(e.height===t.height+1,`Bad chain sync tip ${e.height} while state `+t.height);t.height=e.height,r.put(h.h(e.height),e.toHash()),r.put(h.R,t.toRaw()),await r.write(),this.state=t,X("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?ce.fromRaw(e,t):null}writeBlockMap(e,t,r){this.batch(e).put(h.b(t),r.toRaw())}unwriteBlockMap(e,t){this.batch(e).del(h.b(t))}async getOutpointMap(e,t){var r=await this.db.get(h.o(e,t));return r?ne.fromRaw(e,t,r):null}writeOutpointMap(e,t,r,i){e=this.batch(e),this.addOutpoint(t,r),e.put(h.o(t,r),i.toRaw())}unwriteOutpointMap(e,t,r){this.batch(e).del(h.o(t,r))}async writeBalanceLog(e,t){var r=h.log(e.wid,t.aidx,t.height,t.hash),i=(t=Buffer.from(JSON.stringify(t)),await this.writeLock.lock());try{this.start(e).put(r,t),await this.commit(e)}finally{i()}}async queryBalanceLog(e,t,r=0){return this.db.values({gte:h.log(e,t,r,N.NULL_HASH),lte:h.log(e,t,this.curHeight,N.HIGH_HASH),parse:e=>JSON.parse(e.toString())})}async getBlock(e){var t,r=await this.db.get(h.h(e));return r?((t=new ue).hash=r.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 r=await this.getBlock(e);let i=!1;return r?(await this.revert(r.height),await this.syncState(r),t):(r=new ue,e>=this.state.startHeight?(r.height=this.state.startHeight,r.hash=this.state.startHash,i=this.state.marked,this.logger.warning("Rolling back AccountDB to start block (%d).",r.height)):(r.height=0,r.hash=this.network.genesis.hash,i=!1,this.logger.warning("Rolling back AccountDB to genesis block.")),await this.revert(r.height),await this.resetState(r,i),!1)}async revert(e){var t=this.db.iterator({gte:h.b(e+1),lte:h.b(4294967295),reverse:!0,values:!0});let r=0;for(;;){var i=await t.next();if(!i)break;try{var s=h.bb(i.key),n=ce.fromRaw(s,i.value).toArray();r+=n.length;for(let e=n.length-1;0<=e;e--)await this._unconfirm(n[e])}catch(e){throw await t.end(),e}}this.logger.info("Rolled back %d AccountDB transactions.",r)}async addBlock(e,t){var r=await this.txLock.lock();try{return await this._addBlock(e,t)}finally{r()}}async _addBlock(e,t){var r=ue.fromEntry(e);let i=0;if(r.height<this.curHeight)this.logger.warning("AccountDB is connecting low blocks (%d).",r.height);else{if(r.height===this.curHeight)this.logger.warning("Already saw AccountDB block (%d).",r.height);else if(r.height!==this.curHeight+1)throw new Error(`WDB(addBlock): Bad disconnection (height mismatch, tip ${r.height} while state ${this.curHeight})`);if(await this.syncState(r),!(this.options.checkpoints&&r.height<=this.network.lastCheckpoint)){for(const e of t)await this._insert(e,r)&&i++;0<i&&this.logger.info("Connected AccountDB block %s (tx=%d).",C.revHex(r.hash),i)}}return i}async removeBlock(e,t){var r=await this.txLock.lock();try{return await this._removeBlock(e,t)}finally{r()}}async _removeBlock(e,t){if((e=ue.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} / ${C.revHex(e.hash)} while state ${this.curHeight})`);var r=await this.getBlock(e.height-1);if(!r)throw new Error(`WDB(removeBlock): Bad disconnection (no previous block of ${e.height} / ${C.revHex(e.hash)}).`);var i=await this.getBlockMap(e.height);if(i){for(let e=t.length-1;0<=e;e--){var s=t[e];await this._unconfirm(s,i)}this.logger.warning("Disconnected wallet block %s (tx=%d).",C.revHex(e.hash),i.txs.size)}return await this.syncState(r),i?i.txs.size:0}async rescanBlock(e,t){if(this.rescanning){var r=await this.scanLock.lock();try{await this._addBlock(e,t)}catch(e){throw this.emit("error",e),e}finally{r()}}else this.logger.warning("Unsolicited rescan block: %s.",e.height)}async addTX(e,t,r){var i=await this.txLock.lock();try{return await this._insert(e,t,r)}finally{i()}}listNotify(e){return this.NotifyList.deletes([["h","<",this.curHeight-12]]),this.NotifyList.query(e)}listContact(e,t,r){return this.$contacts.query(e,t,r)}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 r=this.db.batch();r.put(u.txdb.VP(e.pid),e.toRaw()),await r.write()}async getVp(e){return(e=await this.db.get(u.txdb.VP(e)))?Z.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(N.ZERO_CID,"hex"),lte:u.txdb.VP(N.MAX_CID,"hex"),parse:e=>Z.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(N.ZERO_HASH160_HEX),lte:u.txdb.CT(N.MAX_HASH160_HEX),parse:e=>R.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 M(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 M(e);var t,[t,r]=(this.htlcList.set(e.id,e),await this.getAccountByAddress(e.aa)),[t,r]=(t&&this.htlcList.setAccount(e,t,r),await this.getAccountByAddress(e.ba));(t=(t&&this.htlcList.setAccount(e,t,r),this.db.batch())).put(u.txdb.VH(e.shash,e.sidx),e.toRaw()),await t.write()}async setAssent(e){e=new M(e);var t,[t,r]=(this.htlcList.set(e.id,e),await this.getAccountByAddress(e.ab)),[t,r]=(t&&this.htlcList.setAccount(e,t,r),await this.getAccountByAddress(e.bb));(t=(t&&this.htlcList.setAccount(e,t,r),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(N.ZERO_CID,0),lte:u.txdb.VH(N.MAX_CID,4294967295),parse:e=>M.fromRaw(e)})}async delComment(e){var t;(e=new q(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 q(e);var t,[t,r]=(this.commentList.set(e.id,e),await this.getAccountByAddress(e.bob));(t=(t&&(this.commentList.setAccount(e,t,r),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(N.ZERO_CID,0),lte:u.txdb.VC(N.MAX_CID,4294967295),parse:e=>q.fromRaw(e)})}async setStockRecord(e){var t=this.db.batch();switch(t.put(e.itemNo,e.toRaw()),e.type){case G.RecordType.Offer:break;case G.RecordType.Bid:var r=this.accountList.getStockAccount(e.cid,e.addr);r&&(r.stock.sum=e.sum,r.stock.price=e.price,r.stock.period=this.curHeight+10*m.BLOCK_DAY,r.seq=e.seq,t.put(r.getItemNo(),r.toRaw()));break;case G.RecordType.Auction:{let s=this.accountList.getStockAccount(e.cid,e.addr);if(s?(r=s.sum+e.sum,s.price=(e.sum*e.price+s.sum*s.price)/r|0,s.sum=r,s.seq=e.seq):((s=new ee(e.cid,e.addr,e.sum,e.price,0)).seq=e.seq,this.accountList.setStockAccount(s)),t.put(s.getItemNo(),s.toRaw()),!(r=this.accountList.getStockAccount(e.cid,e.to)))break;var i=r.sum-e.sum;r.sum=i,r.stock.sum-=e.sum,t.put(r.getItemNo(),r.toRaw());break}case G.RecordType.Purchase:{let r=this.accountList.getStockAccount(e.cid,e.addr);r?(i=r.sum+e.sum,r.price=(e.sum*e.price+r.sum*r.price)/i,r.sum=i,r.seq=e.seq):((r=new ee(e.cid,e.addr,e.sum,e.price,0)).seq=e.seq,this.accountList.setStockAccount(r)),t.put(r.getItemNo(),r.toRaw());break}case G.RecordType.Send:if(r=this.accountList.getStockAccount(e.cid,e.addr)){r.sum-=e.sum,r.seq=e.seq;let s=this.accountList.getStockAccount(e.cid,e.to);s||(s=new ee(e.cid,e.to,0,0,0),this.accountList.setStockAccount(s)),i=s.sum+e.sum,s.price=(e.sum*r.price+s.sum*s.price)/i,s.sum=i,t.put(r.getItemNo(),r.toRaw()),t.put(s.getItemNo(),s.toRaw())}break;case G.RecordType.Bonus:case G.RecordType.Ads:}await t.write()}async unsetStockRecord(e){var t=this.db.batch();switch(t.del(e.itemNo),e.type){case G.RecordType.Offer:break;case G.RecordType.Bid:(s=this.accountList.getStockAccount(e.cid,e.addr))&&(s.stock.sum=0,s.stock.price=0,s.stock.period=0,s.seq=e.seq-1,t.put(s.getItemNo(),s.toRaw()));break;case G.RecordType.Auction:(s=this.accountList.getStockAccount(e.cid,e.addr))&&(r=s.sum-e.sum,s.price=(s.sum*s.price-e.sum*e.price)/r|0,s.sum=r,s.seq=e.seq-1,t.put(s.getItemNo(),s.toRaw()),s=this.accountList.getStockAccount(e.cid,e.to))&&(r=s.sum+e.sum,s.sum=r,s.stock.sum+=e.sum,t.put(s.getItemNo(),s.toRaw()));break;case G.RecordType.Purchase:var r=this.accountList.getStockAccount(e.cid,e.addr);r&&(s=r.sum-e.sum,r.price=(r.sum*r.price-e.sum*e.price)/s,r.sum=s,r.seq=e.seq-1,t.put(r.getItemNo(),r.toRaw()));break;case G.RecordType.Send:var i,s;(s=this.accountList.getStockAccount(e.cid,e.addr))&&(s.sum+=e.sum,s.seq=e.seq-1,t.put(s.getItemNo(),s.toRaw()),r=this.accountList.getStockAccount(e.cid,e.to))&&(i=r.sum-e.sum,r.price=(r.sum*r.price-e.sum*s.price)/i|0,r.sum=i,t.put(r.getItemNo(),r.toRaw()));break;case G.RecordType.Bonus:}await t.write()}async getStockRecordById(e){return(e=await this.db.get(e))?G.fromRaw(e):null}async verifyClsTx(e,t){if(!this.spv&&1!=(t=await(await k.FactoryOfContract({env:this,block:t,tx:e})).verify()))throw new g(e,S(t),"bad-contract-verify",100);return!0}async getStockRecord(e,t,r){let i=6,s=N.ZERO_CID_BUF,n=N.MAX_CID_BUF,a=0;return e&&(i=e,t)&&(s=t,n=t,a=r||0),e=new I,(await this.db.values({gte:G.itemNo(i,s,a,N.NULL_HASH,0),lte:G.itemNo(i,n,4294967295,N.HIGH_HASH,4294967295),parse:G.fromRaw})).reduce((e,t)=>(e.set(t.itemNo,t),e),e),e}async getStockRecordByCid(e,t){var r,i=new I;for(r of Object.keys(G.RecordType)){var s=await this.getStockRecord(G.RecordType[r],e,t);i.merge(s)}return i}async getStockAccountList(e){var t;return e?(t=ee.SN(e,N.NULL_HASH),e=ee.SN(e,N.HIGH_HASH),this.db.values({gte:t,lte:e,parse:ee.fromRaw})):this.db.values({gte:ee.SN(N.ZERO_CID_BUF,N.NULL_HASH),lte:ee.SN(N.MAX_CID_BUF,N.HIGH_HASH),parse:ee.fromRaw})}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&&(r=v.fromWitnessPubkeyhash(l.hash160(Buffer.from(e.source.pubkey,"hex")),this.network),[r,t]=await this.getAccountByAddress(r,t),e.wid=r,e.account=t);var r=this.db.batch();t=u.txdb.ERR(e.witness,e.erid,e.txid);r.put(t,e.toRaw()),r.put(u.txdb.ER(e.erid),t),await r.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=re.fromRaw(e)).txid=t,e):null}async byPubkey(e,t,r=!1){var i,s=new I;e=await this.db.values({gte:u.txdb.ERR(e,N.NULL_HASH,N.NULL_HASH),lte:u.txdb.ERR(e,N.HIGH_HASH,N.HIGH_HASH),parse:e=>re.fromRaw(e)});let n=[],a=new Map;if(r){for(var o of e)(!a.get(o.source.cluster)||o.startHeight>a.get(o.source.cluster).startHeight)&&a.set(o.source.cluster,await this.caVerifyObj(o));n=a.values()}else n=e;for(i of n)s.set(i.erid,i);return s.query(t)}async caVerifyObj(e){var t={verify:!1};if(!e||e.validHeight<=this.curHeight)return t;var r=await this.erAbList.getErAb(e.erid);return r&&r.abolishHeight<this.curHeight?t:(r=pe.fromPublic(Buffer.from(e.witness,"hex"),this.network.type),e.verify(r)?(e.verify=!0,0<(r=this.cpList.query([["pubKey",e.witness]])).list.length&&(e.cpid=r.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)))?Y.fromRaw(e):null}loadErAbolishList(){return this.db.values({gte:u.txdb.ERA(N.ZERO_CID),lte:u.txdb.ERA(N.MAX_CID),parse:e=>Y.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)))?se.fromRaw(e):null}async loadAuditList(){return this.db.values({gte:u.txdb.AU(N.NULL_HASH),lte:u.txdb.AU(N.HIGH_HASH),parse:e=>se.fromRaw(e)})}async batchPut(e,t){var r=this.db.batch();r.put(e,t),await r.write()}async batchDel(e){var t=this.db.batch();t.del(e),await t.write()}async _insert(e,t,r){s(!e.mutable,"WDB: Cannot add mutable TX.");let i=await this.getWalletsByTX(e);if(i){this.logger.info("Incoming transaction for %d wallets in AccountDB (%s).",i.size,e.txid()),!t||this.state.marked||(this.logger.info("Marking AccountDB start block at %s (%d).",C.revHex(t.hash),t.height),await this.resetState(t,!0));let a=!1;for(const o of i){var n=await this.get(o);s(n),await n.add(e,t,r)&&(this.logger.info("Added transaction to wallet in AccountDB: %s (%d).",n.id,o),a=!0)}a||(i=null)}try{var a=await k.FactoryOfContract({env:this,block:t,tx:e});t?await a.confirm():await a.insert()}catch(a){t?this.logger.error("TX(%s) Smart Contract Confirm Error: %s",e.txid(),a.message):this.logger.error("TX(%s) Smart Contract Insert Error: %s",e.txid(),a.message)}return i}async _unconfirm(e,t){if(t)try{await(await k.FactoryOfContract({env:this,block:t,tx:e})).unconfirm()}catch(t){this.logger.error("TX(%s) Smart Contract Unconfirm Error: %s",e.txid(),t.message)}let r,i=null;if(r=e.wids?(i=e.wids,e.hash):(i=await this.getWalletsByTX(e),e.hash("hex")),!i)return null;for(const e of i){var n=await this.get(e);s(n),await n.unconfirm(r)}for(const e of i){var a=await this.get(e);s(a),await a.abandon(r)}}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.scan(),await this.getWallets())){var r=await this.get(t);for(const t of await r.getPending())try{await r.abandon(t.hash)}catch(e){}await r.resetBalance()}}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(v.getHash(e.addr,"hex"),e.txid),Buffer.from(JSON.stringify(e))),await t.write()}async listMSTrans(e){return e=v.getHash(e,"hex"),this.db.values({gte:h.ms(e,N.NULL_HASH),lte:h.ms(e,N.HIGH_HASH),parse:e=>JSON.parse(e.toString())})}async delMSTrans(e,t){var r=await this.writeLock.lock();try{return await this._delMSTrans(e,t)}finally{r()}}async _delMSTrans(e,t){e=v.getHash(e,"hex");var r=this.db.batch();r.del(h.ms(e,t)),await r.write()}}ye.layout=h,e.exports=ye},function(e,t,r){"use strict";
842
842
  /*!
843
843
  * txdb.js - persistent transaction pool
844
844
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
package/lib/gamegold.js CHANGED
@@ -206,7 +206,7 @@ var r=i(128),s=r.Buffer;function n(t,e){for(var i in t)e[i]=t[i]}function a(t,e,
206
206
  * pkg.js - package constants
207
207
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
208
208
  * https://github.com/bookmansoft/gamegold
209
- */e.protocol="vallnet",e.version="v4.2.1",e.url="https://github.com/bookmansoft/gamegold"},function(t,e,i){"use strict";
209
+ */e.protocol="vallnet",e.version="v4.2.3",e.url="https://github.com/bookmansoft/gamegold"},function(t,e,i){"use strict";
210
210
  /*!
211
211
  * common.js - p2p constants for vallnet
212
212
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -372,7 +372,7 @@ const r=i(21).opcodes;function s(t){let e=null;var i=s.list[t.type];return new(i
372
372
  /*!
373
373
  * layout.js - blockchain data layout for vallnet
374
374
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
375
- */const r=i(0),s={binary:!0,C:function(t,e,i){let s,a=t.length;return r("number"==typeof i),"string"==typeof t&&(a/=2),32===a?((s=Buffer.allocUnsafe(69))[0]=154,n(s,t,1),n(s,e,33),s.writeUInt32BE(i,65,!0)):20===a?((s=Buffer.allocUnsafe(57))[0]=67,n(s,t,1),n(s,e,21),s.writeUInt32BE(i,53,!0)):r(!1),s},Cc:function(t){let e,i;return r(Buffer.isBuffer(t)),69===t.length?(e=t.toString("hex",33,65),i=t.readUInt32BE(65,0)):57===t.length?(e=t.toString("hex",21,53),i=t.readUInt32BE(53,0)):r(!1),[e,i]},CP:function(t,e="ascii"){return t=s.s2b(t,e),(e=Buffer.allocUnsafe(37))[0]=147,n(e,t,1),e},CPc:function(t){let e;return r(Buffer.isBuffer(t)),r.strictEqual(t[0],147),37===t.length?e=t.slice(1,37):r(!1),s.b2s(e)},CV:Buffer.from([118]),EN2:function(t,e,i="ascii"){r("string"==typeof t),r("string"==typeof e);var s=Buffer.allocUnsafe(73);return s[0]=226,s.write(t,1,i),s.write(e,37,i),s},ER:function(t){t=s.s2b(t,"hex");var e=Buffer.allocUnsafe(33);return e[0]=152,n(e,t,1),e},ERR:function(t,e,i){return r("string"==typeof t),r("string"==typeof e),r("string"==typeof i),(i=Buffer.allocUnsafe(98))[0]=217,i.write(t,1,"hex"),i.write(e,34,"hex"),i.write(e,66,"hex"),i},ERRR:function(t){return r(Buffer.isBuffer(t)),[(t=t.slice(1)).toString("hex",0,33),t.toString("hex",33,65),t.toString("hex",65,97)]},ERA:function(t){r("string"==typeof t);var e=Buffer.allocUnsafe(33);return e[0]=216,e.write(t,1,"hex"),e},H:function(t){return o(72,t)},HL:Buffer.from([148]),O:Buffer.from([79]),R:Buffer.from([82]),SC:function(t,e="ascii"){return t=s.s2b(t,e),(e=Buffer.allocUnsafe(37))[0]=150,n(e,t,1),e},SR:function(t,e,i,a,o,c){var h=Buffer.allocUnsafe(117);return h.fill(0),Buffer.isBuffer(e)||(r("string"==typeof e),e=s.s2b(e)),h[0]=165,h.writeUInt32BE(t,1,!0),n(h,e,5),h.writeUInt32BE(i,41,!0),n(h,a,45),h.writeUInt32BE(o,109,!0),h.writeUInt32BE(c,113,!0),h},SRR:function(t){return r(Buffer.isBuffer(t)),[(t=t.slice(1)).readUInt32BE(0,!0),t.toString("ascii",4,40),t.readUInt32BE(40,!0),t.toString("hex",44,108),t.readUInt32BE(109,!0),t.readUInt32BE(109,!0)]},SN:function(t,e){var i=Buffer.allocUnsafe(37+e.length);return i.fill(0),Buffer.isBuffer(t)||(r("string"==typeof t),t=s.s2b(t)),i[0]=161,n(i,t,1),n(i,e,37),i},SNN:function(t){return r(Buffer.isBuffer(t)),[(t=t.slice(1)).toString("ascii",0,36),t.toString("hex",36,t.length)]},SS:function(t,e){var i=Buffer.allocUnsafe(41);return i.fill(0),Buffer.isBuffer(t)||(r("string"==typeof t),t=s.s2b(t)),i[0]=167,n(i,t,1),i.writeUInt32BE(e,37,!0),i},SSS:function(t){return r(Buffer.isBuffer(t)),r.strictEqual(t[0],167),[(t=t.slice(1)).toString("ascii",0,36),t.readUInt32BE(36,!0)]},T:function(t,e){let i,s=t.length;return"string"==typeof t&&(s/=2),32===s?((i=Buffer.allocUnsafe(65))[0]=171,n(i,t,1),n(i,e,33)):20===s?((i=Buffer.allocUnsafe(53))[0]=84,n(i,t,1),n(i,e,21)):r(!1),i},TI:function(t,e){let i,s=t.length;return"string"==typeof t&&(s/=2),32===s?((i=Buffer.allocUnsafe(65))[0]=244,n(i,t,1),n(i,e,33)):20===s?((i=Buffer.allocUnsafe(53))[0]=157,n(i,t,1),n(i,e,21)):r(!1),i},TO:function(t,e){let i,s=t.length;return"string"==typeof t&&(s/=2),32===s?((i=Buffer.allocUnsafe(65))[0]=250,n(i,t,1),n(i,e,33)):20===s?((i=Buffer.allocUnsafe(53))[0]=163,n(i,t,1),n(i,e,21)):r(!1),i},Tt:function(t){return r(Buffer.isBuffer(t)),65===t.length?t.toString("hex",33,65):(r(53===t.length),t.toString("hex",21,53))},V:Buffer.from([86]),VM:function(t){return o(164,t)},VO:function(t){return o(162,t)},VP:function(t,e="utf8"){return t=s.s2b(t,e),(e=Buffer.allocUnsafe(37))[0]=166,n(e,t,1),e},VPc:function(t){let e;return r(Buffer.isBuffer(t)),r.strictEqual(t[0],166),37===t.length?e=t.slice(1,37):r(!1),s.b2s(e)},VH:function(t,e){return this.hi(158,t,e)},b:function(t){return a(98,t)},c:function(t,e){return 99,t=t,e=e,i=Buffer.allocUnsafe(37),r("number"==typeof e),i[0]=99,n(i,t,1),i.writeUInt32BE(e,33,!0),i;var i},e:function(t){return a(101,t)},g:function(t){r("string"==typeof t);var e=Buffer.allocUnsafe(1+t.length/2);return e[0]=103,e.write(t,1,"hex"),e},gs:function(t,e,i){r("string"==typeof t),r("string"==typeof e),r("string"==typeof i);var s=Buffer.allocUnsafe(77);return s[0]=218,s.write(t,1,"hex"),s.write(e,21,"hex"),s.write(i,57,"hex"),s},h:function(t){return a(104,t)},hi:function(t,e,i){r("string"==typeof e),r("number"==typeof i);var s=Buffer.allocUnsafe(37);return s[0]=t,s.write(e,1,"hex"),s.writeUInt32BE(i,33,!0),s},hii:function(t){return r(Buffer.isBuffer(t)),r(37===t.length),[(t=t.slice(1)).toString("hex",0,32),t.readUInt32BE(32,!0)]},n:function(t){return a(110,t)},o:function(t,e){r("string"==typeof t),r("string"==typeof e);var i=Buffer.allocUnsafe(73);return i.fill(0),i[0]=111,i.write(t,1,"ascii"),i.write(e,37,"ascii"),i},oo:function(t){return r(Buffer.isBuffer(t)),r(73===t.length),[t.toString("ascii",1,37),t.toString("ascii",38,73)]},p:function(t){return a(112,t)},pp:function(t){return r(Buffer.isBuffer(t)),r(33===t.length),t.toString("hex",1,33)},s:function(t,e){return this.hi(115,t,e)},ss:function(t){return this.hii(t)},t:function(t){return a(116,t)},th:function(t,e){r("number"==typeof t);var i=Buffer.allocUnsafe(37);return i.fill(0),i[0]=220,i.writeUInt32BE(t,1,!0),n(i,e,5),i},thh:function(t){return r(Buffer.isBuffer(t)),r(220==t[0]),{time:t.readUInt32BE(1,!0),hash:t.slice(5,37).toString("hex")}},tx:function(t){return Buffer.concat([Buffer.from([236]),Buffer.from(t,"hex")])},u:function(t){return a(117,t)},v:function(t,e){var i=Buffer.allocUnsafe(34);return r("number"==typeof t),i[0]=118,i[1]=t,n(i,e,2),i},vv:function(t){return r(Buffer.isBuffer(t)),r(34===t.length),[t[1],t.toString("hex",2,34)]},version:function(t){var e=Buffer.allocUnsafe(4);return e.writeUInt32LE(t,0,!0),e},equalVersion:function(t,e){return r(Buffer.isBuffer(t)),t.readUInt32LE(0,!0)==e},s2b:function(t,e="ascii"){return Buffer.from(t,e)},b2s:(t,e="ascii")=>(r(Buffer.isBuffer(t)),t.toString(e))};function n(t,e,i){if(Buffer.isBuffer(e))return e.copy(t,i);r("string"==typeof e),t.write(e,i,"hex")}function a(t,e){var i=Buffer.allocUnsafe(33);return i[0]=t,n(i,e,1),i}function o(t,e){var i=Buffer.allocUnsafe(5);return r("number"==typeof e),i[0]=t,i.writeUInt32BE(e,1,!0),i}t.exports=s},function(t,e){t.exports=require("tls")},function(t,e,i){"use strict";
375
+ */const r=i(0),s={binary:!0,C:function(t,e,i){let s,a=t.length;return r("number"==typeof i),"string"==typeof t&&(a/=2),32===a?((s=Buffer.allocUnsafe(69))[0]=154,n(s,t,1),n(s,e,33),s.writeUInt32BE(i,65,!0)):20===a?((s=Buffer.allocUnsafe(57))[0]=67,n(s,t,1),n(s,e,21),s.writeUInt32BE(i,53,!0)):r(!1),s},Cc:function(t){let e,i;return r(Buffer.isBuffer(t)),69===t.length?(e=t.toString("hex",33,65),i=t.readUInt32BE(65,0)):57===t.length?(e=t.toString("hex",21,53),i=t.readUInt32BE(53,0)):r(!1),[e,i]},CP:function(t,e="ascii"){return t=s.s2b(t,e),(e=Buffer.allocUnsafe(37))[0]=147,n(e,t,1),e},CPc:function(t){let e;return r(Buffer.isBuffer(t)),r.strictEqual(t[0],147),37===t.length?e=t.slice(1,37):r(!1),s.b2s(e)},CV:Buffer.from([118]),EN2:function(t,e,i="ascii"){r("string"==typeof t),r("string"==typeof e);var s=Buffer.allocUnsafe(73);return s[0]=226,s.write(t,1,i),s.write(e,37,i),s},ER:function(t){t=s.s2b(t,"hex");var e=Buffer.allocUnsafe(33);return e[0]=152,n(e,t,1),e},ERR:function(t,e,i){r("string"==typeof t),r("string"==typeof e),r("string"==typeof i);var s=Buffer.allocUnsafe(98);return s[0]=217,s.write(t,1,"hex"),s.write(e,34,"hex"),s.write(i,66,"hex"),s},ERRR:function(t){return r(Buffer.isBuffer(t)),[(t=t.slice(1)).toString("hex",0,33),t.toString("hex",33,65),t.toString("hex",65,97)]},ERA:function(t){r("string"==typeof t);var e=Buffer.allocUnsafe(33);return e[0]=216,e.write(t,1,"hex"),e},H:function(t){return o(72,t)},HL:Buffer.from([148]),O:Buffer.from([79]),R:Buffer.from([82]),SC:function(t,e="ascii"){return t=s.s2b(t,e),(e=Buffer.allocUnsafe(37))[0]=150,n(e,t,1),e},SR:function(t,e,i,a,o,c){var h=Buffer.allocUnsafe(117);return h.fill(0),Buffer.isBuffer(e)||(r("string"==typeof e),e=s.s2b(e)),h[0]=165,h.writeUInt32BE(t,1,!0),n(h,e,5),h.writeUInt32BE(i,41,!0),n(h,a,45),h.writeUInt32BE(o,109,!0),h.writeUInt32BE(c,113,!0),h},SRR:function(t){return r(Buffer.isBuffer(t)),[(t=t.slice(1)).readUInt32BE(0,!0),t.toString("ascii",4,40),t.readUInt32BE(40,!0),t.toString("hex",44,108),t.readUInt32BE(109,!0),t.readUInt32BE(109,!0)]},SN:function(t,e){var i=Buffer.allocUnsafe(37+e.length);return i.fill(0),Buffer.isBuffer(t)||(r("string"==typeof t),t=s.s2b(t)),i[0]=161,n(i,t,1),n(i,e,37),i},SNN:function(t){return r(Buffer.isBuffer(t)),[(t=t.slice(1)).toString("ascii",0,36),t.toString("hex",36,t.length)]},SS:function(t,e){var i=Buffer.allocUnsafe(41);return i.fill(0),Buffer.isBuffer(t)||(r("string"==typeof t),t=s.s2b(t)),i[0]=167,n(i,t,1),i.writeUInt32BE(e,37,!0),i},SSS:function(t){return r(Buffer.isBuffer(t)),r.strictEqual(t[0],167),[(t=t.slice(1)).toString("ascii",0,36),t.readUInt32BE(36,!0)]},T:function(t,e){let i,s=t.length;return"string"==typeof t&&(s/=2),32===s?((i=Buffer.allocUnsafe(65))[0]=171,n(i,t,1),n(i,e,33)):20===s?((i=Buffer.allocUnsafe(53))[0]=84,n(i,t,1),n(i,e,21)):r(!1),i},TI:function(t,e){let i,s=t.length;return"string"==typeof t&&(s/=2),32===s?((i=Buffer.allocUnsafe(65))[0]=244,n(i,t,1),n(i,e,33)):20===s?((i=Buffer.allocUnsafe(53))[0]=157,n(i,t,1),n(i,e,21)):r(!1),i},TO:function(t,e){let i,s=t.length;return"string"==typeof t&&(s/=2),32===s?((i=Buffer.allocUnsafe(65))[0]=250,n(i,t,1),n(i,e,33)):20===s?((i=Buffer.allocUnsafe(53))[0]=163,n(i,t,1),n(i,e,21)):r(!1),i},Tt:function(t){return r(Buffer.isBuffer(t)),65===t.length?t.toString("hex",33,65):(r(53===t.length),t.toString("hex",21,53))},V:Buffer.from([86]),VM:function(t){return o(164,t)},VO:function(t){return o(162,t)},VP:function(t,e="utf8"){return t=s.s2b(t,e),(e=Buffer.allocUnsafe(37))[0]=166,n(e,t,1),e},VPc:function(t){let e;return r(Buffer.isBuffer(t)),r.strictEqual(t[0],166),37===t.length?e=t.slice(1,37):r(!1),s.b2s(e)},VH:function(t,e){return this.hi(158,t,e)},b:function(t){return a(98,t)},c:function(t,e){return 99,t=t,e=e,i=Buffer.allocUnsafe(37),r("number"==typeof e),i[0]=99,n(i,t,1),i.writeUInt32BE(e,33,!0),i;var i},e:function(t){return a(101,t)},g:function(t){r("string"==typeof t);var e=Buffer.allocUnsafe(1+t.length/2);return e[0]=103,e.write(t,1,"hex"),e},gs:function(t,e,i){r("string"==typeof t),r("string"==typeof e),r("string"==typeof i);var s=Buffer.allocUnsafe(77);return s[0]=218,s.write(t,1,"hex"),s.write(e,21,"hex"),s.write(i,57,"hex"),s},h:function(t){return a(104,t)},hi:function(t,e,i){r("string"==typeof e),r("number"==typeof i);var s=Buffer.allocUnsafe(37);return s[0]=t,s.write(e,1,"hex"),s.writeUInt32BE(i,33,!0),s},hii:function(t){return r(Buffer.isBuffer(t)),r(37===t.length),[(t=t.slice(1)).toString("hex",0,32),t.readUInt32BE(32,!0)]},n:function(t){return a(110,t)},o:function(t,e){r("string"==typeof t),r("string"==typeof e);var i=Buffer.allocUnsafe(73);return i.fill(0),i[0]=111,i.write(t,1,"ascii"),i.write(e,37,"ascii"),i},oo:function(t){return r(Buffer.isBuffer(t)),r(73===t.length),[t.toString("ascii",1,37),t.toString("ascii",38,73)]},p:function(t){return a(112,t)},pp:function(t){return r(Buffer.isBuffer(t)),r(33===t.length),t.toString("hex",1,33)},s:function(t,e){return this.hi(115,t,e)},ss:function(t){return this.hii(t)},t:function(t){return a(116,t)},th:function(t,e){r("number"==typeof t);var i=Buffer.allocUnsafe(37);return i.fill(0),i[0]=220,i.writeUInt32BE(t,1,!0),n(i,e,5),i},thh:function(t){return r(Buffer.isBuffer(t)),r(220==t[0]),{time:t.readUInt32BE(1,!0),hash:t.slice(5,37).toString("hex")}},tx:function(t){return Buffer.concat([Buffer.from([236]),Buffer.from(t,"hex")])},u:function(t){return a(117,t)},v:function(t,e){var i=Buffer.allocUnsafe(34);return r("number"==typeof t),i[0]=118,i[1]=t,n(i,e,2),i},vv:function(t){return r(Buffer.isBuffer(t)),r(34===t.length),[t[1],t.toString("hex",2,34)]},version:function(t){var e=Buffer.allocUnsafe(4);return e.writeUInt32LE(t,0,!0),e},equalVersion:function(t,e){return r(Buffer.isBuffer(t)),t.readUInt32LE(0,!0)==e},s2b:function(t,e="ascii"){return Buffer.from(t,e)},b2s:(t,e="ascii")=>(r(Buffer.isBuffer(t)),t.toString(e))};function n(t,e,i){if(Buffer.isBuffer(e))return e.copy(t,i);r("string"==typeof e),t.write(e,i,"hex")}function a(t,e){var i=Buffer.allocUnsafe(33);return i[0]=t,n(i,e,1),i}function o(t,e){var i=Buffer.allocUnsafe(5);return r("number"==typeof e),i[0]=t,i.writeUInt32BE(e,1,!0),i}t.exports=s},function(t,e){t.exports=require("tls")},function(t,e,i){"use strict";
376
376
  /*!
377
377
  * general.js - bitcoin constants for vallnet
378
378
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -881,7 +881,7 @@ var r=i(775),s=i(777),n=i(778),a=i(779),o=i(780),c=i(781),h=i(782),u=i(783);i=i(
881
881
  /*!
882
882
  * chaindb.js - blockchain data management for vallnet
883
883
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
884
- */const r=i(0),s=i(1),n=i(2),a=i(4),o=i(33),c=i(3),h=i(15),u=i(61),l=i(252),p=i(169),d=i(148),f=i(65),m=i(75),g=i(46),y=i(31),v=i(12),w=i(332),b=i(333),k=i(147),x=c.U8,S=c.U32,{getVerifyMsg:E,BlockFinalType:_,OrderData:R,ContractEnvType:A,ContractType:C}=i(5);var I=i(72);const O=i(43),P=i(19),T=i(60),j=i(114),B=i(26),N=i(7),F=i(145),D=i(6),L=i(161),M=i(154),H=M.scItem,z=i(232),U=z.stockAccount,q=i(342),V=i(85),K=V.cpItem,W=V.cpSnap,G=V.stockItem,$=i(134),X=$.vpItem,Y=i(343),J=Y.vpItem,Z=i(728),Q=i(157),tt=Q.ErItem,et=i(158),it=et.ErAbolishItem,rt=i(237),st=rt.EnchancementItem;i(53);const nt=i(344),at=i(118),{opcodes:ot,nestingCodes:ct}=i(21),ht=i(125),ut=i(28),lt=i(39),pt=i(37).VerifyError;class dt extends I{constructor(t){super(),this.chain=t,this.eid="chaindb",this.fromOptions(t.options),this.db=p(this.options),this.stateCache=new gt(this.network),this.state=new mt,this.pending=null,this.current=null,this.coinCache=new f(this.options.coinCache),this.cacheHash=new f(this.options.entryCache),this.cacheHeight=new f(this.options.entryCache),this.autoTaskMgr=new L(this),this.propList=new $(this),this.htlcList=new Y(this),this.$voteMgr=new Z(this),this.transactionList=new q(this),this.cpList=new V(this),this.scList=new M(this),this.erList=new Q(this),this.erAbList=new et(this),this.enCpList=new rt(this,{type:"cp"}),this.accountList=new z(this),this.middleHashChain=new Set,this.on("contract.order.confirm",t=>{var e=this.cpList.getItem(t.cid);e&&this.node.notifyCp(t,e)}),this.on("contract.order.unconfirm",t=>{var e=this.cpList.getItem(t.cid);e&&this.node.notifyCp(t,e)})}get hmacConnection(){return this.node.specialCp.content()}get voteMgr(){return this.$voteMgr}async setCpHistory(){if(this.curHeight%10==0){var t=await this.cpList.query([["status",1]]);if(0<t.list.length){var e,i=this.db.batch();for(e of t.list){var r=e.cid,s={};let t=100;for(const i of(await this.getStockPropList(r)).reduce((t,e)=>((e=X.fromRaw(e.value)).height<=this.curHeight-D.BLOCK_DAY&&t.push(e),t),[]))if(i.current.address!=e.current.address&&(s[i.current.address]=(s[i.current.address]||0)+1),(t-=3)<=70)break;var n=(await this.accountList.query([["cid",r]])).list.sort((t,e)=>t.addr.localeCompare(e.addr));n=new W({grate:e.grate,addrOfMaster:e.current.address,hSum:e.stock.hSum,lords:s,slist:n});i.put(d.SS(r,this.curHeight),n.toRaw()),e.status=0,i.put(d.CP(e.cid),e.toRaw())}await i.write()}}}async getGuider(t){return t=v.fromString(t).getHash("hex"),(t=await this.db.get(d.g(t)))?v.fromRaw(t).toString():null}async setGuider(t,e,i){var r;i=v.fromString(i),await this.db.has(d.g(i.getHash("hex")))||(t=v.fromString(t),await(r=this.db.batch()).put(d.g(i.getHash("hex")),t.toRaw()),await r.put(d.gs(t.getHash("hex"),Buffer.from(e,"ascii").toString("hex"),i.getHash("hex")),i.toRaw()),await r.write())}async unsetGuider(t,e,i){t=v.fromString(t).getHash("hex"),i=v.fromString(i).getHash("hex");var r=this.db.batch();r.del(d.g(i)),r.del(d.gs(t,Buffer.from(e,"ascii").toString("hex"),i)),await r.write()}async getSimAddresses(t,e){t=v.fromString(t).getHash("hex");let i=Buffer.from(e,"ascii").toString("hex"),r=i;return e||(i=c.ZERO_CID,r=c.MAX_CID),(await this.db.values({gte:d.gs(t,i,c.ZERO_HASH160_HEX),lte:d.gs(t,r,c.MAX_HASH160_HEX),parse:t=>v.fromRaw(t).toString()})).length}async getCpHistory(t,e){return(t=await this.db.get(d.SS(t,e)))?W.fromRaw(t):null}async getCpSnap(t){let e=null,i=this.curHeight;for(;!e;){10<=i?5<(s=i%10)?i-=s:i=i-10-s:i=0;var r,s=await this.getCpHistory(t,i);if(s)(e={cid:t}).grate=s.grate,e.addrOfMaster=s.addrOfMaster,e.hSum=s.hSum,e.slist=s.slist,e.lords=s.lords,e.addresses=Object.keys(e.lords).sort((t,e)=>t.localeCompare(e));else if(0==i)return(r=this.cpList.getItem(t))?{cid:r.cid,grate:r.grate,addrOfMaster:r.current.address,hSum:r.stock.hSum,slist:[],lords:{},addresses:[]}:null}return e}get mode(){return A.Block}fromOptions(t){this.options=t,this.node=t.node,this.network=t.network,this.logger=t.logger.context("chaindb")}get curHeight(){return this.chain.height}get finder(){return this.node.getTXFromAll?this.node.getTXFromAll.bind(this.node):()=>{}}get tidCreator(){return d.tx}rpcExecute(){return this.node.rpc.execute.apply(this.node.rpc,arguments)}createGenesisCoinbase(t,e){var i,r=new P,s=new j,n=((i=((i=(s.script.pushInt(0),s.script.pushData(c.ZERO_HASH160),Buffer.allocUnsafe(4))).writeUInt32LE(0,0,!0),s.script.pushData(i),s.script.pushData(c.ZERO_U64),s.script.compile(),s.witness.push(c.ZERO_HASH),s.witness.compile(),r.inputs.push(s),new B)).script.createScript(c.ZERO_HASH160),i.value=D.ORIGINAL,r.outputs.push(i),c.ZERO_HASH),a=[],[a,,]=(a.push(c.ZERO_HASH),F.createRoot(a));a=N.root256(a,n);return(n=new B).script.fromCommitment(a),r.outputs.push(n),s.script.setData(1,e),s.script.compile(),i.script.fromAddress(t.addresses[0]),r}dummyInput(){return j.fromOutpoint(new g(c.NULL_HASH,0))}createGenesisBlock(t){if(!t.addresses||t.addresses.length<11)throw new Error("addresses length expect 11.");let e=t.flags;e=e||Buffer.from("In the name of Athena: Of the user, By the user, and For the user.","ascii");var i=this.createGenesisCoinbase(t,e),r=this.network.genesisId,n=new T,[n,,]=(n.addInput(this.dummyInput()),n.cpRegister(t.addresses[0],D.COIN,{cid:r,oper:C.cpRegister,name:"ATHENA",ip:"*",pubAddress:"",pubKey:"",signMethod:""}),n.commit()),a=new T;a.addInput(this.dummyInput());for(let e=0;e<10;e++)for(let i=0;i<10;i++){var o={oper:C.propCreate,pid:""+this.network.tokenFix+s.sprintf("%04d",10*e+i+1),oid:this.network.tokenFix+"0000",cid:r,gold:D.COIN};a.propCreate(t.addresses[e+1],o)}var[h,,]=a.commit(),u=new m({version:t.version,prevBlock:c.NULL_HASH,merkleRoot:i.hash("hex"),time:t.time,bits:t.bits,nonce:t.nonce,height:0});return u.txs.push(i),u.txs.push(n),u.txs.push(h),u.refresh(!0),u.merkleRoot=u.createMerkleRoot("hex"),u}async open(t){this.logger.info("Opening ChainDB..."),await this.db.open();var e=await this.db.checkVersion(d,3);if(i=await this.getState()){var i;if(await this.verifyFlags(i),await this.verifyDeployments(),this.stateCache=await this.getStateCache(),this.state=i,!(i=await this.getEntry(0)))throw new Error("genesis block not found.");this.network.genesis.hash=i.hash,this.network.genesis.merkleRoot=i.merkleRoot,this.logger.info("ChainDB successfully loaded.")}else t&&(i=await this.getGenesisParams(t),this.node.miner&&(this.node.miner.addresses=[new v(i.coinbaseAddress)]),this.node.config)&&this.node.config.changeParams(i),await this.saveFlags(),await this.saveDeployments(),await this.saveGenesis(),this.logger.info("ChainDB successfully initialized.");return this.logger.info("Chain State: hash=%s tx=%d coin=%d value=%s.",this.state.rhash(),this.state.tx,this.state.coin,o.btc(this.state.value)),e}async getGenesisParams(t){if(t.isGenesisParams)return t;t=t||{};var e=new nt({name:"wallet-test",db:"memory",resolution:!1,verify:!1}),i=(e=(t.getMnemonicFromMemory=!0,await e.open(t),await e.get("primary")),[]);for(const s of await e.getPaths("default")){var r=s.toAddress();0==s.branch&&i.push(""+r.toString(t.network))}var s,n,a,o,h={};return h[t.network+"Addresses"]=i.reduce((t,e)=>t+(""==t?e:","+e),""),h.coinbaseAddress=i[1],h.notifyAddress=e.notifyAddress,this.node.config.notifyAddress=h.notifyAddress,await ht.writeFile(h,t.network+"-genesis.params"),t.isGenesisEncrypt||(s=N.hash256(Buffer.from(e.master.mnemonic.toSeed().toString("hex"))),n=ut.publicKeyCreate(s,!0),a=v.fromWitnessPubkeyhash(N.hash160(n),this.network.type).toString(),o=N.hash256(Buffer.concat([Buffer.from("root"),e.master.key.privateKey])),e={body:{language:e.master.mnemonic.language,phrase:e.master.mnemonic.getPhrase(),passphrase:e.master.mnemonic.passphrase,awardAddress:h.coinbaseAddress,notifyAddress:e.notifyAddress,alliancePrivateKey:o.toString("hex"),allianceName:"root",allianceNodeId:0,allianceNodeToken:{prv:s.toString("hex"),pub:n.toString("hex"),address:a}},password:t.password||c.MNEMONIC_SALT,network:t.network,file:t.network+"-genesis.keystore"},await ht.writeEncryptFile(e)),h}close(){return this.db.close()}start(){return r(!this.current),r(!this.pending),this.current=this.db.batch(),this.pending=this.state.clone(),this.coinCache.start(),this.cacheHash.start(),this.cacheHeight.start(),this.current}put(t,e){r(this.current),this.current.put(t,e)}del(t){r(this.current),this.current.del(t)}batch(){return r(this.current),this.current}drop(){var t=this.current;r(this.current),r(this.pending),this.current=null,this.pending=null,this.coinCache.drop(),this.cacheHash.drop(),this.cacheHeight.drop(),this.stateCache.drop(),t.clear()}async commit(){r(this.current),r(this.pending);try{await this.current.write()}catch(t){throw this.current=null,this.pending=null,this.coinCache.drop(),this.cacheHash.drop(),this.cacheHeight.drop(),t}this.pending.committed&&(this.state=this.pending),this.current=null,this.pending=null,this.coinCache.commit(),this.cacheHash.commit(),this.cacheHeight.commit(),this.stateCache.commit()}hasCache(t){return("number"==typeof t?this.cacheHeight:(r("string"==typeof t),this.cacheHash)).has(t)}getCache(t){return("number"==typeof t?this.cacheHeight:(r("string"==typeof t),this.cacheHash)).get(t)}async getHeight(t){var e;return"number"==typeof t?t:(r("string"==typeof t),t===c.NULL_HASH?-1:(e=this.cacheHash.get(t))?e.height:(e=await this.db.get(d.h(t)))?e.readUInt32LE(0,!0):-1)}async getHash(t){var e;return"string"==typeof t?t:(r("number"==typeof t),t<0?null:(e=this.cacheHeight.get(t))?e.hash:(e=await this.db.get(d.H(t)))?e.toString("hex"):null)}async getEntryByHeight(t){var e;return r("number"==typeof t),t<0?null:this.cacheHeight.get(t)||((t=await this.db.get(d.H(t)))&&(t=t.toString("hex"),e=this.state,t=await this.getEntryByHash(t))?(this.state===e&&this.cacheHeight.set(t.height,t),t):null)}async getEntryByHash(t){return r("string"==typeof t),t===c.NULL_HASH?null:this.cacheHash.get(t)||((t=await this.db.get(d.e(t)))?(t=w.fromRaw(t),this.cacheHash.set(t.hash,t),t):null)}getEntry(t){return"number"==typeof t?this.getEntryByHeight(t):this.getEntryByHash(t)}async hasEntry(t){return-1!==await this.getHeight(t)}async getAncestor(t,e){if(e<0)return null;if(r(0<=e),r(e<=t.height),await this.isMainChain(t))return this.getEntryByHeight(e);for(;t.height!==e;){t=this.getPrevCache(t)||await this.getPrevious(t),r(t)}return t}getPrevious(t){return this.getEntryByHash(t.prevBlock)}getPrevCache(t){return this.cacheHash.get(t.prevBlock)||null}async getNext(t){return(t=await this.getNextHash(t.hash))?this.getEntryByHash(t):null}async getNextEntry(t){var e=await this.getEntryByHeight(t.height+1);return e&&e.prevBlock===t.hash?e:null}getTip(){return this.getEntryByHash(this.state.tip)}async getState(){var t=await this.db.get(d.R);return t?mt.fromRaw(t):null}async saveGenesis(){let t=[];t=(this.node.config?this.node.config[this.network.type+"Addresses"]:this.network.genesis.addresses).split(",");var e=this.createGenesisBlock({version:this.network.genesis.version,time:this.network.genesis.time,bits:this.network.genesis.bits,nonce:this.network.genesis.nonce,addresses:t}),i=(this.network.genesis.hash=e.hash("hex"),this.network.genesis.merkleRoot=e.merkleRoot,w.fromBlock(e)),r=(this.logger.info("Writing genesis block to ChainDB."),new u);for(let t=0;t<e.txs.length;t++)r.addTX(e.txs[t],e.height,e.time);await this.save(i,e,r)}async getFlags(){var t=await this.db.get(d.O);return t?ft.fromRaw(t):null}async verifyFlags(t){var e=this.options,i=await this.getFlags();let r=!1,s=!1;if(!i)throw new Error("No flags found.");if(e.network!==i.network)throw new Error("Network mismatch for chain.");if(e.spv&&!i.spv)throw new Error("Cannot retroactively enable SPV.");if(!e.spv&&i.spv)throw new Error("Cannot retroactively disable SPV.");if(!i.witness){if(!e.forceFlags)throw new Error("Cannot retroactively enable witness.");r=!0}if(e.prune&&!i.prune){if(!e.forceFlags)throw new Error("Cannot retroactively prune.");s=!0}if(!e.prune&&i.prune)throw new Error("Cannot retroactively unprune.");if(e.indexTX&&!i.indexTX)throw new Error("Cannot retroactively enable TX indexing.");if(!e.indexTX&&i.indexTX)throw new Error("Cannot retroactively disable TX indexing.");if(e.indexAddress&&!i.indexAddress)throw new Error("Cannot retroactively enable address indexing.");if(!e.indexAddress&&i.indexAddress)throw new Error("Cannot retroactively disable address indexing.");r&&(await this.logger.info("Rewriting chain flags."),await this.saveFlags()),s&&(await this.logger.info("Retroactively pruning chain."),await this.prune(t.tip))}async getStateCache(){var t=new gt(this.network);for(const s of await this.db.range({gte:d.v(0,c.ZERO_HASH),lte:d.v(255,c.MAX_HASH),values:!0})){var[e,i]=d.vv(s.key),r=s.value[0];t.insert(e,i,r)}return t}saveDeployments(){var t=this.db.batch();return this.writeDeployments(t),t.write()}async batchPut(t,e){var i=this.db.batch();i.put(t,e),await i.write()}async batchDel(t){var e=this.db.batch();e.del(t),await e.write()}writeDeployments(t){var e=new a(1+17*this.network.deploys.length);e.writeU8(this.network.deploys.length);for(const t of this.network.deploys)e.writeU8(t.bit),e.writeU32(t.startTime),e.writeU32(t.timeout),e.writeI32(t.threshold),e.writeI32(t.window);t.put(d.V,e.render())}async checkDeployments(){var t=await this.db.get(d.V),e=(r(t,"No deployment table found."),new n(t)),i=e.readU8(),s=[];for(let t=0;t<i;t++){var a=e.readU8(),o=e.readU32(),c=e.readU32(),h=e.readI32(),u=e.readI32(),l=this.network.byBit(a);l&&o===l.startTime&&c===l.timeout&&h===l.threshold&&u===l.window||s.push(a)}return s}async verifyDeployments(){let t;try{t=await this.checkDeployments()}catch(e){if("EncodingError"!==e.type)throw e;t=[];for(let e=0;e<32;e++)t.push(e)}if(0===t.length)return!0;var e=this.db.batch();for(const i of t)this.logger.warning("Versionbit deployment params modified."),this.logger.warning("Invalidating cache for bit %d.",i),await this.invalidateCache(i,e);return this.writeDeployments(e),await e.write(),!1}async invalidateCache(t,e){for(const i of await this.db.keys({gte:d.v(t,c.ZERO_HASH),lte:d.v(t,c.MAX_HASH)}))e.del(i)}async prune(){var t=this.options,e=this.network.block.keepBlocks,i=this.network.block.pruneAfterHeight;if((await this.getFlags()).prune)throw new Error("Chain is already pruned.");var s=await this.getHeight(this.state.tip);if(s<=i+e)return!1;i+=1;var n=s-e,a=this.db.batch();for(let t=i;t<=n;t++){var o=await this.getHash(t);if(!o)throw new Error(`Cannot find hash for ${t}.`);a.del(d.b(o)),a.del(d.u(o))}try{t.prune=!0;const e=ft.fromOptions(t);r(e.prune),a.put(d.O,e.toRaw()),await a.write()}catch(e){throw t.prune=!1,e}return await this.db.compactRange(),!0}async getNextHash(t){return(t=await this.db.get(d.n(t)))?t.toString("hex"):null}async isMainHash(t){if(r("string"==typeof t),t===c.NULL_HASH)return!1;if(t===this.network.genesis.hash)return!0;if(t===this.state.tip)return!0;var e=this.cacheHash.get(t);return e&&(e=this.cacheHeight.get(e.height))?e.hash===t:!!await this.getNextHash(t)}async isMainChain(t){var e;return!!t.isGenesis()||t.hash===this.state.tip||((e=this.getCache(t.height))?t.hash===e.hash:!!await this.getNextHash(t.hash))}getEntries(){return this.db.values({gte:d.e(c.ZERO_HASH),lte:d.e(c.MAX_HASH),parse:t=>w.fromRaw(t)})}getTimestampHashes(t,e){return this.db.keys({gte:d.th(e,c.ZERO_HASH),lte:d.th(t,c.MAX_HASH),parse:d.thh})}getContracts(){return this.db.values({gte:d.tx(c.NULL_HASH),lte:d.tx(c.HIGH_HASH),parse:t=>s.parseJson(t.toString())})}getCps(){return this.db.values({gte:d.CP(c.ZERO_CID,"hex"),lte:d.CP(c.MAX_CID,"hex"),parse:t=>K.fromRaw(t)})}async setCp(t){var e=this.db.batch();e.put(d.CP(t.cid),t.toRaw()),await e.write()}async delCp(t){var e=this.db.batch();e.del(d.CP(t)),await e.write()}getScs(){return this.db.values({gte:d.SC(c.ZERO_CID,"hex"),lte:d.SC(c.MAX_CID,"hex"),parse:t=>H.fromRaw(t)})}async setSc(t){var e=this.db.batch();e.put(d.SC(t.id),t.toRaw()),await e.write()}async delSc(t){var e=this.db.batch();e.del(d.SC(t)),await e.write()}async getSCList(t){return r(Array.isArray(t)),this.scList.query(t)}async getStockAccountList(t){return t?this.db.values({gte:U.SN(t,c.NULL_HASH),lte:U.SN(t,c.HIGH_HASH),parse:U.fromRaw}):this.db.values({gte:U.SN(c.ZERO_CID_BUF,c.NULL_HASH),lte:U.SN(c.MAX_CID_BUF,c.HIGH_HASH),parse:U.fromRaw})}async setStockRecord(t){var e=this.db.batch();switch(e.put(t.itemNo,t.toRaw()),t.type){case G.RecordType.Offer:break;case G.RecordType.Bid:var i=this.accountList.getStockAccount(t.cid,t.addr);i&&(i.stock.sum=t.sum,i.stock.price=t.price,i.seq=t.seq,i.stock.period=this.curHeight+1+10*D.BLOCK_DAY,e.put(i.getItemNo(),i.toRaw()));break;case G.RecordType.Auction:{if(!(i=this.accountList.getStockAccount(t.cid,t.to)))break;let s=this.accountList.getStockAccount(t.cid,t.addr);s||(s=new U(t.cid,t.addr,0,0,0),this.accountList.setStockAccount(s));var r=s.sum+t.sum;s.price=(t.sum*t.price+s.sum*s.price)/r|0,s.sum=r,s.seq=t.seq,e.put(s.getItemNo(),s.toRaw()),r=i.sum-t.sum,i.sum=r,i.stock.sum-=t.sum,e.put(i.getItemNo(),i.toRaw());break}case G.RecordType.Purchase:{let i=this.accountList.getStockAccount(t.cid,t.addr);i?(r=i.sum+t.sum,i.price=(t.sum*t.price+i.sum*i.price)/r,i.sum=r,i.seq=t.seq):((i=new U(t.cid,t.addr,t.sum,t.price,0)).seq=t.seq,this.accountList.setStockAccount(i)),e.put(i.getItemNo(),i.toRaw());break}case G.RecordType.Send:if(i=this.accountList.getStockAccount(t.cid,t.addr)){i.sum-=t.sum,i.seq=t.seq;let s=this.accountList.getStockAccount(t.cid,t.to);s||(s=new U(t.cid,t.to,0,0),this.accountList.setStockAccount(s)),r=s.sum+t.sum,s.price=(t.sum*i.price+s.sum*s.price)/r,s.sum=r,e.put(i.getItemNo(),i.toRaw()),e.put(s.getItemNo(),s.toRaw())}break;case G.RecordType.Bonus:case G.RecordType.Ads:}await e.write()}async unsetStockRecord(t){var e=this.db.batch();switch(e.del(t.itemNo),t.type){case G.RecordType.Offer:break;case G.RecordType.Bid:(s=this.accountList.getStockAccount(t.cid,t.addr))&&(s.stock.sum=0,s.stock.price=0,s.stock.period=0,s.seq=t.seq-1,e.put(s.getItemNo(),s.toRaw()));break;case G.RecordType.Auction:(s=this.accountList.getStockAccount(t.cid,t.addr))&&(i=s.sum-t.sum,s.price=(s.sum*s.price-t.sum*t.price)/i|0,s.sum=i,s.seq=t.seq-1,e.put(s.getItemNo(),s.toRaw()),s=this.accountList.getStockAccount(t.cid,t.to))&&(i=s.sum+t.sum,s.sum=i,s.stock.sum+=t.sum,e.put(s.getItemNo(),s.toRaw()));break;case G.RecordType.Purchase:var i=this.accountList.getStockAccount(t.cid,t.addr);i&&(s=i.sum-t.sum,i.price=(i.sum*i.price-t.sum*t.price)/s|0,i.sum=s,i.seq=t.seq-1,e.put(i.getItemNo(),i.toRaw()));break;case G.RecordType.Send:var r,s;(s=this.accountList.getStockAccount(t.cid,t.addr))&&(s.sum+=t.sum,s.seq=t.seq-1,e.put(s.getItemNo(),s.toRaw()),i=this.accountList.getStockAccount(t.cid,t.to))&&(r=i.sum-t.sum,i.price=(i.sum*i.price-t.sum*s.price)/r|0,i.sum=r,e.put(i.getItemNo(),i.toRaw()));break;case G.RecordType.Bonus:}await e.write()}async getStockPropList(t){return this.db.range({gte:d.VP(""+t+this.network.stockFix+s.sprintf("%02d",0)),lte:d.VP(""+t+this.network.stockFix+s.sprintf("%02d",29)),values:!0})}async delVp(t){var e=this.db.batch();e.del(d.VP(t.pid)),await e.write()}async setVp(t){var e=this.db.batch();e.put(d.VP(t.pid),t.toRaw()),await e.write()}async getVp(t){return(t=await this.db.get(d.VP(t)))?X.fromRaw(t):null}loadVpList(){return this.db.values({gte:d.VP(c.ZERO_CID,"hex"),lte:d.VP(c.MAX_CID,"hex"),parse:t=>X.fromRaw(t)})}async delHtlc(t){var e;t.id&&(this.htlcList.delete(t.id),this.htlcList.delAccount(t),(e=this.db.batch()).del(d.VH(t.shash,t.sidx)),await e.write())}async setSuggest(t){t=new J(t);var e=(this.htlcList.set(t.id,t),this.db.batch());e.put(d.VH(t.shash,t.sidx),t.toRaw()),await e.write()}async setAssent(t){t=new J(t);var e=(this.htlcList.set(t.id,t),this.db.batch());e.put(d.VH(t.shash,t.sidx),t.toRaw()),await e.write()}async loadHtlcList(){return this.db.values({gte:d.VH(c.ZERO_CID,0),lte:d.VH(c.MAX_CID,4294967295),parse:t=>J.fromRaw(t)})}async delErAbolish(t){var e=this.db.batch();e.del(d.ERA(t.erid)),await e.write()}async setErAbolish(t){var e=this.db.batch();e.put(d.ERA(t.erid),t.toRaw()),await e.write()}async getErAbolish(t){return(t=await this.db.get(d.ERA(t)))?it.fromRaw(t):null}loadErAbolishList(){return this.db.values({gte:d.ERA(c.ZERO_CID),lte:d.ERA(c.MAX_CID),parse:t=>it.fromRaw(t)})}async delCpEn(t){var e=this.db.batch();e.del(d.EN2(t.to,t.from)),await e.write()}async setCpEn(t){var e=this.db.batch();e.put(d.EN2(t.to,t.from),t.toRaw()),await e.write()}loadCpEnList(){return this.db.values({gte:d.EN2(c.ZERO_CID,c.ZERO_CID,"ascii"),lte:d.EN2(c.MAX_CID,c.MAX_CID,"ascii"),parse:t=>st.fromRaw(t)})}queryCpEnListByCid(t){return this.db.values({gte:d.EN2(t,c.ZERO_CID,"ascii"),lte:d.EN2(t,c.MAX_CID,"ascii"),parse:t=>st.fromRaw(t)})}async delEr(t){var e=this.db.batch();e.del(d.ER(t.erid)),e.del(d.ERR(t.witness,t.erid,t.txid)),await e.write()}async setEr(t,e){var i=this.db.batch(),r=d.ERR(t.witness,t.erid,t.txid);i.put(r,t.toRaw()),i.put(d.ER(t.erid),r),await i.write()}async getEr(t){if(!(t=await this.db.get(d.ER(t))))return null;var[,,t]=d.ERRR(t);let e=await this.db.get(e);return e?((e=tt.fromRaw(e)).txid=t,e):null}async byPubkey(t,e,i=!1){if(!(t=await this.db.values({gte:d.ERR(t,c.NULL_HASH,c.NULL_HASH),lte:d.ERR(t,c.HIGH_HASH,c.HIGH_HASH),parse:t=>tt.fromRaw(t)}))||0==t.length)return[];let r=null;if(i){var s,n=new Map;for(s of t){var a,o=await this.caVerifyObj(s);o&&((a=n.get(o.source.cluster))?o.startHeight>a.startHeight&&n.set(s.source.cluster,o):n.set(o.source.cluster,o))}r=n.values()}else r=t;if(!r||0==r.length)return[];var h,u=new y;for(h of r)u.set(h.erid,h);return u.query(e)}async caVerify(t){return this.caVerifyObj(await this.erList.getEr(t))}async caVerifyObj(t){var e;return t?(t.verify=!1,t.validHeight<=this.chain.height||(e=await this.erAbList.getErAb(t.erid))&&e.abolishHeight<this.chain.height||(e=lt.fromPublic(Buffer.from(t.witness,"hex"),this.network.type),t.verifying(e)&&(t.verify=!0,0<(e=this.cpList.query([["pubKey",t.witness]])).list.length)&&(t.cpid=e.list[0].cid)),t):null}async addOrder(t){await this.batchPut(d.o(t.cid,t.sn),t.toRaw())}async arrangeOrder(t){var e,i=[],r=[];for(e of await this.db.values({gte:d.o(t,c.ZERO_OID),lte:d.o(t,c.MAX_OID),parse:R.fromRaw}))(-1==e.height&&this.curHeight-e.publish>=10*D.BLOCK_DAY?r:i).push(e);return 0<r.length&&this.delOrder(r),i}async getAddressesFromOrder(t){var e,i=[];t.cls&&i.push(["cls",t.cls]);let r=await this.node.rpc.execute({method:"cp.remoteQuery",params:[i]}),s=[];for(e of r=r.list.map(t=>t.cid))s=s?s.concat(await this.arrangeOrder(e)):await this.arrangeOrder(e);s=s.reduce((e,i)=>(i.addr&&0<i.height&&(!t.time||600*(this.chain.height-i.height)<t.time)&&(e[i.addr]?i.sum&&(e[i.addr].sum+=i.sum):(e[i.addr]=i,e[i.addr].sum=e[i.addr].sum||0)),e),{});var n={list:[],pageNum:1,pageCur:1};(s=(s=t.amount?Object.values(s).filter(e=>e.sum>=t.amount):Object.values(s)).map(t=>({addr:t.addr,sum:t.sum}))).length%t.pageSize==0?n.pageNum=s.length/t.pageSize|0:n.pageNum=1+(s.length/t.pageSize|0),n.pageCur=Math.max(1,Math.min(n.pageNum,t.page));for(let e=t.pageSize*(n.pageCur-1);e<t.pageSize*n.pageCur&&s[e];e++)n.list.push(s[e]);return n}async getOrderList(t,e){r("string"==typeof t),r(Array.isArray(e));let i=null;for(var n of e)if("sn"==n[0]){i=2==n.length?n[1]:n[2],i=Array.isArray(i)?1==i.length?s.sprintf("%0-36s",i[0]):i.map(t=>s.sprintf("%0-36s",t)):s.sprintf("%0-36s",i),2==n.length?n[1]=i:n[2]=i;break}var a=new y;return(await this.arrangeOrder(t)).reduce((t,e)=>(t.set(""+e.cid+e.sn,e),t),a),a.query(e)}async getOrderRecord(t,e){return r("string"==typeof t),r("string"==typeof e),e=s.sprintf("%0-36s",e),(t=await this.db.get(d.o(t,e)))?(0<(e=R.fromRaw(t)).height?e.confirm=this.chain.height-e.height+1:e.confirm=0,e):null}async delOrder(t){const e=this.db.batch();Array.isArray(t)?t.map(t=>{e.del(d.o(t.cid,t.sn))}):e.del(d.o(t.cid,t.sn)),await e.write()}async getStockRecordById(t){return(t=await this.db.get(t))?G.fromRaw(t):null}async getStockRecord(t,e,i){let r=6,s=c.ZERO_CID_BUF,n=c.MAX_CID_BUF,a=0;return t&&(r=t,e)&&(s=e,n=e,i)&&(a=i),t=await this.db.values({gte:G.itemNo(r,s,a,c.NULL_HASH,0),lte:G.itemNo(r,n,4294967295,c.HIGH_HASH,4294967295),parse:G.fromRaw}),e=new y,t.reduce((t,e)=>(t.set(e.itemNo,e),t),e),e}async getStockRecordByCid(t,e){var i,r=new y;for(i of Object.keys(G.RecordType))r.merge(await this.getStockRecord(G.RecordType[i],t,e));return r}async saveVote(t,e){var i=this.db.batch();i.put(d.VM(t),Buffer.from(JSON.stringify(e))),await i.write()}async saveOracle(t,e){var i=this.db.batch();i.put(d.VO(t),Buffer.from(JSON.stringify(e))),await i.write()}getTips(){return this.db.keys({gte:d.p(c.ZERO_HASH),lte:d.p(c.MAX_HASH),parse:d.pp})}async readCoin(t){var e,i,r,s;return this.options.spv?null:(({hash:e,index:i}=t),t=t.toKey(),r=this.state,(s=this.coinCache.get(t))?k.fromRaw(s):(s=await this.db.get(d.c(e,i)))?(r===this.state&&this.coinCache.set(t,s),k.fromRaw(s)):null)}async getCoin(t,e){return t=new g(t,e),(e=await this.readCoin(t))?e.toCoin(t):null}async hasCoins(t){for(let i=0;i<t.outputs.length;i++){var e=d.c(t.hash(),i);if(await this.db.has(e))return!0}return!1}async getCoinView(t){var e,i=new u;for({prevout:e}of t.inputs){var r=await this.readCoin(e);r&&i.addEntry(e,r)}return i}async getSpentView(t){var e,i=await this.getCoinView(t);for({prevout:e}of t.inputs)if(!i.hasEntry(e)){var r,{hash:r,index:s}=e;if(r=await this.getMeta(r)){const{tx:t,height:e,time:n}=r;s<t.outputs.length&&i.addIndex(t,s,e,n)}}return i}async getUndoCoins(t){return(t=await this.db.get(d.u(t)))?l.fromRaw(t):new l}async getBlock(t){return(t=await this.getRawBlock(t))?m.fromRaw(t):null}async getRawBlock(t){return!this.options.spv&&(t=await this.getHash(t))?this.db.get(d.b(t)):null}async getBlockView(t){var e=new u,i=await this.getUndoCoins(t.hash());if(!i.isEmpty()){for(let r=t.txs.length-1;0<r;r--){var s=t.txs[r];for(let t=s.inputs.length-1;0<=t;t--){var n=s.inputs[t];i.apply(e,n.prevout)}}r(i.isEmpty(),"Undo coins data inconsistency.")}return e}async getMeta(t){return this.options.indexTX&&(t=await this.db.get(d.t(t)))?b.fromRaw(t):null}async getTX(t){return(t=await this.getMeta(t))?t.tx:null}async getExtendTX(t){return(t=await this.getMeta(t))||null}async hasTX(t){return!!this.options.indexTX&&this.db.has(d.t(t))}async getCoinsByAddress(t){if(!this.options.indexAddress)return[];var e=[];for(const o of t=Array.isArray(t)?t:[t]){var i,s,n=v.getHash(o);for([i,s]of await this.db.keys({gte:d.C(n,c.ZERO_HASH,0),lte:d.C(n,c.MAX_HASH,4294967295),parse:d.Cc})){var a=await this.getCoin(i,s);r(a),e.push(a)}}return e}async getHashesByAddress(t,e="both"){if(Array.isArray(t)||(t=[t]),!this.options.indexTX||!this.options.indexAddress)return[];const i=Object.create(null);for(const s of t){var r=v.getHash(s);let t,n;n="input"==e?(t=d.TI(r,c.ZERO_HASH),d.TI(r,c.MAX_HASH)):"output"==e?(t=d.TO(r,c.ZERO_HASH),d.TO(r,c.MAX_HASH)):(t=d.T(r,c.ZERO_HASH),d.T(r,c.MAX_HASH)),await this.db.keys({gte:t,lte:n,parse:t=>{t=d.Tt(t),i[t]=!0}})}return Object.keys(i)}async getTXByAddress(t){var e=[];for(const i of await this.getMetaByAddress(t))e.push(i.tx);return e}async getVpByOid(t){return{list:[],count:0}}async getVpByAddress(t){var e=[];for(const s of await this.getMetaByAddress(t))for(let t=0;t<s.tx.outputs.length;t++){var i=s.tx.outputs[t],r=i.getReturnData([ot.OP_PROPCREATE,ot.OP_PROPEXCHANGE]);r&&(r.current={hash:s.tx.rhash("hex"),index:t,address:i.getAddress().toString()},e.push(r))}return{list:e,count:e.length}}async getMetaByAddress(t){if(!this.options.indexTX||!this.options.indexAddress)return[];Array.isArray(t)||(t=[t]);var e=[];for(const s of await this.getHashesByAddress(t)){var i=await this.getMeta(s);r(i),e.push(i)}return e}async scan(t,e,i){"number"==typeof(t=null==t?this.network.genesis.hash:t)?this.logger.info("Scanning from height %d.",t):this.logger.info("Scanning from block %s.",s.revHex(t));let r=await this.getEntry(t);if(r){if(!await this.isMainChain(r))throw new Error("Cannot rescan an alternate chain.");let t=0;for(;r;){var n=await this.getBlock(r.hash),a=[];if(t++,n){this.logger.info("Scanning block %s (%d).",r.rhash(),r.height);for(let t=0;t<n.txs.length;t++){var o=n.txs[t];let i=!1;for(let t=0;t<o.outputs.length;t++){var c=o.outputs[t].getHash();c&&(0==r.height||e&&e.test(c))&&(c=g.fromTX(o,t),e.add(c.toRaw()),i=!0)}if(!e||i)a.push(o);else if(0!==t)for(var{prevout:h}of o.inputs)if(!e||e.test(h.toRaw())){a.push(o);break}}}else if(!this.options.spv&&!this.options.prune)throw new Error("Block not found.");await i(r,a),r=await this.getNext(r)}this.logger.info("Finished scanning %d blocks.",t)}}async save(t,e,i){this.start();try{await this._save(t,e,i)}catch(t){throw this.drop(),t}await this.commit()}async _save(t,e,i){var r=e.hash();this.put(d.h(r),S(t.height)),this.put(d.th(e.time,r),null),this.put(d.e(r),t.toRaw()),this.cacheHash.push(t.hash,t),this.del(d.p(t.prevBlock)),this.put(d.p(r),null),this.saveUpdates(),i?(t.isGenesis()||this.put(d.n(t.prevBlock),r),this.put(d.H(t.height),r),this.cacheHeight.push(t.height,t),await this.saveBlock(t,e,i),this.put(d.R,this.pending.commit(r))):await this.saveBlock(t,e)}async reconnect(t,e,i){this.start();try{await this._reconnect(t,e,i)}catch(t){throw this.drop(),t}await this.commit()}async _reconnect(t,e,i){var s=e.hash();r(!t.isGenesis()),this.put(d.n(t.prevBlock),s),this.put(d.H(t.height),s),this.cacheHeight.push(t.height,t),this.cacheHash.push(t.hash,t),this.saveUpdates(),await this.connectBlock(t,e,i),this.put(d.R,this.pending.commit(s))}async disconnect(t,e){let i;this.start();try{i=await this._disconnect(t,e)}catch(t){throw this.drop(),t}return await this.commit(),i}async _disconnect(t,e){return this.del(d.n(t.prevBlock)),this.del(d.H(t.height)),this.cacheHeight.unpush(t.height),this.saveUpdates(),e=await this.disconnectBlock(t,e),this.put(d.R,this.pending.commit(t.prevBlock)),e}saveUpdates(){var t=this.stateCache.updates;if(0!==t.length){this.logger.info("Saving %d state cache updates.",t.length);for(const r of t){var{bit:e,hash:i}=r;this.put(d.v(e,i),r.toRaw())}}}async reset(t){var e=await this.getEntry(t);if(!e)throw new Error("Block not found.");if(!await this.isMainChain(e))throw new Error("Cannot reset on alternate chain.");if(this.options.prune)throw new Error("Cannot reset when pruned.");await this.removeChains();let i=await this.getTip();for(r(i),this.logger.debug("Resetting main chain to: %s",e.rhash());;){if(this.start(),i.hash===e.hash){this.put(d.R,this.pending.commit(i.hash)),await this.commit();break}r(!i.isGenesis()),this.del(d.p(i.hash)),this.put(d.p(i.prevBlock),null),this.del(d.H(i.height)),this.del(d.h(i.hash)),this.del(d.th(i.time,i.hash)),this.del(d.e(i.hash)),this.del(d.n(i.prevBlock));try{await this.removeBlock(i)}catch(t){throw this.drop(),t}this.cacheHeight.remove(i.height),this.cacheHash.remove(i.hash),i=await this.getPrevious(i),r(i)}return i}async removeChains(){var t=await this.getTips();this.start();try{for(const e of t)await this._removeChain(e)}catch(t){throw this.drop(),t}await this.commit()}async _removeChain(t){let e=await this.getEntryByHash(t);if(!e)throw new Error("Alternate chain tip not found.");for(this.logger.debug("Removing alternate chain: %s.",e.rhash());!await this.isMainChain(e);)r(!e.isGenesis()),this.del(d.p(e.hash)),this.del(d.h(e.hash)),this.del(d.th(e.time,e.hash)),this.del(d.e(e.hash)),this.del(d.b(e.hash)),this.cacheHash.unpush(e.hash),e=await this.getPrevious(e),r(e)}async saveBlock(t,e,i){var r=e.hash();this.options.spv||(this.put(d.b(r),e.toRaw()),i&&await this.connectBlock(t,e,i))}async removeBlock(t){if(this.options.spv)return new u;var e=await this.getBlock(t.hash);if(!e)throw new Error("Block not found.");this.del(d.b(e.hash()));var i=await this.disconnectBlock(t,e);return this.put(d.R,this.pending.commit(t.prevBlock)),await this.commit(),await this.chain.fire("block.disconnect",t,e,i),i}saveView(t){for(var[e,i]of t.map)for(var[r,s]of i.outputs)s.spent?(this.del(d.c(e,r)),this.coinCache.unpush(e+r)):(this.del(d.s(e,r)),s=s.toRaw(),this.put(d.c(e,r),s),this.coinCache.push(e+r,s))}async getSpender(t,e){return(t=await this.db.get(d.s(t,e)))?P.DecodeSpenderValue(t):null}async connectBlock(t,e,i){if(!this.options.spv){var r=e.hash("hex");this.pending.connect(e);for(let u=0;u<e.txs.length;u++){var s=e.txs[u],n=s.hash("hex");if(!t.isGenesis()&&0<u)for(let t=0;t<s.inputs.length;t++){var a=s.inputs[t].prevout,o=i.getOutput(a);this.pending.spend(o);try{await this.emitCoinSpent(s.inputs[t],o,s,e)}catch(t){this.logger.error("connect block:",t.message)}this.put(d.s(a.hash,a.index),P.EncodeSpenderValue(n,t,e.height,r))}for(const t of s.outputs)t.script.isUnspendable()||this.pending.add(t);try{var c=await O.FactoryOfContract({env:this,block:e,tx:s,coins:i});if(!t.isGenesis()){var h=await c.verify();if(1!=h)throw new pt(s,E(h),"bad-contract-verify",100)}await c.isBlockFinal()==_.Final&&await c.confirm()}catch(t){this.logger.error("TX(%s) Smart Contract Execute Error: %s",s.txid(),t.message)}this.indexTX(s,i,t,u)}this.saveView(i),i.undo.isEmpty()||this.put(d.u(r),i.undo.commit()),await this.setCpHistory(),await this.voteMgr.saveVote(),this.scList.deletes([["indate","<",this.chain.height]]),await this.pruneBlock(t)}}async disconnectBlock(t,e){var i=new u;if(!this.options.spv){var s=e.hash(),n=await this.getUndoCoins(s);this.pending.disconnect(e);for(let r=e.txs.length-1;0<=r;r--){var a=e.txs[r];if(0<r)for(let t=a.inputs.length-1;0<=t;t--){var o=a.inputs[t].prevout;n.apply(i,o),this.pending.add(i.getOutput(o))}i.removeTX(a,t.height,t.time);for(let t=a.outputs.length-1;0<=t;t--){var c=a.outputs[t];c.script.isUnspendable()||this.pending.spend(c)}try{await(await O.FactoryOfContract({env:this,block:e,tx:a})).unconfirm()}catch(s){this.logger.error("TX(%s) Smart Contract Unconfirm Error: %s",a.txid(),s.message)}await this.unindexTX(a,i)}r(n.isEmpty(),"Undo coins data inconsistency."),this.saveView(i),this.del(d.u(s)),await this.voteMgr.saveVote()}return i}async pruneBlock(t){this.options.spv||!this.options.prune||(t=t.height-this.network.block.keepBlocks)<=this.network.block.pruneAfterHeight||(t=await this.getHash(t))&&(this.del(d.b(t)),this.del(d.u(t)))}saveFlags(){var t=ft.fromOptions(this.options),e=this.db.batch();return e.put(d.O,t.toRaw()),e.write()}indexTX(t,e,i,r){var s=t.hash();if(this.options.indexTX&&(r=b.fromTX(t,i,r),this.put(d.t(s),r.toRaw()),this.options.indexAddress)){for(const e of t.getHashes())this.put(d.T(e,s),null);for(const e of t.getOutputHashes())this.put(d.TO(e,s),null);for(const i of t.getInputHashes(e))this.put(d.TI(i,s),null)}if(this.options.indexAddress){if(!i.isGenesis()&&!t.isCoinbase())for(var{prevout:n}of t.inputs){var a=e.getOutput(n).getHash();a&&this.del(d.C(a,n.hash,n.index))}for(let e=0;e<t.outputs.length;e++){var o=t.outputs[e].getHash();o&&this.put(d.C(o,s,e),null)}}}async unindexTX(t,e){var i,r=t.hash();if(this.options.indexTX&&(this.del(d.t(r)),this.options.indexAddress))for(i of t.getHashes(e))this.del(d.T(i,r)),this.del(d.TI(i,r)),this.del(d.TO(i,r));if(this.options.indexAddress){if(!t.isCoinbase())for(var{prevout:s}of t.inputs){var n=e.getOutput(s).getHash();n&&this.put(d.C(n,s.hash,s.index),null)}for(let e=0;e<t.outputs.length;e++){var a=t.outputs[e].getHash();a&&this.del(d.C(a,r,e))}}}async readHostList(){return this.db.get(d.HL)}async writeHostList(t){var e=this.db.batch();return e.put(d.HL,t),e.write()}async emitCoinSpent(t,e,i,r){(i={env:this,block:r,tx:i,hash:t.prevout.hash,i:t.prevout.index,height:r.height,output:e,type:e.getReturnType(),data:e.getReturnData(ct)}).data&&await at(i).spent(t)}}function ft(t){if(!(this instanceof ft))return new ft(t);this.network=h.primary,this.spv=!1,this.witness=!0,this.prune=!1,this.indexTX=!1,this.indexAddress=!1,t&&this.fromOptions(t)}dt.layout=d,ft.prototype.fromOptions=function(t){return this.network=h.get(t.network),null!=t.spv&&(r("boolean"==typeof t.spv),this.spv=t.spv),null!=t.prune&&(r("boolean"==typeof t.prune),this.prune=t.prune),null!=t.indexTX&&(r("boolean"==typeof t.indexTX),this.indexTX=t.indexTX),null!=t.indexAddress&&(r("boolean"==typeof t.indexAddress),this.indexAddress=t.indexAddress),this},ft.fromOptions=function(t){return(new ft).fromOptions(t)},ft.prototype.toRaw=function(){var t=new a(12);let e=0;return this.spv&&(e|=1),this.witness&&(e|=2),this.prune&&(e|=4),this.indexTX&&(e|=8),this.indexAddress&&(e|=16),t.writeU32(this.network.magic),t.writeU32(e),t.writeU32(0),t.render()},ft.prototype.fromRaw=function(t){return t=new n(t),this.network=h.fromMagic(t.readU32()),t=t.readU32(),this.spv=0!=(1&t),this.witness=0!=(2&t),this.prune=0!=(4&t),this.indexTX=0!=(8&t),this.indexAddress=0!=(16&t),this},ft.fromRaw=function(t){return(new ft).fromRaw(t)};class mt{constructor(){this.tip=c.NULL_HASH,this.tx=0,this.coin=0,this.value=0,this.committed=!1}rhash(){return s.revHex(this.tip)}clone(){var t=new mt;return t.tip=this.tip,t.tx=this.tx,t.coin=this.coin,t.value=this.value,t}connect(t){this.tx+=t.txs.length}disconnect(t){this.tx-=t.txs.length}add(t){this.coin++,this.value+=t.value}spend(t){this.coin--,this.value-=t.value}commit(t){return"string"!=typeof t&&(t=t.toString("hex")),this.tip=t,this.committed=!0,this.toRaw()}toRaw(){var t=new a(56);return t.writeHash(this.tip),t.writeU64(this.tx),t.writeU64(this.coin),t.writeU64(this.value),t.render()}static fromRaw(t){var e=new mt;t=new n(t);return e.tip=t.readHash("hex"),e.tx=t.readU64(),e.coin=t.readU64(),e.value=t.readU64(),e}}function gt(t){this.network=t,this.bits=[],this.updates=[],this._init()}function yt(t,e,i){this.bit=t,this.hash=e,this.state=i}gt.prototype._init=function(){for(let t=0;t<32;t++)this.bits.push(null);for(var{bit:t}of this.network.deploys)r(!this.bits[t]),this.bits[t]=new Map},gt.prototype.set=function(t,e,i){var s=this.bits[t];r(s),s.get(e.hash)!==i&&(s.set(e.hash,i),this.updates.push(new yt(t,e.hash,i)))},gt.prototype.get=function(t,e){return t=this.bits[t],r(t),null==(t=t.get(e.hash))?-1:t},gt.prototype.commit=function(){this.updates.length=0},gt.prototype.drop=function(){for(var{bit:t,hash:e}of this.updates)t=this.bits[t],r(t),t.delete(e);this.updates.length=0},gt.prototype.insert=function(t,e,i){t=this.bits[t],r(t),t.set(e,i)},yt.prototype.toRaw=function(){return x(this.state)},t.exports=dt},function(t,e,i){"use strict";
884
+ */const r=i(0),s=i(1),n=i(2),a=i(4),o=i(33),c=i(3),h=i(15),u=i(61),l=i(252),p=i(169),d=i(148),f=i(65),m=i(75),g=i(46),y=i(31),v=i(12),w=i(332),b=i(333),k=i(147),x=c.U8,S=c.U32,{getVerifyMsg:E,BlockFinalType:_,OrderData:R,ContractEnvType:A,ContractType:C}=i(5);var I=i(72);const O=i(43),P=i(19),T=i(60),j=i(114),B=i(26),N=i(7),F=i(145),D=i(6),L=i(161),M=i(154),H=M.scItem,z=i(232),U=z.stockAccount,q=i(342),V=i(85),K=V.cpItem,W=V.cpSnap,G=V.stockItem,$=i(134),X=$.vpItem,Y=i(343),J=Y.vpItem,Z=i(728),Q=i(157),tt=Q.ErItem,et=i(158),it=et.ErAbolishItem,rt=i(237),st=rt.EnchancementItem;i(53);const nt=i(344),at=i(118),{opcodes:ot,nestingCodes:ct}=i(21),ht=i(125),ut=i(28),lt=i(39),pt=i(37).VerifyError;class dt extends I{constructor(t){super(),this.chain=t,this.eid="chaindb",this.fromOptions(t.options),this.db=p(this.options),this.stateCache=new gt(this.network),this.state=new mt,this.pending=null,this.current=null,this.coinCache=new f(this.options.coinCache),this.cacheHash=new f(this.options.entryCache),this.cacheHeight=new f(this.options.entryCache),this.autoTaskMgr=new L(this),this.propList=new $(this),this.htlcList=new Y(this),this.$voteMgr=new Z(this),this.transactionList=new q(this),this.cpList=new V(this),this.scList=new M(this),this.erList=new Q(this),this.erAbList=new et(this),this.enCpList=new rt(this,{type:"cp"}),this.accountList=new z(this),this.middleHashChain=new Set,this.on("contract.order.confirm",t=>{var e=this.cpList.getItem(t.cid);e&&this.node.notifyCp(t,e)}),this.on("contract.order.unconfirm",t=>{var e=this.cpList.getItem(t.cid);e&&this.node.notifyCp(t,e)})}get hmacConnection(){return this.node.specialCp.content()}get voteMgr(){return this.$voteMgr}async setCpHistory(){if(this.curHeight%10==0){var t=await this.cpList.query([["status",1]]);if(0<t.list.length){var e,i=this.db.batch();for(e of t.list){var r=e.cid,s={};let t=100;for(const i of(await this.getStockPropList(r)).reduce((t,e)=>((e=X.fromRaw(e.value)).height<=this.curHeight-D.BLOCK_DAY&&t.push(e),t),[]))if(i.current.address!=e.current.address&&(s[i.current.address]=(s[i.current.address]||0)+1),(t-=3)<=70)break;var n=(await this.accountList.query([["cid",r]])).list.sort((t,e)=>t.addr.localeCompare(e.addr));n=new W({grate:e.grate,addrOfMaster:e.current.address,hSum:e.stock.hSum,lords:s,slist:n});i.put(d.SS(r,this.curHeight),n.toRaw()),e.status=0,i.put(d.CP(e.cid),e.toRaw())}await i.write()}}}async getGuider(t){return t=v.fromString(t).getHash("hex"),(t=await this.db.get(d.g(t)))?v.fromRaw(t).toString():null}async setGuider(t,e,i){var r;i=v.fromString(i),await this.db.has(d.g(i.getHash("hex")))||(t=v.fromString(t),await(r=this.db.batch()).put(d.g(i.getHash("hex")),t.toRaw()),await r.put(d.gs(t.getHash("hex"),Buffer.from(e,"ascii").toString("hex"),i.getHash("hex")),i.toRaw()),await r.write())}async unsetGuider(t,e,i){t=v.fromString(t).getHash("hex"),i=v.fromString(i).getHash("hex");var r=this.db.batch();r.del(d.g(i)),r.del(d.gs(t,Buffer.from(e,"ascii").toString("hex"),i)),await r.write()}async getSimAddresses(t,e){t=v.fromString(t).getHash("hex");let i=Buffer.from(e,"ascii").toString("hex"),r=i;return e||(i=c.ZERO_CID,r=c.MAX_CID),(await this.db.values({gte:d.gs(t,i,c.ZERO_HASH160_HEX),lte:d.gs(t,r,c.MAX_HASH160_HEX),parse:t=>v.fromRaw(t).toString()})).length}async getCpHistory(t,e){return(t=await this.db.get(d.SS(t,e)))?W.fromRaw(t):null}async getCpSnap(t){let e=null,i=this.curHeight;for(;!e;){10<=i?5<(s=i%10)?i-=s:i=i-10-s:i=0;var r,s=await this.getCpHistory(t,i);if(s)(e={cid:t}).grate=s.grate,e.addrOfMaster=s.addrOfMaster,e.hSum=s.hSum,e.slist=s.slist,e.lords=s.lords,e.addresses=Object.keys(e.lords).sort((t,e)=>t.localeCompare(e));else if(0==i)return(r=this.cpList.getItem(t))?{cid:r.cid,grate:r.grate,addrOfMaster:r.current.address,hSum:r.stock.hSum,slist:[],lords:{},addresses:[]}:null}return e}get mode(){return A.Block}fromOptions(t){this.options=t,this.node=t.node,this.network=t.network,this.logger=t.logger.context("chaindb")}get curHeight(){return this.chain.height}get finder(){return this.node.getTXFromAll?this.node.getTXFromAll.bind(this.node):()=>{}}get tidCreator(){return d.tx}rpcExecute(){return this.node.rpc.execute.apply(this.node.rpc,arguments)}createGenesisCoinbase(t,e){var i,r=new P,s=new j,n=((i=((i=(s.script.pushInt(0),s.script.pushData(c.ZERO_HASH160),Buffer.allocUnsafe(4))).writeUInt32LE(0,0,!0),s.script.pushData(i),s.script.pushData(c.ZERO_U64),s.script.compile(),s.witness.push(c.ZERO_HASH),s.witness.compile(),r.inputs.push(s),new B)).script.createScript(c.ZERO_HASH160),i.value=D.ORIGINAL,r.outputs.push(i),c.ZERO_HASH),a=[],[a,,]=(a.push(c.ZERO_HASH),F.createRoot(a));a=N.root256(a,n);return(n=new B).script.fromCommitment(a),r.outputs.push(n),s.script.setData(1,e),s.script.compile(),i.script.fromAddress(t.addresses[0]),r}dummyInput(){return j.fromOutpoint(new g(c.NULL_HASH,0))}createGenesisBlock(t){if(!t.addresses||t.addresses.length<11)throw new Error("addresses length expect 11.");let e=t.flags;e=e||Buffer.from("In the name of Athena: Of the user, By the user, and For the user.","ascii");var i=this.createGenesisCoinbase(t,e),r=this.network.genesisId,n=new T,[n,,]=(n.addInput(this.dummyInput()),n.cpRegister(t.addresses[0],D.COIN,{cid:r,oper:C.cpRegister,name:"ATHENA",ip:"*",pubAddress:"",pubKey:"",signMethod:""}),n.commit()),a=new T;a.addInput(this.dummyInput());for(let e=0;e<10;e++)for(let i=0;i<10;i++){var o={oper:C.propCreate,pid:""+this.network.tokenFix+s.sprintf("%04d",10*e+i+1),oid:this.network.tokenFix+"0000",cid:r,gold:D.COIN};a.propCreate(t.addresses[e+1],o)}var[h,,]=a.commit(),u=new m({version:t.version,prevBlock:c.NULL_HASH,merkleRoot:i.hash("hex"),time:t.time,bits:t.bits,nonce:t.nonce,height:0});return u.txs.push(i),u.txs.push(n),u.txs.push(h),u.refresh(!0),u.merkleRoot=u.createMerkleRoot("hex"),u}async open(t){this.logger.info("Opening ChainDB..."),await this.db.open();var e=await this.db.checkVersion(d,3);if(i=await this.getState()){var i;if(await this.verifyFlags(i),await this.verifyDeployments(),this.stateCache=await this.getStateCache(),this.state=i,!(i=await this.getEntry(0)))throw new Error("genesis block not found.");this.network.genesis.hash=i.hash,this.network.genesis.merkleRoot=i.merkleRoot,this.logger.info("ChainDB successfully loaded.")}else t&&(i=await this.getGenesisParams(t),this.node.miner&&(this.node.miner.addresses=[new v(i.coinbaseAddress)]),this.node.config)&&this.node.config.changeParams(i),await this.saveFlags(),await this.saveDeployments(),await this.saveGenesis(),this.logger.info("ChainDB successfully initialized.");return this.logger.info("Chain State: hash=%s tx=%d coin=%d value=%s.",this.state.rhash(),this.state.tx,this.state.coin,o.btc(this.state.value)),e}async getGenesisParams(t){if(t.isGenesisParams)return t;t=t||{};var e=new nt({name:"wallet-test",db:"memory",resolution:!1,verify:!1}),i=(e=(t.getMnemonicFromMemory=!0,await e.open(t),await e.get("primary")),[]);for(const s of await e.getPaths("default")){var r=s.toAddress();0==s.branch&&i.push(""+r.toString(t.network))}var s,n,a,o,h={};return h[t.network+"Addresses"]=i.reduce((t,e)=>t+(""==t?e:","+e),""),h.coinbaseAddress=i[1],h.notifyAddress=e.notifyAddress,this.node.config.notifyAddress=h.notifyAddress,await ht.writeFile(h,t.network+"-genesis.params"),t.isGenesisEncrypt||(s=N.hash256(Buffer.from(e.master.mnemonic.toSeed().toString("hex"))),n=ut.publicKeyCreate(s,!0),a=v.fromWitnessPubkeyhash(N.hash160(n),this.network.type).toString(),o=N.hash256(Buffer.concat([Buffer.from("root"),e.master.key.privateKey])),e={body:{language:e.master.mnemonic.language,phrase:e.master.mnemonic.getPhrase(),passphrase:e.master.mnemonic.passphrase,awardAddress:h.coinbaseAddress,notifyAddress:e.notifyAddress,alliancePrivateKey:o.toString("hex"),allianceName:"root",allianceNodeId:0,allianceNodeToken:{prv:s.toString("hex"),pub:n.toString("hex"),address:a}},password:t.password||c.MNEMONIC_SALT,network:t.network,file:t.network+"-genesis.keystore"},await ht.writeEncryptFile(e)),h}close(){return this.db.close()}start(){return r(!this.current),r(!this.pending),this.current=this.db.batch(),this.pending=this.state.clone(),this.coinCache.start(),this.cacheHash.start(),this.cacheHeight.start(),this.current}put(t,e){r(this.current),this.current.put(t,e)}del(t){r(this.current),this.current.del(t)}batch(){return r(this.current),this.current}drop(){var t=this.current;r(this.current),r(this.pending),this.current=null,this.pending=null,this.coinCache.drop(),this.cacheHash.drop(),this.cacheHeight.drop(),this.stateCache.drop(),t.clear()}async commit(){r(this.current),r(this.pending);try{await this.current.write()}catch(t){throw this.current=null,this.pending=null,this.coinCache.drop(),this.cacheHash.drop(),this.cacheHeight.drop(),t}this.pending.committed&&(this.state=this.pending),this.current=null,this.pending=null,this.coinCache.commit(),this.cacheHash.commit(),this.cacheHeight.commit(),this.stateCache.commit()}hasCache(t){return("number"==typeof t?this.cacheHeight:(r("string"==typeof t),this.cacheHash)).has(t)}getCache(t){return("number"==typeof t?this.cacheHeight:(r("string"==typeof t),this.cacheHash)).get(t)}async getHeight(t){var e;return"number"==typeof t?t:(r("string"==typeof t),t===c.NULL_HASH?-1:(e=this.cacheHash.get(t))?e.height:(e=await this.db.get(d.h(t)))?e.readUInt32LE(0,!0):-1)}async getHash(t){var e;return"string"==typeof t?t:(r("number"==typeof t),t<0?null:(e=this.cacheHeight.get(t))?e.hash:(e=await this.db.get(d.H(t)))?e.toString("hex"):null)}async getEntryByHeight(t){var e;return r("number"==typeof t),t<0?null:this.cacheHeight.get(t)||((t=await this.db.get(d.H(t)))&&(t=t.toString("hex"),e=this.state,t=await this.getEntryByHash(t))?(this.state===e&&this.cacheHeight.set(t.height,t),t):null)}async getEntryByHash(t){return r("string"==typeof t),t===c.NULL_HASH?null:this.cacheHash.get(t)||((t=await this.db.get(d.e(t)))?(t=w.fromRaw(t),this.cacheHash.set(t.hash,t),t):null)}getEntry(t){return"number"==typeof t?this.getEntryByHeight(t):this.getEntryByHash(t)}async hasEntry(t){return-1!==await this.getHeight(t)}async getAncestor(t,e){if(e<0)return null;if(r(0<=e),r(e<=t.height),await this.isMainChain(t))return this.getEntryByHeight(e);for(;t.height!==e;){t=this.getPrevCache(t)||await this.getPrevious(t),r(t)}return t}getPrevious(t){return this.getEntryByHash(t.prevBlock)}getPrevCache(t){return this.cacheHash.get(t.prevBlock)||null}async getNext(t){return(t=await this.getNextHash(t.hash))?this.getEntryByHash(t):null}async getNextEntry(t){var e=await this.getEntryByHeight(t.height+1);return e&&e.prevBlock===t.hash?e:null}getTip(){return this.getEntryByHash(this.state.tip)}async getState(){var t=await this.db.get(d.R);return t?mt.fromRaw(t):null}async saveGenesis(){let t=[];t=(this.node.config?this.node.config[this.network.type+"Addresses"]:this.network.genesis.addresses).split(",");var e=this.createGenesisBlock({version:this.network.genesis.version,time:this.network.genesis.time,bits:this.network.genesis.bits,nonce:this.network.genesis.nonce,addresses:t}),i=(this.network.genesis.hash=e.hash("hex"),this.network.genesis.merkleRoot=e.merkleRoot,w.fromBlock(e)),r=(this.logger.info("Writing genesis block to ChainDB."),new u);for(let t=0;t<e.txs.length;t++)r.addTX(e.txs[t],e.height,e.time);await this.save(i,e,r)}async getFlags(){var t=await this.db.get(d.O);return t?ft.fromRaw(t):null}async verifyFlags(t){var e=this.options,i=await this.getFlags();let r=!1,s=!1;if(!i)throw new Error("No flags found.");if(e.network!==i.network)throw new Error("Network mismatch for chain.");if(e.spv&&!i.spv)throw new Error("Cannot retroactively enable SPV.");if(!e.spv&&i.spv)throw new Error("Cannot retroactively disable SPV.");if(!i.witness){if(!e.forceFlags)throw new Error("Cannot retroactively enable witness.");r=!0}if(e.prune&&!i.prune){if(!e.forceFlags)throw new Error("Cannot retroactively prune.");s=!0}if(!e.prune&&i.prune)throw new Error("Cannot retroactively unprune.");if(e.indexTX&&!i.indexTX)throw new Error("Cannot retroactively enable TX indexing.");if(!e.indexTX&&i.indexTX)throw new Error("Cannot retroactively disable TX indexing.");if(e.indexAddress&&!i.indexAddress)throw new Error("Cannot retroactively enable address indexing.");if(!e.indexAddress&&i.indexAddress)throw new Error("Cannot retroactively disable address indexing.");r&&(await this.logger.info("Rewriting chain flags."),await this.saveFlags()),s&&(await this.logger.info("Retroactively pruning chain."),await this.prune(t.tip))}async getStateCache(){var t=new gt(this.network);for(const s of await this.db.range({gte:d.v(0,c.ZERO_HASH),lte:d.v(255,c.MAX_HASH),values:!0})){var[e,i]=d.vv(s.key),r=s.value[0];t.insert(e,i,r)}return t}saveDeployments(){var t=this.db.batch();return this.writeDeployments(t),t.write()}async batchPut(t,e){var i=this.db.batch();i.put(t,e),await i.write()}async batchDel(t){var e=this.db.batch();e.del(t),await e.write()}writeDeployments(t){var e=new a(1+17*this.network.deploys.length);e.writeU8(this.network.deploys.length);for(const t of this.network.deploys)e.writeU8(t.bit),e.writeU32(t.startTime),e.writeU32(t.timeout),e.writeI32(t.threshold),e.writeI32(t.window);t.put(d.V,e.render())}async checkDeployments(){var t=await this.db.get(d.V),e=(r(t,"No deployment table found."),new n(t)),i=e.readU8(),s=[];for(let t=0;t<i;t++){var a=e.readU8(),o=e.readU32(),c=e.readU32(),h=e.readI32(),u=e.readI32(),l=this.network.byBit(a);l&&o===l.startTime&&c===l.timeout&&h===l.threshold&&u===l.window||s.push(a)}return s}async verifyDeployments(){let t;try{t=await this.checkDeployments()}catch(e){if("EncodingError"!==e.type)throw e;t=[];for(let e=0;e<32;e++)t.push(e)}if(0===t.length)return!0;var e=this.db.batch();for(const i of t)this.logger.warning("Versionbit deployment params modified."),this.logger.warning("Invalidating cache for bit %d.",i),await this.invalidateCache(i,e);return this.writeDeployments(e),await e.write(),!1}async invalidateCache(t,e){for(const i of await this.db.keys({gte:d.v(t,c.ZERO_HASH),lte:d.v(t,c.MAX_HASH)}))e.del(i)}async prune(){var t=this.options,e=this.network.block.keepBlocks,i=this.network.block.pruneAfterHeight;if((await this.getFlags()).prune)throw new Error("Chain is already pruned.");var s=await this.getHeight(this.state.tip);if(s<=i+e)return!1;i+=1;var n=s-e,a=this.db.batch();for(let t=i;t<=n;t++){var o=await this.getHash(t);if(!o)throw new Error(`Cannot find hash for ${t}.`);a.del(d.b(o)),a.del(d.u(o))}try{t.prune=!0;const e=ft.fromOptions(t);r(e.prune),a.put(d.O,e.toRaw()),await a.write()}catch(e){throw t.prune=!1,e}return await this.db.compactRange(),!0}async getNextHash(t){return(t=await this.db.get(d.n(t)))?t.toString("hex"):null}async isMainHash(t){if(r("string"==typeof t),t===c.NULL_HASH)return!1;if(t===this.network.genesis.hash)return!0;if(t===this.state.tip)return!0;var e=this.cacheHash.get(t);return e&&(e=this.cacheHeight.get(e.height))?e.hash===t:!!await this.getNextHash(t)}async isMainChain(t){var e;return!!t.isGenesis()||t.hash===this.state.tip||((e=this.getCache(t.height))?t.hash===e.hash:!!await this.getNextHash(t.hash))}getEntries(){return this.db.values({gte:d.e(c.ZERO_HASH),lte:d.e(c.MAX_HASH),parse:t=>w.fromRaw(t)})}getTimestampHashes(t,e){return this.db.keys({gte:d.th(e,c.ZERO_HASH),lte:d.th(t,c.MAX_HASH),parse:d.thh})}getContracts(){return this.db.values({gte:d.tx(c.NULL_HASH),lte:d.tx(c.HIGH_HASH),parse:t=>s.parseJson(t.toString())})}getCps(){return this.db.values({gte:d.CP(c.ZERO_CID,"hex"),lte:d.CP(c.MAX_CID,"hex"),parse:t=>K.fromRaw(t)})}async setCp(t){var e=this.db.batch();e.put(d.CP(t.cid),t.toRaw()),await e.write()}async delCp(t){var e=this.db.batch();e.del(d.CP(t)),await e.write()}getScs(){return this.db.values({gte:d.SC(c.ZERO_CID,"hex"),lte:d.SC(c.MAX_CID,"hex"),parse:t=>H.fromRaw(t)})}async setSc(t){var e=this.db.batch();e.put(d.SC(t.id),t.toRaw()),await e.write()}async delSc(t){var e=this.db.batch();e.del(d.SC(t)),await e.write()}async getSCList(t){return r(Array.isArray(t)),this.scList.query(t)}async getStockAccountList(t){return t?this.db.values({gte:U.SN(t,c.NULL_HASH),lte:U.SN(t,c.HIGH_HASH),parse:U.fromRaw}):this.db.values({gte:U.SN(c.ZERO_CID_BUF,c.NULL_HASH),lte:U.SN(c.MAX_CID_BUF,c.HIGH_HASH),parse:U.fromRaw})}async setStockRecord(t){var e=this.db.batch();switch(e.put(t.itemNo,t.toRaw()),t.type){case G.RecordType.Offer:break;case G.RecordType.Bid:var i=this.accountList.getStockAccount(t.cid,t.addr);i&&(i.stock.sum=t.sum,i.stock.price=t.price,i.seq=t.seq,i.stock.period=this.curHeight+1+10*D.BLOCK_DAY,e.put(i.getItemNo(),i.toRaw()));break;case G.RecordType.Auction:{if(!(i=this.accountList.getStockAccount(t.cid,t.to)))break;let s=this.accountList.getStockAccount(t.cid,t.addr);s||(s=new U(t.cid,t.addr,0,0,0),this.accountList.setStockAccount(s));var r=s.sum+t.sum;s.price=(t.sum*t.price+s.sum*s.price)/r|0,s.sum=r,s.seq=t.seq,e.put(s.getItemNo(),s.toRaw()),r=i.sum-t.sum,i.sum=r,i.stock.sum-=t.sum,e.put(i.getItemNo(),i.toRaw());break}case G.RecordType.Purchase:{let i=this.accountList.getStockAccount(t.cid,t.addr);i?(r=i.sum+t.sum,i.price=(t.sum*t.price+i.sum*i.price)/r,i.sum=r,i.seq=t.seq):((i=new U(t.cid,t.addr,t.sum,t.price,0)).seq=t.seq,this.accountList.setStockAccount(i)),e.put(i.getItemNo(),i.toRaw());break}case G.RecordType.Send:if(i=this.accountList.getStockAccount(t.cid,t.addr)){i.sum-=t.sum,i.seq=t.seq;let s=this.accountList.getStockAccount(t.cid,t.to);s||(s=new U(t.cid,t.to,0,0),this.accountList.setStockAccount(s)),r=s.sum+t.sum,s.price=(t.sum*i.price+s.sum*s.price)/r,s.sum=r,e.put(i.getItemNo(),i.toRaw()),e.put(s.getItemNo(),s.toRaw())}break;case G.RecordType.Bonus:case G.RecordType.Ads:}await e.write()}async unsetStockRecord(t){var e=this.db.batch();switch(e.del(t.itemNo),t.type){case G.RecordType.Offer:break;case G.RecordType.Bid:(s=this.accountList.getStockAccount(t.cid,t.addr))&&(s.stock.sum=0,s.stock.price=0,s.stock.period=0,s.seq=t.seq-1,e.put(s.getItemNo(),s.toRaw()));break;case G.RecordType.Auction:(s=this.accountList.getStockAccount(t.cid,t.addr))&&(i=s.sum-t.sum,s.price=(s.sum*s.price-t.sum*t.price)/i|0,s.sum=i,s.seq=t.seq-1,e.put(s.getItemNo(),s.toRaw()),s=this.accountList.getStockAccount(t.cid,t.to))&&(i=s.sum+t.sum,s.sum=i,s.stock.sum+=t.sum,e.put(s.getItemNo(),s.toRaw()));break;case G.RecordType.Purchase:var i=this.accountList.getStockAccount(t.cid,t.addr);i&&(s=i.sum-t.sum,i.price=(i.sum*i.price-t.sum*t.price)/s|0,i.sum=s,i.seq=t.seq-1,e.put(i.getItemNo(),i.toRaw()));break;case G.RecordType.Send:var r,s;(s=this.accountList.getStockAccount(t.cid,t.addr))&&(s.sum+=t.sum,s.seq=t.seq-1,e.put(s.getItemNo(),s.toRaw()),i=this.accountList.getStockAccount(t.cid,t.to))&&(r=i.sum-t.sum,i.price=(i.sum*i.price-t.sum*s.price)/r|0,i.sum=r,e.put(i.getItemNo(),i.toRaw()));break;case G.RecordType.Bonus:}await e.write()}async getStockPropList(t){return this.db.range({gte:d.VP(""+t+this.network.stockFix+s.sprintf("%02d",0)),lte:d.VP(""+t+this.network.stockFix+s.sprintf("%02d",29)),values:!0})}async delVp(t){var e=this.db.batch();e.del(d.VP(t.pid)),await e.write()}async setVp(t){var e=this.db.batch();e.put(d.VP(t.pid),t.toRaw()),await e.write()}async getVp(t){return(t=await this.db.get(d.VP(t)))?X.fromRaw(t):null}loadVpList(){return this.db.values({gte:d.VP(c.ZERO_CID,"hex"),lte:d.VP(c.MAX_CID,"hex"),parse:t=>X.fromRaw(t)})}async delHtlc(t){var e;t.id&&(this.htlcList.delete(t.id),this.htlcList.delAccount(t),(e=this.db.batch()).del(d.VH(t.shash,t.sidx)),await e.write())}async setSuggest(t){t=new J(t);var e=(this.htlcList.set(t.id,t),this.db.batch());e.put(d.VH(t.shash,t.sidx),t.toRaw()),await e.write()}async setAssent(t){t=new J(t);var e=(this.htlcList.set(t.id,t),this.db.batch());e.put(d.VH(t.shash,t.sidx),t.toRaw()),await e.write()}async loadHtlcList(){return this.db.values({gte:d.VH(c.ZERO_CID,0),lte:d.VH(c.MAX_CID,4294967295),parse:t=>J.fromRaw(t)})}async delErAbolish(t){var e=this.db.batch();e.del(d.ERA(t.erid)),await e.write()}async setErAbolish(t){var e=this.db.batch();e.put(d.ERA(t.erid),t.toRaw()),await e.write()}async getErAbolish(t){return(t=await this.db.get(d.ERA(t)))?it.fromRaw(t):null}loadErAbolishList(){return this.db.values({gte:d.ERA(c.ZERO_CID),lte:d.ERA(c.MAX_CID),parse:t=>it.fromRaw(t)})}async delCpEn(t){var e=this.db.batch();e.del(d.EN2(t.to,t.from)),await e.write()}async setCpEn(t){var e=this.db.batch();e.put(d.EN2(t.to,t.from),t.toRaw()),await e.write()}loadCpEnList(){return this.db.values({gte:d.EN2(c.ZERO_CID,c.ZERO_CID,"ascii"),lte:d.EN2(c.MAX_CID,c.MAX_CID,"ascii"),parse:t=>st.fromRaw(t)})}queryCpEnListByCid(t){return this.db.values({gte:d.EN2(t,c.ZERO_CID,"ascii"),lte:d.EN2(t,c.MAX_CID,"ascii"),parse:t=>st.fromRaw(t)})}async delEr(t){var e=this.db.batch();e.del(d.ER(t.erid)),e.del(d.ERR(t.witness,t.erid,t.txid)),await e.write()}async setEr(t,e){var i=this.db.batch(),r=d.ERR(t.witness,t.erid,t.txid);i.put(r,t.toRaw()),i.put(d.ER(t.erid),r),await i.write()}async getEr(t){var e;return(t=await this.db.get(d.ER(t)))&&([,,e]=d.ERRR(t),t=await this.db.get(t))?((t=tt.fromRaw(t)).txid=e,t):null}async byPubkey(t,e,i=!1){if(!(t=await this.db.values({gte:d.ERR(t,c.NULL_HASH,c.NULL_HASH),lte:d.ERR(t,c.HIGH_HASH,c.HIGH_HASH),parse:t=>tt.fromRaw(t)}))||0==t.length)return[];let r=null;if(i){var s,n=new Map;for(s of t){var a,o=await this.caVerifyObj(s);o&&((a=n.get(o.source.cluster))?o.startHeight>a.startHeight&&n.set(s.source.cluster,o):n.set(o.source.cluster,o))}r=n.values()}else r=t;if(!r||0==r.length)return[];var h,u=new y;for(h of r)u.set(h.erid,h);return u.query(e)}async caVerify(t){return this.caVerifyObj(await this.erList.getEr(t))}async caVerifyObj(t){var e;return t?(t.verify=!1,t.validHeight<=this.chain.height||(e=await this.erAbList.getErAb(t.erid))&&e.abolishHeight<this.chain.height||(e=lt.fromPublic(Buffer.from(t.witness,"hex"),this.network.type),t.verifying(e)&&(t.verify=!0,0<(e=this.cpList.query([["pubKey",t.witness]])).list.length)&&(t.cpid=e.list[0].cid)),t):null}async addOrder(t){await this.batchPut(d.o(t.cid,t.sn),t.toRaw())}async arrangeOrder(t){var e,i=[],r=[];for(e of await this.db.values({gte:d.o(t,c.ZERO_OID),lte:d.o(t,c.MAX_OID),parse:R.fromRaw}))(-1==e.height&&this.curHeight-e.publish>=10*D.BLOCK_DAY?r:i).push(e);return 0<r.length&&this.delOrder(r),i}async getAddressesFromOrder(t){var e,i=[];t.cls&&i.push(["cls",t.cls]);let r=await this.node.rpc.execute({method:"cp.remoteQuery",params:[i]}),s=[];for(e of r=r.list.map(t=>t.cid))s=s?s.concat(await this.arrangeOrder(e)):await this.arrangeOrder(e);s=s.reduce((e,i)=>(i.addr&&0<i.height&&(!t.time||600*(this.chain.height-i.height)<t.time)&&(e[i.addr]?i.sum&&(e[i.addr].sum+=i.sum):(e[i.addr]=i,e[i.addr].sum=e[i.addr].sum||0)),e),{});var n={list:[],pageNum:1,pageCur:1};(s=(s=t.amount?Object.values(s).filter(e=>e.sum>=t.amount):Object.values(s)).map(t=>({addr:t.addr,sum:t.sum}))).length%t.pageSize==0?n.pageNum=s.length/t.pageSize|0:n.pageNum=1+(s.length/t.pageSize|0),n.pageCur=Math.max(1,Math.min(n.pageNum,t.page));for(let e=t.pageSize*(n.pageCur-1);e<t.pageSize*n.pageCur&&s[e];e++)n.list.push(s[e]);return n}async getOrderList(t,e){r("string"==typeof t),r(Array.isArray(e));let i=null;for(var n of e)if("sn"==n[0]){i=2==n.length?n[1]:n[2],i=Array.isArray(i)?1==i.length?s.sprintf("%0-36s",i[0]):i.map(t=>s.sprintf("%0-36s",t)):s.sprintf("%0-36s",i),2==n.length?n[1]=i:n[2]=i;break}var a=new y;return(await this.arrangeOrder(t)).reduce((t,e)=>(t.set(""+e.cid+e.sn,e),t),a),a.query(e)}async getOrderRecord(t,e){return r("string"==typeof t),r("string"==typeof e),e=s.sprintf("%0-36s",e),(t=await this.db.get(d.o(t,e)))?(0<(e=R.fromRaw(t)).height?e.confirm=this.chain.height-e.height+1:e.confirm=0,e):null}async delOrder(t){const e=this.db.batch();Array.isArray(t)?t.map(t=>{e.del(d.o(t.cid,t.sn))}):e.del(d.o(t.cid,t.sn)),await e.write()}async getStockRecordById(t){return(t=await this.db.get(t))?G.fromRaw(t):null}async getStockRecord(t,e,i){let r=6,s=c.ZERO_CID_BUF,n=c.MAX_CID_BUF,a=0;return t&&(r=t,e)&&(s=e,n=e,i)&&(a=i),t=await this.db.values({gte:G.itemNo(r,s,a,c.NULL_HASH,0),lte:G.itemNo(r,n,4294967295,c.HIGH_HASH,4294967295),parse:G.fromRaw}),e=new y,t.reduce((t,e)=>(t.set(e.itemNo,e),t),e),e}async getStockRecordByCid(t,e){var i,r=new y;for(i of Object.keys(G.RecordType))r.merge(await this.getStockRecord(G.RecordType[i],t,e));return r}async saveVote(t,e){var i=this.db.batch();i.put(d.VM(t),Buffer.from(JSON.stringify(e))),await i.write()}async saveOracle(t,e){var i=this.db.batch();i.put(d.VO(t),Buffer.from(JSON.stringify(e))),await i.write()}getTips(){return this.db.keys({gte:d.p(c.ZERO_HASH),lte:d.p(c.MAX_HASH),parse:d.pp})}async readCoin(t){var e,i,r,s;return this.options.spv?null:(({hash:e,index:i}=t),t=t.toKey(),r=this.state,(s=this.coinCache.get(t))?k.fromRaw(s):(s=await this.db.get(d.c(e,i)))?(r===this.state&&this.coinCache.set(t,s),k.fromRaw(s)):null)}async getCoin(t,e){return t=new g(t,e),(e=await this.readCoin(t))?e.toCoin(t):null}async hasCoins(t){for(let i=0;i<t.outputs.length;i++){var e=d.c(t.hash(),i);if(await this.db.has(e))return!0}return!1}async getCoinView(t){var e,i=new u;for({prevout:e}of t.inputs){var r=await this.readCoin(e);r&&i.addEntry(e,r)}return i}async getSpentView(t){var e,i=await this.getCoinView(t);for({prevout:e}of t.inputs)if(!i.hasEntry(e)){var r,{hash:r,index:s}=e;if(r=await this.getMeta(r)){const{tx:t,height:e,time:n}=r;s<t.outputs.length&&i.addIndex(t,s,e,n)}}return i}async getUndoCoins(t){return(t=await this.db.get(d.u(t)))?l.fromRaw(t):new l}async getBlock(t){return(t=await this.getRawBlock(t))?m.fromRaw(t):null}async getRawBlock(t){return!this.options.spv&&(t=await this.getHash(t))?this.db.get(d.b(t)):null}async getBlockView(t){var e=new u,i=await this.getUndoCoins(t.hash());if(!i.isEmpty()){for(let r=t.txs.length-1;0<r;r--){var s=t.txs[r];for(let t=s.inputs.length-1;0<=t;t--){var n=s.inputs[t];i.apply(e,n.prevout)}}r(i.isEmpty(),"Undo coins data inconsistency.")}return e}async getMeta(t){return this.options.indexTX&&(t=await this.db.get(d.t(t)))?b.fromRaw(t):null}async getTX(t){return(t=await this.getMeta(t))?t.tx:null}async getExtendTX(t){return(t=await this.getMeta(t))||null}async hasTX(t){return!!this.options.indexTX&&this.db.has(d.t(t))}async getCoinsByAddress(t){if(!this.options.indexAddress)return[];var e=[];for(const o of t=Array.isArray(t)?t:[t]){var i,s,n=v.getHash(o);for([i,s]of await this.db.keys({gte:d.C(n,c.ZERO_HASH,0),lte:d.C(n,c.MAX_HASH,4294967295),parse:d.Cc})){var a=await this.getCoin(i,s);r(a),e.push(a)}}return e}async getHashesByAddress(t,e="both"){if(Array.isArray(t)||(t=[t]),!this.options.indexTX||!this.options.indexAddress)return[];const i=Object.create(null);for(const s of t){var r=v.getHash(s);let t,n;n="input"==e?(t=d.TI(r,c.ZERO_HASH),d.TI(r,c.MAX_HASH)):"output"==e?(t=d.TO(r,c.ZERO_HASH),d.TO(r,c.MAX_HASH)):(t=d.T(r,c.ZERO_HASH),d.T(r,c.MAX_HASH)),await this.db.keys({gte:t,lte:n,parse:t=>{t=d.Tt(t),i[t]=!0}})}return Object.keys(i)}async getTXByAddress(t){var e=[];for(const i of await this.getMetaByAddress(t))e.push(i.tx);return e}async getVpByOid(t){return{list:[],count:0}}async getVpByAddress(t){var e=[];for(const s of await this.getMetaByAddress(t))for(let t=0;t<s.tx.outputs.length;t++){var i=s.tx.outputs[t],r=i.getReturnData([ot.OP_PROPCREATE,ot.OP_PROPEXCHANGE]);r&&(r.current={hash:s.tx.rhash("hex"),index:t,address:i.getAddress().toString()},e.push(r))}return{list:e,count:e.length}}async getMetaByAddress(t){if(!this.options.indexTX||!this.options.indexAddress)return[];Array.isArray(t)||(t=[t]);var e=[];for(const s of await this.getHashesByAddress(t)){var i=await this.getMeta(s);r(i),e.push(i)}return e}async scan(t,e,i){"number"==typeof(t=null==t?this.network.genesis.hash:t)?this.logger.info("Scanning from height %d.",t):this.logger.info("Scanning from block %s.",s.revHex(t));let r=await this.getEntry(t);if(r){if(!await this.isMainChain(r))throw new Error("Cannot rescan an alternate chain.");let t=0;for(;r;){var n=await this.getBlock(r.hash),a=[];if(t++,n){this.logger.info("Scanning block %s (%d).",r.rhash(),r.height);for(let t=0;t<n.txs.length;t++){var o=n.txs[t];let i=!1;for(let t=0;t<o.outputs.length;t++){var c=o.outputs[t].getHash();c&&(0==r.height||e&&e.test(c))&&(c=g.fromTX(o,t),e.add(c.toRaw()),i=!0)}if(!e||i)a.push(o);else if(0!==t)for(var{prevout:h}of o.inputs)if(!e||e.test(h.toRaw())){a.push(o);break}}}else if(!this.options.spv&&!this.options.prune)throw new Error("Block not found.");await i(r,a),r=await this.getNext(r)}this.logger.info("Finished scanning %d blocks.",t)}}async save(t,e,i){this.start();try{await this._save(t,e,i)}catch(t){throw this.drop(),t}await this.commit()}async _save(t,e,i){var r=e.hash();this.put(d.h(r),S(t.height)),this.put(d.th(e.time,r),null),this.put(d.e(r),t.toRaw()),this.cacheHash.push(t.hash,t),this.del(d.p(t.prevBlock)),this.put(d.p(r),null),this.saveUpdates(),i?(t.isGenesis()||this.put(d.n(t.prevBlock),r),this.put(d.H(t.height),r),this.cacheHeight.push(t.height,t),await this.saveBlock(t,e,i),this.put(d.R,this.pending.commit(r))):await this.saveBlock(t,e)}async reconnect(t,e,i){this.start();try{await this._reconnect(t,e,i)}catch(t){throw this.drop(),t}await this.commit()}async _reconnect(t,e,i){var s=e.hash();r(!t.isGenesis()),this.put(d.n(t.prevBlock),s),this.put(d.H(t.height),s),this.cacheHeight.push(t.height,t),this.cacheHash.push(t.hash,t),this.saveUpdates(),await this.connectBlock(t,e,i),this.put(d.R,this.pending.commit(s))}async disconnect(t,e){let i;this.start();try{i=await this._disconnect(t,e)}catch(t){throw this.drop(),t}return await this.commit(),i}async _disconnect(t,e){return this.del(d.n(t.prevBlock)),this.del(d.H(t.height)),this.cacheHeight.unpush(t.height),this.saveUpdates(),e=await this.disconnectBlock(t,e),this.put(d.R,this.pending.commit(t.prevBlock)),e}saveUpdates(){var t=this.stateCache.updates;if(0!==t.length){this.logger.info("Saving %d state cache updates.",t.length);for(const r of t){var{bit:e,hash:i}=r;this.put(d.v(e,i),r.toRaw())}}}async reset(t){var e=await this.getEntry(t);if(!e)throw new Error("Block not found.");if(!await this.isMainChain(e))throw new Error("Cannot reset on alternate chain.");if(this.options.prune)throw new Error("Cannot reset when pruned.");await this.removeChains();let i=await this.getTip();for(r(i),this.logger.debug("Resetting main chain to: %s",e.rhash());;){if(this.start(),i.hash===e.hash){this.put(d.R,this.pending.commit(i.hash)),await this.commit();break}r(!i.isGenesis()),this.del(d.p(i.hash)),this.put(d.p(i.prevBlock),null),this.del(d.H(i.height)),this.del(d.h(i.hash)),this.del(d.th(i.time,i.hash)),this.del(d.e(i.hash)),this.del(d.n(i.prevBlock));try{await this.removeBlock(i)}catch(t){throw this.drop(),t}this.cacheHeight.remove(i.height),this.cacheHash.remove(i.hash),i=await this.getPrevious(i),r(i)}return i}async removeChains(){var t=await this.getTips();this.start();try{for(const e of t)await this._removeChain(e)}catch(t){throw this.drop(),t}await this.commit()}async _removeChain(t){let e=await this.getEntryByHash(t);if(!e)throw new Error("Alternate chain tip not found.");for(this.logger.debug("Removing alternate chain: %s.",e.rhash());!await this.isMainChain(e);)r(!e.isGenesis()),this.del(d.p(e.hash)),this.del(d.h(e.hash)),this.del(d.th(e.time,e.hash)),this.del(d.e(e.hash)),this.del(d.b(e.hash)),this.cacheHash.unpush(e.hash),e=await this.getPrevious(e),r(e)}async saveBlock(t,e,i){var r=e.hash();this.options.spv||(this.put(d.b(r),e.toRaw()),i&&await this.connectBlock(t,e,i))}async removeBlock(t){if(this.options.spv)return new u;var e=await this.getBlock(t.hash);if(!e)throw new Error("Block not found.");this.del(d.b(e.hash()));var i=await this.disconnectBlock(t,e);return this.put(d.R,this.pending.commit(t.prevBlock)),await this.commit(),await this.chain.fire("block.disconnect",t,e,i),i}saveView(t){for(var[e,i]of t.map)for(var[r,s]of i.outputs)s.spent?(this.del(d.c(e,r)),this.coinCache.unpush(e+r)):(this.del(d.s(e,r)),s=s.toRaw(),this.put(d.c(e,r),s),this.coinCache.push(e+r,s))}async getSpender(t,e){return(t=await this.db.get(d.s(t,e)))?P.DecodeSpenderValue(t):null}async connectBlock(t,e,i){if(!this.options.spv){var r=e.hash("hex");this.pending.connect(e);for(let u=0;u<e.txs.length;u++){var s=e.txs[u],n=s.hash("hex");if(!t.isGenesis()&&0<u)for(let t=0;t<s.inputs.length;t++){var a=s.inputs[t].prevout,o=i.getOutput(a);this.pending.spend(o);try{await this.emitCoinSpent(s.inputs[t],o,s,e)}catch(t){this.logger.error("connect block:",t.message)}this.put(d.s(a.hash,a.index),P.EncodeSpenderValue(n,t,e.height,r))}for(const t of s.outputs)t.script.isUnspendable()||this.pending.add(t);try{var c=await O.FactoryOfContract({env:this,block:e,tx:s,coins:i});if(!t.isGenesis()){var h=await c.verify();if(1!=h)throw new pt(s,E(h),"bad-contract-verify",100)}await c.isBlockFinal()==_.Final&&await c.confirm()}catch(t){this.logger.error("TX(%s) Smart Contract Execute Error: %s",s.txid(),t.message)}this.indexTX(s,i,t,u)}this.saveView(i),i.undo.isEmpty()||this.put(d.u(r),i.undo.commit()),await this.setCpHistory(),await this.voteMgr.saveVote(),this.scList.deletes([["indate","<",this.chain.height]]),await this.pruneBlock(t)}}async disconnectBlock(t,e){var i=new u;if(!this.options.spv){var s=e.hash(),n=await this.getUndoCoins(s);this.pending.disconnect(e);for(let r=e.txs.length-1;0<=r;r--){var a=e.txs[r];if(0<r)for(let t=a.inputs.length-1;0<=t;t--){var o=a.inputs[t].prevout;n.apply(i,o),this.pending.add(i.getOutput(o))}i.removeTX(a,t.height,t.time);for(let t=a.outputs.length-1;0<=t;t--){var c=a.outputs[t];c.script.isUnspendable()||this.pending.spend(c)}try{await(await O.FactoryOfContract({env:this,block:e,tx:a})).unconfirm()}catch(s){this.logger.error("TX(%s) Smart Contract Unconfirm Error: %s",a.txid(),s.message)}await this.unindexTX(a,i)}r(n.isEmpty(),"Undo coins data inconsistency."),this.saveView(i),this.del(d.u(s)),await this.voteMgr.saveVote()}return i}async pruneBlock(t){this.options.spv||!this.options.prune||(t=t.height-this.network.block.keepBlocks)<=this.network.block.pruneAfterHeight||(t=await this.getHash(t))&&(this.del(d.b(t)),this.del(d.u(t)))}saveFlags(){var t=ft.fromOptions(this.options),e=this.db.batch();return e.put(d.O,t.toRaw()),e.write()}indexTX(t,e,i,r){var s=t.hash();if(this.options.indexTX&&(r=b.fromTX(t,i,r),this.put(d.t(s),r.toRaw()),this.options.indexAddress)){for(const e of t.getHashes())this.put(d.T(e,s),null);for(const e of t.getOutputHashes())this.put(d.TO(e,s),null);for(const i of t.getInputHashes(e))this.put(d.TI(i,s),null)}if(this.options.indexAddress){if(!i.isGenesis()&&!t.isCoinbase())for(var{prevout:n}of t.inputs){var a=e.getOutput(n).getHash();a&&this.del(d.C(a,n.hash,n.index))}for(let e=0;e<t.outputs.length;e++){var o=t.outputs[e].getHash();o&&this.put(d.C(o,s,e),null)}}}async unindexTX(t,e){var i,r=t.hash();if(this.options.indexTX&&(this.del(d.t(r)),this.options.indexAddress))for(i of t.getHashes(e))this.del(d.T(i,r)),this.del(d.TI(i,r)),this.del(d.TO(i,r));if(this.options.indexAddress){if(!t.isCoinbase())for(var{prevout:s}of t.inputs){var n=e.getOutput(s).getHash();n&&this.put(d.C(n,s.hash,s.index),null)}for(let e=0;e<t.outputs.length;e++){var a=t.outputs[e].getHash();a&&this.del(d.C(a,r,e))}}}async readHostList(){return this.db.get(d.HL)}async writeHostList(t){var e=this.db.batch();return e.put(d.HL,t),e.write()}async emitCoinSpent(t,e,i,r){(i={env:this,block:r,tx:i,hash:t.prevout.hash,i:t.prevout.index,height:r.height,output:e,type:e.getReturnType(),data:e.getReturnData(ct)}).data&&await at(i).spent(t)}}function ft(t){if(!(this instanceof ft))return new ft(t);this.network=h.primary,this.spv=!1,this.witness=!0,this.prune=!1,this.indexTX=!1,this.indexAddress=!1,t&&this.fromOptions(t)}dt.layout=d,ft.prototype.fromOptions=function(t){return this.network=h.get(t.network),null!=t.spv&&(r("boolean"==typeof t.spv),this.spv=t.spv),null!=t.prune&&(r("boolean"==typeof t.prune),this.prune=t.prune),null!=t.indexTX&&(r("boolean"==typeof t.indexTX),this.indexTX=t.indexTX),null!=t.indexAddress&&(r("boolean"==typeof t.indexAddress),this.indexAddress=t.indexAddress),this},ft.fromOptions=function(t){return(new ft).fromOptions(t)},ft.prototype.toRaw=function(){var t=new a(12);let e=0;return this.spv&&(e|=1),this.witness&&(e|=2),this.prune&&(e|=4),this.indexTX&&(e|=8),this.indexAddress&&(e|=16),t.writeU32(this.network.magic),t.writeU32(e),t.writeU32(0),t.render()},ft.prototype.fromRaw=function(t){return t=new n(t),this.network=h.fromMagic(t.readU32()),t=t.readU32(),this.spv=0!=(1&t),this.witness=0!=(2&t),this.prune=0!=(4&t),this.indexTX=0!=(8&t),this.indexAddress=0!=(16&t),this},ft.fromRaw=function(t){return(new ft).fromRaw(t)};class mt{constructor(){this.tip=c.NULL_HASH,this.tx=0,this.coin=0,this.value=0,this.committed=!1}rhash(){return s.revHex(this.tip)}clone(){var t=new mt;return t.tip=this.tip,t.tx=this.tx,t.coin=this.coin,t.value=this.value,t}connect(t){this.tx+=t.txs.length}disconnect(t){this.tx-=t.txs.length}add(t){this.coin++,this.value+=t.value}spend(t){this.coin--,this.value-=t.value}commit(t){return"string"!=typeof t&&(t=t.toString("hex")),this.tip=t,this.committed=!0,this.toRaw()}toRaw(){var t=new a(56);return t.writeHash(this.tip),t.writeU64(this.tx),t.writeU64(this.coin),t.writeU64(this.value),t.render()}static fromRaw(t){var e=new mt;t=new n(t);return e.tip=t.readHash("hex"),e.tx=t.readU64(),e.coin=t.readU64(),e.value=t.readU64(),e}}function gt(t){this.network=t,this.bits=[],this.updates=[],this._init()}function yt(t,e,i){this.bit=t,this.hash=e,this.state=i}gt.prototype._init=function(){for(let t=0;t<32;t++)this.bits.push(null);for(var{bit:t}of this.network.deploys)r(!this.bits[t]),this.bits[t]=new Map},gt.prototype.set=function(t,e,i){var s=this.bits[t];r(s),s.get(e.hash)!==i&&(s.set(e.hash,i),this.updates.push(new yt(t,e.hash,i)))},gt.prototype.get=function(t,e){return t=this.bits[t],r(t),null==(t=t.get(e.hash))?-1:t},gt.prototype.commit=function(){this.updates.length=0},gt.prototype.drop=function(){for(var{bit:t,hash:e}of this.updates)t=this.bits[t],r(t),t.delete(e);this.updates.length=0},gt.prototype.insert=function(t,e,i){t=this.bits[t],r(t),t.set(e,i)},yt.prototype.toRaw=function(){return x(this.state)},t.exports=dt},function(t,e,i){"use strict";
885
885
  /*!
886
886
  * lowlevelup.js - LevelUP module for vallnet
887
887
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -908,7 +908,7 @@ var r=i(775),s=i(777),n=i(778),a=i(779),o=i(780),c=i(781),h=i(782),u=i(783);i=i(
908
908
  /*!
909
909
  * accountdb.js - storage for account management
910
910
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
911
- */const r=i(8),s=i(0),n=i(73),a=i(122),o=i(159),c=i(612),h=i(95),u=h.walletdb,l=i(7),p=i(160),d=i(127),f=i(169),m=i(6),g=i(37).VerifyError,y=i(46),v=i(12);i(19);const w=i(60),b=i(198),k=i(69),x=i(43),{getVerifyMsg:S,BlockFinalType:E,ContractEnvType:_}=i(5),R=i(161),A=i(614),C=i(31);var I=i(72);const O=i(1),P=i(119).sortWithSeq,T=i(34),j=i(199),B=i(65),N=i(101),F=i(3),D=F.U32,L=i(341),M=i(342),H=i(343),z=H.vpItem,U=i(616),q=U.vpItem,V=i(85),K=i(617),W=V.cpItem,G=V.stockItem,$=i(158),X=$.ErAbolishItem,Y=i(36).broadcast,J=i(134),Z=J.vpItem,Q=i(232),tt=Q.stockAccount,et=i(157),it=et.ErItem,rt=i(618),st=rt.AuditItem,nt=i(315),at=i(110),ot=i(619),ct=i(316),ht=i(123),ut=i(620),lt=i(222),pt=i(39),dt=i(35),ft=i(59),mt=i(78).errors,gt=i(77);class yt extends I{constructor(t){super(),this.readyLoad=!1,this.options=new c(t),this.network=this.options.network,this.logger=this.options.logger.context("wallet"),this.workers=this.options.workers,this.keys={hmacSalt:F.DefaultChainCode},t.keys&&t.keys.hmacSalt&&(s(Buffer.isBuffer(t.keys.hmacSalt)),this.keys.hmacSalt=t.keys.hmacSalt),this.client=this.options.client,this.client&&(this.client.wdb=this),this.jsonp=this.options.jsonp,this.jsonp&&(this.jsonp.wdb=this),this.spv=this.options.spv,this.feeRate=this.options.feeRate,this.db=f(this.options),this.rpc=new L(this),this.primary=null,this.state=new ot,this.wallets=new Map,this.depth=0,this.rescanning=!1,this.bound=!1,this.newRecord=!0,this.readLock=new j,this.writeLock=new T,this.txLock=new T,this.scanLock=new T,this.widCache=new B(1e4),this.pathMapCache=new B(1e5),this.filter=new N,this.middleHashMem=new Set,this.middleHashChain=new Set,this.autoTaskMgr=new R(this),this.transactionList=new M(this),this.htlcList=new H(this),this.commentList=new U(this),this.NotifyList=new C,this.propList=new J(this),this.accountList=new Q(this),this.$contacts=new C,this.cpList=new V(this),this.cpMemList=new V(this),this.accountCoinList=new K(this),this.auditList=new rt(this),this.erList=new et(this),this.erAbList=new $(this),this.hmacConnection=[],this._init()}async logAudit(t){t.height=this.curHeight,t.time=O.now(),t.erid=l.sha256(O.stringify(t)).toString("hex"),t=new st(t),await this.auditList.setAudit(t)}async getAccountByAddress(t,e){if(t){let s=null;if(s=e?await this.getWalletsByTX(e):await this.getWallets())for(const e of s){var i=await this.get(e);if(i){var r=await i.getPath(t);if(r)return[i.wid,r.name,i.id]}}}return[0,"",""]}_init(){let t=1e6,e=-1;this.spv&&(t=2e4,e=N.flags.ALL),this.filter=N.fromRate(t,.001,e)}async getCpSnap(){return{}}get mode(){return _.Wallet}async getTXFromAll(t){return this.getTXFromDb(t)}async checkNewRecord(){var t={createIfMissing:this.db.options.createIfMissing,errorIfExists:this.db.options.errorIfExists};this.db.options.createIfMissing=!1,this.db.options.errorIfExists=!0;try{await this.db.open();var e=await this.db.checkVersion(u,6);this.newRecord="new"==e}catch(t){if(-1!=t.message.indexOf("does not exist (create_if_missing is false)"))this.newRecord=!0;else{if(-1==t.message.indexOf("exists (error_if_exists is true)"))throw t;this.newRecord=!1}}try{await this.db.close()}catch(t){}this.db.options.createIfMissing=t.createIfMissing,this.db.options.errorIfExists=t.errorIfExists}async isNewRecord(){return await this.checkNewRecord(),this.newRecord}setmnemonic(t){if(this.options.mnemonic=this.options.mnemonic||{},t.bits)this.options.mnemonic={bits:t.bits};else if(t.entropy)this.options.mnemonic={entropy:Buffer.from(t.entropy,"hex")};else if(t.phrase){var e=this.testmnemonic(t.phrase);if(0!=e.code)throw e.msg;this.options.mnemonic={phrase:t.phrase}}t.passphrase&&(this.options.mnemonic.passphrase=t.passphrase),t.language&&(this.options.mnemonic.language=t.language)}testmnemonic(t){try{return new b(t),{code:0}}catch(t){return{code:-1,msg:t.message}}}async getContracts(t){var e=await this.db.values({gte:h.txdb.tx(F.NULL_HASH),lte:h.txdb.tx(F.HIGH_HASH),parse:t=>O.parseJson(t.toString())});return t?e.filter(e=>e.srcact==t||e.dstact==t):e}isFull(){return this.spv||this.synced||!1}async _open(t){}async handleNotify(t,e=!1){if(!e){let i=t.body.content;if("string"==typeof i)try{i=JSON.parse(t.body.content)}catch(t){return}"object"==typeof i&&"secret"===i.type&&(e={contact:t.body.src,messenger:t.body.dst},i.init&&(e.init=Buffer.from(i.init,"hex")),i.packet&&(e.packet=Buffer.from(i.packet)),await this.handleSecret(e))}}async handleSecret(t){if(t.contact&&t.messenger&&t.contact!=t.messenger){try{v.fromString(t.contact,this.network.type),v.fromString(t.messenger,this.network.type)}catch(t){return}var e=await this.ensureContact(t);e&&await e.ensureMessenger(t).answer(t)}}async scanContact(t,e=-1){var i=async t=>{var e;t.witness&&"witnesspubkeyhash"==t.getType()&&(e=t.witness.getPubkeyhashInput()[1],t=v.fromWitness(t.witness).toString(),e)&&t&&await this.ensureContact({contact:t,publicKey:e})};if(0<=e&&e<t.inputs.length)await i(t.inputs[e]);else for(var r of t.inputs)await i(r)}async ensureContact(t){if(!t.contact||t.contact==t.messenger)return null;try{v.fromString(t.contact,this.network.type),t.messenger&&v.fromString(t.messenger,this.network.type)}catch(t){return null}t.network=this.network.type,this.$contacts.get(t.contact)||this.$contacts.set(t.contact,new A(t));var e=this.$contacts.get(t.contact);if(t.messenger&&!(t=e.ensureMessenger(t)).wallet){var i,[i,r]=await this.getAccountByAddress(t.address);if(!(i=await this.get(i)))return;t.wallet=i,t.account=r}return e}getCps(){return this.db.values({gte:h.txdb.cp(F.ZERO_CID,"hex"),lte:h.txdb.cp(F.MAX_CID,"hex"),parse:t=>W.fromRaw(t)})}async _close(){await this.disconnect(),this.http&&this.options.listen&&await this.http.close();for(const t of this.wallets.values())await t.destroy();await this.db.close(),this.options.listen&&await this.logger.close()}async destroy(){await this.db.destroy(),this.widCache.reset(),this.pathMapCache.reset()}async load(t){if(this.readyLoad){var e=await this.ensure({id:"primary",witness:!0,mnemonic:this.options.mnemonic}),i=await this.txLock.lock();try{await this.init(t),await this.watch(),await e.createReceive(0,1,e.master,this.network.type),await e.ensureNotifyKey(),await this.sync()}finally{i()}setTimeout(()=>{this.resend()},5e3)}}bind(){!this.client||this.bound||(this.bound=!0,this.client.hook("htlcassent.cancel",t=>{this.setAssent(t),this.emit("htlcassent.cancel",t)}),this.client.hook("htlcassent.deal",t=>{this.setAssent(t),this.emit("htlcassent.deal",t)}),this.client.hook("htlcassent.receive",t=>{this.setAssent(t),this.emit("htlcassent.receive",t)}),this.client.hook("htlcsuggest.cancel",t=>{this.setSuggest(t),this.emit("htlcsuggest.cancel",t)}),this.client.hook("htlcsuggest.deal",t=>{this.setSuggest(t),this.emit("htlcsuggest.deal",t)}),this.client.hook("htlcsuggest.receive",t=>{this.setSuggest(t),this.emit("htlcsuggest.receive",t)}),this.on("mssendpubk/receive",async t=>{let e=await this.get(t.addr);var i,r,s;if(!e&&(e=await this.ensure({id:t.addr,type:"multisig",m:t.m,n:t.n,witness:!0}),[s,r]=await this.getAccountByAddress(t.addr),s=await this.get(s))&&await s.send({subtractFee:!1,sort:!1,outputs:[{address:t.contract,value:1e4}],comment:JSON.stringify({oper:"scrun",params:{oper:"pubk",addr:t.addr,puba:e.account.accountKey}})},r),e.account.keys.length<e.account.n-1){for(i of t.data.split(","))try{await e.addSharedKey(i)}catch(t){}e.account.keys.length==e.account.n-1&&([s,r]=await this.getAccountByAddress(t.addr),s=await this.get(s))&&await s.send({subtractFee:!1,sort:!1,outputs:[{address:t.contract,value:1e4}],comment:JSON.stringify({oper:"scrun",params:{oper:"puba",addr:t.addr,puba:e.account.receive.getAddress().toString()}})},r)}}),this.on("mssendtx/receive",async t=>{var e,i=await this.get(t.addr);i&&i.account.type==o.types.MULTISIG&&((e=w.fromRaw(t.data,"hex")).view=await i.getCoinView(e),e.isSigned()||(t.txid=e.txid(),await this.saveMSTrans(t)))}),this.client.hook("onConnect",async()=>{await this.load()}),this.client.hook("error",t=>{this.emit("error",t)}),this.client.hook("block.connect",async(t,e)=>{try{await this.addBlock(t,e)}catch(t){this.emit("error",t)}}),this.client.hook("block.disconnect",async(t,e)=>{try{await this.removeBlock(t,e)}catch(t){this.emit("error",t)}}),this.client.hook("chain.full",()=>{this.synced=!0}),this.client.hook("block.rescan",async(t,e)=>{try{await this.rescanBlock(t,e)}catch(t){this.emit("error",t)}}),this.client.on("tx",async(t,e,i)=>{try{await this.addTX(t,null,i)}catch(t){this.emit("error",t)}}),this.client.on("entry.remove",async(t,e)=>{try{if(e){var i=t.tx.hash("hex"),r=await this.getWalletsByTX(t.tx);if(r)for(const e of r){var n=await this.get(e);s(n),await n.remove(i),(await x.FactoryOfContract({tx:t.tx,env:this})).erase()}}}catch(t){this.emit("error",t)}}),this.client.hook("chain.reset",async t=>{try{await this.resetChain(t)}catch(t){this.emit("error",t)}}),this.jsonp&&this.jsonp.hook("error",t=>{this.emit("error",t)}))}async disconnect(){this.client&&await this.client._close(),this.jsonp&&await this.jsonp._close()}async flushCP(t,e=!1){this.client&&(t=t||[],e||(t=this.cpList.excludeCids(t),e=e||0<t.length),e)&&await this.client.execute("cp.remoteQuery",[[["cid","include",t]]])}async watch(){let t=this.db.iterator({gte:u.p(F.NULL_HASH),lte:u.p(F.HIGH_HASH)}),e=0,i=0;for(;;){var r=await t.next();if(!r)break;try{var s=u.pp(r.key);this.filter.add(s,"hex")}catch(e){throw await t.end(),e}e++}for(t=this.db.iterator({gte:u.o(F.NULL_HASH,0),lte:u.o(F.HIGH_HASH,4294967295)});;){var n=await t.next();if(!n)break;try{var[a,o]=u.oo(n.key),c=new y(a,o).toRaw();this.filter.add(c)}catch(e){throw await t.end(),e}i++}this.logger.info("Filter: Added %d hashes to AccountDB filter.",e),this.logger.info("Filter: Added %d outpoints to AccountDB filter.",i),await this.setFilter()}async sync(){if(this.client){let e,i=this.curHeight;for(;0<=i;){var t=await this.getBlock(i);if(!t)break;if(e=await this.client.getEntry(t.hash))break;i--}e||(i=this.state.startHeight,e=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.accountList.loadHistory(),await this.transactionList.loadHistory(),await this.loadContact(),await this.erList.loadHistory(),await this.auditList.loadHistory(),await this.erAbList.loadHistory(),await this.accountCoinList.loadHistory(),await this.scan(i,!1)}}async scan(t,e=!0){if(this.client){null==t&&(t=this.state.startHeight),s(t>>>0===t,"WDB: Must pass in a height.");var i=this.curHeight;e=(await this.rollback(t,e),this.logger.info("AccountDB is scanning %d blocks.",i-t+1),await this.getTip());try{this.rescanning=!0,await this.client.rescan(e.hash)}finally{this.rescanning=!1}}}async rescan(t){var e=await this.txLock.lock();try{return await this.scan(t,!1)}finally{e()}}async send(t){if(this.client)return this.client.send(t);this.emit("send",t)}async getTX(t){for(const i of this.wallets.values()){var e=await i.getTX(t);if(e)return e.tx}return null}async getTXFromDb(t){for(const i of this.wallets.values()){var e=await i.getTX(t);if(e)return e.tx}return null}async getExtendTX(t){for(const i of this.wallets.values()){var e=await i.getTX(t);if(e)return e}return null}async removeTX(t){this.client?await this.client.removeTX(t):this.emit("remove",t)}async estimateFee(t){return 0<this.feeRate?this.feeRate:!this.client||(t=await this.client.estimateFee(t))<this.network.feeRate?this.network.feeRate:t>this.network.maxFeeRate?this.network.maxFeeRate:t}setFilter(){return this.client?this.client.setFilter(this.filter):(this.emit("filter.set",this.filter),Promise.resolve())}addFilter(t){return this.client?this.client.addFilter(t):(this.emit("filter.add",t),Promise.resolve())}resetFilter(){return this.client?this.client.resetFilter():(this.emit("filter.reset"),Promise.resolve())}backup(t){return this.db.backup(t)}async wipe(){this.logger.warning("Wiping AccountDB TXDB..."),this.logger.warning("I hope you know what you're doing.");var t=this.db.iterator({gte:Buffer.from([0]),lte:Buffer.from([255])}),e=this.db.batch();let i=0;for(;;){var r=await t.next();if(!r)break;try{switch(r.key[0]){case 98:case 99:case 101:case 116:case 111:case 104:case 82:e.del(r.key),i++}}catch(e){throw await t.end(),e}}this.logger.warning("Wiped %d txdb records.",i),await e.write()}async getDepth(){var t=this.db.iterator({gte:u.w(0),lte:u.w(4294967295),reverse:!0,limit:1}),e=await t.next();return e?(await t.end(),u.ww(e.key)+1):1}start(t){return s(!t.current,"WDB: Batch already started."),t.current=this.db.batch(),t.accountCache.start(),t.pathCache.start(),t.current}drop(t){var e=this.batch(t);t.current=null,t.accountCache.drop(),t.pathCache.drop(),e.clear()}clear(t){var e=this.batch(t);t.accountCache.clear(),t.pathCache.clear(),e.clear()}batch(t){return s(t.current,"WDB: Batch does not exist."),t.current}async commit(t){var e=this.batch(t);try{await e.write()}catch(t){throw this.drop(),t}t.current=null,t.accountCache.commit(),t.pathCache.commit()}testFilter(t){return this.filter.test(t,"hex")}addHash(t){return this.filter.add(t,"hex"),this.addFilter(t)}addOutpoint(t,e){t=new y(t,e),this.filter.add(t.toRaw())}dump(){return this.db.dump()}register(t){s(!this.wallets.has(t.wid)),this.wallets.set(t.wid,t)}unregister(t){s(this.wallets.has(t.wid)),this.wallets.delete(t.wid)}async getWalletID(t){var e;return t?"number"==typeof t?t:this.widCache.get(t)||((e=await this.db.get(u.l(t)))?(e=e.readUInt32LE(0,!0),this.widCache.set(t,e),e):null):null}async get(t){if(!(t=await this.getWalletID(t)))return null;var e=await this.readLock.lock(t);try{return await this._get(t)}finally{e()}}async _get(t){var e=this.wallets.get(t);return e||((e=await this.db.get(u.w(t)))?(await(t=a.fromRaw(this,e)).open(),this.register(t),t):null)}async loadBackup(t){if(ft.unsupported)throw new gt(mt.INTERNAL_ERROR,"FS not available.");let e=await this.get("primary");var i;for(i of(await ft.readFile(t,"utf8")).split(/\n+/))if(0!==(i=i.trim()).length&&!/^\s*#/.test(i)){var r=i.split(/\s+/);if(r.length<4)throw new gt(mt.DESERIALIZATION_ERROR,"Malformed wallet Data File.");switch(r[0]){case"W":var n=Buffer.from(r[1],"base64");n=a.fromRaw(e.db,n);if(e.wid!=n.wid)throw new gt(mt.DESERIALIZATION_ERROR,"Malformed wallet Key");await this.replace(n),e=await this.get("primary"),this.logger.info("Import Wallet %s(%s)",e.id,e.wid);break;case"C":n=Buffer.from(r[1],"base64");(c=((h=o.fromRaw(e.db,n)).wallet=e,h.wid=e.wid,h.id=e.id,h.initialized=!0,h.watchOnly=e.watchOnly,h.receive=h.deriveReceive(h.receiveDepth-1),h.change=h.deriveChange(h.changeDepth-1),h.witness&&(h.nested=h.deriveNested(h.nestedDepth-1)),e.master.key.deriveAccount(44,h.accountIndex))).publicKey.toString("hex")!==h.accountKey.publicKey.toString("hex")&&s(c.publicKey.toString("hex")==h.accountKey.publicKey.toString("hex")),await e.saveAccount(h),this.logger.info("Import Account %s(%s)",h.name,h.accountIndex);break;case"A":var c=parseInt(r[5]),h=parseInt(r[7]),u=parseInt(r[9]),l=r[11].trim(),p=await e.deriveKey(c,h,u),d=await e.deriveKey(c,h,u,e.master);p.getAddress("string")!==d.getAddress("string")&&s(p.getAddress("string")==d.getAddress("string")),p.getAddress("string")!==l&&s(p.getAddress("string")==l),this.logger.info("Import Address %s %s %s %s",c,h,u,p.getAddress("string"))}}return e.accountCache.reset(),e}save(t){var e=t.wid,i=t.id,r=this.batch(t);this.widCache.set(i,e),r.put(u.w(e),t.toRaw()),r.put(u.l(i),D(e))}async rename(t,e){var i=await this.writeLock.lock();try{return await this._rename(t,e)}finally{i()}}async _rename(t,e){var i=t.id;if(!n.isName(e))throw new Error("WDB: Bad wallet ID.");if(await this.has(e))throw new Error("WDB: ID not available.");this.start(t).del(u.l(i)),t.id=e,this.save(t),await this.commit(t),this.widCache.remove(i),i=t.pathCache.values();for(const t of i)t.id=e}async replace(t){var e=await this.writeLock.lock();try{return await this._replace(t)}finally{e()}}async _replace(t){var e=this.start(t);e.del(u.l(t.id)),e.del(u.w(t.wid)),this.save(t),await this.commit(t),this.widCache.remove(t.id),this.wallets.delete(t.wid)}renameAccount(t,e){var i=t.wallet;this.batch(i).del(u.i(t.wid,t.name)),t.name=e,this.saveAccount(t)}async auth(t,e){if("string"==typeof e){if(!O.isHex256(e))throw new Error("WDB Authentication: Invalid Token.");e=Buffer.from(e,"hex")}t=k.getHmac(t.toString(),this.keys.hmacSalt);var i=r.createHmac("sha256",t.random);i=Buffer.from(i.update(t.token).digest("hex"),"hex");if(!p(e,i))throw new Error("WDB Authentication: CRC Error.")}async create(t){var e=await this.writeLock.lock();t=t||{};try{return await this._create(t)}finally{e()}}async _create(t){if(await this.has(t.id))throw new Error("WDB: Wallet already exists.");"string"==typeof t.mnemonic&&(t.mnemonic={phrase:t.mnemonic}),t.mnemonic=t.mnemonic||{},!t.mnemonic.language&&this.options.mnemonic&&this.options.mnemonic.language&&(t.mnemonic.language=this.options.mnemonic.language);var e=a.fromOptions(this,t);return e.wid=this.depth++,await e.init(t),this.register(e),this.logger.info("Created wallet %s in AccountDB.",e.id),e}async has(t){return null!=await this.getWalletID(t)}async ensure(t){return await this.get(t.id)||this.create(t)}async getAccount(t,e){return(t=await this.db.get(u.a(t,e)))?o.fromRaw(this,t):null}getAccounts(t){return this.db.values({gte:u.n(t,0),lte:u.n(t,4294967295),parse:t=>t.toString("ascii")})}async getAccountIndex(t,e){return(t=await this.db.get(u.i(t,e)))?t.readUInt32LE(0,!0):-1}async getGuider(t){return t=v.fromString(t,this.network.type).getHash("hex"),(t=await this.db.get(u.g(t)))?v.fromRaw(t).toString():null}async setGuider(t,e,i){var r;i=v.fromString(i,this.network.type).getHash("hex"),await this.db.has(u.g(i))||(t=v.fromString(t,this.network.type),(r=this.db.batch()).put(u.g(i),t.toRaw()),r.put(u.gs(t.getHash("hex"),Buffer.from(e,"ascii").toString("hex"),i),null),await r.write())}async unsetGuider(t,e,i){t=v.fromString(t,this.network.type).getHash("hex"),i=v.fromString(i,this.network.type).getHash("hex");var r=this.db.batch();r.del(u.g(i)),r.del(u.gs(t,Buffer.from(e,"ascii").toString("hex"),i)),await r.write()}async getAccountName(t,e){return(t=await this.db.get(u.n(t,e)))?t.toString("ascii"):null}saveAccount(t){var e=t.wid,i=t.wallet,r=t.accountIndex,s=t.name,n=this.batch(i);n.put(u.a(e,r),t.toRaw()),n.put(u.i(e,s),D(r)),n.put(u.n(e,r),Buffer.from(s,"ascii")),i.accountCache.push(r,t)}hasAccount(t,e){return"number"==typeof t&&"number"==typeof e&&this.db.has(u.a(t,e))}async getPathMap(t){var e=this.pathMapCache.get(t);return e||((e=await this.db.get(u.p(t)))?(e=ut.fromRaw(t,e),this.pathMapCache.set(t,e),e):null)}saveKey(t,e){return this.savePath(t,e.toPath())}async savePath(t,e){var i=t.wid,r=e.hash,s=this.batch(t);await this.addHash(r);let n=await this.getPathMap(r);(n=n||new ut(r)).add(i)&&(this.pathMapCache.set(r,n),t.pathCache.push(r,e),s.put(u.p(r),n.toRaw()),s.put(u.P(i,r),e.toRaw()),s.put(u.r(i,e.account,r),null))}async getPath(t,e){var i=await this.db.get(u.P(t,e));return i?((i=at.fromRaw(i)).wid=t,i.hash=e,i):null}hasPath(t,e){return this.db.has(u.P(t,e))}getHashes(){return this.db.keys({gte:u.p(F.NULL_HASH),lte:u.p(F.HIGH_HASH),parse:u.pp})}getOutpoints(){return this.db.keys({gte:u.o(F.NULL_HASH,0),lte:u.o(F.HIGH_HASH,4294967295),parse:t=>{var[t,e]=u.oo(t);return new y(t,e)}})}getWalletHashes(t){return this.db.keys({gte:u.P(t,F.NULL_HASH),lte:u.P(t,F.HIGH_HASH),parse:u.Pp})}getAccountHashes(t,e){return this.db.keys({gte:u.r(t,e,F.NULL_HASH),lte:u.r(t,e,F.HIGH_HASH),parse:u.rr})}async getWalletPaths(t){var e=[];for(const s of await this.db.range({gte:u.P(t,F.NULL_HASH),lte:u.P(t,F.HIGH_HASH)})){var i=u.Pp(s.key),r=at.fromRaw(s.value);r.hash=i,r.wid=t,e.push(r)}return e}async encryptKeys(t,e){var i,r,n=t.wid,a=await t.getPaths(),o=this.batch(t);for(i of a)i.data&&(s(!i.encrypted),r=Buffer.from(i.hash,"hex").slice(0,16),(i=i.clone()).data=d.encipher(i.data,e,r),i.encrypted=!0,t.pathCache.push(i.hash,i),o.put(u.P(n,i.hash),i.toRaw()))}async decryptKeys(t,e){var i,r,n=t.wid,a=await t.getPaths(),o=this.batch(t);for(i of a)i.data&&(s(i.encrypted),r=Buffer.from(i.hash,"hex").slice(0,16),(i=i.clone()).data=d.decipher(i.data,e,r),i.encrypted=!1,t.pathCache.push(i.hash,i),o.put(u.P(n,i.hash),i.toRaw()))}async resend(){var t,e={};for(const t of await this.db.keys({gte:u.w(0),lte:u.w(4294967295)})){var i,r=u.ww(t);r&&(i=await this.resendPending(r))&&Array.isArray(i)&&(e[r]=i)}for(t of Object.keys(e)){var s=await this.get(parseInt(t));if(s)for(const i of e[t]){try{await this.send(i)}catch(t){this.logger.warning("wdb resend:",t.message);try{await s.abandon(i.hash("hex"))}catch(t){this.logger.warning("wdb abandon:",t.message)}}await dt.timeout(50)}}}async resendPending(t){var e=await this.get(t),i=await this.db.keys({gte:h.txdb.prefix(t,h.txdb.p(F.NULL_HASH)),lte:h.txdb.prefix(t,h.txdb.p(F.HIGH_HASH))});if(0!==i.length){this.logger.info("Rebroadcasting %d transactions for %d.",i.length,t);var r=[];for(const o of i){var s=h.txdb.pp(o),n=h.txdb.prefix(t,h.txdb.t(s));if((n=await this.db.get(n))&&!(n=lt.fromRaw(n)).tx.isCoinbase())try{var a=await x.FactoryOfContract({tx:n.tx,env:this});await a.isBlockFinal()==E.Expired?e&&(await this.removeTX(n.tx),await e.remove(s),await a.erase()):"notify"!=a.oper&&r.push(n.tx)}catch(t){this.logger.error("TX(%s) Smart Contract Error: %s",n.tx.txid(),t.message)}}return await P(r,this)}}getWallets(){return this.db.keys({gte:u.l("\0"),lte:u.l("ÿ"),parse:u.ll})}async getWalletsByTX(t){var e=new Set;if(!t.isCoinbase())for(const r of t.inputs){var i=r.prevout;if(this.testFilter(i.toRaw())&&(i=await this.getOutpointMap(i.hash,i.index)))for(const t of i.wids)e.add(t)}for(const i of t.getOutputHashes("hex"))if(this.testFilter(i)){var r=await this.getPathMap(i);if(r)for(const t of r.wids)e.add(t)}return 0===e.size?null:e}async getState(){var t=await this.db.get(u.R);return t?ot.fromRaw(t):null}async init(t){var e=this.options.startHeight;let i;if(this.client){if(null!=e){if(!(i=await this.client.getEntry(e)))throw new Error("WDB: Could not find start block.")}else i=await this.client.getTip();i=ht.fromEntry(i)}else i=ht.fromEntry(this.network.genesis);this.logger.info("Initializing AccountDB chain state (height %d).",i.height),(e=await this.getState())?this.state=e:await this.resetState(i,!1),await this.ensure({id:"primary",witness:!0,mnemonic:this.options.mnemonic}),t&&t.backup&&await this.loadBackup(t.backup)}async resetState(t,e){for(var i=this.state.clone(),r=(i.startHeight=t.height,i.startHash=t.hash,i.height=t.height,i.marked=e,this.db.batch()),s=this.db.iterator({gte:u.h(t.height),lte:u.h(4294967295),values:!1});;){var n=await s.next();if(!n)break;try{r.del(n.key)}catch(t){throw await s.end(),t}}r.put(u.h(t.height),t.toHash()),r.put(u.R,i.toRaw()),await r.write(),this.state=i}async syncState(t){var e=this.state.clone(),i=this.db.batch();if(t.height<e.height){let s=e.height;var r=s-t.height;for(let t=0;t<r;t++)i.del(u.h(s--))}else t.height>e.height&&s(t.height===e.height+1,`Bad chain sync tip ${t.height} while state `+e.height);e.height=t.height,i.put(u.h(t.height),t.toHash()),i.put(u.R,e.toRaw()),await i.write(),this.state=e,Y("block/tips",e)}get curHeight(){return this.state.height}get tidCreator(){return h.txdb.tx}get finder(){return this.getTXFromDb.bind(this)}rpcExecute(){return this.rpc.execute.apply(this.rpc,arguments)}async getBlockMap(t){var e=await this.db.get(u.b(t));return e?ct.fromRaw(t,e):null}writeBlockMap(t,e,i){this.batch(t).put(u.b(e),i.toRaw())}unwriteBlockMap(t,e){this.batch(t).del(u.b(e))}async getOutpointMap(t,e){var i=await this.db.get(u.o(t,e));return i?nt.fromRaw(t,e,i):null}writeOutpointMap(t,e,i,r){t=this.batch(t),this.addOutpoint(e,i),t.put(u.o(e,i),r.toRaw())}unwriteOutpointMap(t,e,i){this.batch(t).del(u.o(e,i))}async writeBalanceLog(t,e){var i=u.log(t.wid,e.aidx,e.height,e.hash),r=(e=Buffer.from(JSON.stringify(e)),await this.writeLock.lock());try{this.start(t).put(i,e),await this.commit(t)}finally{r()}}async queryBalanceLog(t,e,i=0){return this.db.values({gte:u.log(t,e,i,F.NULL_HASH),lte:u.log(t,e,this.curHeight,F.HIGH_HASH),parse:t=>JSON.parse(t.toString())})}async getBlock(t){var e,i=await this.db.get(u.h(t));return i?((e=new ht).hash=i.toString("hex"),e.height=t,e):null}async getTip(){var t=await this.getBlock(this.curHeight);if(t)return t;throw new Error("WDB: Tip not found!")}async rollback(t,e=!0){if(t>this.curHeight)throw new Error("WDB: Cannot rollback to the future.");if(t===this.curHeight)return this.logger.debug("Rolled back to same height (%d).",t),!0;this.logger.info("Rolling back %d AccountDB blocks to height %d.",this.curHeight-t,t);var i=await this.getBlock(t);let r=!1;return i?(await this.revert(i.height),await this.syncState(i),e):(i=new ht,t>=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(t){var e=this.db.iterator({gte:u.b(t+1),lte:u.b(4294967295),reverse:!0,values:!0});let i=0;for(;;){var r=await e.next();if(!r)break;try{var s=u.bb(r.key),n=ct.fromRaw(s,r.value).toArray();i+=n.length;for(let t=n.length-1;0<=t;t--)await this._unconfirm(n[t])}catch(t){throw await e.end(),t}}this.logger.info("Rolled back %d AccountDB transactions.",i)}async addBlock(t,e){var i=await this.txLock.lock();try{return await this._addBlock(t,e)}finally{i()}}async _addBlock(t,e){var i=ht.fromEntry(t);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),!(this.options.checkpoints&&i.height<=this.network.lastCheckpoint)){for(const t of e)await this._insert(t,i)&&r++;0<r&&this.logger.info("Connected AccountDB block %s (tx=%d).",O.revHex(i.hash),r)}}return r}async removeBlock(t,e){var i=await this.txLock.lock();try{return await this._removeBlock(t,e)}finally{i()}}async _removeBlock(t,e){if((t=ht.fromEntry(t)).height>this.curHeight)return this.logger.warning("AccountDB is disconnecting high blocks (%d).",t.height),0;if(t.height!==this.curHeight)throw new Error(`WDB(removeBlock): Bad disconnection (height mismatch, tip ${t.height} / ${O.revHex(t.hash)} while state ${this.curHeight})`);var i=await this.getBlock(t.height-1);if(!i)throw new Error(`WDB(removeBlock): Bad disconnection (no previous block of ${t.height} / ${O.revHex(t.hash)}).`);var r=await this.getBlockMap(t.height);if(r){for(let t=e.length-1;0<=t;t--){var s=e[t];await this._unconfirm(s,r)}this.logger.warning("Disconnected wallet block %s (tx=%d).",O.revHex(t.hash),r.txs.size)}return await this.syncState(i),r?r.txs.size:0}async rescanBlock(t,e){if(this.rescanning){var i=await this.scanLock.lock();try{await this._addBlock(t,e)}catch(t){throw this.emit("error",t),t}finally{i()}}else this.logger.warning("Unsolicited rescan block: %s.",t.height)}async addTX(t,e,i){var r=await this.txLock.lock();try{return await this._insert(t,e,i)}finally{r()}}listNotify(t){return this.NotifyList.deletes([["h","<",this.curHeight-12]]),this.NotifyList.query(t)}listContact(t,e,i){return this.$contacts.query(t,e,i)}async setCp(t){await this.batchPut(h.txdb.cp(t.cid),t.toRaw())}async delCp(t){await this.batchDel(h.txdb.cp(t))}async delVp(t){var e=this.db.batch();e.del(h.txdb.VP(t.pid)),await e.write()}async setVp(t,e){var i=this.db.batch();i.put(h.txdb.VP(t.pid),t.toRaw()),await i.write()}async getVp(t){return(t=await this.db.get(h.txdb.VP(t)))?Z.fromRaw(t):null}async getVpByAddress(t){return{list:[],count:0}}async getVpByOid(t){return{list:[],count:0}}async loadVpList(){return this.db.values({gte:h.txdb.VP(F.ZERO_CID,"hex"),lte:h.txdb.VP(F.MAX_CID,"hex"),parse:t=>Z.fromRaw(t)})}async saveContact(t){var e=this.db.batch();e.put(h.txdb.CT(t.getAddress()),t.toRaw()),await e.write()}async loadContact(t){var e;for(e of await this.db.values({gte:h.txdb.CT(F.ZERO_HASH160_HEX),lte:h.txdb.CT(F.MAX_HASH160_HEX),parse:t=>A.fromRaw(t,this)}))e.sender&&(e.sender.wallet=await this.get(e.sender.wid)),this.$contacts.set(e.address,e)}async delHtlc(t){var e;(t=new z(t)).id&&(this.htlcList.delete(t.id),this.htlcList.delAccount(t),(e=this.db.batch()).del(h.txdb.VH(t.shash,t.sidx)),await e.write())}async setSuggest(t){t=new z(t);var e,[e,i]=(this.htlcList.set(t.id,t),await this.getAccountByAddress(t.aa)),[e,i]=(e&&this.htlcList.setAccount(t,e,i),await this.getAccountByAddress(t.ba));(e=(e&&this.htlcList.setAccount(t,e,i),this.db.batch())).put(h.txdb.VH(t.shash,t.sidx),t.toRaw()),await e.write()}async setAssent(t){t=new z(t);var e,[e,i]=(this.htlcList.set(t.id,t),await this.getAccountByAddress(t.ab)),[e,i]=(e&&this.htlcList.setAccount(t,e,i),await this.getAccountByAddress(t.bb));(e=(e&&this.htlcList.setAccount(t,e,i),this.db.batch())).put(h.txdb.VH(t.shash,t.sidx),t.toRaw()),await e.write()}async loadHtlcList(){return this.db.values({gte:h.txdb.VH(F.ZERO_CID,0),lte:h.txdb.VH(F.MAX_CID,4294967295),parse:t=>z.fromRaw(t)})}async delComment(t){var e;(t=new q(t)).id&&(this.commentList.delete(t.id),this.commentList.delAccount(t),(e=this.db.batch()).del(h.txdb.VC(t.shash,t.sidx)),await e.write())}async setComment(t){t=new q(t);var e,[e,i]=(this.commentList.set(t.id,t),await this.getAccountByAddress(t.bob));(e=(e&&(this.commentList.setAccount(t,e,i),this.emit("comm.comment",t)),this.db.batch())).put(h.txdb.VC(t.shash,t.sidx),t.toRaw()),await e.write()}async loadCommentList(){return this.db.values({gte:h.txdb.VC(F.ZERO_CID,0),lte:h.txdb.VC(F.MAX_CID,4294967295),parse:t=>q.fromRaw(t)})}async setStockRecord(t){var e=this.db.batch();switch(e.put(t.itemNo,t.toRaw()),t.type){case G.RecordType.Offer:break;case G.RecordType.Bid:var i=this.accountList.getStockAccount(t.cid,t.addr);i&&(i.stock.sum=t.sum,i.stock.price=t.price,i.stock.period=this.curHeight+10*m.BLOCK_DAY,i.seq=t.seq,e.put(i.getItemNo(),i.toRaw()));break;case G.RecordType.Auction:{let s=this.accountList.getStockAccount(t.cid,t.addr);if(s?(i=s.sum+t.sum,s.price=(t.sum*t.price+s.sum*s.price)/i|0,s.sum=i,s.seq=t.seq):((s=new tt(t.cid,t.addr,t.sum,t.price,0)).seq=t.seq,this.accountList.setStockAccount(s)),e.put(s.getItemNo(),s.toRaw()),!(i=this.accountList.getStockAccount(t.cid,t.to)))break;var r=i.sum-t.sum;i.sum=r,i.stock.sum-=t.sum,e.put(i.getItemNo(),i.toRaw());break}case G.RecordType.Purchase:{let i=this.accountList.getStockAccount(t.cid,t.addr);i?(r=i.sum+t.sum,i.price=(t.sum*t.price+i.sum*i.price)/r,i.sum=r,i.seq=t.seq):((i=new tt(t.cid,t.addr,t.sum,t.price,0)).seq=t.seq,this.accountList.setStockAccount(i)),e.put(i.getItemNo(),i.toRaw());break}case G.RecordType.Send:if(i=this.accountList.getStockAccount(t.cid,t.addr)){i.sum-=t.sum,i.seq=t.seq;let s=this.accountList.getStockAccount(t.cid,t.to);s||(s=new tt(t.cid,t.to,0,0,0),this.accountList.setStockAccount(s)),r=s.sum+t.sum,s.price=(t.sum*i.price+s.sum*s.price)/r,s.sum=r,e.put(i.getItemNo(),i.toRaw()),e.put(s.getItemNo(),s.toRaw())}break;case G.RecordType.Bonus:case G.RecordType.Ads:}await e.write()}async unsetStockRecord(t){var e=this.db.batch();switch(e.del(t.itemNo),t.type){case G.RecordType.Offer:break;case G.RecordType.Bid:(s=this.accountList.getStockAccount(t.cid,t.addr))&&(s.stock.sum=0,s.stock.price=0,s.stock.period=0,s.seq=t.seq-1,e.put(s.getItemNo(),s.toRaw()));break;case G.RecordType.Auction:(s=this.accountList.getStockAccount(t.cid,t.addr))&&(i=s.sum-t.sum,s.price=(s.sum*s.price-t.sum*t.price)/i|0,s.sum=i,s.seq=t.seq-1,e.put(s.getItemNo(),s.toRaw()),s=this.accountList.getStockAccount(t.cid,t.to))&&(i=s.sum+t.sum,s.sum=i,s.stock.sum+=t.sum,e.put(s.getItemNo(),s.toRaw()));break;case G.RecordType.Purchase:var i=this.accountList.getStockAccount(t.cid,t.addr);i&&(s=i.sum-t.sum,i.price=(i.sum*i.price-t.sum*t.price)/s,i.sum=s,i.seq=t.seq-1,e.put(i.getItemNo(),i.toRaw()));break;case G.RecordType.Send:var r,s;(s=this.accountList.getStockAccount(t.cid,t.addr))&&(s.sum+=t.sum,s.seq=t.seq-1,e.put(s.getItemNo(),s.toRaw()),i=this.accountList.getStockAccount(t.cid,t.to))&&(r=i.sum-t.sum,i.price=(i.sum*i.price-t.sum*s.price)/r|0,i.sum=r,e.put(i.getItemNo(),i.toRaw()));break;case G.RecordType.Bonus:}await e.write()}async getStockRecordById(t){return(t=await this.db.get(t))?G.fromRaw(t):null}async verifyClsTx(t,e){if(!this.spv&&1!=(e=await(await x.FactoryOfContract({env:this,block:e,tx:t})).verify()))throw new g(t,S(e),"bad-contract-verify",100);return!0}async getStockRecord(t,e,i){let r=6,s=F.ZERO_CID_BUF,n=F.MAX_CID_BUF,a=0;return t&&(r=t,e)&&(s=e,n=e,a=i||0),t=new C,(await this.db.values({gte:G.itemNo(r,s,a,F.NULL_HASH,0),lte:G.itemNo(r,n,4294967295,F.HIGH_HASH,4294967295),parse:G.fromRaw})).reduce((t,e)=>(t.set(e.itemNo,e),t),t),t}async getStockRecordByCid(t,e){var i,r=new C;for(i of Object.keys(G.RecordType)){var s=await this.getStockRecord(G.RecordType[i],t,e);r.merge(s)}return r}async getStockAccountList(t){var e;return t?(e=tt.SN(t,F.NULL_HASH),t=tt.SN(t,F.HIGH_HASH),this.db.values({gte:e,lte:t,parse:tt.fromRaw})):this.db.values({gte:tt.SN(F.ZERO_CID_BUF,F.NULL_HASH),lte:tt.SN(F.MAX_CID_BUF,F.HIGH_HASH),parse:tt.fromRaw})}async delEr(t){var e=this.db.batch();e.del(h.txdb.ER(t.erid)),e.del(h.txdb.ERR(t.witness,t.erid,t.txid)),await e.write()}async setEr(t,e){e&&t.source&&(i=v.fromWitnessPubkeyhash(l.hash160(Buffer.from(t.source.pubkey,"hex")),this.network),[i,e]=await this.getAccountByAddress(i,e),t.wid=i,t.account=e);var i=this.db.batch();e=h.txdb.ERR(t.witness,t.erid,t.txid);i.put(e,t.toRaw()),i.put(h.txdb.ER(t.erid),e),await i.write()}async getEr(t){return(t=(t=await this.db.get(h.txdb.ER(t)))&&await this.db.get(t))?it.fromRaw(t):null}async byPubkey(t,e,i=!1){var r,s=new C;t=await this.db.values({gte:h.txdb.ERR(t,F.NULL_HASH,F.NULL_HASH),lte:h.txdb.ERR(t,F.HIGH_HASH,F.HIGH_HASH),parse:t=>it.fromRaw(t)});let n=[],a=new Map;if(i){for(var o of t)(!a.get(o.source.cluster)||o.startHeight>a.get(o.source.cluster).startHeight)&&a.set(o.source.cluster,await this.caVerifyObj(o));n=a.values()}else n=t;for(r of n)s.set(r.erid,r);return s.query(e)}async caVerifyObj(t){var e={verify:!1};if(!t||t.validHeight<=this.curHeight)return e;var i=await this.erAbList.getErAb(t.erid);return i&&i.abolishHeight<this.curHeight?e:(i=pt.fromPublic(Buffer.from(t.witness,"hex"),this.network.type),t.verify(i)?(t.verify=!0,0<(i=this.cpList.query([["pubKey",t.witness]])).list.length&&(t.cpid=i.list[0].cid),t):e)}async delErAbolish(t){var e=this.db.batch();e.del(h.txdb.ERA(t.erid)),await e.write()}async setErAbolish(t){var e=this.db.batch();e.put(h.txdb.ERA(t.erid),t.toRaw()),await e.write()}async getErAbolish(t){return(t=await this.db.get(h.txdb.ERA(t)))?X.fromRaw(t):null}loadErAbolishList(){return this.db.values({gte:h.txdb.ERA(F.ZERO_CID),lte:h.txdb.ERA(F.MAX_CID),parse:t=>X.fromRaw(t)})}async delAudit(t){var e=this.db.batch();e.del(h.txdb.AU(t.erid)),await e.write()}async setAudit(t){var e=this.db.batch();e.put(h.txdb.AU(t.erid),t.toRaw()),await e.write()}async getAudit(t){return(t=await this.db.get(h.txdb.AU(t)))?st.fromRaw(t):null}async loadAuditList(){return this.db.values({gte:h.txdb.AU(F.NULL_HASH),lte:h.txdb.AU(F.HIGH_HASH),parse:t=>st.fromRaw(t)})}async batchPut(t,e){var i=this.db.batch();i.put(t,e),await i.write()}async batchDel(t){var e=this.db.batch();e.del(t),await e.write()}async _insert(t,e,i){s(!t.mutable,"WDB: Cannot add mutable TX.");let r=await this.getWalletsByTX(t);if(r){this.logger.info("Incoming transaction for %d wallets in AccountDB (%s).",r.size,t.txid()),!e||this.state.marked||(this.logger.info("Marking AccountDB start block at %s (%d).",O.revHex(e.hash),e.height),await this.resetState(e,!0));let a=!1;for(const o of r){var n=await this.get(o);s(n),await n.add(t,e,i)&&(this.logger.info("Added transaction to wallet in AccountDB: %s (%d).",n.id,o),a=!0)}a||(r=null)}try{var a=await x.FactoryOfContract({env:this,block:e,tx:t});e?await a.confirm():await a.insert()}catch(a){e?this.logger.error("TX(%s) Smart Contract Confirm Error: %s",t.txid(),a.message):this.logger.error("TX(%s) Smart Contract Insert Error: %s",t.txid(),a.message)}return r}async _unconfirm(t,e){if(e)try{await(await x.FactoryOfContract({env:this,block:e,tx:t})).unconfirm()}catch(e){this.logger.error("TX(%s) Smart Contract Unconfirm Error: %s",t.txid(),e.message)}let i,r=null;if(i=t.wids?(r=t.wids,t.hash):(r=await this.getWalletsByTX(t),t.hash("hex")),!r)return null;for(const t of r){var n=await this.get(t);s(n),await n.unconfirm(i)}for(const t of r){var a=await this.get(t);s(a),await a.abandon(i)}}async resetChain(t){var e=await this.txLock.lock();try{return await this._resetChain(t)}finally{e()}}async _resetChain(t){if(t.height>this.curHeight)throw new Error(`WDB: Bad reset height ${t.height} while curHeight `+this.curHeight);var e;for(e of(await this.rollback(t.height)||await this.scan(),await this.getWallets())){var i=await this.get(e);for(const e of await i.getPending())try{await i.abandon(e.hash)}catch(t){}await i.resetBalance()}}async saveMSTrans(t){var e=await this.writeLock.lock();try{return await this._saveMSTrans(t)}finally{e()}}async _saveMSTrans(t){var e=this.db.batch();e.put(u.ms(v.getHash(t.addr,"hex"),t.txid),Buffer.from(JSON.stringify(t))),await e.write()}async listMSTrans(t){return t=v.getHash(t,"hex"),this.db.values({gte:u.ms(t,F.NULL_HASH),lte:u.ms(t,F.HIGH_HASH),parse:t=>JSON.parse(t.toString())})}async delMSTrans(t,e){var i=await this.writeLock.lock();try{return await this._delMSTrans(t,e)}finally{i()}}async _delMSTrans(t,e){t=v.getHash(t,"hex");var i=this.db.batch();i.del(u.ms(t,e)),await i.write()}}yt.layout=u,t.exports=yt},function(t,e,i){"use strict";
911
+ */const r=i(8),s=i(0),n=i(73),a=i(122),o=i(159),c=i(612),h=i(95),u=h.walletdb,l=i(7),p=i(160),d=i(127),f=i(169),m=i(6),g=i(37).VerifyError,y=i(46),v=i(12);i(19);const w=i(60),b=i(198),k=i(69),x=i(43),{getVerifyMsg:S,BlockFinalType:E,ContractEnvType:_}=i(5),R=i(161),A=i(614),C=i(31);var I=i(72);const O=i(1),P=i(119).sortWithSeq,T=i(34),j=i(199),B=i(65),N=i(101),F=i(3),D=F.U32,L=i(341),M=i(342),H=i(343),z=H.vpItem,U=i(616),q=U.vpItem,V=i(85),K=i(617),W=V.cpItem,G=V.stockItem,$=i(158),X=$.ErAbolishItem,Y=i(36).broadcast,J=i(134),Z=J.vpItem,Q=i(232),tt=Q.stockAccount,et=i(157),it=et.ErItem,rt=i(618),st=rt.AuditItem,nt=i(315),at=i(110),ot=i(619),ct=i(316),ht=i(123),ut=i(620),lt=i(222),pt=i(39),dt=i(35),ft=i(59),mt=i(78).errors,gt=i(77);class yt extends I{constructor(t){super(),this.readyLoad=!1,this.options=new c(t),this.network=this.options.network,this.logger=this.options.logger.context("wallet"),this.workers=this.options.workers,this.keys={hmacSalt:F.DefaultChainCode},t.keys&&t.keys.hmacSalt&&(s(Buffer.isBuffer(t.keys.hmacSalt)),this.keys.hmacSalt=t.keys.hmacSalt),this.client=this.options.client,this.client&&(this.client.wdb=this),this.jsonp=this.options.jsonp,this.jsonp&&(this.jsonp.wdb=this),this.spv=this.options.spv,this.feeRate=this.options.feeRate,this.db=f(this.options),this.rpc=new L(this),this.primary=null,this.state=new ot,this.wallets=new Map,this.depth=0,this.rescanning=!1,this.bound=!1,this.newRecord=!0,this.readLock=new j,this.writeLock=new T,this.txLock=new T,this.scanLock=new T,this.widCache=new B(1e4),this.pathMapCache=new B(1e5),this.filter=new N,this.middleHashMem=new Set,this.middleHashChain=new Set,this.autoTaskMgr=new R(this),this.transactionList=new M(this),this.htlcList=new H(this),this.commentList=new U(this),this.NotifyList=new C,this.propList=new J(this),this.accountList=new Q(this),this.$contacts=new C,this.cpList=new V(this),this.cpMemList=new V(this),this.accountCoinList=new K(this),this.auditList=new rt(this),this.erList=new et(this),this.erAbList=new $(this),this.hmacConnection=[],this._init()}async logAudit(t){t.height=this.curHeight,t.time=O.now(),t.erid=l.sha256(O.stringify(t)).toString("hex"),t=new st(t),await this.auditList.setAudit(t)}async getAccountByAddress(t,e){if(t){let s=null;if(s=e?await this.getWalletsByTX(e):await this.getWallets())for(const e of s){var i=await this.get(e);if(i){var r=await i.getPath(t);if(r)return[i.wid,r.name,i.id]}}}return[0,"",""]}_init(){let t=1e6,e=-1;this.spv&&(t=2e4,e=N.flags.ALL),this.filter=N.fromRate(t,.001,e)}async getCpSnap(){return{}}get mode(){return _.Wallet}async getTXFromAll(t){return this.getTXFromDb(t)}async checkNewRecord(){var t={createIfMissing:this.db.options.createIfMissing,errorIfExists:this.db.options.errorIfExists};this.db.options.createIfMissing=!1,this.db.options.errorIfExists=!0;try{await this.db.open();var e=await this.db.checkVersion(u,6);this.newRecord="new"==e}catch(t){if(-1!=t.message.indexOf("does not exist (create_if_missing is false)"))this.newRecord=!0;else{if(-1==t.message.indexOf("exists (error_if_exists is true)"))throw t;this.newRecord=!1}}try{await this.db.close()}catch(t){}this.db.options.createIfMissing=t.createIfMissing,this.db.options.errorIfExists=t.errorIfExists}async isNewRecord(){return await this.checkNewRecord(),this.newRecord}setmnemonic(t){if(this.options.mnemonic=this.options.mnemonic||{},t.bits)this.options.mnemonic={bits:t.bits};else if(t.entropy)this.options.mnemonic={entropy:Buffer.from(t.entropy,"hex")};else if(t.phrase){var e=this.testmnemonic(t.phrase);if(0!=e.code)throw e.msg;this.options.mnemonic={phrase:t.phrase}}t.passphrase&&(this.options.mnemonic.passphrase=t.passphrase),t.language&&(this.options.mnemonic.language=t.language)}testmnemonic(t){try{return new b(t),{code:0}}catch(t){return{code:-1,msg:t.message}}}async getContracts(t){var e=await this.db.values({gte:h.txdb.tx(F.NULL_HASH),lte:h.txdb.tx(F.HIGH_HASH),parse:t=>O.parseJson(t.toString())});return t?e.filter(e=>e.srcact==t||e.dstact==t):e}isFull(){return this.spv||this.synced||!1}async _open(t){}async handleNotify(t,e=!1){if(!e){let i=t.body.content;if("string"==typeof i)try{i=JSON.parse(t.body.content)}catch(t){return}"object"==typeof i&&"secret"===i.type&&(e={contact:t.body.src,messenger:t.body.dst},i.init&&(e.init=Buffer.from(i.init,"hex")),i.packet&&(e.packet=Buffer.from(i.packet)),await this.handleSecret(e))}}async handleSecret(t){if(t.contact&&t.messenger&&t.contact!=t.messenger){try{v.fromString(t.contact,this.network.type),v.fromString(t.messenger,this.network.type)}catch(t){return}var e=await this.ensureContact(t);e&&await e.ensureMessenger(t).answer(t)}}async scanContact(t,e=-1){var i=async t=>{var e;t.witness&&"witnesspubkeyhash"==t.getType()&&(e=t.witness.getPubkeyhashInput()[1],t=v.fromWitness(t.witness).toString(),e)&&t&&await this.ensureContact({contact:t,publicKey:e})};if(0<=e&&e<t.inputs.length)await i(t.inputs[e]);else for(var r of t.inputs)await i(r)}async ensureContact(t){if(!t.contact||t.contact==t.messenger)return null;try{v.fromString(t.contact,this.network.type),t.messenger&&v.fromString(t.messenger,this.network.type)}catch(t){return null}t.network=this.network.type,this.$contacts.get(t.contact)||this.$contacts.set(t.contact,new A(t));var e=this.$contacts.get(t.contact);if(t.messenger&&!(t=e.ensureMessenger(t)).wallet){var i,[i,r]=await this.getAccountByAddress(t.address);if(!(i=await this.get(i)))return;t.wallet=i,t.account=r}return e}getCps(){return this.db.values({gte:h.txdb.cp(F.ZERO_CID,"hex"),lte:h.txdb.cp(F.MAX_CID,"hex"),parse:t=>W.fromRaw(t)})}async _close(){await this.disconnect(),this.http&&this.options.listen&&await this.http.close();for(const t of this.wallets.values())await t.destroy();await this.db.close(),this.options.listen&&await this.logger.close()}async destroy(){await this.db.destroy(),this.widCache.reset(),this.pathMapCache.reset()}async load(t){if(this.readyLoad){var e=await this.ensure({id:"primary",witness:!0,mnemonic:this.options.mnemonic}),i=await this.txLock.lock();try{await this.init(t),await this.watch(),await e.createReceive(0,1,e.master,this.network.type),await e.ensureNotifyKey(),await this.sync()}finally{i()}setTimeout(()=>{this.resend()},5e3)}}bind(){!this.client||this.bound||(this.bound=!0,this.client.hook("htlcassent.cancel",t=>{this.setAssent(t),this.emit("htlcassent.cancel",t)}),this.client.hook("htlcassent.deal",t=>{this.setAssent(t),this.emit("htlcassent.deal",t)}),this.client.hook("htlcassent.receive",t=>{this.setAssent(t),this.emit("htlcassent.receive",t)}),this.client.hook("htlcsuggest.cancel",t=>{this.setSuggest(t),this.emit("htlcsuggest.cancel",t)}),this.client.hook("htlcsuggest.deal",t=>{this.setSuggest(t),this.emit("htlcsuggest.deal",t)}),this.client.hook("htlcsuggest.receive",t=>{this.setSuggest(t),this.emit("htlcsuggest.receive",t)}),this.on("mssendpubk/receive",async t=>{let e=await this.get(t.addr);var i,r,s;if(!e&&(e=await this.ensure({id:t.addr,type:"multisig",m:t.m,n:t.n,witness:!0}),[s,r]=await this.getAccountByAddress(t.addr),s=await this.get(s))&&await s.send({subtractFee:!1,sort:!1,outputs:[{address:t.contract,value:1e4}],comment:JSON.stringify({oper:"scrun",params:{oper:"pubk",addr:t.addr,puba:e.account.accountKey}})},r),e.account.keys.length<e.account.n-1){for(i of t.data.split(","))try{await e.addSharedKey(i)}catch(t){}e.account.keys.length==e.account.n-1&&([s,r]=await this.getAccountByAddress(t.addr),s=await this.get(s))&&await s.send({subtractFee:!1,sort:!1,outputs:[{address:t.contract,value:1e4}],comment:JSON.stringify({oper:"scrun",params:{oper:"puba",addr:t.addr,puba:e.account.receive.getAddress().toString()}})},r)}}),this.on("mssendtx/receive",async t=>{var e,i=await this.get(t.addr);i&&i.account.type==o.types.MULTISIG&&((e=w.fromRaw(t.data,"hex")).view=await i.getCoinView(e),e.isSigned()||(t.txid=e.txid(),await this.saveMSTrans(t)))}),this.client.hook("onConnect",async()=>{await this.load()}),this.client.hook("error",t=>{this.emit("error",t)}),this.client.hook("block.connect",async(t,e)=>{try{await this.addBlock(t,e)}catch(t){this.emit("error",t)}}),this.client.hook("block.disconnect",async(t,e)=>{try{await this.removeBlock(t,e)}catch(t){this.emit("error",t)}}),this.client.hook("chain.full",()=>{this.synced=!0}),this.client.hook("block.rescan",async(t,e)=>{try{await this.rescanBlock(t,e)}catch(t){this.emit("error",t)}}),this.client.on("tx",async(t,e,i)=>{try{await this.addTX(t,null,i)}catch(t){this.emit("error",t)}}),this.client.on("entry.remove",async(t,e)=>{try{if(e){var i=t.tx.hash("hex"),r=await this.getWalletsByTX(t.tx);if(r)for(const e of r){var n=await this.get(e);s(n),await n.remove(i),(await x.FactoryOfContract({tx:t.tx,env:this})).erase()}}}catch(t){this.emit("error",t)}}),this.client.hook("chain.reset",async t=>{try{await this.resetChain(t)}catch(t){this.emit("error",t)}}),this.jsonp&&this.jsonp.hook("error",t=>{this.emit("error",t)}))}async disconnect(){this.client&&await this.client._close(),this.jsonp&&await this.jsonp._close()}async flushCP(t,e=!1){this.client&&(t=t||[],e||(t=this.cpList.excludeCids(t),e=e||0<t.length),e)&&await this.client.execute("cp.remoteQuery",[[["cid","include",t]]])}async watch(){let t=this.db.iterator({gte:u.p(F.NULL_HASH),lte:u.p(F.HIGH_HASH)}),e=0,i=0;for(;;){var r=await t.next();if(!r)break;try{var s=u.pp(r.key);this.filter.add(s,"hex")}catch(e){throw await t.end(),e}e++}for(t=this.db.iterator({gte:u.o(F.NULL_HASH,0),lte:u.o(F.HIGH_HASH,4294967295)});;){var n=await t.next();if(!n)break;try{var[a,o]=u.oo(n.key),c=new y(a,o).toRaw();this.filter.add(c)}catch(e){throw await t.end(),e}i++}this.logger.info("Filter: Added %d hashes to AccountDB filter.",e),this.logger.info("Filter: Added %d outpoints to AccountDB filter.",i),await this.setFilter()}async sync(){if(this.client){let e,i=this.curHeight;for(;0<=i;){var t=await this.getBlock(i);if(!t)break;if(e=await this.client.getEntry(t.hash))break;i--}e||(i=this.state.startHeight,e=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.accountList.loadHistory(),await this.transactionList.loadHistory(),await this.loadContact(),await this.erList.loadHistory(),await this.auditList.loadHistory(),await this.erAbList.loadHistory(),await this.accountCoinList.loadHistory(),await this.scan(i,!1)}}async scan(t,e=!0){if(this.client){null==t&&(t=this.state.startHeight),s(t>>>0===t,"WDB: Must pass in a height.");var i=this.curHeight;e=(await this.rollback(t,e),this.logger.info("AccountDB is scanning %d blocks.",i-t+1),await this.getTip());try{this.rescanning=!0,await this.client.rescan(e.hash)}finally{this.rescanning=!1}}}async rescan(t){var e=await this.txLock.lock();try{return await this.scan(t,!1)}finally{e()}}async send(t){if(this.client)return this.client.send(t);this.emit("send",t)}async getTX(t){for(const i of this.wallets.values()){var e=await i.getTX(t);if(e)return e.tx}return null}async getTXFromDb(t){for(const i of this.wallets.values()){var e=await i.getTX(t);if(e)return e.tx}return null}async getExtendTX(t){for(const i of this.wallets.values()){var e=await i.getTX(t);if(e)return e}return null}async removeTX(t){this.client?await this.client.removeTX(t):this.emit("remove",t)}async estimateFee(t){return 0<this.feeRate?this.feeRate:!this.client||(t=await this.client.estimateFee(t))<this.network.feeRate?this.network.feeRate:t>this.network.maxFeeRate?this.network.maxFeeRate:t}setFilter(){return this.client?this.client.setFilter(this.filter):(this.emit("filter.set",this.filter),Promise.resolve())}addFilter(t){return this.client?this.client.addFilter(t):(this.emit("filter.add",t),Promise.resolve())}resetFilter(){return this.client?this.client.resetFilter():(this.emit("filter.reset"),Promise.resolve())}backup(t){return this.db.backup(t)}async wipe(){this.logger.warning("Wiping AccountDB TXDB..."),this.logger.warning("I hope you know what you're doing.");var t=this.db.iterator({gte:Buffer.from([0]),lte:Buffer.from([255])}),e=this.db.batch();let i=0;for(;;){var r=await t.next();if(!r)break;try{switch(r.key[0]){case 98:case 99:case 101:case 116:case 111:case 104:case 82:e.del(r.key),i++}}catch(e){throw await t.end(),e}}this.logger.warning("Wiped %d txdb records.",i),await e.write()}async getDepth(){var t=this.db.iterator({gte:u.w(0),lte:u.w(4294967295),reverse:!0,limit:1}),e=await t.next();return e?(await t.end(),u.ww(e.key)+1):1}start(t){return s(!t.current,"WDB: Batch already started."),t.current=this.db.batch(),t.accountCache.start(),t.pathCache.start(),t.current}drop(t){var e=this.batch(t);t.current=null,t.accountCache.drop(),t.pathCache.drop(),e.clear()}clear(t){var e=this.batch(t);t.accountCache.clear(),t.pathCache.clear(),e.clear()}batch(t){return s(t.current,"WDB: Batch does not exist."),t.current}async commit(t){var e=this.batch(t);try{await e.write()}catch(t){throw this.drop(),t}t.current=null,t.accountCache.commit(),t.pathCache.commit()}testFilter(t){return this.filter.test(t,"hex")}addHash(t){return this.filter.add(t,"hex"),this.addFilter(t)}addOutpoint(t,e){t=new y(t,e),this.filter.add(t.toRaw())}dump(){return this.db.dump()}register(t){s(!this.wallets.has(t.wid)),this.wallets.set(t.wid,t)}unregister(t){s(this.wallets.has(t.wid)),this.wallets.delete(t.wid)}async getWalletID(t){var e;return t?"number"==typeof t?t:this.widCache.get(t)||((e=await this.db.get(u.l(t)))?(e=e.readUInt32LE(0,!0),this.widCache.set(t,e),e):null):null}async get(t){if(!(t=await this.getWalletID(t)))return null;var e=await this.readLock.lock(t);try{return await this._get(t)}finally{e()}}async _get(t){var e=this.wallets.get(t);return e||((e=await this.db.get(u.w(t)))?(await(t=a.fromRaw(this,e)).open(),this.register(t),t):null)}async loadBackup(t){if(ft.unsupported)throw new gt(mt.INTERNAL_ERROR,"FS not available.");let e=await this.get("primary");var i;for(i of(await ft.readFile(t,"utf8")).split(/\n+/))if(0!==(i=i.trim()).length&&!/^\s*#/.test(i)){var r=i.split(/\s+/);if(r.length<4)throw new gt(mt.DESERIALIZATION_ERROR,"Malformed wallet Data File.");switch(r[0]){case"W":var n=Buffer.from(r[1],"base64");n=a.fromRaw(e.db,n);if(e.wid!=n.wid)throw new gt(mt.DESERIALIZATION_ERROR,"Malformed wallet Key");await this.replace(n),e=await this.get("primary"),this.logger.info("Import Wallet %s(%s)",e.id,e.wid);break;case"C":n=Buffer.from(r[1],"base64");(c=((h=o.fromRaw(e.db,n)).wallet=e,h.wid=e.wid,h.id=e.id,h.initialized=!0,h.watchOnly=e.watchOnly,h.receive=h.deriveReceive(h.receiveDepth-1),h.change=h.deriveChange(h.changeDepth-1),h.witness&&(h.nested=h.deriveNested(h.nestedDepth-1)),e.master.key.deriveAccount(44,h.accountIndex))).publicKey.toString("hex")!==h.accountKey.publicKey.toString("hex")&&s(c.publicKey.toString("hex")==h.accountKey.publicKey.toString("hex")),await e.saveAccount(h),this.logger.info("Import Account %s(%s)",h.name,h.accountIndex);break;case"A":var c=parseInt(r[5]),h=parseInt(r[7]),u=parseInt(r[9]),l=r[11].trim(),p=await e.deriveKey(c,h,u),d=await e.deriveKey(c,h,u,e.master);p.getAddress("string")!==d.getAddress("string")&&s(p.getAddress("string")==d.getAddress("string")),p.getAddress("string")!==l&&s(p.getAddress("string")==l),this.logger.info("Import Address %s %s %s %s",c,h,u,p.getAddress("string"))}}return e.accountCache.reset(),e}save(t){var e=t.wid,i=t.id,r=this.batch(t);this.widCache.set(i,e),r.put(u.w(e),t.toRaw()),r.put(u.l(i),D(e))}async rename(t,e){var i=await this.writeLock.lock();try{return await this._rename(t,e)}finally{i()}}async _rename(t,e){var i=t.id;if(!n.isName(e))throw new Error("WDB: Bad wallet ID.");if(await this.has(e))throw new Error("WDB: ID not available.");this.start(t).del(u.l(i)),t.id=e,this.save(t),await this.commit(t),this.widCache.remove(i),i=t.pathCache.values();for(const t of i)t.id=e}async replace(t){var e=await this.writeLock.lock();try{return await this._replace(t)}finally{e()}}async _replace(t){var e=this.start(t);e.del(u.l(t.id)),e.del(u.w(t.wid)),this.save(t),await this.commit(t),this.widCache.remove(t.id),this.wallets.delete(t.wid)}renameAccount(t,e){var i=t.wallet;this.batch(i).del(u.i(t.wid,t.name)),t.name=e,this.saveAccount(t)}async auth(t,e){if("string"==typeof e){if(!O.isHex256(e))throw new Error("WDB Authentication: Invalid Token.");e=Buffer.from(e,"hex")}t=k.getHmac(t.toString(),this.keys.hmacSalt);var i=r.createHmac("sha256",t.random);i=Buffer.from(i.update(t.token).digest("hex"),"hex");if(!p(e,i))throw new Error("WDB Authentication: CRC Error.")}async create(t){var e=await this.writeLock.lock();t=t||{};try{return await this._create(t)}finally{e()}}async _create(t){if(await this.has(t.id))throw new Error("WDB: Wallet already exists.");"string"==typeof t.mnemonic&&(t.mnemonic={phrase:t.mnemonic}),t.mnemonic=t.mnemonic||{},!t.mnemonic.language&&this.options.mnemonic&&this.options.mnemonic.language&&(t.mnemonic.language=this.options.mnemonic.language);var e=a.fromOptions(this,t);return e.wid=this.depth++,await e.init(t),this.register(e),this.logger.info("Created wallet %s in AccountDB.",e.id),e}async has(t){return null!=await this.getWalletID(t)}async ensure(t){return await this.get(t.id)||this.create(t)}async getAccount(t,e){return(t=await this.db.get(u.a(t,e)))?o.fromRaw(this,t):null}getAccounts(t){return this.db.values({gte:u.n(t,0),lte:u.n(t,4294967295),parse:t=>t.toString("ascii")})}async getAccountIndex(t,e){return(t=await this.db.get(u.i(t,e)))?t.readUInt32LE(0,!0):-1}async getGuider(t){return t=v.fromString(t,this.network.type).getHash("hex"),(t=await this.db.get(u.g(t)))?v.fromRaw(t).toString():null}async setGuider(t,e,i){var r;i=v.fromString(i,this.network.type).getHash("hex"),await this.db.has(u.g(i))||(t=v.fromString(t,this.network.type),(r=this.db.batch()).put(u.g(i),t.toRaw()),r.put(u.gs(t.getHash("hex"),Buffer.from(e,"ascii").toString("hex"),i),null),await r.write())}async unsetGuider(t,e,i){t=v.fromString(t,this.network.type).getHash("hex"),i=v.fromString(i,this.network.type).getHash("hex");var r=this.db.batch();r.del(u.g(i)),r.del(u.gs(t,Buffer.from(e,"ascii").toString("hex"),i)),await r.write()}async getAccountName(t,e){return(t=await this.db.get(u.n(t,e)))?t.toString("ascii"):null}saveAccount(t){var e=t.wid,i=t.wallet,r=t.accountIndex,s=t.name,n=this.batch(i);n.put(u.a(e,r),t.toRaw()),n.put(u.i(e,s),D(r)),n.put(u.n(e,r),Buffer.from(s,"ascii")),i.accountCache.push(r,t)}hasAccount(t,e){return"number"==typeof t&&"number"==typeof e&&this.db.has(u.a(t,e))}async getPathMap(t){var e=this.pathMapCache.get(t);return e||((e=await this.db.get(u.p(t)))?(e=ut.fromRaw(t,e),this.pathMapCache.set(t,e),e):null)}saveKey(t,e){return this.savePath(t,e.toPath())}async savePath(t,e){var i=t.wid,r=e.hash,s=this.batch(t);await this.addHash(r);let n=await this.getPathMap(r);(n=n||new ut(r)).add(i)&&(this.pathMapCache.set(r,n),t.pathCache.push(r,e),s.put(u.p(r),n.toRaw()),s.put(u.P(i,r),e.toRaw()),s.put(u.r(i,e.account,r),null))}async getPath(t,e){var i=await this.db.get(u.P(t,e));return i?((i=at.fromRaw(i)).wid=t,i.hash=e,i):null}hasPath(t,e){return this.db.has(u.P(t,e))}getHashes(){return this.db.keys({gte:u.p(F.NULL_HASH),lte:u.p(F.HIGH_HASH),parse:u.pp})}getOutpoints(){return this.db.keys({gte:u.o(F.NULL_HASH,0),lte:u.o(F.HIGH_HASH,4294967295),parse:t=>{var[t,e]=u.oo(t);return new y(t,e)}})}getWalletHashes(t){return this.db.keys({gte:u.P(t,F.NULL_HASH),lte:u.P(t,F.HIGH_HASH),parse:u.Pp})}getAccountHashes(t,e){return this.db.keys({gte:u.r(t,e,F.NULL_HASH),lte:u.r(t,e,F.HIGH_HASH),parse:u.rr})}async getWalletPaths(t){var e=[];for(const s of await this.db.range({gte:u.P(t,F.NULL_HASH),lte:u.P(t,F.HIGH_HASH)})){var i=u.Pp(s.key),r=at.fromRaw(s.value);r.hash=i,r.wid=t,e.push(r)}return e}async encryptKeys(t,e){var i,r,n=t.wid,a=await t.getPaths(),o=this.batch(t);for(i of a)i.data&&(s(!i.encrypted),r=Buffer.from(i.hash,"hex").slice(0,16),(i=i.clone()).data=d.encipher(i.data,e,r),i.encrypted=!0,t.pathCache.push(i.hash,i),o.put(u.P(n,i.hash),i.toRaw()))}async decryptKeys(t,e){var i,r,n=t.wid,a=await t.getPaths(),o=this.batch(t);for(i of a)i.data&&(s(i.encrypted),r=Buffer.from(i.hash,"hex").slice(0,16),(i=i.clone()).data=d.decipher(i.data,e,r),i.encrypted=!1,t.pathCache.push(i.hash,i),o.put(u.P(n,i.hash),i.toRaw()))}async resend(){var t,e={};for(const t of await this.db.keys({gte:u.w(0),lte:u.w(4294967295)})){var i,r=u.ww(t);r&&(i=await this.resendPending(r))&&Array.isArray(i)&&(e[r]=i)}for(t of Object.keys(e)){var s=await this.get(parseInt(t));if(s)for(const i of e[t]){try{await this.send(i)}catch(t){this.logger.warning("wdb resend:",t.message);try{await s.abandon(i.hash("hex"))}catch(t){this.logger.warning("wdb abandon:",t.message)}}await dt.timeout(50)}}}async resendPending(t){var e=await this.get(t),i=await this.db.keys({gte:h.txdb.prefix(t,h.txdb.p(F.NULL_HASH)),lte:h.txdb.prefix(t,h.txdb.p(F.HIGH_HASH))});if(0!==i.length){this.logger.info("Rebroadcasting %d transactions for %d.",i.length,t);var r=[];for(const o of i){var s=h.txdb.pp(o),n=h.txdb.prefix(t,h.txdb.t(s));if((n=await this.db.get(n))&&!(n=lt.fromRaw(n)).tx.isCoinbase())try{var a=await x.FactoryOfContract({tx:n.tx,env:this});await a.isBlockFinal()==E.Expired?e&&(await this.removeTX(n.tx),await e.remove(s),await a.erase()):"notify"!=a.oper&&r.push(n.tx)}catch(t){this.logger.error("TX(%s) Smart Contract Error: %s",n.tx.txid(),t.message)}}return await P(r,this)}}getWallets(){return this.db.keys({gte:u.l("\0"),lte:u.l("ÿ"),parse:u.ll})}async getWalletsByTX(t){var e=new Set;if(!t.isCoinbase())for(const r of t.inputs){var i=r.prevout;if(this.testFilter(i.toRaw())&&(i=await this.getOutpointMap(i.hash,i.index)))for(const t of i.wids)e.add(t)}for(const i of t.getOutputHashes("hex"))if(this.testFilter(i)){var r=await this.getPathMap(i);if(r)for(const t of r.wids)e.add(t)}return 0===e.size?null:e}async getState(){var t=await this.db.get(u.R);return t?ot.fromRaw(t):null}async init(t){var e=this.options.startHeight;let i;if(this.client){if(null!=e){if(!(i=await this.client.getEntry(e)))throw new Error("WDB: Could not find start block.")}else i=await this.client.getTip();i=ht.fromEntry(i)}else i=ht.fromEntry(this.network.genesis);this.logger.info("Initializing AccountDB chain state (height %d).",i.height),(e=await this.getState())?this.state=e:await this.resetState(i,!1),await this.ensure({id:"primary",witness:!0,mnemonic:this.options.mnemonic}),t&&t.backup&&await this.loadBackup(t.backup)}async resetState(t,e){for(var i=this.state.clone(),r=(i.startHeight=t.height,i.startHash=t.hash,i.height=t.height,i.marked=e,this.db.batch()),s=this.db.iterator({gte:u.h(t.height),lte:u.h(4294967295),values:!1});;){var n=await s.next();if(!n)break;try{r.del(n.key)}catch(t){throw await s.end(),t}}r.put(u.h(t.height),t.toHash()),r.put(u.R,i.toRaw()),await r.write(),this.state=i}async syncState(t){var e=this.state.clone(),i=this.db.batch();if(t.height<e.height){let s=e.height;var r=s-t.height;for(let t=0;t<r;t++)i.del(u.h(s--))}else t.height>e.height&&s(t.height===e.height+1,`Bad chain sync tip ${t.height} while state `+e.height);e.height=t.height,i.put(u.h(t.height),t.toHash()),i.put(u.R,e.toRaw()),await i.write(),this.state=e,Y("block/tips",e)}get curHeight(){return this.state.height}get tidCreator(){return h.txdb.tx}get finder(){return this.getTXFromDb.bind(this)}rpcExecute(){return this.rpc.execute.apply(this.rpc,arguments)}async getBlockMap(t){var e=await this.db.get(u.b(t));return e?ct.fromRaw(t,e):null}writeBlockMap(t,e,i){this.batch(t).put(u.b(e),i.toRaw())}unwriteBlockMap(t,e){this.batch(t).del(u.b(e))}async getOutpointMap(t,e){var i=await this.db.get(u.o(t,e));return i?nt.fromRaw(t,e,i):null}writeOutpointMap(t,e,i,r){t=this.batch(t),this.addOutpoint(e,i),t.put(u.o(e,i),r.toRaw())}unwriteOutpointMap(t,e,i){this.batch(t).del(u.o(e,i))}async writeBalanceLog(t,e){var i=u.log(t.wid,e.aidx,e.height,e.hash),r=(e=Buffer.from(JSON.stringify(e)),await this.writeLock.lock());try{this.start(t).put(i,e),await this.commit(t)}finally{r()}}async queryBalanceLog(t,e,i=0){return this.db.values({gte:u.log(t,e,i,F.NULL_HASH),lte:u.log(t,e,this.curHeight,F.HIGH_HASH),parse:t=>JSON.parse(t.toString())})}async getBlock(t){var e,i=await this.db.get(u.h(t));return i?((e=new ht).hash=i.toString("hex"),e.height=t,e):null}async getTip(){var t=await this.getBlock(this.curHeight);if(t)return t;throw new Error("WDB: Tip not found!")}async rollback(t,e=!0){if(t>this.curHeight)throw new Error("WDB: Cannot rollback to the future.");if(t===this.curHeight)return this.logger.debug("Rolled back to same height (%d).",t),!0;this.logger.info("Rolling back %d AccountDB blocks to height %d.",this.curHeight-t,t);var i=await this.getBlock(t);let r=!1;return i?(await this.revert(i.height),await this.syncState(i),e):(i=new ht,t>=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(t){var e=this.db.iterator({gte:u.b(t+1),lte:u.b(4294967295),reverse:!0,values:!0});let i=0;for(;;){var r=await e.next();if(!r)break;try{var s=u.bb(r.key),n=ct.fromRaw(s,r.value).toArray();i+=n.length;for(let t=n.length-1;0<=t;t--)await this._unconfirm(n[t])}catch(t){throw await e.end(),t}}this.logger.info("Rolled back %d AccountDB transactions.",i)}async addBlock(t,e){var i=await this.txLock.lock();try{return await this._addBlock(t,e)}finally{i()}}async _addBlock(t,e){var i=ht.fromEntry(t);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),!(this.options.checkpoints&&i.height<=this.network.lastCheckpoint)){for(const t of e)await this._insert(t,i)&&r++;0<r&&this.logger.info("Connected AccountDB block %s (tx=%d).",O.revHex(i.hash),r)}}return r}async removeBlock(t,e){var i=await this.txLock.lock();try{return await this._removeBlock(t,e)}finally{i()}}async _removeBlock(t,e){if((t=ht.fromEntry(t)).height>this.curHeight)return this.logger.warning("AccountDB is disconnecting high blocks (%d).",t.height),0;if(t.height!==this.curHeight)throw new Error(`WDB(removeBlock): Bad disconnection (height mismatch, tip ${t.height} / ${O.revHex(t.hash)} while state ${this.curHeight})`);var i=await this.getBlock(t.height-1);if(!i)throw new Error(`WDB(removeBlock): Bad disconnection (no previous block of ${t.height} / ${O.revHex(t.hash)}).`);var r=await this.getBlockMap(t.height);if(r){for(let t=e.length-1;0<=t;t--){var s=e[t];await this._unconfirm(s,r)}this.logger.warning("Disconnected wallet block %s (tx=%d).",O.revHex(t.hash),r.txs.size)}return await this.syncState(i),r?r.txs.size:0}async rescanBlock(t,e){if(this.rescanning){var i=await this.scanLock.lock();try{await this._addBlock(t,e)}catch(t){throw this.emit("error",t),t}finally{i()}}else this.logger.warning("Unsolicited rescan block: %s.",t.height)}async addTX(t,e,i){var r=await this.txLock.lock();try{return await this._insert(t,e,i)}finally{r()}}listNotify(t){return this.NotifyList.deletes([["h","<",this.curHeight-12]]),this.NotifyList.query(t)}listContact(t,e,i){return this.$contacts.query(t,e,i)}async setCp(t){await this.batchPut(h.txdb.cp(t.cid),t.toRaw())}async delCp(t){await this.batchDel(h.txdb.cp(t))}async delVp(t){var e=this.db.batch();e.del(h.txdb.VP(t.pid)),await e.write()}async setVp(t,e){var i=this.db.batch();i.put(h.txdb.VP(t.pid),t.toRaw()),await i.write()}async getVp(t){return(t=await this.db.get(h.txdb.VP(t)))?Z.fromRaw(t):null}async getVpByAddress(t){return{list:[],count:0}}async getVpByOid(t){return{list:[],count:0}}async loadVpList(){return this.db.values({gte:h.txdb.VP(F.ZERO_CID,"hex"),lte:h.txdb.VP(F.MAX_CID,"hex"),parse:t=>Z.fromRaw(t)})}async saveContact(t){var e=this.db.batch();e.put(h.txdb.CT(t.getAddress()),t.toRaw()),await e.write()}async loadContact(t){var e;for(e of await this.db.values({gte:h.txdb.CT(F.ZERO_HASH160_HEX),lte:h.txdb.CT(F.MAX_HASH160_HEX),parse:t=>A.fromRaw(t,this)}))e.sender&&(e.sender.wallet=await this.get(e.sender.wid)),this.$contacts.set(e.address,e)}async delHtlc(t){var e;(t=new z(t)).id&&(this.htlcList.delete(t.id),this.htlcList.delAccount(t),(e=this.db.batch()).del(h.txdb.VH(t.shash,t.sidx)),await e.write())}async setSuggest(t){t=new z(t);var e,[e,i]=(this.htlcList.set(t.id,t),await this.getAccountByAddress(t.aa)),[e,i]=(e&&this.htlcList.setAccount(t,e,i),await this.getAccountByAddress(t.ba));(e=(e&&this.htlcList.setAccount(t,e,i),this.db.batch())).put(h.txdb.VH(t.shash,t.sidx),t.toRaw()),await e.write()}async setAssent(t){t=new z(t);var e,[e,i]=(this.htlcList.set(t.id,t),await this.getAccountByAddress(t.ab)),[e,i]=(e&&this.htlcList.setAccount(t,e,i),await this.getAccountByAddress(t.bb));(e=(e&&this.htlcList.setAccount(t,e,i),this.db.batch())).put(h.txdb.VH(t.shash,t.sidx),t.toRaw()),await e.write()}async loadHtlcList(){return this.db.values({gte:h.txdb.VH(F.ZERO_CID,0),lte:h.txdb.VH(F.MAX_CID,4294967295),parse:t=>z.fromRaw(t)})}async delComment(t){var e;(t=new q(t)).id&&(this.commentList.delete(t.id),this.commentList.delAccount(t),(e=this.db.batch()).del(h.txdb.VC(t.shash,t.sidx)),await e.write())}async setComment(t){t=new q(t);var e,[e,i]=(this.commentList.set(t.id,t),await this.getAccountByAddress(t.bob));(e=(e&&(this.commentList.setAccount(t,e,i),this.emit("comm.comment",t)),this.db.batch())).put(h.txdb.VC(t.shash,t.sidx),t.toRaw()),await e.write()}async loadCommentList(){return this.db.values({gte:h.txdb.VC(F.ZERO_CID,0),lte:h.txdb.VC(F.MAX_CID,4294967295),parse:t=>q.fromRaw(t)})}async setStockRecord(t){var e=this.db.batch();switch(e.put(t.itemNo,t.toRaw()),t.type){case G.RecordType.Offer:break;case G.RecordType.Bid:var i=this.accountList.getStockAccount(t.cid,t.addr);i&&(i.stock.sum=t.sum,i.stock.price=t.price,i.stock.period=this.curHeight+10*m.BLOCK_DAY,i.seq=t.seq,e.put(i.getItemNo(),i.toRaw()));break;case G.RecordType.Auction:{let s=this.accountList.getStockAccount(t.cid,t.addr);if(s?(i=s.sum+t.sum,s.price=(t.sum*t.price+s.sum*s.price)/i|0,s.sum=i,s.seq=t.seq):((s=new tt(t.cid,t.addr,t.sum,t.price,0)).seq=t.seq,this.accountList.setStockAccount(s)),e.put(s.getItemNo(),s.toRaw()),!(i=this.accountList.getStockAccount(t.cid,t.to)))break;var r=i.sum-t.sum;i.sum=r,i.stock.sum-=t.sum,e.put(i.getItemNo(),i.toRaw());break}case G.RecordType.Purchase:{let i=this.accountList.getStockAccount(t.cid,t.addr);i?(r=i.sum+t.sum,i.price=(t.sum*t.price+i.sum*i.price)/r,i.sum=r,i.seq=t.seq):((i=new tt(t.cid,t.addr,t.sum,t.price,0)).seq=t.seq,this.accountList.setStockAccount(i)),e.put(i.getItemNo(),i.toRaw());break}case G.RecordType.Send:if(i=this.accountList.getStockAccount(t.cid,t.addr)){i.sum-=t.sum,i.seq=t.seq;let s=this.accountList.getStockAccount(t.cid,t.to);s||(s=new tt(t.cid,t.to,0,0,0),this.accountList.setStockAccount(s)),r=s.sum+t.sum,s.price=(t.sum*i.price+s.sum*s.price)/r,s.sum=r,e.put(i.getItemNo(),i.toRaw()),e.put(s.getItemNo(),s.toRaw())}break;case G.RecordType.Bonus:case G.RecordType.Ads:}await e.write()}async unsetStockRecord(t){var e=this.db.batch();switch(e.del(t.itemNo),t.type){case G.RecordType.Offer:break;case G.RecordType.Bid:(s=this.accountList.getStockAccount(t.cid,t.addr))&&(s.stock.sum=0,s.stock.price=0,s.stock.period=0,s.seq=t.seq-1,e.put(s.getItemNo(),s.toRaw()));break;case G.RecordType.Auction:(s=this.accountList.getStockAccount(t.cid,t.addr))&&(i=s.sum-t.sum,s.price=(s.sum*s.price-t.sum*t.price)/i|0,s.sum=i,s.seq=t.seq-1,e.put(s.getItemNo(),s.toRaw()),s=this.accountList.getStockAccount(t.cid,t.to))&&(i=s.sum+t.sum,s.sum=i,s.stock.sum+=t.sum,e.put(s.getItemNo(),s.toRaw()));break;case G.RecordType.Purchase:var i=this.accountList.getStockAccount(t.cid,t.addr);i&&(s=i.sum-t.sum,i.price=(i.sum*i.price-t.sum*t.price)/s,i.sum=s,i.seq=t.seq-1,e.put(i.getItemNo(),i.toRaw()));break;case G.RecordType.Send:var r,s;(s=this.accountList.getStockAccount(t.cid,t.addr))&&(s.sum+=t.sum,s.seq=t.seq-1,e.put(s.getItemNo(),s.toRaw()),i=this.accountList.getStockAccount(t.cid,t.to))&&(r=i.sum-t.sum,i.price=(i.sum*i.price-t.sum*s.price)/r|0,i.sum=r,e.put(i.getItemNo(),i.toRaw()));break;case G.RecordType.Bonus:}await e.write()}async getStockRecordById(t){return(t=await this.db.get(t))?G.fromRaw(t):null}async verifyClsTx(t,e){if(!this.spv&&1!=(e=await(await x.FactoryOfContract({env:this,block:e,tx:t})).verify()))throw new g(t,S(e),"bad-contract-verify",100);return!0}async getStockRecord(t,e,i){let r=6,s=F.ZERO_CID_BUF,n=F.MAX_CID_BUF,a=0;return t&&(r=t,e)&&(s=e,n=e,a=i||0),t=new C,(await this.db.values({gte:G.itemNo(r,s,a,F.NULL_HASH,0),lte:G.itemNo(r,n,4294967295,F.HIGH_HASH,4294967295),parse:G.fromRaw})).reduce((t,e)=>(t.set(e.itemNo,e),t),t),t}async getStockRecordByCid(t,e){var i,r=new C;for(i of Object.keys(G.RecordType)){var s=await this.getStockRecord(G.RecordType[i],t,e);r.merge(s)}return r}async getStockAccountList(t){var e;return t?(e=tt.SN(t,F.NULL_HASH),t=tt.SN(t,F.HIGH_HASH),this.db.values({gte:e,lte:t,parse:tt.fromRaw})):this.db.values({gte:tt.SN(F.ZERO_CID_BUF,F.NULL_HASH),lte:tt.SN(F.MAX_CID_BUF,F.HIGH_HASH),parse:tt.fromRaw})}async delEr(t){var e=this.db.batch();e.del(h.txdb.ER(t.erid)),e.del(h.txdb.ERR(t.witness,t.erid,t.txid)),await e.write()}async setEr(t,e){e&&t.source&&(i=v.fromWitnessPubkeyhash(l.hash160(Buffer.from(t.source.pubkey,"hex")),this.network),[i,e]=await this.getAccountByAddress(i,e),t.wid=i,t.account=e);var i=this.db.batch();e=h.txdb.ERR(t.witness,t.erid,t.txid);i.put(e,t.toRaw()),i.put(h.txdb.ER(t.erid),e),await i.write()}async getEr(t){var e;return(t=await this.db.get(h.txdb.ER(t)))&&([,,e]=h.txdb.ERRR(t),t=await this.db.get(t))?((t=it.fromRaw(t)).txid=e,t):null}async byPubkey(t,e,i=!1){var r,s=new C;t=await this.db.values({gte:h.txdb.ERR(t,F.NULL_HASH,F.NULL_HASH),lte:h.txdb.ERR(t,F.HIGH_HASH,F.HIGH_HASH),parse:t=>it.fromRaw(t)});let n=[],a=new Map;if(i){for(var o of t)(!a.get(o.source.cluster)||o.startHeight>a.get(o.source.cluster).startHeight)&&a.set(o.source.cluster,await this.caVerifyObj(o));n=a.values()}else n=t;for(r of n)s.set(r.erid,r);return s.query(e)}async caVerifyObj(t){var e={verify:!1};if(!t||t.validHeight<=this.curHeight)return e;var i=await this.erAbList.getErAb(t.erid);return i&&i.abolishHeight<this.curHeight?e:(i=pt.fromPublic(Buffer.from(t.witness,"hex"),this.network.type),t.verify(i)?(t.verify=!0,0<(i=this.cpList.query([["pubKey",t.witness]])).list.length&&(t.cpid=i.list[0].cid),t):e)}async delErAbolish(t){var e=this.db.batch();e.del(h.txdb.ERA(t.erid)),await e.write()}async setErAbolish(t){var e=this.db.batch();e.put(h.txdb.ERA(t.erid),t.toRaw()),await e.write()}async getErAbolish(t){return(t=await this.db.get(h.txdb.ERA(t)))?X.fromRaw(t):null}loadErAbolishList(){return this.db.values({gte:h.txdb.ERA(F.ZERO_CID),lte:h.txdb.ERA(F.MAX_CID),parse:t=>X.fromRaw(t)})}async delAudit(t){var e=this.db.batch();e.del(h.txdb.AU(t.erid)),await e.write()}async setAudit(t){var e=this.db.batch();e.put(h.txdb.AU(t.erid),t.toRaw()),await e.write()}async getAudit(t){return(t=await this.db.get(h.txdb.AU(t)))?st.fromRaw(t):null}async loadAuditList(){return this.db.values({gte:h.txdb.AU(F.NULL_HASH),lte:h.txdb.AU(F.HIGH_HASH),parse:t=>st.fromRaw(t)})}async batchPut(t,e){var i=this.db.batch();i.put(t,e),await i.write()}async batchDel(t){var e=this.db.batch();e.del(t),await e.write()}async _insert(t,e,i){s(!t.mutable,"WDB: Cannot add mutable TX.");let r=await this.getWalletsByTX(t);if(r){this.logger.info("Incoming transaction for %d wallets in AccountDB (%s).",r.size,t.txid()),!e||this.state.marked||(this.logger.info("Marking AccountDB start block at %s (%d).",O.revHex(e.hash),e.height),await this.resetState(e,!0));let a=!1;for(const o of r){var n=await this.get(o);s(n),await n.add(t,e,i)&&(this.logger.info("Added transaction to wallet in AccountDB: %s (%d).",n.id,o),a=!0)}a||(r=null)}try{var a=await x.FactoryOfContract({env:this,block:e,tx:t});e?await a.confirm():await a.insert()}catch(a){e?this.logger.error("TX(%s) Smart Contract Confirm Error: %s",t.txid(),a.message):this.logger.error("TX(%s) Smart Contract Insert Error: %s",t.txid(),a.message)}return r}async _unconfirm(t,e){if(e)try{await(await x.FactoryOfContract({env:this,block:e,tx:t})).unconfirm()}catch(e){this.logger.error("TX(%s) Smart Contract Unconfirm Error: %s",t.txid(),e.message)}let i,r=null;if(i=t.wids?(r=t.wids,t.hash):(r=await this.getWalletsByTX(t),t.hash("hex")),!r)return null;for(const t of r){var n=await this.get(t);s(n),await n.unconfirm(i)}for(const t of r){var a=await this.get(t);s(a),await a.abandon(i)}}async resetChain(t){var e=await this.txLock.lock();try{return await this._resetChain(t)}finally{e()}}async _resetChain(t){if(t.height>this.curHeight)throw new Error(`WDB: Bad reset height ${t.height} while curHeight `+this.curHeight);var e;for(e of(await this.rollback(t.height)||await this.scan(),await this.getWallets())){var i=await this.get(e);for(const e of await i.getPending())try{await i.abandon(e.hash)}catch(t){}await i.resetBalance()}}async saveMSTrans(t){var e=await this.writeLock.lock();try{return await this._saveMSTrans(t)}finally{e()}}async _saveMSTrans(t){var e=this.db.batch();e.put(u.ms(v.getHash(t.addr,"hex"),t.txid),Buffer.from(JSON.stringify(t))),await e.write()}async listMSTrans(t){return t=v.getHash(t,"hex"),this.db.values({gte:u.ms(t,F.NULL_HASH),lte:u.ms(t,F.HIGH_HASH),parse:t=>JSON.parse(t.toString())})}async delMSTrans(t,e){var i=await this.writeLock.lock();try{return await this._delMSTrans(t,e)}finally{i()}}async _delMSTrans(t,e){t=v.getHash(t,"hex");var i=this.db.batch();i.del(u.ms(t,e)),await i.write()}}yt.layout=u,t.exports=yt},function(t,e,i){"use strict";
912
912
  /*!
913
913
  * txdb.js - persistent transaction pool
914
914
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -1710,7 +1710,7 @@ object-assign
1710
1710
  * vary
1711
1711
  * Copyright(c) 2014-2017 Douglas Christopher Wilson
1712
1712
  * MIT Licensed
1713
- */t.exports=function(t,e){if(!t||!t.getHeader||!t.setHeader)throw new TypeError("res argument is required");var i=t.getHeader("Vary")||"";(i=s(Array.isArray(i)?i.join(", "):String(i),e))&&t.setHeader("Vary",i)},t.exports.append=s;var r=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function s(t,e){if("string"!=typeof t)throw new TypeError("header argument is required");if(!e)throw new TypeError("field argument is required");for(var i=Array.isArray(e)?e:n(String(e)),s=0;s<i.length;s++)if(!r.test(i[s]))throw new TypeError("field argument contains an invalid header name");if("*"===t)return t;var a=t,o=n(t.toLowerCase());if(-1!==i.indexOf("*")||-1!==o.indexOf("*"))return"*";for(var c=0;c<i.length;c++){var h=i[c].toLowerCase();-1===o.indexOf(h)&&(o.push(h),a=a?a+", "+i[c]:i[c])}return a}function n(t){for(var e=0,i=[],r=0,s=0,n=t.length;s<n;s++)switch(t.charCodeAt(s)){case 32:r===e&&(r=e=s+1);break;case 44:i.push(t.substring(r,e)),r=e=s+1;break;default:e=s+1}return i.push(t.substring(r,e)),i}},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.uServer=void 0;var r=i(93);const s=i(664),n=i(762),a=(0,r.default)("engine:uws");class o extends s.BaseServer{init(){}cleanup(){}prepare(t,e){t.method=t.getMethod().toUpperCase();var i=new URLSearchParams(t.getQuery());t._query=Object.fromEntries(i.entries()),t.headers={},t.forEach((e,i)=>{t.headers[e]=i}),t.connection={remoteAddress:Buffer.from(e.getRemoteAddressAsText()).toString()},e.onAborted(()=>{a("response has been aborted")})}createTransport(t,e){return new n.default[t](e)}attach(t,e={}){var i=(e.path||"/engine.io").replace(/\/$/,"")+"/";t.any(i,this.handleRequest.bind(this)).ws(i,{compression:e.compression,idleTimeout:e.idleTimeout,maxBackpressure:e.maxBackpressure,maxPayloadLength:this.opts.maxHttpBufferSize,upgrade:this.handleUpgrade.bind(this),open:t=>{(t.transport.socket=t).transport.writable=!0,t.transport.emit("drain")},message:(t,e,i)=>{t.transport.onData(i?e:Buffer.from(e).toString())},close:(t,e,i)=>{t.transport.onClose(e,i)}})}handleRequest(t,e){a('handling "%s" http request "%s"',e.getMethod(),e.getUrl()),this.prepare(e,t),e.res=t;const i=(i,r)=>{void 0!==i?(this.emit("connection_error",{req:e,code:i,message:s.Server.errorMessages[i],context:r}),this.abortRequest(e.res,i,r)):e._query.sid?(a("setting new request for existing client"),this.clients[e._query.sid].transport.onRequest(e)):this.handshake(e._query.transport,e,(e,i)=>this.abortRequest(t,e,i))};this.corsMiddleware?(e.res=new c(t),this.corsMiddleware.call(null,e,e.res,()=>{this.verify(e,!1,i)})):this.verify(e,!1,i)}handleUpgrade(t,e,i){a("on upgrade"),this.prepare(e,t),e.res=t,this.verify(e,!0,async(r,n)=>{if(r)this.emit("connection_error",{req:e,code:r,message:s.Server.errorMessages[r],context:n}),this.abortRequest(t,r,n);else{let s;if(r=e._query.sid)(n=this.clients[r])?n.upgrading?(a("transport has already been trying to upgrade"),t.close()):n.upgraded?(a("transport had already been upgraded"),t.close()):(a("upgrading existing transport"),s=this.createTransport(e._query.transport,e),n.maybeUpgrade(s)):(a("upgrade attempt for closed client"),t.close());else if(!(s=await this.handshake(e._query.transport,e,(e,i)=>this.abortRequest(t,e,i))))return;t.upgrade({transport:s},e.getHeader("sec-websocket-key"),e.getHeader("sec-websocket-protocol"),e.getHeader("sec-websocket-extensions"),i)}})}abortRequest(t,e,i){var r=e===s.Server.errors.FORBIDDEN?"403 Forbidden":"400 Bad Request";i=i&&i.message?i.message:s.Server.errorMessages[e];t.writeStatus(r),t.writeHeader("Content-Type","application/json"),t.end(JSON.stringify({code:e,message:i}))}}e.uServer=o;class c{constructor(t){this.res=t,this.statusWritten=!1,this.headers=[]}set statusCode(t){this.writeStatus(200===t?"200 OK":"204 No Content")}setHeader(t,e){this.writeHeader(t,e)}getHeader(){}writeStatus(t){this.res.writeStatus(t),this.statusWritten=!0,this.writeBufferedHeaders()}writeHeader(t,e){"Content-Length"!==t&&(this.statusWritten?this.res.writeHeader(t,e):this.headers.push([t,e]))}writeBufferedHeaders(){this.headers.forEach(([t,e])=>{this.res.writeHeader(t,e)})}end(t){this.statusWritten||this.writeBufferedHeaders(),this.res.end(t)}onData(t){this.res.onData(t)}onAborted(t){this.res.onAborted(t)}}},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=i(763);i=i(764);e.default={polling:r.Polling,websocket:i.WebSocket}},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Polling=void 0;var r=i(318),s=i(176);const n=i(623),a=(0,i(93).default)("engine:polling"),o={gzip:s.createGzip,deflate:s.createDeflate};class c extends r.Transport{constructor(t){super(t),this.closeTimeout=3e4}get name(){return"polling"}get supportsFraming(){return!1}onRequest(t){var e=t.res;"get"===t.getMethod()?this.onPollRequest(t,e):"post"===t.getMethod()?this.onDataRequest(t,e):(e.writeStatus("500 Internal Server Error"),e.end())}onPollRequest(t,e){this.req?(a("request overlap"),this.onError("overlap from client"),e.writeStatus("500 Internal Server Error"),e.end()):(a("setting request"),this.req=t,this.res=e,t.cleanup=()=>{this.req=this.res=null},e.onAborted(()=>{this.writable=!1,this.onError("poll connection closed prematurely")}),this.writable=!0,this.emit("drain"),this.writable&&this.shouldClose&&(a("triggering empty send to append close packet"),this.send([{type:"noop"}])))}onDataRequest(t,e){if(this.dataReq)this.onError("data request overlap from client"),e.writeStatus("500 Internal Server Error"),e.end();else{const s=Number(t.headers["content-length"]);if(s)if(s>this.maxHttpBufferSize)this.onError("payload too large"),e.writeStatus("413 Payload Too Large").end();else{if("application/octet-stream"===t.headers["content-type"]&&4===this.protocol)return this.onError("invalid content");this.dataReq=t,this.dataRes=e;let n,a=0;var i,r={"Content-Type":"text/html"};for(i in this.headers(t,r),r)e.writeHeader(i,String(r[i]));const o=t=>{this.onData(t.toString()),this.onDataRequestCleanup(),e.end("ok")};e.onAborted(()=>{this.onDataRequestCleanup(),this.onError("data request connection closed prematurely")}),e.onData((t,i)=>{var r=a+t.byteLength;if(r>s)this.onError("content-length mismatch"),e.close();else{if(!n){if(i)return void o(Buffer.from(t));n=Buffer.allocUnsafe(s)}if(Buffer.from(t).copy(n,a),i)return r!=s?(this.onError("content-length mismatch"),e.writeStatus("400 Content-Length Mismatch").end(),void this.onDataRequestCleanup()):void o(n);a=r}})}else this.onError("content-length header required"),e.writeStatus("411 Length Required").end()}}onDataRequestCleanup(){this.dataReq=this.dataRes=null}onData(t){a('received "%s"',t);var e=t=>{if("close"===t.type)return a("got xhr close packet"),this.onClose(),!1;this.onPacket(t)};3===this.protocol?this.parser.decodePayload(t,e):this.parser.decodePayload(t).forEach(e)}onClose(){this.writable&&this.send([{type:"noop"}]),super.onClose()}send(t){this.writable=!1,this.shouldClose&&(a("appending close packet to payload"),t.push({type:"close"}),this.shouldClose(),this.shouldClose=null);var e=e=>{var i=t.some(t=>t.options&&t.options.compress);this.write(e,{compress:i})};3===this.protocol?this.parser.encodePayload(t,this.supportsBinary,e):this.parser.encodePayload(t,e)}write(t,e){a('writing "%s"',t),this.doWrite(t,e,()=>{this.req.cleanup()})}doWrite(t,e,i){var r="string"==typeof t;const s={"Content-Type":r?"text/plain; charset=UTF-8":"application/octet-stream"},a=t=>{this.headers(this.req,s),Object.keys(s).forEach(t=>{this.res.writeHeader(t,String(s[t]))}),this.res.end(t),i()};if(this.httpCompression&&e.compress)if((r?Buffer.byteLength(t):t.length)<this.httpCompression.threshold)a(t);else{const e=n(this.req).encodings(["gzip","deflate"]);e?this.compress(t,e,(t,r)=>{t?(this.res.writeStatus("500 Internal Server Error"),this.res.end(),i(t)):(s["Content-Encoding"]=e,a(r))}):a(t)}else a(t)}compress(t,e,i){a("compressing");const r=[];let s=0;o[e](this.httpCompression).on("error",i).on("data",(function(t){r.push(t),s+=t.length})).on("end",(function(){i(null,Buffer.concat(r,s))})).end(t)}doClose(t){let e;a("closing");var i=()=>{clearTimeout(e),t(),this.onClose()};this.writable?(a("transport writable - closing right away"),this.send([{type:"close"}]),i()):this.discarded?(a("transport discarded - closing right away"),i()):(a("transport not writable - buffering orderly close"),this.shouldClose=i,e=setTimeout(i,this.closeTimeout))}headers(t,e){e=e||{};var i=t.headers["user-agent"];return i&&(~i.indexOf(";MSIE")||~i.indexOf("Trident/"))&&(e["X-XSS-Protection"]="0"),this.emit("headers",e,t),e}}e.Polling=c},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.WebSocket=void 0;var r=i(318);const s=(0,i(93).default)("engine:ws");class n extends r.Transport{constructor(t){super(t),this.writable=!1,this.perMessageDeflate=null}get name(){return"websocket"}get handlesUpgrades(){return!0}get supportsFraming(){return!0}send(t){var e,i=t.shift();void 0===i?(this.writable=!0,this.emit("drain")):(i.options&&i.options.compress,e=e=>{var i="string"!=typeof e,r=this.perMessageDeflate&&Buffer.byteLength(e)>this.perMessageDeflate.threshold;s('writing "%s"',e),this.writable=!1,this.socket.send(e,i,r),this.send(t)},i.options&&"string"==typeof i.options.wsPreEncoded?e(i.options.wsPreEncoded):this.parser.encodePacket(i,this.supportsBinary,e))}doClose(t){s("closing"),t&&t(),this.socket.close()}}e.WebSocket=n},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Client=void 0;const r=i(52);var s=i(93);const n=i(44),a=s("socket.io:client");e.Client=class{constructor(t,e){this.sockets=new Map,this.nsps=new Map,this.server=t,this.conn=e,this.encoder=t.encoder,this.decoder=new t._parser.Decoder,this.id=e.id,this.setup()}get request(){return this.conn.request}setup(){this.onclose=this.onclose.bind(this),this.ondata=this.ondata.bind(this),this.onerror=this.onerror.bind(this),this.ondecoded=this.ondecoded.bind(this),this.decoder.on("decoded",this.ondecoded),this.conn.on("data",this.ondata),this.conn.on("error",this.onerror),this.conn.on("close",this.onclose),this.connectTimeout=setTimeout(()=>{0===this.nsps.size?(a("no namespace joined yet, close the client"),this.close()):a("the client has already joined a namespace, nothing to do")},this.server._connectTimeout)}connect(t,e={}){if(this.server._nsps.has(t))return a("connecting to namespace %s",t),this.doConnect(t,e);this.server._checkNamespace(t,e,i=>{i?this.doConnect(t,e):(a("creation of namespace %s was denied",t),this._packet({type:r.PacketType.CONNECT_ERROR,nsp:t,data:{message:"Invalid namespace"}}))})}doConnect(t,e){const i=this.server.of(t),r=i._add(this,e,()=>{this.sockets.set(r.id,r),this.nsps.set(i.name,r),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0)})}_disconnect(){for(const t of this.sockets.values())t.disconnect();this.sockets.clear(),this.close()}_remove(t){var e;this.sockets.has(t.id)?(e=this.sockets.get(t.id).nsp.name,this.sockets.delete(t.id),this.nsps.delete(e)):a("ignoring remove for %s",t.id)}close(){"open"===this.conn.readyState&&(a("forcing transport close"),this.conn.close(),this.onclose("forced server close"))}_packet(t,e={}){"open"!==this.conn.readyState?a("ignoring packet write %j",t):(t=e.preEncoded?t:this.encoder.encode(t),this.writeToEngine(t,e))}writeToEngine(t,e){if(e.volatile&&!this.conn.transport.writable)a("volatile packet is discarded since the transport is not currently writable");else for(const i of Array.isArray(t)?t:[t])this.conn.write(i,e)}ondata(t){try{this.decoder.add(t)}catch(t){a("invalid packet format"),this.onerror(t)}}ondecoded(t){let e,i;var s;i=3===this.conn.protocol?(e=(s=n.parse(t.nsp,!0)).pathname,s.query):(e=t.nsp,t.data);const o=this.nsps.get(e);o||t.type!==r.PacketType.CONNECT?o&&t.type!==r.PacketType.CONNECT&&t.type!==r.PacketType.CONNECT_ERROR?process.nextTick((function(){o._onpacket(t)})):(a("invalid state (packet type: %s)",t.type),this.close()):this.connect(e,i)}onerror(t){for(const e of this.sockets.values())e._onerror(t);this.conn.close()}onclose(t){a("client close with reason %s",t),this.destroy();for(const e of this.sockets.values())e._onclose(t);this.sockets.clear(),this.decoder.destroy()}destroy(){this.conn.removeListener("data",this.ondata),this.conn.removeListener("error",this.onerror),this.conn.removeListener("close",this.onclose),this.decoder.removeListener("decoded",this.ondecoded),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0)}}},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ParentNamespace=void 0;const r=i(674);class s extends r.Namespace{constructor(t){super(t,"/_"+s.count++),this.children=new Set}_initAdapter(){this.adapter={broadcast:(t,e)=>{this.children.forEach(i=>{i.adapter.broadcast(t,e)})}}}emit(t,...e){return this.children.forEach(i=>{i.emit(t,...e)}),!0}createChild(t){const e=new r.Namespace(this.server,t);return e._fns=this._fns.slice(0),this.listeners("connect").forEach(t=>e.on("connect",t)),this.listeners("connection").forEach(t=>e.on("connection",t)),this.children.add(e),this.server._nsps.set(t,e),e}fetchSockets(){throw new Error("fetchSockets() is not supported on parent namespaces")}}(e.ParentNamespace=s).count=0},function(t,e,i){"use strict";var r=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.serveFile=e.restoreAdapter=e.patchAdapter=void 0;const s=i(676),n=i(88),a=(0,r(i(93)).default)("socket.io:adapter-uws"),{addAll:o,del:c,broadcast:h}=s.Adapter.prototype;function u(t,e,i,r){const s=e.conn.id,n=e.conn.transport.socket;i&&(a("subscribe connection %s to topic %s",s,t),n.subscribe(t)),r.forEach(e=>{a("subscribe connection %s to topic %s",s,e=t+""+e),n.subscribe(e)})}e.patchAdapter=function(t){s.Adapter.prototype.addAll=function(t,e){const i=!this.sids.has(t),r=(o.call(this,t,e),this.nsp.sockets.get(t));r&&("websocket"===r.conn.transport.name?u(this.nsp.name,r,i,e):i&&r.conn.on("upgrade",()=>{var e=this.sids.get(t);e&&u(this.nsp.name,r,i,e)}))},s.Adapter.prototype.del=function(t,e){var i;c.call(this,t,e),(t=this.nsp.sockets.get(t))&&"websocket"===t.conn.transport.name&&(i=t.conn.id,t=t.conn.transport.socket,e=this.nsp.name+""+e,a("unsubscribe connection %s from topic %s",i,e),t.unsubscribe(e))},s.Adapter.prototype.broadcast=function(e,i){if(i.rooms.size<=1&&0===i.except.size){var r=i.flags||{};const s={preEncoded:!0,volatile:r.volatile,compress:r.compress},n=(e.nsp=this.nsp.name,this.encoder.encode(e)),o=0===i.rooms.size?this.nsp.name:this.nsp.name+""+i.rooms.keys().next().value;a("fast publish to %s",o),n.forEach(e=>{var i="string"!=typeof e;t.publish(o,i?e:"4"+e,i)}),this.apply(i,t=>{"websocket"!==t.conn.transport.name&&t.client.writeToEngine(n,s)})}else h.call(this,e,i)}},e.restoreAdapter=function(){s.Adapter.prototype.addAll=o,s.Adapter.prototype.del=c,s.Adapter.prototype.broadcast=h};e.serveFile=function(t,e){const i=(0,n.statSync)(e).size,r=(0,n.createReadStream)(e),s=()=>!r.destroyed&&r.destroy();t.onAborted(s),r.on("data",e=>{const s=(t=>{var{buffer:t,byteOffset:e,byteLength:i}=t;return t.slice(e,e+i)})(e),n=t.getWriteOffset();var[e,a]=t.tryEnd(s,i);a||e||(r.pause(),t.onWritable(e=>{var[e,a]=t.tryEnd(s.slice(e-n),i);return!a&&e&&r.resume(),e}))}).on("error",t=>{throw s(),t}).on("end",s)}},function(t){t.exports=JSON.parse('{"name":"socket.io","version":"4.5.4","description":"node.js realtime framework server","keywords":["realtime","framework","websocket","tcp","events","socket","io"],"files":["dist/","client-dist/","wrapper.mjs","!**/*.tsbuildinfo"],"directories":{"doc":"docs/","example":"example/","lib":"lib/","test":"test/"},"type":"commonjs","main":"./dist/index.js","exports":{"import":"./wrapper.mjs","require":"./dist/index.js","types":"./dist/index.d.ts"},"types":"./dist/index.d.ts","license":"MIT","repository":{"type":"git","url":"git://github.com/socketio/socket.io"},"scripts":{"compile":"rimraf ./dist && tsc","test":"npm run format:check && npm run compile && npm run test:types && npm run test:unit","test:types":"tsd","test:unit":"nyc mocha --require ts-node/register --reporter spec --slow 200 --bail --timeout 10000 test/index.ts","format:check":"prettier --check \\"lib/**/*.ts\\" \\"test/**/*.ts\\"","format:fix":"prettier --write \\"lib/**/*.ts\\" \\"test/**/*.ts\\"","prepack":"npm run compile"},"dependencies":{"accepts":"~1.3.4","base64id":"~2.0.0","debug":"~4.3.2","engine.io":"~6.2.1","socket.io-adapter":"~2.4.0","socket.io-parser":"~4.2.1"},"devDependencies":{"@types/mocha":"^9.0.0","expect.js":"0.3.1","mocha":"^10.0.0","nyc":"^15.1.0","prettier":"^2.3.2","rimraf":"^3.0.2","socket.io-client":"4.5.4","socket.io-client-v2":"npm:socket.io-client@^2.4.0","superagent":"^8.0.0","supertest":"^6.1.6","ts-node":"^10.2.1","tsd":"^0.21.0","typescript":"^4.4.2","uWebSockets.js":"github:uNetworking/uWebSockets.js#v20.0.0"},"contributors":[{"name":"Guillermo Rauch","email":"rauchg@gmail.com"},{"name":"Arnout Kazemier","email":"info@3rd-eden.com"},{"name":"Vladimir Dronnikov","email":"dronnikov@gmail.com"},{"name":"Einar Otto Stangvik","email":"einaros@gmail.com"}],"engines":{"node":">=10.0.0"},"tsd":{"directory":"test"}}')},function(t,e,i){const r=i(0);t.exports=class{constructor(t){this.keyLimit=100,this.bodyLimit=20<<20,this.contentType=null,this.timeout=1e4,t&&this.fromOptions(t)}fromOptions(t){return r(t),null!=t.keyLimit&&(r("number"==typeof t.keyLimit),this.keyLimit=t.keyLimit),null!=t.bodyLimit&&(r("number"==typeof t.bodyLimit),this.bodyLimit=t.bodyLimit),null!=t.contentType&&(r("string"==typeof t.contentType),this.contentType=t.contentType),this}}},function(t,e,i){const r=i(679),s=i(625).StringDecoder;t.exports=async function(t,e){let i=Object.create(null);if("GET"!==t.method){let h=t.contentType;if("bin"!==(h=e.contentType?e.contentType:h)){var n=await(a=t,o="utf8",c=e,new Promise((t,e)=>{{var i=a,r=c,n=t,h=e;const u=new s(o);let l=!1,p=0,d="";const f=()=>{i.removeListener("data",m),i.removeListener("error",g),i.removeListener("end",y),null!=v&&(v=null,clearTimeout(v))},m=t=>{p+=t.length,l=!0,p>r.bodyLimit?h(new Error("Request body overflow.")):d+=u.write(t)},g=t=>{f(),h(t)},y=()=>{f(),n(l?d:null)};let v=setTimeout(()=>{v=null,f(),h(new Error("Request body timed out."))},r.timeout);i.on("data",m),i.on("error",g),i.on("end",y)}}));if(n)switch(h){case"json":if(!(i=JSON.parse(n))||"object"!=typeof i||Array.isArray(i))throw new Error("JSON body must be an object.");break;case"form":i=r.parsePairs(n,e.keyLimit)}}}var a,o,c;return i}},function(t,e,i){const{generateKey:r,verifyObj:s}=i(63),n=i(69),a=i(7);t.exports=class{constructor(t){this.wdb=t}async call(t,e,i){try{var o,c=e.body.sig,h=n.getHmac(e.options.cid||"",this.wdb.keys.hmacSalt).token,u=r(a.hash256(Buffer.from(h)));if(!this.wdb.options.devMode&&!s({method:e.body.method,params:e.body.params,cid:e.body.cid,wid:e.body.wid},c,u.public))return o={result:null,code:404,error:{type:"HmacError",message:"Verify Error"}},i.send(404,o,"json"),{interrupt:!0,result:null};if(!(e.options.auth&&e.options.authWid==e.options.wid||(this.wdb.options.devMode||await this.wdb.auth(e.options.cid,e.options.token),e.body.method&&"wallet.create"===e.body.method))){var l=await this.wdb.get(e.options.wid);if(!l)return i.send(404,{result:null,code:404,error:{type:"HmacError",message:"Not Found Wallet"}},"json"),{interrupt:!0,result:null};this.wdb.logger.info("Successful auth for %s on %s.",e.options.cid,e.options.wid),e.options.auth=!0,e.options.authWid=e.options.wid,e.wallet=l}return{interrupt:!1}}catch(t){return this.wdb.logger.info("Auth failure for %s on %s: %s.",e.options.cid,e.options.wid,t.message),i.send(403,{result:null,code:403,error:{type:"HmacError",message:"Hmac Auth failure."}},"json"),{interrupt:!0,result:null}}}}},function(t,e){t.exports=class{async call(t,e,i){return t.node.config.devMode||t.node.acl.canAccess(e.body.method,e.options.cid)?{interrupt:!1}:(i.send(407,{result:null,code:407,error:{type:"ACLError",message:"TerminalNo Authentication Required."}},"json"),{interrupt:!0,result:null})}}},function(t,e){t.exports=class{constructor(t,e){this.routes=t,this.openapi=e}async call(t,e,i){switch(e.options.mode){case"web":if(0===e.pathname.indexOf("/public/")){var r=this.routes.getHandlers(e.method);if(!r)return{interrupt:!0,result:null};for(const n of r){var s=n.match(e.pathname);if(s){e.params=s;try{return{interrupt:!0,result:{code:0,error:null,result:await n.call(e,i)}}}catch(t){i.error(500,t)}return{interrupt:!0,result:null}}}}else if(r=this.openapi[e.body.method]){try{return{interrupt:!0,result:{code:0,error:null,result:await t.node.conn_s2local.execute(r.name,e.body.params,e)}}}catch(t){i.error(500,t)}return{interrupt:!0,result:null}}break;case"ws":if(r=this.openapi[e.body.method])return{interrupt:!0,result:{code:0,error:null,result:await t.node.conn_s2local.execute(r.name,e.body.params,e)}}}return{interrupt:!1}}}},function(t,e,i){const r=i(0),s=i(1),n=i(7),a=i(160);t.exports=class{constructor(t){r(t,"Basic auth requires options."),this.user=t.username,this.pass=t.password,this.realm=t.realm,null!=this.user&&(r("string"==typeof this.user),r(this.user.length<=255,"Username too long."),r(s.isAscii(this.user),"Username must be ASCII."),this.user=n.hash256(Buffer.from(this.user,"ascii"))),r("string"==typeof this.pass),r(this.pass.length<=255,"Password too long."),r(s.isAscii(this.pass),"Password must be ASCII."),this.pass=n.hash256(Buffer.from(this.pass,"ascii")),this.realm||(this.realm="server"),r("string"==typeof this.realm)}fail(t){t.setHeader("WWW-Authenticate",`Basic realm="${this.realm}"`),t.send(401,{result:null,code:401,error:{type:"AuthError",message:"Unauthorized."}},"json"),t.end()}async call(t,e,i){if(!t.node.config.devMode&&!e.options.auth){if(this.user){if(255<e.options.user.username.length)return this.fail(i),{interrupt:!0,result:null};const t=Buffer.from(e.options.user.username,"ascii"),r=n.hash256(t);if(!a(r,this.user))return this.fail(i),{interrupt:!0,result:null}}if(!e.options.user||!e.options.user.password||255<e.options.user.password.length)return this.fail(i),{interrupt:!0,result:null};const t=Buffer.from(e.options.user.password,"ascii"),r=n.hash256(t);if(!a(r,this.pass))return this.fail(i),{interrupt:!0,result:null};e.options.auth=!0}return{interrupt:!1}}}},function(t,e,i){const r=i(1),s=i(77),n=i(78).errors,a=i(84),o=i(120),{getBlockOverview:c,getBlockByHash:h,formatTimestamp:u}=i(626);t.exports=[{name:"blocks",method:"get",path:"/public/blocks",callback:async function(t,e){var i,r=(t=t.valid()).str("blockDate"),s=t.str("startTimestamp",""),n=(t=t.uint("limit",10),u(new Date));if(r){if(!/\d{4}-\d{2}-\d{2}/.test(r))throw new Error("Please use yyyy-mm-dd format");i=r===n}else r=n,i=!0;n=Math.round(new Date(r).getTime()/1e3),s=parseInt(s)||n+86400;var a=u(new Date(1e3*(n-86400))),o=s?u(new Date(1e3*s)):null,c=(t=parseInt(t||200),!1),l=s;try{var p,d=await this.chain.db.getTimestampHashes(s,n);let u=[];for(p of d)u.push(p.hash);u.reverse(),u.length>t&&(c=!0,u=u.slice(0,t));var f,m={blocks:[],length:u.length,pagination:{next:o,prev:a,currentTs:s-1,current:r,isToday:i,more:c,moreTs:c?l:void 0}};for(f of u){var g=await h(this,f,e);m.blocks.push(g)}return m.blocks.sort((t,e)=>e.height-t.height),m}catch(t){throw t}}},{name:"block-index",method:"get",path:"/public/block-index/:height",callback:async function(t,e){var i=this;if(-1===(t=(t=t.valid()).uint("height")))throw new s(n.TYPE_ERROR,"Invalid block height.");if(!(t=await i.chain.getEntry(t)))throw new s(n.MISC_ERROR,"Block not found");if(i=await h(i.node,t.hash,e))return i}},{name:"block-tip",method:"get",path:"/public/block-tip",callback:async function(t,e){var i=this;if(t.valid(),!(t=await i.chain.tip))throw new s(n.MISC_ERROR,"Block not found");if(i=await h(i.node,t.hash,e))return i}},{name:"block",method:"get",path:"/public/block/:blockHash",callback:async function(t,e){var i=this;if(t=(t=t.valid()).str("blockHash"),i=await h(i.node,t,e))return i}},{name:"getBlock",method:"jsonp",path:"/",callback:async function(t,e){return e=(e=new a([e])).str(0),h(t,e)}},{name:"rawblock",method:"get",path:"/public/rawblock/:param",callback:async function(t,e){var i=this;let a=(t=t.valid()).str("param");if(a=r.checkNum(a)?parseInt(a):r.revHex(a),t=await i.chain.getBlock(a))return t.toRaw().toString("hex");if(i.chain.options.spv)throw new s(n.MISC_ERROR,"Block not available (spv mode)");if(i.chain.options.prune)throw new s(n.MISC_ERROR,"Block not available (pruned data)");throw new s(n.DATABASE_ERROR,"Can't read block from disk")}},{name:"getRawBlock",method:"jsonp",path:"/",callback:async function(t,e){let i=(e=new a([e])).str(0);return r.checkNum(i)&&(i=parseInt(i)),(e=await t.chain.getBlock(i))?e.toRaw().toString("hex"):null}},{name:"isSynced",method:"jsonp",path:"/",callback:async function(t,e){return t.chain.synced}},{name:"getBlockOverview",method:"jsonp",path:"/",callback:async function(t,e){return e=(e=new a([e])).str(0),c(t,e)}},{name:"getInfo",method:"jsonp",path:"/",callback:async function(t,e){var i=await t.rpc.execute({corba:!0,method:"miner.difficulty"});return{blocks:t.chain.height,connections:t.pool.peers.size(),timeoffset:0,proxy:"",testnet:"main"!==t.network.type,errors:"",network:t.network.type,relayFee:0,version:"bitcore-1.1.2",protocolversion:700001,difficulty:i}}},{name:"getBestHeight",method:"jsonp",path:"/",callback:async function(t,e){return t.chain.height}},{name:"getBlockHeader",method:"jsonp",path:"/",callback:async function(t,e){var i=(e=new a([e])).hash(0);e=e.bool(1,!0);if(!i)throw new s(n.MISC_ERROR,"Invalid block hash.");if(!(i=await t.chain.getEntry(i)))throw new s(n.MISC_ERROR,"Block not found");if(!e)return i.toRaw().toString("hex",0,80);e=await t.chain.getMedianTime(i);var c=await t.chain.getNextHash(i.hash);return{hash:i.rhash(),confirmations:t.chain.height-i.height+1,height:i.height,version:i.version,versionHex:r.hex32(i.version),merkleroot:r.revHex(i.merkleRoot),time:i.time,mediantime:e,bits:i.bits,difficulty:o.bits2Diff(i.bits),chainwork:i.chainwork.toString("hex",64),previousblockhash:i.prevBlock!==encoding.NULL_HASH?r.revHex(i.prevBlock):null,nextblockhash:c?r.revHex(c):null}}}]},function(t){t.exports=JSON.parse('[{"poolName":"50BTC","url":"https://50btc.com/","searchStrings":["50BTC.com","50btc.com"]},{"poolName":"175btc","url":"http://www.175btc.com/","searchStrings":["Mined By 175btc.com"]},{"poolName":"ASICminer","url":"https://bitcointalk.org/index.php?topic=99497.0","searchStrings":["Mined By ASICMiner"]},{"poolName":"AntMiner","url":"https://bitmaintech.com/","searchStrings":["AntPool"]},{"poolName":"agentD","url":"http://","searchStrings":["agentD"]},{"poolName":"Bitfury","url":"http://bitfury.org/","searchStrings":["2av0id51pct"]},{"poolName":"BitMinter","url":"https://bitminter.com/","searchStrings":["BitMinter"]},{"poolName":"Bitparking","url":"http://bitparking.com/","searchStrings":["bitparking"]},{"poolName":"BTC Guild","url":"https://www.btcguild.com/","searchStrings":["Mined by BTC Guild","BTC Guild"]},{"poolName":"bcpool.io","url":"https://bcpool.io/","searchStrings":["bcpool"]},{"poolName":"Discus Fish","url":"http://f2pool.com/","searchStrings":["七彩神仙鱼","Made in China","Mined by user"]},{"poolName":"Discus Fish Solo","url":"http://f2pool.com/","searchStrings":["For Pierce and Paul"]},{"poolName":"Cointerra","url":"http://cointerra.com/","searchStrings":["cointerra"]},{"poolName":"Eligius","url":"http://eligius.st/","searchStrings":["Eligius"]},{"poolName":"EclipseMC","url":"https://eclipsemc.com/","searchStrings":["Josh Zerlan was here!","EclipseMC","Aluminum Falcon"]},{"poolName":"GIVE-ME-COINS","url":"https://give-me-coins.com/","searchStrings":["Mined at GIVE-ME-COINS.com"]},{"poolName":"ghash.io","url":"https://ghash.io/","searchStrings":["ghash.io","GHash.IO"]},{"poolName":"HHTT","url":"http://hhtt.1209k.com/","searchStrings":["HHTT"]},{"poolName":"KNCminer","url":"https://www.kncminer.com/","searchStrings":["KnCMiner"]},{"poolName":"Megabigpower","url":"http://megabigpower.com/","searchStrings":["megabigpower.com"]},{"poolName":"MultiCoin","url":"https://multicoin.co/","searchStrings":["MultiCoin.co"]},{"poolName":"Mt Red","url":"https://mtred.com/‎","searchStrings":["/mtred/"]},{"poolName":"MaxBTC","url":"https://www.maxbtc.com","searchStrings":["MaxBTC"]},{"poolName":"NMCbit","url":"http://nmcbit.com/","searchStrings":["nmcbit.com"]},{"poolName":"ozcoin","url":"https://ozco.in/","searchStrings":["ozco.in","ozcoin"]},{"poolName":"Polmine.pl","url":"https://polmine.pl","searchStrings":["by polmine.pl"]},{"poolName":"simplecoin","url":"http://simplecoin.us/","searchStrings":["simplecoin.us ftw"]},{"poolName":"SlushPool","url":"https://slushpool.com/","searchStrings":["/slush/"]},{"poolName":"TripleMining","url":"https://www.triplemining.com/","searchStrings":["Triplemining.com"]},{"poolName":"wizkid057","url":"http://wizkid057.com/btc","searchStrings":["wizkid057"]},{"poolName":"Yourbtc.net","url":"http://yourbtc.net/","searchStrings":["yourbtc.net"]},{"poolName":"BTCChina Pool","url":"https://pool.btcchina.com/","searchStrings":["BTCChina Pool","btcchina.com"]},{"poolName":"BTCC Pool","url":"https://pool.btcc.com/","searchStrings":["/BTCC/"]}]')},function(t,e,i){const{utxo:r,_setOutputResults:s,_setInputResults:n,transformTransaction:a,getDetailFromMeta:o,translateOutputAddress:c}=i(626),h=i(33),u=i(84),l=i(1);async function p(t,e){var i=(e=new u([e])).array(0,[]),r=e.obj(1,{}),s=(r.from=r.from||0,r.to=r.to||4294967295,[]);e=await t.getMetaByAddress(i);let n=0;for(const i of e){if(n<r.from);else{if(n>=r.to)break;var a=await o(t,i);s.push(a)}n++}return{totalCount:e.length,items:s}}async function d(t,e){let i=(r=t.valid()).str("addr");i=i||r.str("addrs");var r,s=((r={from:parseInt(t.query.from)||parseInt(t.body.from)||0}).to=parseInt(t.query.to)||parseInt(t.body.to)||parseInt(r.from)+10,t=t,{noAsm:!!parseInt(t.query.noAsm),noScriptSig:!!parseInt(t.query.noScriptSig),noSpent:!!parseInt(t.query.noSpent)});try{var n,c=await this.node.getMetaByAddress(i.split(",")),h=[];for(n of c){var u=await o(this.node,n);h.push(await a(this.node,u,s))}return{totalItems:c.length,from:r.from,to:Math.min(r.to,c.length),items:h}}catch(t){throw t}}async function f(t,e){var i=t.valid();let s=i.str("addr");s=s||i.str("addrs"),t.query.from&&t.query.to&&(parseInt(t.query.from),parseInt(t.query.to));try{var n,a=[];for(n of await r(this.node,s.split(",")))a.push(function(t,e){var i={address:c(e.address),txid:l.revHex(e.txid),vout:e.vout,scriptPubKey:e.scriptPubKey,amount:e.satoshis/1e8,satoshis:e.satoshis};return e.height&&0<e.height?(i.height=e.height,i.confirmations=t.chain.height-e.height+1):i.confirmations=0,e.timestamp&&(i.ts=e.timestamp),i}(this,n));return a}catch(t){throw t}}async function m(t,e,i){i=i||{};var r={totalCount:0,items:[]};let a=0;for(const s of await t.node.getMetaByAddress(e)){if(i.from&&a<i.from);else{if(i.to&&a>=i.to)break;var u=await o(t.node,s);r.items.push(u)}a++}r.totalCount=r.items.length;for(var p={addrStr:e,balance:0,balanceSat:0,totalReceived:0,totalReceivedSat:0,totalSent:0,totalSentSat:0,unconfirmedBalance:0,unconfirmedBalanceSat:0,unconfirmedTxApperances:0,txApperances:0},d=0;d<r.items.length;d++){var f=r.items[d];s(t,f,e,p),n(t,f,e,p),i.noTxList||(p.transactions||(p.transactions=[]),p.transactions.push(l.revHex(f.txid())))}return p.balance=h.fromSatoshis(p.balanceSat).toBTC(),p.totalReceived=h.fromSatoshis(p.totalReceivedSat).toBTC(),p.totalSent=h.fromSatoshis(p.totalSentSat).toBTC(),p.unconfirmedBalance=h.fromSatoshis(p.unconfirmedBalanceSat).toBTC(),p.addrStr&&(p.addrStr=c(p.addrStr)),p}t.exports=[{name:"address.reflect",method:"get",path:"/public/addr/reflect/:id",callback:async function(t,e){t=(t=t.valid()).str("id");var i=this.node.require("walletdb");if(i&&(i=await i.get("primary"),await i.ensureAccount({name:t,witness:!0}),i=await i.createReceive(t,1)))return i.toJSON().address}},{name:"getInfo",method:"get",path:"/public/addr/:addr",callback:async function(t,e){var i=(i=t.valid()).str("addr"),r={noTxList:parseInt(t.query.noTxList)};t.query.from&&t.query.to?(r.from=parseInt(t.query.from),r.to=parseInt(t.query.to)):(r.from=0,r.to=10);try{return await m(this,i,r)}catch(t){throw t}}},{name:"getUTXOByAddress",method:"get",path:"/public/addr/:addr/utxo",callback:f},{name:"getUTXOByAddresses",method:"get",path:"/public/addrs/:addr/utxo",callback:f},{name:"postUTXOByAddresses",method:"post",path:"/public/addrs/utxo",callback:f},{name:"getTXSByAddresses",method:"get",path:"/public/addrs/:addrs/txs",callback:d},{name:"postTXSByAddresses",method:"post",path:"/public/addrs/txs",callback:d},{name:"getBalanceByAddress",method:"get",path:"/public/addr/:addr/balance",callback:async function(t,e){var i=this;let r=(t=t.valid()).str("addr");r=r||t.str("addrs"),t=await i.node.getCoinsByAddress(r.split(","));var s=(i=t.reduce((t,e)=>t+e.value,0))-(t=t.reduce((t,e)=>(-1==e.height&&(t+=e.value),t),0));return{confirmed:h.fromSatoshis(s).toBTC(),unconfirmed:h.fromSatoshis(t).toBTC(),balance:h.fromSatoshis(i).toBTC()}}},{name:"getUnconfirmedBalance",method:"get",path:"/public/addr/:addr/unconfirmedBalance",callback:async function(t,e){var i=this;let r=(t=t.valid()).str("addr");return r=r||t.str("addrs"),t=await i.node.getCoinsByAddress(r.split(",")),i=t.reduce((t,e)=>(-1==e.height&&(t+=e.value),t),0),h.fromSatoshis(i).toBTC()}},{name:"getTotalReceived",method:"get",path:"/public/addr/:addr/totalReceived",callback:async function(t,e){let i=(t=t.valid()).str("addr");i=i||t.str("addrs");try{return(await m(this,i)).totalReceivedSat}catch(t){throw t}}},{name:"getTotalSent",method:"get",path:"/public/addr/:addr/totalSent",callback:async function(t,e){let i=(t=t.valid()).str("addr");i=i||t.str("addrs");try{return(await m(this,i)).totalSent}catch(t){throw t}}},{name:"getAddressHistory",method:"jsonp",path:"/",callback:p},{name:"getAddressSummary",method:"jsonp",path:"/",callback:async function(t,e){var i=new u([e]),r=i.array(0,[]),a=i.obj(1,{});a.from=a.from||0,a.to=a.to||4294967295;for(var o={addrStr:r,balance:0,balanceSat:0,totalReceived:0,totalReceivedSat:0,totalSent:0,totalSentSat:0,unconfirmedBalance:0,unconfirmedBalanceSat:0,unconfirmedTxApperances:0,txApperances:0},c=(i=await p(t,e)).items,l=0;l<c.length;l++){var d=c[l];s(t,d,r,o),n(t,d,r,o),a.noTxList||(o.transactions||(o.transactions=[]),o.transactions.push(d.txid()))}return o.balance=h.fromSatoshis(o.balanceSat).toBTC(),o.totalReceived=h.fromSatoshis(o.totalReceivedSat).toBTC(),o.totalSent=h.fromSatoshis(o.totalSentSat).toBTC(),o.unconfirmedBalance=h.fromSatoshis(o.unconfirmedBalanceSat).toBTC(),o}},{name:"getAddressUnspentOutputs",method:"jsonp",path:"/",callback:async function(t,e){return e=(e=new u([e])).array(0,[]),t=await r(t,e)}},{name:"getTxidsByAddress",method:"jsonp",path:"/",callback:async function(t,e){var i=(e=new u([e])).array(0);e=e.str(1,"both");return t.chain.getHashesByAddress(i,e)}}]},function(t,e,i){var r=i(82);const s=i(33),n=i(84);var a=i(334),o=0,c=Date.now();async function h(t){var e=await t.rpc.execute({corba:!0,method:"miner.difficulty"});return{blocks:t.chain.height,connections:t.node.pool.peers.size,timeoffset:0,proxy:"",testnet:"main"!==t.node.network.type,errors:"",network:t.node.network.type,relayFee:0,version:"gamegold-"+r.version,protocolversion:700001,difficulty:e}}t.exports=[{name:"getStatus",method:"get",path:"/public/status",callback:async function(t,e){switch(t.query.q){case"getDifficulty":try{return{difficulty:(await h(this)).difficulty}}catch(t){throw t}break;case"getLastBlockHash":var i=await this.chain.db.getTip();return{syncTipHash:i.hash,lastblockhash:i.hash};case"getBestBlockHash":try{return{bestblockhash:await this.rpc.execute({corba:!0,method:"block.best"})}}catch(t){throw t}break;default:try{return{info:await h(this)}}catch(t){throw t}}}},{name:"getSync",method:"get",path:"/public/sync",callback:async function(t,e){var i="syncing";try{this.chain.synced&&(i="finished");var r=(100*this.chain.getProgress()).toFixed(2);return{status:i,blockChainHeight:this.chain.height,syncPercentage:Math.round(r),height:this.chain.height,error:null,type:"gamegold node"}}catch(t){throw t}}},{name:"getVersion",method:"get",path:"/public/version",callback:async function(t,e){return{version:r.version}}},{name:"getPeer",method:"get",path:"/public/peer",callback:function(t,e){var i=this.pool.getLoader()||{connected:!1,address:{host:null,port:null}};return{connected:i.connected,host:i.address.host,port:i.address.port}}},{name:"getEstimateFee",method:"get",path:"/public/utils/estimatefee",callback:function(t,e){t=(t.query.nbBlocks||"2").split(",");try{var i,r={};for(i of t){var n=parseInt(i);let t=this.fees.estimateFee(n,!1);0===t&&(t=-1),t=s.btc(t,!0),r[n]=t}return r}catch(t){throw t}}},{name:"estimateFee",method:"jsonp",path:"/",callback:function(t,e){e=(e=new n([e])).array(0,["2"]);try{var i,r={};for(i of e){var a=parseInt(i);let e=t.fees.estimateFee(a,!1);0===e&&(e=-1),e=s.btc(e,!0),r[a]=e}return r}catch(e){throw e}}},{name:"currency",method:"get",path:"/public/currency",callback:async function(t,e){var i=Date.now();if(!(0===o||c+6e5<=i))return{status:200,data:{bitstamp:o}};c=i;try{var r=await new Promise((t,e)=>{a("https://www.bitstamp.net/api/ticker/",(function(i,r,s){i&&e(i),i||200!==r.statusCode||t(s)}))});return{status:200,data:{bitstamp:o=parseFloat(JSON.parse(r).last)}}}catch(t){throw t}}},{name:"explorers",method:"get",path:"/public/explorers",callback:async function(t,e){return[{name:"gamegold",ticker:"GG",url:"https://insight.gamegold.xin"}]}},{name:"syncPercentage",method:"jsonp",path:"/",callback:async function(t,e){return Math.round((100*t.chain.getProgress()).toFixed(2))}},{name:"sysEcho",method:"jsonp",path:"/",callback:function(t,e){return 0}},{name:"getBestBlockHash",method:"jsonp",path:"/",callback:async function(t,e){return{bestblockhash:t=await t.rpc.execute({corba:!0,method:"block.best"})}}}]},function(t,e,i){const r=i(682),s=i(0),n=i(1),{handleErrors:a,getDetailedTransaction:o,transformTransaction:c,getDetailFromMeta:h,getBlockOverview:u,translateInputAddresses:l}=i(626),p=i(84);t.exports=[{name:"getTx",method:"get",path:"/public/tx/:txid",callback:async function(t,e){return t=(t=t.valid()).hash("txid"),(t=await o(this.node,t))?await c(this.node,t,{}):null}},{name:"getRawTx",method:"get",path:"/public/rawtx/:txid",callback:async function(t,e){return t=(t=t.valid()).str("txid"),{rawtx:t=await this.rpc.execute({method:"tx.raw.get",params:[t]})}}},{name:"getList",method:"get",path:"/public/txs",callback:async function(t,e){s(!this.chain.options.spv,"Cannot get TX in SPV mode.");var i,p=t.query.blockHash,d=l(t.query.address),f=(t=parseInt(t.query.pageNum)||0,1);if(p){if(!(p=await u(this.node,p,e)))return a(null,e);e=p.txids.length;var m,g,y=(r.isUndefined(t)?i=p.txids:(m=10*t,i=p.txids.slice(m,10+m),f=Math.ceil(e/10)),[]);for(g of i){var v=await o(this.node,n.revHex(g));v&&y.push(await c(this.node,v,{}))}return{pagesTotal:f,txs:y}}if(d){var w=10*t,b=10*(t+1),k=[];p=await this.node.getMetaByAddress(d);let e=0;for(const t of p){if(e<w);else{if(e>=b)break;var x=await h(this.node,t);k.push(await c(this.node,x,{}))}e++}return{pagesTotal:Math.ceil(p.length/10),txs:k}}throw new Error("Block hash or address expected")}},{name:"getDetailedTransaction",method:"jsonp",path:"/",callback:async function(t,e){return e=(e=new p([e])).hash(0),o(t,e,!0)}},{name:"getTransaction",method:"jsonp",path:"/",callback:async function(t,e){return e=(e=new p([e])).hash(0),t=await o(t,e,!1)}},{name:"getRawTransaction",method:"jsonp",path:"/",callback:async function(t,e){return e=(e=new p([e])).str(0),t=await t.rpc.execute({method:"tx.raw.get",params:[e]})}},{name:"getMempoolTransaction",method:"jsonp",path:"/",callback:async function(t,e){return e=(e=new p([e])).hash(0),t.mempool.getTX(e)}}]},function(t,e,i){const r=i(21).opcodes,s=i(1).revHex;t.exports=[{name:"prop.get",method:"get",path:"/public/prop/:pid",callback:async function(t,e){var i=[];t=t.valid().str("pid");if(t=await this.node.chain.db.propList.getVp(t)){var n=t.current.hash;t.oper="exchange",i.push({oper:"exchange",pid:t.pid,oid:t.oid,cid:t.cid,current:{hash:s(t.current.hash),index:t.current.index,address:t.current.address},height:t.height});let e=[n,t.current.index];for(;;){var a=await this.node.getMeta(e[0]),o=a.tx;if(!o)break;if(!(o=o.outputs[e[1]]))break;var c=o.getReturnData([r.OP_PROPCREATE,r.OP_PROPEXCHANGE]);if(!c)break;if("new"==c.oper){c.current={hash:s(e[0]),index:e[1],address:o.getAddress().toString()},c.height=a.height,i.push(c);break}if(!c.prev)break;e=[c.prev.hash,c.prev.index]}}return i}},{name:"queryProps",method:"post",path:"/public/prop/query",callback:async function(t,e){var i=(t=t.valid()).str("game_id");t=t.str("user_addr");return await this.node.queryProps(i,t)}},{name:"queryProps",method:"get",path:"/public/prop/:game_id/addr/:user_addr",callback:async function(t,e){var i=(t=t.valid()).str("game_id");t=t.str("user_addr");return await this.node.queryProps(i,t)}},{name:"queryProps",method:"get",path:"/public/props/query",callback:async function(t,e){var i=(t=t.valid()).str("pid"),r=t.str("cid"),s=t.str("oid"),n=t.str("addr");t=t.str("page");return await this.node.queryProps(r,n,i,s,t)}}]},function(t,e,i){const r=i(84);t.exports=[{name:"cp.remoteQuery",method:"jsonp",path:"/",callback:async function(t,e){return e=(e=new r([e])).array(0,[]),t.chain.db.cpList.query(e)},remoteCb:async function(t){if(t&&Array.isArray(t.list))for(var e of t.list)this.wdb.cpList.getItem(e.cid)||await this.wdb.cpList.addItem(e);return t}},{name:"cps",method:"get",path:"/public/cps",callback:async function(t,e){return t={page:t.valid().u32("page",1),pageCount:0},{list:this.chain.db.cpList.getCPList([],t),cur:t.page,page:t.pageCount}}},{name:"cpById",method:"get",path:"/public/cp/:id",callback:async function(t,e){var i=(t=t.valid()).u32("page",1);t=t.str("id");return(t=this.chain.db.cpList.getCPList(t?[t]:[],{page:i}))&&0<t.length?t[0]:null}},{name:"cpByName",method:"get",path:"/public/cp/name/:name",callback:async function(t,e){var i=(t=t.valid()).u32("page",1);t=decodeURIComponent(t.str("name"));return(t=this.chain.db.cpList.getCPListByName(t?[t]:[],{page:i}))&&0<t.length?t[0]:null}}]},function(t,e){t.exports=[{name:"queryStockHolder",method:"get",path:"/public/stock/holder",callback:async function(t,e){var i=(t=t.valid()).str("cid");t=t.str("page");return this.node.queryStockHolder(i,t)}},{name:"queryStockRecord",method:"get",path:"/public/stock/record",callback:async function(t,e){var i=(t=t.valid()).str("type"),r=t.str("cid");t=t.str("page");return this.node.queryStockRecord(i,r,t)}}]},function(t,e,i){const r=i(84),s=i(101),n=i(77),a=i(78).errors,o=i(69),c=i(5).ContractStatus,h=i(19),u=i(33);t.exports=[{name:"token.random",local:!0,method:"jsonp",path:"/",callback:async function(t,e,i){if(1!==e.length)throw new n(a.MISC_ERROR,"token.random clientNo: 生成令牌随机量 终端编码");return e=new r([e]).str(0),e=o.getHmac(e,t.keys.hmacSalt).random}},{name:"mempool.watch",method:"jsonp",path:"/",callback:async function(t,e,i){i&&i.join("mempool")}},{name:"mempool.unwatch",method:"jsonp",path:"/",callback:async function(t,e,i){i&&i.leave("mempool")}},{name:"chain.watch",method:"jsonp",path:"/",callback:async function(t,e,i){i&&i.join("chain")}},{name:"chain.unwatch",method:"jsonp",path:"/",callback:async function(t,e,i){i&&i.leave("chain")}},{name:"chain.rescan",method:"jsonp",path:"/",callback:async function(t,e,i){if(null==(e=new r([e]).numhash(0)))throw new Error("Invalid parameter.");return t.http.scan(i,e)}},{name:"subscribe",local:!0,method:"jsonp",path:"/",callback:async function(t,e,i){if(i&&Array.isArray(e))for(var r of e)i.bus.subscribe(r);return!0}},{name:"unsubscribe",local:!0,method:"jsonp",path:"/",callback:async function(t,e,i){if(i&&Array.isArray(e))for(var r of e)i.bus.unsubscribe(r);return!0}},{name:"filter.set",local:!0,method:"jsonp",path:"/",callback:async function(t,e,i){if(i){if(e=new r([e]).buf(0))return i.filter=s.fromRaw(e),null;throw new Error("Invalid parameter.")}}},{name:"filter.reset",local:!0,method:"jsonp",path:"/",callback:async function(t,e,i){i&&(i.filter=null)}},{name:"filter.add",local:!0,method:"jsonp",path:"/",callback:async function(t,e,i){if(i){var s=new r([e]).array(0);if(!s)throw new Error("Invalid parameter.");if(!i.filter)throw new Error("No filter set.");var n=new r([s]);for(let e=0;e<s.length;e++){var a=n.buf(e);if(!a)throw new Error("Bad data chunk.");i.filter.add(a),t.spv&&t.pool.watch(a)}}}},{name:"canExecute",method:"jsonp",path:"/",callback:async function(t,e){return(e=new r([e]).obj(0,{})).confirm||"cpChange"==e.oper?t.chain.db.cpList.canExecute(e):await t.mempool.cpMemList.canExecute(e)&&await t.chain.db.cpList.canExecute(e)}},{name:"stock.record",method:"jsonp",path:"/",callback:async function(t,e,i){var s=(e=new r([e])).uint(0,0),n=e.str(1),a=e.uint(2,0);e=e.array(3,[]);let o=null;return(s?await t.chain.db.getStockRecord(s,n,a):await t.chain.db.getStockRecordByCid(n,a)).query(e)},remoteCb:async function(t){if(t&&Array.isArray(t))for(var e of t)await this.wdb.setStockRecord(e);return t}},{name:"contract.list",method:"jsonp",path:"/",callback:async function(t,e){var i,s,n,a;return 0==e.length?"contract.list type page ids size: 查询并返回交易对 交易类型 指定查询的ID数组 页码":(a=(e=new r([e])).uint(0,1),i=e.uint(1,1),s=e.array(2,[]),e=e.int(3,10),(n=[]).push(["transStatus",c.CreatedOnMem]),a&&n.push(["type",a]),0<s.length&&n.push(["id","include",s]),{pageNum:(a=t.chain.db.transactionList.where(n).paginate(e,i)).pageNum,pageCur:a.pageCur,list:a.records()})},remoteCb:async function(t){if(t&&Array.isArray(t.list))for(var e of t.list)this.wdb.transactionList.saveContract(e,!0);return t}},{name:"queryProps",method:"jsonp",path:"/",callback:async function(t,e){var i=(e=new r([e])).str(0,"");e=e.str(1,"");return t.queryProps(i,e)}},{name:"block.tip",method:"jsonp",path:"/",callback:async function(t,e){return t.chain.tip.toRaw()}},{name:"block.entry",method:"jsonp",path:"/",callback:async function(t,e){if(null==(e=new r([e]).numhash(0)))throw new Error("Invalid parameter.");return(e=await t.chain.getEntry(e))&&await t.chain.isMainChain(e)?e.toRaw():null}},{name:"$tx.broadcast",method:"jsonp",path:"/",callback:async function(t,e,i){e=new r([e]).buf(0),e=h.fromRaw(e),await t.sendTX(e)}},{name:"$estimate.fee",method:"jsonp",path:"/",callback:async function(t,e){if(e=new r([e]).u32(0,1),t.fees)return 0===(t=t.fees.estimateFee(e,!1))?-1:u.btc(t,!0);throw new n(a.MISC_ERROR,"Fee estimation not available.")}}]},function(t,e,i){const r=i(84);i(39);const s=i(785);i(19),t.exports=[{name:"ca.rank",method:"jsonp",path:"/",callback:async function(t,e){return e=(e=new r([e])).str(0,""),(t=await(async t=>new Promise((e,i)=>{s(t,.85,1e-4,(function(t,r){t?i(t):e(r)}))}))(t.chain.db.enCpList.rank))[e]},remoteCb:async function(t){return t}},{name:"ca.list",method:"jsonp",path:"/",callback:async function(t,e){return e=(e=new r([e])).array(0,[]),(e=await t.chain.db.erList.query(e)).height=t.chain.height,e}},{name:"ca.verify",method:"jsonp",path:"/",callback:async function(t,e){return e=(e=new r([e])).str(0,""),(e=await t.chain.db.caVerify(e))&&(e.curHeight=t.chain.height),e},remoteCb:async function(t){return t}},{name:"ca.list.ab",method:"jsonp",path:"/",callback:async function(t,e){return e=(e=new r([e])).array(0,[]),t.chain.db.erAbList.query(e)},remoteCb:async function(t){return t}}]},function(t,e,i){"use strict";class r{constructor(t,e,i,r,s){this.outgoingNodes=t,this.linkProb=e,this.tolerance=i,this.callback=r,this.pageCount=Object.keys(this.outgoingNodes).length,this.coeff=(1-e)/this.pageCount,this.probabilityNodes=t instanceof Array?[]:{},this.incomingNodes=t instanceof Array?[]:{},this.debug=s,this.startRanking()}startRanking(){var t,e,i,r=1/this.pageCount,s=this.outgoingNodes;for(t in s)for(e in this.probabilityNodes[t]=r,s[t])i=s[t][e],this.incomingNodes[i]||(this.incomingNodes[i]=[]),this.incomingNodes[i].push(t);this.debug&&this.reportDebug(1),this.iterate(1)}reportDebug(t){console.log("____ITERATION "+t+"____"),console.log("Pages: "+Object.keys(this.outgoingNodes).length),console.log("outgoing %j",this.outgoingNodes),console.log("incoming %j",this.incomingNodes),console.log("probability %j",this.probabilityNodes)}iterate(t){var e,i,r,s,n,a=[],o={};for(e in this.probabilityNodes){if(r=0,this.incomingNodes[e])for(i=0;i<this.incomingNodes[e].length;i++)r+=this.probabilityNodes[this.incomingNodes[e][i]]/this.outgoingNodes[this.incomingNodes[e][i]].length;s=this.coeff+this.linkProb*r,n=this.probabilityNodes[e]+this.tolerance,this.probabilityNodes[e]-this.tolerance<=s&&s<=n&&a.push(o[e]=s),this.probabilityNodes[e]=s}return a.length==this.pageCount?this.outgoingNodes instanceof Array?this.callback(null,a):this.callback(null,o):(this.debug&&this.reportDebug(t),this.iterate(++t))}}t.exports=function(t,e,i,s,n=!1){if(t&&e&&i&&s)return new r(t,e,i,s,n);throw new Error("Provide 4 arguments: nodeMatrix, link probability, tolerance, callback")}},function(t,e,i){"use strict";t.exports=class{constructor(t){this.config=t,this.hmacConnection=this.config.array("hmac-connection")||[],this.config.hmacConnection=this.hmacConnection}add(t){-1==this.hmacConnection.indexOf(t)&&this.hmacConnection.push(t),this.config.hmacConnection=this.hmacConnection}del(t){-1!=(t=this.hmacConnection.indexOf(t))&&(this.hmacConnection.splice(t,1),this.config.hmacConnection=this.hmacConnection)}clear(){this.hmacConnection=[],this.config.hmacConnection=this.hmacConnection}content(){return this.hmacConnection}has(t){return-1!=this.hmacConnection.indexOf(t)}}},function(t,e,i){"use strict";
1713
+ */t.exports=function(t,e){if(!t||!t.getHeader||!t.setHeader)throw new TypeError("res argument is required");var i=t.getHeader("Vary")||"";(i=s(Array.isArray(i)?i.join(", "):String(i),e))&&t.setHeader("Vary",i)},t.exports.append=s;var r=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function s(t,e){if("string"!=typeof t)throw new TypeError("header argument is required");if(!e)throw new TypeError("field argument is required");for(var i=Array.isArray(e)?e:n(String(e)),s=0;s<i.length;s++)if(!r.test(i[s]))throw new TypeError("field argument contains an invalid header name");if("*"===t)return t;var a=t,o=n(t.toLowerCase());if(-1!==i.indexOf("*")||-1!==o.indexOf("*"))return"*";for(var c=0;c<i.length;c++){var h=i[c].toLowerCase();-1===o.indexOf(h)&&(o.push(h),a=a?a+", "+i[c]:i[c])}return a}function n(t){for(var e=0,i=[],r=0,s=0,n=t.length;s<n;s++)switch(t.charCodeAt(s)){case 32:r===e&&(r=e=s+1);break;case 44:i.push(t.substring(r,e)),r=e=s+1;break;default:e=s+1}return i.push(t.substring(r,e)),i}},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.uServer=void 0;var r=i(93);const s=i(664),n=i(762),a=(0,r.default)("engine:uws");class o extends s.BaseServer{init(){}cleanup(){}prepare(t,e){t.method=t.getMethod().toUpperCase();var i=new URLSearchParams(t.getQuery());t._query=Object.fromEntries(i.entries()),t.headers={},t.forEach((e,i)=>{t.headers[e]=i}),t.connection={remoteAddress:Buffer.from(e.getRemoteAddressAsText()).toString()},e.onAborted(()=>{a("response has been aborted")})}createTransport(t,e){return new n.default[t](e)}attach(t,e={}){var i=(e.path||"/engine.io").replace(/\/$/,"")+"/";t.any(i,this.handleRequest.bind(this)).ws(i,{compression:e.compression,idleTimeout:e.idleTimeout,maxBackpressure:e.maxBackpressure,maxPayloadLength:this.opts.maxHttpBufferSize,upgrade:this.handleUpgrade.bind(this),open:t=>{(t.transport.socket=t).transport.writable=!0,t.transport.emit("drain")},message:(t,e,i)=>{t.transport.onData(i?e:Buffer.from(e).toString())},close:(t,e,i)=>{t.transport.onClose(e,i)}})}handleRequest(t,e){a('handling "%s" http request "%s"',e.getMethod(),e.getUrl()),this.prepare(e,t),e.res=t;const i=(i,r)=>{void 0!==i?(this.emit("connection_error",{req:e,code:i,message:s.Server.errorMessages[i],context:r}),this.abortRequest(e.res,i,r)):e._query.sid?(a("setting new request for existing client"),this.clients[e._query.sid].transport.onRequest(e)):this.handshake(e._query.transport,e,(e,i)=>this.abortRequest(t,e,i))};this.corsMiddleware?(e.res=new c(t),this.corsMiddleware.call(null,e,e.res,()=>{this.verify(e,!1,i)})):this.verify(e,!1,i)}handleUpgrade(t,e,i){a("on upgrade"),this.prepare(e,t),e.res=t,this.verify(e,!0,async(r,n)=>{if(r)this.emit("connection_error",{req:e,code:r,message:s.Server.errorMessages[r],context:n}),this.abortRequest(t,r,n);else{let s;if(r=e._query.sid)(n=this.clients[r])?n.upgrading?(a("transport has already been trying to upgrade"),t.close()):n.upgraded?(a("transport had already been upgraded"),t.close()):(a("upgrading existing transport"),s=this.createTransport(e._query.transport,e),n.maybeUpgrade(s)):(a("upgrade attempt for closed client"),t.close());else if(!(s=await this.handshake(e._query.transport,e,(e,i)=>this.abortRequest(t,e,i))))return;t.upgrade({transport:s},e.getHeader("sec-websocket-key"),e.getHeader("sec-websocket-protocol"),e.getHeader("sec-websocket-extensions"),i)}})}abortRequest(t,e,i){var r=e===s.Server.errors.FORBIDDEN?"403 Forbidden":"400 Bad Request";i=i&&i.message?i.message:s.Server.errorMessages[e];t.writeStatus(r),t.writeHeader("Content-Type","application/json"),t.end(JSON.stringify({code:e,message:i}))}}e.uServer=o;class c{constructor(t){this.res=t,this.statusWritten=!1,this.headers=[]}set statusCode(t){this.writeStatus(200===t?"200 OK":"204 No Content")}setHeader(t,e){this.writeHeader(t,e)}getHeader(){}writeStatus(t){this.res.writeStatus(t),this.statusWritten=!0,this.writeBufferedHeaders()}writeHeader(t,e){"Content-Length"!==t&&(this.statusWritten?this.res.writeHeader(t,e):this.headers.push([t,e]))}writeBufferedHeaders(){this.headers.forEach(([t,e])=>{this.res.writeHeader(t,e)})}end(t){this.statusWritten||this.writeBufferedHeaders(),this.res.end(t)}onData(t){this.res.onData(t)}onAborted(t){this.res.onAborted(t)}}},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=i(763);i=i(764);e.default={polling:r.Polling,websocket:i.WebSocket}},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Polling=void 0;var r=i(318),s=i(176);const n=i(623),a=(0,i(93).default)("engine:polling"),o={gzip:s.createGzip,deflate:s.createDeflate};class c extends r.Transport{constructor(t){super(t),this.closeTimeout=3e4}get name(){return"polling"}get supportsFraming(){return!1}onRequest(t){var e=t.res;"get"===t.getMethod()?this.onPollRequest(t,e):"post"===t.getMethod()?this.onDataRequest(t,e):(e.writeStatus("500 Internal Server Error"),e.end())}onPollRequest(t,e){this.req?(a("request overlap"),this.onError("overlap from client"),e.writeStatus("500 Internal Server Error"),e.end()):(a("setting request"),this.req=t,this.res=e,t.cleanup=()=>{this.req=this.res=null},e.onAborted(()=>{this.writable=!1,this.onError("poll connection closed prematurely")}),this.writable=!0,this.emit("drain"),this.writable&&this.shouldClose&&(a("triggering empty send to append close packet"),this.send([{type:"noop"}])))}onDataRequest(t,e){if(this.dataReq)this.onError("data request overlap from client"),e.writeStatus("500 Internal Server Error"),e.end();else{const s=Number(t.headers["content-length"]);if(s)if(s>this.maxHttpBufferSize)this.onError("payload too large"),e.writeStatus("413 Payload Too Large").end();else{if("application/octet-stream"===t.headers["content-type"]&&4===this.protocol)return this.onError("invalid content");this.dataReq=t,this.dataRes=e;let n,a=0;var i,r={"Content-Type":"text/html"};for(i in this.headers(t,r),r)e.writeHeader(i,String(r[i]));const o=t=>{this.onData(t.toString()),this.onDataRequestCleanup(),e.end("ok")};e.onAborted(()=>{this.onDataRequestCleanup(),this.onError("data request connection closed prematurely")}),e.onData((t,i)=>{var r=a+t.byteLength;if(r>s)this.onError("content-length mismatch"),e.close();else{if(!n){if(i)return void o(Buffer.from(t));n=Buffer.allocUnsafe(s)}if(Buffer.from(t).copy(n,a),i)return r!=s?(this.onError("content-length mismatch"),e.writeStatus("400 Content-Length Mismatch").end(),void this.onDataRequestCleanup()):void o(n);a=r}})}else this.onError("content-length header required"),e.writeStatus("411 Length Required").end()}}onDataRequestCleanup(){this.dataReq=this.dataRes=null}onData(t){a('received "%s"',t);var e=t=>{if("close"===t.type)return a("got xhr close packet"),this.onClose(),!1;this.onPacket(t)};3===this.protocol?this.parser.decodePayload(t,e):this.parser.decodePayload(t).forEach(e)}onClose(){this.writable&&this.send([{type:"noop"}]),super.onClose()}send(t){this.writable=!1,this.shouldClose&&(a("appending close packet to payload"),t.push({type:"close"}),this.shouldClose(),this.shouldClose=null);var e=e=>{var i=t.some(t=>t.options&&t.options.compress);this.write(e,{compress:i})};3===this.protocol?this.parser.encodePayload(t,this.supportsBinary,e):this.parser.encodePayload(t,e)}write(t,e){a('writing "%s"',t),this.doWrite(t,e,()=>{this.req.cleanup()})}doWrite(t,e,i){var r="string"==typeof t;const s={"Content-Type":r?"text/plain; charset=UTF-8":"application/octet-stream"},a=t=>{this.headers(this.req,s),Object.keys(s).forEach(t=>{this.res.writeHeader(t,String(s[t]))}),this.res.end(t),i()};if(this.httpCompression&&e.compress)if((r?Buffer.byteLength(t):t.length)<this.httpCompression.threshold)a(t);else{const e=n(this.req).encodings(["gzip","deflate"]);e?this.compress(t,e,(t,r)=>{t?(this.res.writeStatus("500 Internal Server Error"),this.res.end(),i(t)):(s["Content-Encoding"]=e,a(r))}):a(t)}else a(t)}compress(t,e,i){a("compressing");const r=[];let s=0;o[e](this.httpCompression).on("error",i).on("data",(function(t){r.push(t),s+=t.length})).on("end",(function(){i(null,Buffer.concat(r,s))})).end(t)}doClose(t){let e;a("closing");var i=()=>{clearTimeout(e),t(),this.onClose()};this.writable?(a("transport writable - closing right away"),this.send([{type:"close"}]),i()):this.discarded?(a("transport discarded - closing right away"),i()):(a("transport not writable - buffering orderly close"),this.shouldClose=i,e=setTimeout(i,this.closeTimeout))}headers(t,e){e=e||{};var i=t.headers["user-agent"];return i&&(~i.indexOf(";MSIE")||~i.indexOf("Trident/"))&&(e["X-XSS-Protection"]="0"),this.emit("headers",e,t),e}}e.Polling=c},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.WebSocket=void 0;var r=i(318);const s=(0,i(93).default)("engine:ws");class n extends r.Transport{constructor(t){super(t),this.writable=!1,this.perMessageDeflate=null}get name(){return"websocket"}get handlesUpgrades(){return!0}get supportsFraming(){return!0}send(t){var e,i=t.shift();void 0===i?(this.writable=!0,this.emit("drain")):(i.options&&i.options.compress,e=e=>{var i="string"!=typeof e,r=this.perMessageDeflate&&Buffer.byteLength(e)>this.perMessageDeflate.threshold;s('writing "%s"',e),this.writable=!1,this.socket.send(e,i,r),this.send(t)},i.options&&"string"==typeof i.options.wsPreEncoded?e(i.options.wsPreEncoded):this.parser.encodePacket(i,this.supportsBinary,e))}doClose(t){s("closing"),t&&t(),this.socket.close()}}e.WebSocket=n},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Client=void 0;const r=i(52);var s=i(93);const n=i(44),a=s("socket.io:client");e.Client=class{constructor(t,e){this.sockets=new Map,this.nsps=new Map,this.server=t,this.conn=e,this.encoder=t.encoder,this.decoder=new t._parser.Decoder,this.id=e.id,this.setup()}get request(){return this.conn.request}setup(){this.onclose=this.onclose.bind(this),this.ondata=this.ondata.bind(this),this.onerror=this.onerror.bind(this),this.ondecoded=this.ondecoded.bind(this),this.decoder.on("decoded",this.ondecoded),this.conn.on("data",this.ondata),this.conn.on("error",this.onerror),this.conn.on("close",this.onclose),this.connectTimeout=setTimeout(()=>{0===this.nsps.size?(a("no namespace joined yet, close the client"),this.close()):a("the client has already joined a namespace, nothing to do")},this.server._connectTimeout)}connect(t,e={}){if(this.server._nsps.has(t))return a("connecting to namespace %s",t),this.doConnect(t,e);this.server._checkNamespace(t,e,i=>{i?this.doConnect(t,e):(a("creation of namespace %s was denied",t),this._packet({type:r.PacketType.CONNECT_ERROR,nsp:t,data:{message:"Invalid namespace"}}))})}doConnect(t,e){const i=this.server.of(t),r=i._add(this,e,()=>{this.sockets.set(r.id,r),this.nsps.set(i.name,r),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0)})}_disconnect(){for(const t of this.sockets.values())t.disconnect();this.sockets.clear(),this.close()}_remove(t){var e;this.sockets.has(t.id)?(e=this.sockets.get(t.id).nsp.name,this.sockets.delete(t.id),this.nsps.delete(e)):a("ignoring remove for %s",t.id)}close(){"open"===this.conn.readyState&&(a("forcing transport close"),this.conn.close(),this.onclose("forced server close"))}_packet(t,e={}){"open"!==this.conn.readyState?a("ignoring packet write %j",t):(t=e.preEncoded?t:this.encoder.encode(t),this.writeToEngine(t,e))}writeToEngine(t,e){if(e.volatile&&!this.conn.transport.writable)a("volatile packet is discarded since the transport is not currently writable");else for(const i of Array.isArray(t)?t:[t])this.conn.write(i,e)}ondata(t){try{this.decoder.add(t)}catch(t){a("invalid packet format"),this.onerror(t)}}ondecoded(t){let e,i;var s;i=3===this.conn.protocol?(e=(s=n.parse(t.nsp,!0)).pathname,s.query):(e=t.nsp,t.data);const o=this.nsps.get(e);o||t.type!==r.PacketType.CONNECT?o&&t.type!==r.PacketType.CONNECT&&t.type!==r.PacketType.CONNECT_ERROR?process.nextTick((function(){o._onpacket(t)})):(a("invalid state (packet type: %s)",t.type),this.close()):this.connect(e,i)}onerror(t){for(const e of this.sockets.values())e._onerror(t);this.conn.close()}onclose(t){a("client close with reason %s",t),this.destroy();for(const e of this.sockets.values())e._onclose(t);this.sockets.clear(),this.decoder.destroy()}destroy(){this.conn.removeListener("data",this.ondata),this.conn.removeListener("error",this.onerror),this.conn.removeListener("close",this.onclose),this.decoder.removeListener("decoded",this.ondecoded),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0)}}},function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ParentNamespace=void 0;const r=i(674);class s extends r.Namespace{constructor(t){super(t,"/_"+s.count++),this.children=new Set}_initAdapter(){this.adapter={broadcast:(t,e)=>{this.children.forEach(i=>{i.adapter.broadcast(t,e)})}}}emit(t,...e){return this.children.forEach(i=>{i.emit(t,...e)}),!0}createChild(t){const e=new r.Namespace(this.server,t);return e._fns=this._fns.slice(0),this.listeners("connect").forEach(t=>e.on("connect",t)),this.listeners("connection").forEach(t=>e.on("connection",t)),this.children.add(e),this.server._nsps.set(t,e),e}fetchSockets(){throw new Error("fetchSockets() is not supported on parent namespaces")}}(e.ParentNamespace=s).count=0},function(t,e,i){"use strict";var r=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.serveFile=e.restoreAdapter=e.patchAdapter=void 0;const s=i(676),n=i(88),a=(0,r(i(93)).default)("socket.io:adapter-uws"),{addAll:o,del:c,broadcast:h}=s.Adapter.prototype;function u(t,e,i,r){const s=e.conn.id,n=e.conn.transport.socket;i&&(a("subscribe connection %s to topic %s",s,t),n.subscribe(t)),r.forEach(e=>{a("subscribe connection %s to topic %s",s,e=t+""+e),n.subscribe(e)})}e.patchAdapter=function(t){s.Adapter.prototype.addAll=function(t,e){const i=!this.sids.has(t),r=(o.call(this,t,e),this.nsp.sockets.get(t));r&&("websocket"===r.conn.transport.name?u(this.nsp.name,r,i,e):i&&r.conn.on("upgrade",()=>{var e=this.sids.get(t);e&&u(this.nsp.name,r,i,e)}))},s.Adapter.prototype.del=function(t,e){var i;c.call(this,t,e),(t=this.nsp.sockets.get(t))&&"websocket"===t.conn.transport.name&&(i=t.conn.id,t=t.conn.transport.socket,e=this.nsp.name+""+e,a("unsubscribe connection %s from topic %s",i,e),t.unsubscribe(e))},s.Adapter.prototype.broadcast=function(e,i){if(i.rooms.size<=1&&0===i.except.size){var r=i.flags||{};const s={preEncoded:!0,volatile:r.volatile,compress:r.compress},n=(e.nsp=this.nsp.name,this.encoder.encode(e)),o=0===i.rooms.size?this.nsp.name:this.nsp.name+""+i.rooms.keys().next().value;a("fast publish to %s",o),n.forEach(e=>{var i="string"!=typeof e;t.publish(o,i?e:"4"+e,i)}),this.apply(i,t=>{"websocket"!==t.conn.transport.name&&t.client.writeToEngine(n,s)})}else h.call(this,e,i)}},e.restoreAdapter=function(){s.Adapter.prototype.addAll=o,s.Adapter.prototype.del=c,s.Adapter.prototype.broadcast=h};e.serveFile=function(t,e){const i=(0,n.statSync)(e).size,r=(0,n.createReadStream)(e),s=()=>!r.destroyed&&r.destroy();t.onAborted(s),r.on("data",e=>{const s=(t=>{var{buffer:t,byteOffset:e,byteLength:i}=t;return t.slice(e,e+i)})(e),n=t.getWriteOffset();var[e,a]=t.tryEnd(s,i);a||e||(r.pause(),t.onWritable(e=>{var[e,a]=t.tryEnd(s.slice(e-n),i);return!a&&e&&r.resume(),e}))}).on("error",t=>{throw s(),t}).on("end",s)}},function(t){t.exports=JSON.parse('{"name":"socket.io","version":"4.5.4","description":"node.js realtime framework server","keywords":["realtime","framework","websocket","tcp","events","socket","io"],"files":["dist/","client-dist/","wrapper.mjs","!**/*.tsbuildinfo"],"directories":{"doc":"docs/","example":"example/","lib":"lib/","test":"test/"},"type":"commonjs","main":"./dist/index.js","exports":{"import":"./wrapper.mjs","require":"./dist/index.js","types":"./dist/index.d.ts"},"types":"./dist/index.d.ts","license":"MIT","repository":{"type":"git","url":"git://github.com/socketio/socket.io"},"scripts":{"compile":"rimraf ./dist && tsc","test":"npm run format:check && npm run compile && npm run test:types && npm run test:unit","test:types":"tsd","test:unit":"nyc mocha --require ts-node/register --reporter spec --slow 200 --bail --timeout 10000 test/index.ts","format:check":"prettier --check \\"lib/**/*.ts\\" \\"test/**/*.ts\\"","format:fix":"prettier --write \\"lib/**/*.ts\\" \\"test/**/*.ts\\"","prepack":"npm run compile"},"dependencies":{"accepts":"~1.3.4","base64id":"~2.0.0","debug":"~4.3.2","engine.io":"~6.2.1","socket.io-adapter":"~2.4.0","socket.io-parser":"~4.2.1"},"devDependencies":{"@types/mocha":"^9.0.0","expect.js":"0.3.1","mocha":"^10.0.0","nyc":"^15.1.0","prettier":"^2.3.2","rimraf":"^3.0.2","socket.io-client":"4.5.4","socket.io-client-v2":"npm:socket.io-client@^2.4.0","superagent":"^8.0.0","supertest":"^6.1.6","ts-node":"^10.2.1","tsd":"^0.21.0","typescript":"^4.4.2","uWebSockets.js":"github:uNetworking/uWebSockets.js#v20.0.0"},"contributors":[{"name":"Guillermo Rauch","email":"rauchg@gmail.com"},{"name":"Arnout Kazemier","email":"info@3rd-eden.com"},{"name":"Vladimir Dronnikov","email":"dronnikov@gmail.com"},{"name":"Einar Otto Stangvik","email":"einaros@gmail.com"}],"engines":{"node":">=10.0.0"},"tsd":{"directory":"test"}}')},function(t,e,i){const r=i(0);t.exports=class{constructor(t){this.keyLimit=100,this.bodyLimit=20<<20,this.contentType=null,this.timeout=1e4,t&&this.fromOptions(t)}fromOptions(t){return r(t),null!=t.keyLimit&&(r("number"==typeof t.keyLimit),this.keyLimit=t.keyLimit),null!=t.bodyLimit&&(r("number"==typeof t.bodyLimit),this.bodyLimit=t.bodyLimit),null!=t.contentType&&(r("string"==typeof t.contentType),this.contentType=t.contentType),this}}},function(t,e,i){const r=i(679),s=i(625).StringDecoder;t.exports=async function(t,e){let i=Object.create(null);if("GET"!==t.method){let h=t.contentType;if("bin"!==(h=e.contentType?e.contentType:h)){var n=await(a=t,o="utf8",c=e,new Promise((t,e)=>{{var i=a,r=c,n=t,h=e;const u=new s(o);let l=!1,p=0,d="";const f=()=>{i.removeListener("data",m),i.removeListener("error",g),i.removeListener("end",y),null!=v&&(v=null,clearTimeout(v))},m=t=>{p+=t.length,l=!0,p>r.bodyLimit?h(new Error("Request body overflow.")):d+=u.write(t)},g=t=>{f(),h(t)},y=()=>{f(),n(l?d:null)};let v=setTimeout(()=>{v=null,f(),h(new Error("Request body timed out."))},r.timeout);i.on("data",m),i.on("error",g),i.on("end",y)}}));if(n)switch(h){case"json":if(!(i=JSON.parse(n))||"object"!=typeof i||Array.isArray(i))throw new Error("JSON body must be an object.");break;case"form":i=r.parsePairs(n,e.keyLimit)}}}var a,o,c;return i}},function(t,e,i){const{generateKey:r,verifyObj:s}=i(63),n=i(69),a=i(7);t.exports=class{constructor(t){this.wdb=t}async call(t,e,i){try{var o,c=e.body.sig,h=n.getHmac(e.options.cid||"",this.wdb.keys.hmacSalt).token,u=r(a.hash256(Buffer.from(h)));if(!this.wdb.options.devMode&&!s({method:e.body.method,params:e.body.params,cid:e.body.cid,wid:e.body.wid},c,u.public))return o={result:null,code:404,error:{type:"HmacError",message:"Verify Error"}},i.send(404,o,"json"),{interrupt:!0,result:null};if(!(e.options.auth&&e.options.authWid==e.options.wid||(this.wdb.options.devMode||await this.wdb.auth(e.options.cid,e.options.token),e.body.method&&"wallet.create"===e.body.method))){var l=await this.wdb.get(e.options.wid);if(!l)return i.send(404,{result:null,code:404,error:{type:"HmacError",message:"Not Found Wallet"}},"json"),{interrupt:!0,result:null};this.wdb.logger.info("Successful auth for %s on %s.",e.options.cid,e.options.wid),e.options.auth=!0,e.options.authWid=e.options.wid,e.wallet=l}return{interrupt:!1}}catch(t){return this.wdb.logger.info("Auth failure for %s on %s: %s.",e.options.cid,e.options.wid,t.message),i.send(403,{result:null,code:403,error:{type:"HmacError",message:"Hmac Auth failure."}},"json"),{interrupt:!0,result:null}}}}},function(t,e){t.exports=class{async call(t,e,i){return t.node.config.devMode||t.node.acl.canAccess(e.body.method,e.options.cid)?{interrupt:!1}:(i.send(407,{result:null,code:407,error:{type:"ACLError",message:"TerminalNo Authentication Required."}},"json"),{interrupt:!0,result:null})}}},function(t,e){t.exports=class{constructor(t,e){this.routes=t,this.openapi=e}async call(t,e,i){switch(e.options.mode){case"web":if(0===e.pathname.indexOf("/public/")){var r=this.routes.getHandlers(e.method);if(!r)return{interrupt:!0,result:null};for(const n of r){var s=n.match(e.pathname);if(s){e.params=s;try{return{interrupt:!0,result:{code:0,error:null,result:await n.call(e,i)}}}catch(t){i.error(500,t)}return{interrupt:!0,result:null}}}}else if(r=this.openapi[e.body.method]){try{return{interrupt:!0,result:{code:0,error:null,result:await t.node.conn_s2local.execute(r.name,e.body.params,e)}}}catch(t){i.error(500,t)}return{interrupt:!0,result:null}}break;case"ws":if(r=this.openapi[e.body.method])return{interrupt:!0,result:{code:0,error:null,result:await t.node.conn_s2local.execute(r.name,e.body.params,e)}}}return{interrupt:!1}}}},function(t,e,i){const r=i(0),s=i(1),n=i(7),a=i(160);t.exports=class{constructor(t){r(t,"Basic auth requires options."),this.user=t.username,this.pass=t.password,this.realm=t.realm,null!=this.user&&(r("string"==typeof this.user),r(this.user.length<=255,"Username too long."),r(s.isAscii(this.user),"Username must be ASCII."),this.user=n.hash256(Buffer.from(this.user,"ascii"))),r("string"==typeof this.pass),r(this.pass.length<=255,"Password too long."),r(s.isAscii(this.pass),"Password must be ASCII."),this.pass=n.hash256(Buffer.from(this.pass,"ascii")),this.realm||(this.realm="server"),r("string"==typeof this.realm)}fail(t){t.setHeader("WWW-Authenticate",`Basic realm="${this.realm}"`),t.send(401,{result:null,code:401,error:{type:"AuthError",message:"Unauthorized."}},"json"),t.end()}async call(t,e,i){if(!t.node.config.devMode&&!e.options.auth){if(this.user){if(255<e.options.user.username.length)return this.fail(i),{interrupt:!0,result:null};const t=Buffer.from(e.options.user.username,"ascii"),r=n.hash256(t);if(!a(r,this.user))return this.fail(i),{interrupt:!0,result:null}}if(!e.options.user||!e.options.user.password||255<e.options.user.password.length)return this.fail(i),{interrupt:!0,result:null};const t=Buffer.from(e.options.user.password,"ascii"),r=n.hash256(t);if(!a(r,this.pass))return this.fail(i),{interrupt:!0,result:null};e.options.auth=!0}return{interrupt:!1}}}},function(t,e,i){const r=i(1),s=i(77),n=i(78).errors,a=i(84),o=i(120),{getBlockOverview:c,getBlockByHash:h,formatTimestamp:u}=i(626);t.exports=[{name:"blocks",method:"get",path:"/public/blocks",callback:async function(t,e){var i,r=(t=t.valid()).str("blockDate"),s=t.str("startTimestamp",""),n=(t=t.uint("limit",10),u(new Date));if(r){if(!/\d{4}-\d{2}-\d{2}/.test(r))throw new Error("Please use yyyy-mm-dd format");i=r===n}else r=n,i=!0;n=Math.round(new Date(r).getTime()/1e3),s=parseInt(s)||n+86400;var a=u(new Date(1e3*(n-86400))),o=s?u(new Date(1e3*s)):null,c=(t=parseInt(t||200),!1),l=s;try{var p,d=await this.chain.db.getTimestampHashes(s,n);let u=[];for(p of d)u.push(p.hash);u.reverse(),u.length>t&&(c=!0,u=u.slice(0,t));var f,m={blocks:[],length:u.length,pagination:{next:o,prev:a,currentTs:s-1,current:r,isToday:i,more:c,moreTs:c?l:void 0}};for(f of u){var g=await h(this,f,e);m.blocks.push(g)}return m.blocks.sort((t,e)=>e.height-t.height),m}catch(t){throw t}}},{name:"block-index",method:"get",path:"/public/block-index/:height",callback:async function(t,e){var i=this;if(-1===(t=(t=t.valid()).uint("height")))throw new s(n.TYPE_ERROR,"Invalid block height.");if(!(t=await i.chain.getEntry(t)))throw new s(n.MISC_ERROR,"Block not found");if(i=await h(i.node,t.hash,e))return i}},{name:"block-tip",method:"get",path:"/public/block-tip",callback:async function(t,e){var i=this;if(t.valid(),!(t=await i.chain.tip))throw new s(n.MISC_ERROR,"Block not found");if(i=await h(i.node,t.hash,e))return i}},{name:"block",method:"get",path:"/public/block/:blockHash",callback:async function(t,e){var i=this;if(t=(t=t.valid()).str("blockHash"),i=await h(i.node,t,e))return i}},{name:"getBlock",method:"jsonp",path:"/",callback:async function(t,e){return e=(e=new a([e])).str(0),h(t,e)}},{name:"rawblock",method:"get",path:"/public/rawblock/:param",callback:async function(t,e){var i=this;let a=(t=t.valid()).str("param");if(a=r.checkNum(a)?parseInt(a):r.revHex(a),t=await i.chain.getBlock(a))return t.toRaw().toString("hex");if(i.chain.options.spv)throw new s(n.MISC_ERROR,"Block not available (spv mode)");if(i.chain.options.prune)throw new s(n.MISC_ERROR,"Block not available (pruned data)");throw new s(n.DATABASE_ERROR,"Can't read block from disk")}},{name:"getRawBlock",method:"jsonp",path:"/",callback:async function(t,e){let i=(e=new a([e])).str(0);return r.checkNum(i)&&(i=parseInt(i)),(e=await t.chain.getBlock(i))?e.toRaw().toString("hex"):null}},{name:"isSynced",method:"jsonp",path:"/",callback:async function(t,e){return t.chain.synced}},{name:"getBlockOverview",method:"jsonp",path:"/",callback:async function(t,e){return e=(e=new a([e])).str(0),c(t,e)}},{name:"getInfo",method:"jsonp",path:"/",callback:async function(t,e){var i=await t.rpc.execute({corba:!0,method:"miner.difficulty"});return{blocks:t.chain.height,connections:t.pool.peers.size(),timeoffset:0,proxy:"",testnet:"main"!==t.network.type,errors:"",network:t.network.type,relayFee:0,version:"bitcore-1.1.2",protocolversion:700001,difficulty:i}}},{name:"getBestHeight",method:"jsonp",path:"/",callback:async function(t,e){return t.chain.height}},{name:"getBlockHeader",method:"jsonp",path:"/",callback:async function(t,e){var i=(e=new a([e])).hash(0);e=e.bool(1,!0);if(!i)throw new s(n.MISC_ERROR,"Invalid block hash.");if(!(i=await t.chain.getEntry(i)))throw new s(n.MISC_ERROR,"Block not found");if(!e)return i.toRaw().toString("hex",0,80);e=await t.chain.getMedianTime(i);var c=await t.chain.getNextHash(i.hash);return{hash:i.rhash(),confirmations:t.chain.height-i.height+1,height:i.height,version:i.version,versionHex:r.hex32(i.version),merkleroot:r.revHex(i.merkleRoot),time:i.time,mediantime:e,bits:i.bits,difficulty:o.bits2Diff(i.bits),chainwork:i.chainwork.toString("hex",64),previousblockhash:i.prevBlock!==encoding.NULL_HASH?r.revHex(i.prevBlock):null,nextblockhash:c?r.revHex(c):null}}}]},function(t){t.exports=JSON.parse('[{"poolName":"50BTC","url":"https://50btc.com/","searchStrings":["50BTC.com","50btc.com"]},{"poolName":"175btc","url":"http://www.175btc.com/","searchStrings":["Mined By 175btc.com"]},{"poolName":"ASICminer","url":"https://bitcointalk.org/index.php?topic=99497.0","searchStrings":["Mined By ASICMiner"]},{"poolName":"AntMiner","url":"https://bitmaintech.com/","searchStrings":["AntPool"]},{"poolName":"agentD","url":"http://","searchStrings":["agentD"]},{"poolName":"Bitfury","url":"http://bitfury.org/","searchStrings":["2av0id51pct"]},{"poolName":"BitMinter","url":"https://bitminter.com/","searchStrings":["BitMinter"]},{"poolName":"Bitparking","url":"http://bitparking.com/","searchStrings":["bitparking"]},{"poolName":"BTC Guild","url":"https://www.btcguild.com/","searchStrings":["Mined by BTC Guild","BTC Guild"]},{"poolName":"bcpool.io","url":"https://bcpool.io/","searchStrings":["bcpool"]},{"poolName":"Discus Fish","url":"http://f2pool.com/","searchStrings":["七彩神仙鱼","Made in China","Mined by user"]},{"poolName":"Discus Fish Solo","url":"http://f2pool.com/","searchStrings":["For Pierce and Paul"]},{"poolName":"Cointerra","url":"http://cointerra.com/","searchStrings":["cointerra"]},{"poolName":"Eligius","url":"http://eligius.st/","searchStrings":["Eligius"]},{"poolName":"EclipseMC","url":"https://eclipsemc.com/","searchStrings":["Josh Zerlan was here!","EclipseMC","Aluminum Falcon"]},{"poolName":"GIVE-ME-COINS","url":"https://give-me-coins.com/","searchStrings":["Mined at GIVE-ME-COINS.com"]},{"poolName":"ghash.io","url":"https://ghash.io/","searchStrings":["ghash.io","GHash.IO"]},{"poolName":"HHTT","url":"http://hhtt.1209k.com/","searchStrings":["HHTT"]},{"poolName":"KNCminer","url":"https://www.kncminer.com/","searchStrings":["KnCMiner"]},{"poolName":"Megabigpower","url":"http://megabigpower.com/","searchStrings":["megabigpower.com"]},{"poolName":"MultiCoin","url":"https://multicoin.co/","searchStrings":["MultiCoin.co"]},{"poolName":"Mt Red","url":"https://mtred.com/‎","searchStrings":["/mtred/"]},{"poolName":"MaxBTC","url":"https://www.maxbtc.com","searchStrings":["MaxBTC"]},{"poolName":"NMCbit","url":"http://nmcbit.com/","searchStrings":["nmcbit.com"]},{"poolName":"ozcoin","url":"https://ozco.in/","searchStrings":["ozco.in","ozcoin"]},{"poolName":"Polmine.pl","url":"https://polmine.pl","searchStrings":["by polmine.pl"]},{"poolName":"simplecoin","url":"http://simplecoin.us/","searchStrings":["simplecoin.us ftw"]},{"poolName":"SlushPool","url":"https://slushpool.com/","searchStrings":["/slush/"]},{"poolName":"TripleMining","url":"https://www.triplemining.com/","searchStrings":["Triplemining.com"]},{"poolName":"wizkid057","url":"http://wizkid057.com/btc","searchStrings":["wizkid057"]},{"poolName":"Yourbtc.net","url":"http://yourbtc.net/","searchStrings":["yourbtc.net"]},{"poolName":"BTCChina Pool","url":"https://pool.btcchina.com/","searchStrings":["BTCChina Pool","btcchina.com"]},{"poolName":"BTCC Pool","url":"https://pool.btcc.com/","searchStrings":["/BTCC/"]}]')},function(t,e,i){const{utxo:r,_setOutputResults:s,_setInputResults:n,transformTransaction:a,getDetailFromMeta:o,translateOutputAddress:c}=i(626),h=i(33),u=i(84),l=i(1);async function p(t,e){var i=(e=new u([e])).array(0,[]),r=e.obj(1,{}),s=(r.from=r.from||0,r.to=r.to||4294967295,[]);e=await t.getMetaByAddress(i);let n=0;for(const i of e){if(n<r.from);else{if(n>=r.to)break;var a=await o(t,i);s.push(a)}n++}return{totalCount:e.length,items:s}}async function d(t,e){let i=(r=t.valid()).str("addr");i=i||r.str("addrs");var r,s=((r={from:parseInt(t.query.from)||parseInt(t.body.from)||0}).to=parseInt(t.query.to)||parseInt(t.body.to)||parseInt(r.from)+10,t=t,{noAsm:!!parseInt(t.query.noAsm),noScriptSig:!!parseInt(t.query.noScriptSig),noSpent:!!parseInt(t.query.noSpent)});try{var n,c=await this.node.getMetaByAddress(i.split(",")),h=[];for(n of c){var u=await o(this.node,n);h.push(await a(this.node,u,s))}return{totalItems:c.length,from:r.from,to:Math.min(r.to,c.length),items:h}}catch(t){throw t}}async function f(t,e){var i=t.valid();let s=i.str("addr");s=s||i.str("addrs"),t.query.from&&t.query.to&&(parseInt(t.query.from),parseInt(t.query.to));try{var n,a=[];for(n of await r(this.node,s.split(",")))a.push(function(t,e){var i={address:c(e.address),txid:l.revHex(e.txid),vout:e.vout,scriptPubKey:e.scriptPubKey,amount:e.satoshis/1e8,satoshis:e.satoshis};return e.height&&0<e.height?(i.height=e.height,i.confirmations=t.chain.height-e.height+1):i.confirmations=0,e.timestamp&&(i.ts=e.timestamp),i}(this,n));return a}catch(t){throw t}}async function m(t,e){var i=(t=t.valid()).str("id"),r=(t=t.uint("index",1),this.node.require("walletdb"));if(r&&(r=await r.get("primary"),await r.ensureAccount({name:i,witness:!0}),r=await r.createReceive(i,t)))return r.toJSON().address}async function g(t,e,i){i=i||{};var r={totalCount:0,items:[]};let a=0;for(const s of await t.node.getMetaByAddress(e)){if(i.from&&a<i.from);else{if(i.to&&a>=i.to)break;var u=await o(t.node,s);r.items.push(u)}a++}r.totalCount=r.items.length;for(var p={addrStr:e,balance:0,balanceSat:0,totalReceived:0,totalReceivedSat:0,totalSent:0,totalSentSat:0,unconfirmedBalance:0,unconfirmedBalanceSat:0,unconfirmedTxApperances:0,txApperances:0},d=0;d<r.items.length;d++){var f=r.items[d];s(t,f,e,p),n(t,f,e,p),i.noTxList||(p.transactions||(p.transactions=[]),p.transactions.push(l.revHex(f.txid())))}return p.balance=h.fromSatoshis(p.balanceSat).toBTC(),p.totalReceived=h.fromSatoshis(p.totalReceivedSat).toBTC(),p.totalSent=h.fromSatoshis(p.totalSentSat).toBTC(),p.unconfirmedBalance=h.fromSatoshis(p.unconfirmedBalanceSat).toBTC(),p.addrStr&&(p.addrStr=c(p.addrStr)),p}t.exports=[{name:"address.reflect",method:"get",path:"/public/addr/reflect/:id",callback:m},{name:"address.reflect.index",method:"get",path:"/public/addr/reflect/:id/:index",callback:m},{name:"getInfo",method:"get",path:"/public/addr/:addr",callback:async function(t,e){var i=(i=t.valid()).str("addr"),r={noTxList:parseInt(t.query.noTxList)};t.query.from&&t.query.to?(r.from=parseInt(t.query.from),r.to=parseInt(t.query.to)):(r.from=0,r.to=10);try{return await g(this,i,r)}catch(t){throw t}}},{name:"getUTXOByAddress",method:"get",path:"/public/addr/:addr/utxo",callback:f},{name:"getUTXOByAddresses",method:"get",path:"/public/addrs/:addr/utxo",callback:f},{name:"postUTXOByAddresses",method:"post",path:"/public/addrs/utxo",callback:f},{name:"getTXSByAddresses",method:"get",path:"/public/addrs/:addrs/txs",callback:d},{name:"postTXSByAddresses",method:"post",path:"/public/addrs/txs",callback:d},{name:"getBalanceByAddress",method:"get",path:"/public/addr/:addr/balance",callback:async function(t,e){var i=this;let r=(t=t.valid()).str("addr");r=r||t.str("addrs"),t=await i.node.getCoinsByAddress(r.split(","));var s=(i=t.reduce((t,e)=>t+e.value,0))-(t=t.reduce((t,e)=>(-1==e.height&&(t+=e.value),t),0));return{confirmed:h.fromSatoshis(s).toBTC(),unconfirmed:h.fromSatoshis(t).toBTC(),balance:h.fromSatoshis(i).toBTC()}}},{name:"getUnconfirmedBalance",method:"get",path:"/public/addr/:addr/unconfirmedBalance",callback:async function(t,e){var i=this;let r=(t=t.valid()).str("addr");return r=r||t.str("addrs"),t=await i.node.getCoinsByAddress(r.split(",")),i=t.reduce((t,e)=>(-1==e.height&&(t+=e.value),t),0),h.fromSatoshis(i).toBTC()}},{name:"getTotalReceived",method:"get",path:"/public/addr/:addr/totalReceived",callback:async function(t,e){let i=(t=t.valid()).str("addr");i=i||t.str("addrs");try{return(await g(this,i)).totalReceivedSat}catch(t){throw t}}},{name:"getTotalSent",method:"get",path:"/public/addr/:addr/totalSent",callback:async function(t,e){let i=(t=t.valid()).str("addr");i=i||t.str("addrs");try{return(await g(this,i)).totalSent}catch(t){throw t}}},{name:"getAddressHistory",method:"jsonp",path:"/",callback:p},{name:"getAddressSummary",method:"jsonp",path:"/",callback:async function(t,e){var i=new u([e]),r=i.array(0,[]),a=i.obj(1,{});a.from=a.from||0,a.to=a.to||4294967295;for(var o={addrStr:r,balance:0,balanceSat:0,totalReceived:0,totalReceivedSat:0,totalSent:0,totalSentSat:0,unconfirmedBalance:0,unconfirmedBalanceSat:0,unconfirmedTxApperances:0,txApperances:0},c=(i=await p(t,e)).items,l=0;l<c.length;l++){var d=c[l];s(t,d,r,o),n(t,d,r,o),a.noTxList||(o.transactions||(o.transactions=[]),o.transactions.push(d.txid()))}return o.balance=h.fromSatoshis(o.balanceSat).toBTC(),o.totalReceived=h.fromSatoshis(o.totalReceivedSat).toBTC(),o.totalSent=h.fromSatoshis(o.totalSentSat).toBTC(),o.unconfirmedBalance=h.fromSatoshis(o.unconfirmedBalanceSat).toBTC(),o}},{name:"getAddressUnspentOutputs",method:"jsonp",path:"/",callback:async function(t,e){return e=(e=new u([e])).array(0,[]),t=await r(t,e)}},{name:"getTxidsByAddress",method:"jsonp",path:"/",callback:async function(t,e){var i=(e=new u([e])).array(0);e=e.str(1,"both");return t.chain.getHashesByAddress(i,e)}}]},function(t,e,i){var r=i(82);const s=i(33),n=i(84);var a=i(334),o=0,c=Date.now();async function h(t){var e=await t.rpc.execute({corba:!0,method:"miner.difficulty"});return{blocks:t.chain.height,connections:t.node.pool.peers.size,timeoffset:0,proxy:"",testnet:"main"!==t.node.network.type,errors:"",network:t.node.network.type,relayFee:0,version:"gamegold-"+r.version,protocolversion:700001,difficulty:e}}t.exports=[{name:"getStatus",method:"get",path:"/public/status",callback:async function(t,e){switch(t.query.q){case"getDifficulty":try{return{difficulty:(await h(this)).difficulty}}catch(t){throw t}break;case"getLastBlockHash":var i=await this.chain.db.getTip();return{syncTipHash:i.hash,lastblockhash:i.hash};case"getBestBlockHash":try{return{bestblockhash:await this.rpc.execute({corba:!0,method:"block.best"})}}catch(t){throw t}break;default:try{return{info:await h(this)}}catch(t){throw t}}}},{name:"getSync",method:"get",path:"/public/sync",callback:async function(t,e){var i="syncing";try{this.chain.synced&&(i="finished");var r=(100*this.chain.getProgress()).toFixed(2);return{status:i,blockChainHeight:this.chain.height,syncPercentage:Math.round(r),height:this.chain.height,error:null,type:"gamegold node"}}catch(t){throw t}}},{name:"getVersion",method:"get",path:"/public/version",callback:async function(t,e){return{version:r.version}}},{name:"getPeer",method:"get",path:"/public/peer",callback:function(t,e){var i=this.pool.getLoader()||{connected:!1,address:{host:null,port:null}};return{connected:i.connected,host:i.address.host,port:i.address.port}}},{name:"getEstimateFee",method:"get",path:"/public/utils/estimatefee",callback:function(t,e){t=(t.query.nbBlocks||"2").split(",");try{var i,r={};for(i of t){var n=parseInt(i);let t=this.fees.estimateFee(n,!1);0===t&&(t=-1),t=s.btc(t,!0),r[n]=t}return r}catch(t){throw t}}},{name:"estimateFee",method:"jsonp",path:"/",callback:function(t,e){e=(e=new n([e])).array(0,["2"]);try{var i,r={};for(i of e){var a=parseInt(i);let e=t.fees.estimateFee(a,!1);0===e&&(e=-1),e=s.btc(e,!0),r[a]=e}return r}catch(e){throw e}}},{name:"currency",method:"get",path:"/public/currency",callback:async function(t,e){var i=Date.now();if(!(0===o||c+6e5<=i))return{status:200,data:{bitstamp:o}};c=i;try{var r=await new Promise((t,e)=>{a("https://www.bitstamp.net/api/ticker/",(function(i,r,s){i&&e(i),i||200!==r.statusCode||t(s)}))});return{status:200,data:{bitstamp:o=parseFloat(JSON.parse(r).last)}}}catch(t){throw t}}},{name:"explorers",method:"get",path:"/public/explorers",callback:async function(t,e){return[{name:"gamegold",ticker:"GG",url:"https://insight.gamegold.xin"}]}},{name:"syncPercentage",method:"jsonp",path:"/",callback:async function(t,e){return Math.round((100*t.chain.getProgress()).toFixed(2))}},{name:"sysEcho",method:"jsonp",path:"/",callback:function(t,e){return 0}},{name:"getBestBlockHash",method:"jsonp",path:"/",callback:async function(t,e){return{bestblockhash:t=await t.rpc.execute({corba:!0,method:"block.best"})}}}]},function(t,e,i){const r=i(682),s=i(0),n=i(1),{handleErrors:a,getDetailedTransaction:o,transformTransaction:c,getDetailFromMeta:h,getBlockOverview:u,translateInputAddresses:l}=i(626),p=i(84);t.exports=[{name:"getTx",method:"get",path:"/public/tx/:txid",callback:async function(t,e){return t=(t=t.valid()).hash("txid"),(t=await o(this.node,t))?await c(this.node,t,{}):null}},{name:"getRawTx",method:"get",path:"/public/rawtx/:txid",callback:async function(t,e){return t=(t=t.valid()).str("txid"),{rawtx:t=await this.rpc.execute({method:"tx.raw.get",params:[t]})}}},{name:"getList",method:"get",path:"/public/txs",callback:async function(t,e){s(!this.chain.options.spv,"Cannot get TX in SPV mode.");var i,p=t.query.blockHash,d=l(t.query.address),f=(t=parseInt(t.query.pageNum)||0,1);if(p){if(!(p=await u(this.node,p,e)))return a(null,e);e=p.txids.length;var m,g,y=(r.isUndefined(t)?i=p.txids:(m=10*t,i=p.txids.slice(m,10+m),f=Math.ceil(e/10)),[]);for(g of i){var v=await o(this.node,n.revHex(g));v&&y.push(await c(this.node,v,{}))}return{pagesTotal:f,txs:y}}if(d){var w=10*t,b=10*(t+1),k=[];p=await this.node.getMetaByAddress(d);let e=0;for(const t of p){if(e<w);else{if(e>=b)break;var x=await h(this.node,t);k.push(await c(this.node,x,{}))}e++}return{pagesTotal:Math.ceil(p.length/10),txs:k}}throw new Error("Block hash or address expected")}},{name:"getDetailedTransaction",method:"jsonp",path:"/",callback:async function(t,e){return e=(e=new p([e])).hash(0),o(t,e,!0)}},{name:"getTransaction",method:"jsonp",path:"/",callback:async function(t,e){return e=(e=new p([e])).hash(0),t=await o(t,e,!1)}},{name:"getRawTransaction",method:"jsonp",path:"/",callback:async function(t,e){return e=(e=new p([e])).str(0),t=await t.rpc.execute({method:"tx.raw.get",params:[e]})}},{name:"getMempoolTransaction",method:"jsonp",path:"/",callback:async function(t,e){return e=(e=new p([e])).hash(0),t.mempool.getTX(e)}}]},function(t,e,i){const r=i(21).opcodes,s=i(1).revHex;t.exports=[{name:"prop.get",method:"get",path:"/public/prop/:pid",callback:async function(t,e){var i=[];t=t.valid().str("pid");if(t=await this.node.chain.db.propList.getVp(t)){var n=t.current.hash;t.oper="exchange",i.push({oper:"exchange",pid:t.pid,oid:t.oid,cid:t.cid,current:{hash:s(t.current.hash),index:t.current.index,address:t.current.address},height:t.height});let e=[n,t.current.index];for(;;){var a=await this.node.getMeta(e[0]),o=a.tx;if(!o)break;if(!(o=o.outputs[e[1]]))break;var c=o.getReturnData([r.OP_PROPCREATE,r.OP_PROPEXCHANGE]);if(!c)break;if("new"==c.oper){c.current={hash:s(e[0]),index:e[1],address:o.getAddress().toString()},c.height=a.height,i.push(c);break}if(!c.prev)break;e=[c.prev.hash,c.prev.index]}}return i}},{name:"queryProps",method:"post",path:"/public/prop/query",callback:async function(t,e){var i=(t=t.valid()).str("game_id");t=t.str("user_addr");return await this.node.queryProps(i,t)}},{name:"queryProps",method:"get",path:"/public/prop/:game_id/addr/:user_addr",callback:async function(t,e){var i=(t=t.valid()).str("game_id");t=t.str("user_addr");return await this.node.queryProps(i,t)}},{name:"queryProps",method:"get",path:"/public/props/query",callback:async function(t,e){var i=(t=t.valid()).str("pid"),r=t.str("cid"),s=t.str("oid"),n=t.str("addr");t=t.str("page");return await this.node.queryProps(r,n,i,s,t)}}]},function(t,e,i){const r=i(84);t.exports=[{name:"cp.remoteQuery",method:"jsonp",path:"/",callback:async function(t,e){return e=(e=new r([e])).array(0,[]),t.chain.db.cpList.query(e)},remoteCb:async function(t){if(t&&Array.isArray(t.list))for(var e of t.list)this.wdb.cpList.getItem(e.cid)||await this.wdb.cpList.addItem(e);return t}},{name:"cps",method:"get",path:"/public/cps",callback:async function(t,e){return t={page:t.valid().u32("page",1),pageCount:0},{list:this.chain.db.cpList.getCPList([],t),cur:t.page,page:t.pageCount}}},{name:"cpById",method:"get",path:"/public/cp/:id",callback:async function(t,e){var i=(t=t.valid()).u32("page",1);t=t.str("id");return(t=this.chain.db.cpList.getCPList(t?[t]:[],{page:i}))&&0<t.length?t[0]:null}},{name:"cpByName",method:"get",path:"/public/cp/name/:name",callback:async function(t,e){var i=(t=t.valid()).u32("page",1);t=decodeURIComponent(t.str("name"));return(t=this.chain.db.cpList.getCPListByName(t?[t]:[],{page:i}))&&0<t.length?t[0]:null}}]},function(t,e){t.exports=[{name:"queryStockHolder",method:"get",path:"/public/stock/holder",callback:async function(t,e){var i=(t=t.valid()).str("cid");t=t.str("page");return this.node.queryStockHolder(i,t)}},{name:"queryStockRecord",method:"get",path:"/public/stock/record",callback:async function(t,e){var i=(t=t.valid()).str("type"),r=t.str("cid");t=t.str("page");return this.node.queryStockRecord(i,r,t)}}]},function(t,e,i){const r=i(84),s=i(101),n=i(77),a=i(78).errors,o=i(69),c=i(5).ContractStatus,h=i(19),u=i(33);t.exports=[{name:"token.random",local:!0,method:"jsonp",path:"/",callback:async function(t,e,i){if(1!==e.length)throw new n(a.MISC_ERROR,"token.random clientNo: 生成令牌随机量 终端编码");return e=new r([e]).str(0),e=o.getHmac(e,t.keys.hmacSalt).random}},{name:"mempool.watch",method:"jsonp",path:"/",callback:async function(t,e,i){i&&i.join("mempool")}},{name:"mempool.unwatch",method:"jsonp",path:"/",callback:async function(t,e,i){i&&i.leave("mempool")}},{name:"chain.watch",method:"jsonp",path:"/",callback:async function(t,e,i){i&&i.join("chain")}},{name:"chain.unwatch",method:"jsonp",path:"/",callback:async function(t,e,i){i&&i.leave("chain")}},{name:"chain.rescan",method:"jsonp",path:"/",callback:async function(t,e,i){if(null==(e=new r([e]).numhash(0)))throw new Error("Invalid parameter.");return t.http.scan(i,e)}},{name:"subscribe",local:!0,method:"jsonp",path:"/",callback:async function(t,e,i){if(i&&Array.isArray(e))for(var r of e)i.bus.subscribe(r);return!0}},{name:"unsubscribe",local:!0,method:"jsonp",path:"/",callback:async function(t,e,i){if(i&&Array.isArray(e))for(var r of e)i.bus.unsubscribe(r);return!0}},{name:"filter.set",local:!0,method:"jsonp",path:"/",callback:async function(t,e,i){if(i){if(e=new r([e]).buf(0))return i.filter=s.fromRaw(e),null;throw new Error("Invalid parameter.")}}},{name:"filter.reset",local:!0,method:"jsonp",path:"/",callback:async function(t,e,i){i&&(i.filter=null)}},{name:"filter.add",local:!0,method:"jsonp",path:"/",callback:async function(t,e,i){if(i){var s=new r([e]).array(0);if(!s)throw new Error("Invalid parameter.");if(!i.filter)throw new Error("No filter set.");var n=new r([s]);for(let e=0;e<s.length;e++){var a=n.buf(e);if(!a)throw new Error("Bad data chunk.");i.filter.add(a),t.spv&&t.pool.watch(a)}}}},{name:"canExecute",method:"jsonp",path:"/",callback:async function(t,e){return(e=new r([e]).obj(0,{})).confirm||"cpChange"==e.oper?t.chain.db.cpList.canExecute(e):await t.mempool.cpMemList.canExecute(e)&&await t.chain.db.cpList.canExecute(e)}},{name:"stock.record",method:"jsonp",path:"/",callback:async function(t,e,i){var s=(e=new r([e])).uint(0,0),n=e.str(1),a=e.uint(2,0);e=e.array(3,[]);let o=null;return(s?await t.chain.db.getStockRecord(s,n,a):await t.chain.db.getStockRecordByCid(n,a)).query(e)},remoteCb:async function(t){if(t&&Array.isArray(t))for(var e of t)await this.wdb.setStockRecord(e);return t}},{name:"contract.list",method:"jsonp",path:"/",callback:async function(t,e){var i,s,n,a;return 0==e.length?"contract.list type page ids size: 查询并返回交易对 交易类型 指定查询的ID数组 页码":(a=(e=new r([e])).uint(0,1),i=e.uint(1,1),s=e.array(2,[]),e=e.int(3,10),(n=[]).push(["transStatus",c.CreatedOnMem]),a&&n.push(["type",a]),0<s.length&&n.push(["id","include",s]),{pageNum:(a=t.chain.db.transactionList.where(n).paginate(e,i)).pageNum,pageCur:a.pageCur,list:a.records()})},remoteCb:async function(t){if(t&&Array.isArray(t.list))for(var e of t.list)this.wdb.transactionList.saveContract(e,!0);return t}},{name:"queryProps",method:"jsonp",path:"/",callback:async function(t,e){var i=(e=new r([e])).str(0,"");e=e.str(1,"");return t.queryProps(i,e)}},{name:"block.tip",method:"jsonp",path:"/",callback:async function(t,e){return t.chain.tip.toRaw()}},{name:"block.entry",method:"jsonp",path:"/",callback:async function(t,e){if(null==(e=new r([e]).numhash(0)))throw new Error("Invalid parameter.");return(e=await t.chain.getEntry(e))&&await t.chain.isMainChain(e)?e.toRaw():null}},{name:"$tx.broadcast",method:"jsonp",path:"/",callback:async function(t,e,i){e=new r([e]).buf(0),e=h.fromRaw(e),await t.sendTX(e)}},{name:"$estimate.fee",method:"jsonp",path:"/",callback:async function(t,e){if(e=new r([e]).u32(0,1),t.fees)return 0===(t=t.fees.estimateFee(e,!1))?-1:u.btc(t,!0);throw new n(a.MISC_ERROR,"Fee estimation not available.")}}]},function(t,e,i){const r=i(84),s=i(785);t.exports=[{name:"ca.get",method:"get",path:"/public/ca/:erid",callback:async function(t,e){return t=t.valid().str("erid"),(t=await this.node.chain.db.erList.query([["erid",t]])).height=this.node.chain.height,t}},{name:"ca.rank",method:"jsonp",path:"/",callback:async function(t,e){return e=(e=new r([e])).str(0,""),(t=await(async t=>new Promise((e,i)=>{s(t,.85,1e-4,(function(t,r){t?i(t):e(r)}))}))(t.chain.db.enCpList.rank))[e]},remoteCb:async function(t){return t}},{name:"ca.list",method:"jsonp",path:"/",callback:async function(t,e){return e=(e=new r([e])).array(0,[]),(e=await t.chain.db.erList.query(e)).height=t.chain.height,e}},{name:"ca.verify",method:"jsonp",path:"/",callback:async function(t,e){return e=(e=new r([e])).str(0,""),(e=await t.chain.db.caVerify(e))&&(e.curHeight=t.chain.height),e},remoteCb:async function(t){return t}},{name:"ca.list.ab",method:"jsonp",path:"/",callback:async function(t,e){return e=(e=new r([e])).array(0,[]),t.chain.db.erAbList.query(e)},remoteCb:async function(t){return t}}]},function(t,e,i){"use strict";class r{constructor(t,e,i,r,s){this.outgoingNodes=t,this.linkProb=e,this.tolerance=i,this.callback=r,this.pageCount=Object.keys(this.outgoingNodes).length,this.coeff=(1-e)/this.pageCount,this.probabilityNodes=t instanceof Array?[]:{},this.incomingNodes=t instanceof Array?[]:{},this.debug=s,this.startRanking()}startRanking(){var t,e,i,r=1/this.pageCount,s=this.outgoingNodes;for(t in s)for(e in this.probabilityNodes[t]=r,s[t])i=s[t][e],this.incomingNodes[i]||(this.incomingNodes[i]=[]),this.incomingNodes[i].push(t);this.debug&&this.reportDebug(1),this.iterate(1)}reportDebug(t){console.log("____ITERATION "+t+"____"),console.log("Pages: "+Object.keys(this.outgoingNodes).length),console.log("outgoing %j",this.outgoingNodes),console.log("incoming %j",this.incomingNodes),console.log("probability %j",this.probabilityNodes)}iterate(t){var e,i,r,s,n,a=[],o={};for(e in this.probabilityNodes){if(r=0,this.incomingNodes[e])for(i=0;i<this.incomingNodes[e].length;i++)r+=this.probabilityNodes[this.incomingNodes[e][i]]/this.outgoingNodes[this.incomingNodes[e][i]].length;s=this.coeff+this.linkProb*r,n=this.probabilityNodes[e]+this.tolerance,this.probabilityNodes[e]-this.tolerance<=s&&s<=n&&a.push(o[e]=s),this.probabilityNodes[e]=s}return a.length==this.pageCount?this.outgoingNodes instanceof Array?this.callback(null,a):this.callback(null,o):(this.debug&&this.reportDebug(t),this.iterate(++t))}}t.exports=function(t,e,i,s,n=!1){if(t&&e&&i&&s)return new r(t,e,i,s,n);throw new Error("Provide 4 arguments: nodeMatrix, link probability, tolerance, callback")}},function(t,e,i){"use strict";t.exports=class{constructor(t){this.config=t,this.hmacConnection=this.config.array("hmac-connection")||[],this.config.hmacConnection=this.hmacConnection}add(t){-1==this.hmacConnection.indexOf(t)&&this.hmacConnection.push(t),this.config.hmacConnection=this.hmacConnection}del(t){-1!=(t=this.hmacConnection.indexOf(t))&&(this.hmacConnection.splice(t,1),this.config.hmacConnection=this.hmacConnection)}clear(){this.hmacConnection=[],this.config.hmacConnection=this.hmacConnection}content(){return this.hmacConnection}has(t){return-1!=this.hmacConnection.indexOf(t)}}},function(t,e,i){"use strict";
1714
1714
  /*!
1715
1715
  * mempool/index.js - mempool for vallnet
1716
1716
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gamegold",
3
- "version": "4.2.1",
3
+ "version": "4.2.3",
4
4
  "description": "Vallnet Core",
5
5
  "license": "MIT",
6
6
  "repository": "git://github.com/bookmansoft/gamegold",