gamegold 4.0.10 → 4.0.11

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.
@@ -194,7 +194,7 @@ let i=[];[r(561),r(562),r(563),r(564),r(565),r(566),r(567),r(568),r(569),r(570),
194
194
  * pkg.js - package constants
195
195
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
196
196
  * https://github.com/bookmansoft/gamegold
197
- */e.protocol="vallnet",e.version="v4.0.10",e.url="https://github.com/bookmansoft/gamegold"},function(t,e,r){"use strict";
197
+ */e.protocol="vallnet",e.version="v4.0.11",e.url="https://github.com/bookmansoft/gamegold"},function(t,e,r){"use strict";
198
198
  /*!
199
199
  * common.js - p2p constants for vallnet
200
200
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -836,7 +836,7 @@ const i=r(5).ContractType;t.exports=function(t){if(!t)return r(190);switch(t.ope
836
836
  /*!
837
837
  * accountdb.js - storage for account management
838
838
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
839
- */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),z=r(342),H=r(343),M=H.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),tt=Q.stockAccount,et=r(157),rt=et.ErItem,it=r(618),st=it.AuditItem,nt=r(315),at=r(110),ot=r(619),ct=r(316),ut=r(123),ht=r(620),lt=r(222),pt=r(39),dt=r(35),ft=r(59),mt=r(78).errors,gt=r(77);class yt extends j{constructor(t){super(),this.readyLoad=!1,this.options=new c(t),this.network=this.options.network,this.logger=this.options.logger.context("wallet"),this.workers=this.options.workers,this.keys={hmacSalt:N.DefaultChainCode},t.keys&&t.keys.hmacSalt&&(s(Buffer.isBuffer(t.keys.hmacSalt)),this.keys.hmacSalt=t.keys.hmacSalt),this.client=this.options.client,this.client&&(this.client.wdb=this),this.jsonp=this.options.jsonp,this.jsonp&&(this.jsonp.wdb=this),this.spv=this.options.spv,this.feeRate=this.options.feeRate,this.db=f(this.options),this.rpc=new L(this),this.primary=null,this.state=new ot,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 z(this),this.htlcList=new H(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 it(this),this.erList=new et(this),this.erAbList=new $(this),this.hmacConnection=[],this._init()}async logAudit(t){t.height=this.curHeight,t.time=C.now(),t.erid=l.sha256(C.stringify(t)).toString("hex"),t=new st(t),await this.auditList.setAudit(t)}async getAccountByAddress(t,e){if(t){let i=null;if(i=e?await this.getWalletsByTX(e):await this.getWallets())for(const e of i){const i=await this.get(e);if(i){var r=await i.getPath(t);if(r)return[i.wid,r.name,i.id]}}}return[0,"",""]}_init(){let t=1e6,e=-1;this.spv&&(t=2e4,e=B.flags.ALL),this.filter=B.fromRate(t,.001,e)}async getCpSnap(){return{}}get mode(){return _.Wallet}async getTXFromAll(t){return this.getTXFromDb(t)}async checkNewRecord(){var t={createIfMissing:this.db.options.createIfMissing,errorIfExists:this.db.options.errorIfExists};this.db.options.createIfMissing=!1,this.db.options.errorIfExists=!0;try{await this.db.open();var e=await this.db.checkVersion(h,6);this.newRecord="new"==e}catch(t){if(-1!=t.message.indexOf("does not exist (create_if_missing is false)"))this.newRecord=!0;else{if(-1==t.message.indexOf("exists (error_if_exists is true)"))throw t;this.newRecord=!1}}try{await this.db.close()}catch(t){}this.db.options.createIfMissing=t.createIfMissing,this.db.options.errorIfExists=t.errorIfExists}async isNewRecord(){return await this.checkNewRecord(),this.newRecord}setmnemonic(t){if(this.options.mnemonic=this.options.mnemonic||{},t.bits)this.options.mnemonic={bits:t.bits};else if(t.entropy)this.options.mnemonic={entropy:Buffer.from(t.entropy,"hex")};else if(t.phrase){var e=this.testmnemonic(t.phrase);if(0!=e.code)throw e.msg;this.options.mnemonic={phrase:t.phrase}}t.passphrase&&(this.options.mnemonic.passphrase=t.passphrase),t.language&&(this.options.mnemonic.language=t.language)}testmnemonic(t){try{return new w(t),{code:0}}catch(t){return{code:-1,msg:t.message}}}async getContracts(t){let e=await this.db.values({gte:u.txdb.tx(N.NULL_HASH),lte:u.txdb.tx(N.HIGH_HASH),parse:t=>C.parseJson(t.toString())});return t?e.filter(e=>e.srcact==t||e.dstact==t):e}isFull(){return this.spv||this.synced||!1}async _open(t){}async handleNotify(t,e=!1){if(!e){let r=t.body.content;if("string"==typeof r)try{r=JSON.parse(t.body.content)}catch(e){return}if("object"==typeof r&&"secret"===r.type){let e={contact:t.body.src,messenger:t.body.dst};r.init&&(e.init=Buffer.from(r.init,"hex")),r.packet&&(e.packet=Buffer.from(r.packet)),await this.handleSecret(e)}}}async handleSecret(t){if(t.contact&&t.messenger&&t.contact!=t.messenger){try{v.fromString(t.contact,this.network.type),v.fromString(t.messenger,this.network.type)}catch(t){return}let e=await this.ensureContact(t);e&&await e.ensureMessenger(t).answer(t)}}async scanContact(t,e=-1){var r=async t=>{var e;t.witness&&"witnesspubkeyhash"==t.getType()&&(e=t.witness.getPubkeyhashInput()[1],t=v.fromWitness(t.witness).toString(),e&&t&&await this.ensureContact({contact:t,publicKey:e}))};if(0<=e&&e<t.inputs.length)await r(t.inputs[e]);else for(var i of t.inputs)await r(i)}async ensureContact(t){if(!t.contact||t.contact==t.messenger)return null;try{v.fromString(t.contact,this.network.type),t.messenger&&v.fromString(t.messenger,this.network.type)}catch(t){return null}t.network=this.network.type,this.$contacts.get(t.contact)||this.$contacts.set(t.contact,new R(t));let e=this.$contacts.get(t.contact);if(t.messenger){let i=e.ensureMessenger(t);if(!i.wallet){var[t,r]=await this.getAccountByAddress(i.address);if(!(t=await this.get(t)))return;i.wallet=t,i.account=r}}return e}getCps(){return this.db.values({gte:u.txdb.cp(N.ZERO_CID,"hex"),lte:u.txdb.cp(N.MAX_CID,"hex"),parse:t=>W.fromRaw(t)})}async _close(){await this.disconnect(),this.http&&this.options.listen&&await this.http.close();for(const t of this.wallets.values())await t.destroy();await this.db.close(),this.options.listen&&await this.logger.close()}async destroy(){await this.db.destroy(),this.widCache.reset(),this.pathMapCache.reset()}async load(t){if(this.readyLoad){await this.txLock.lock();try{await this.init(t),await this.watch();let e=await this.ensure({id:"primary",witness:!0,mnemonic:this.options.mnemonic});await e.createReceive(0,1,e.master,this.network.type),await e.ensureNotifyKey(),await this.sync()}finally{e()}setTimeout(()=>{this.resend()},5e3)}}bind(){!this.client||this.bound||(this.bound=!0,this.client.hook("htlcassent.cancel",t=>{this.setAssent(t),this.emit("htlcassent.cancel",t)}),this.client.hook("htlcassent.deal",t=>{this.setAssent(t),this.emit("htlcassent.deal",t)}),this.client.hook("htlcassent.receive",t=>{this.setAssent(t),this.emit("htlcassent.receive",t)}),this.client.hook("htlcsuggest.cancel",t=>{this.setSuggest(t),this.emit("htlcsuggest.cancel",t)}),this.client.hook("htlcsuggest.deal",t=>{this.setSuggest(t),this.emit("htlcsuggest.deal",t)}),this.client.hook("htlcsuggest.receive",t=>{this.setSuggest(t),this.emit("htlcsuggest.receive",t)}),this.on("mssendpubk/receive",async t=>{let e=await this.get(t.addr);if(!e){e=await this.ensure({id:t.addr,type:"multisig",m:t.m,n:t.n,witness:!0});var[r,i]=await this.getAccountByAddress(t.addr);let s=await this.get(r);s&&await s.send({subtractFee:!1,sort:!1,outputs:[{address:t.contract,value:1e4}],comment:JSON.stringify({oper:"scrun",params:{oper:"pubk",addr:t.addr,puba:e.account.accountKey}})},i)}if(e.account.keys.length<e.account.n-1){var s;for(s of t.data.split(","))try{await e.addSharedKey(s)}catch(s){}if(e.account.keys.length==e.account.n-1){var[r,i]=await this.getAccountByAddress(t.addr);let s=await this.get(r);s&&await s.send({subtractFee:!1,sort:!1,outputs:[{address:t.contract,value:1e4}],comment:JSON.stringify({oper:"scrun",params:{oper:"puba",addr:t.addr,puba:e.account.receive.getAddress().toString()}})},i)}}}),this.on("mssendtx/receive",async t=>{let e=await this.get(t.addr);if(e&&e.account.type==o.types.MULTISIG){const r=b.fromRaw(t.data,"hex");r.view=await e.getCoinView(r),r.isSigned()||(t.txid=r.txid(),await this.saveMSTrans(t))}}),this.client.hook("onConnect",async()=>{await this.load()}),this.client.hook("error",t=>{this.emit("error",t)}),this.client.hook("block.connect",async(t,e)=>{try{await this.addBlock(t,e)}catch(t){this.emit("error",t)}}),this.client.hook("block.disconnect",async(t,e)=>{try{await this.removeBlock(t,e)}catch(t){this.emit("error",t)}}),this.client.hook("chain.full",()=>{this.synced=!0}),this.client.hook("block.rescan",async(t,e)=>{try{await this.rescanBlock(t,e)}catch(t){this.emit("error",t)}}),this.client.hook("tx",async(t,e,r)=>{try{await this.addTX(t,null,r)}catch(t){this.emit("error",t)}}),this.client.hook("entry.remove",async(t,e)=>{try{if(e){var r=t.tx.hash("hex"),i=await this.getWalletsByTX(t.tx);if(i)for(const e of i){const i=await this.get(e);s(i),await i.remove(r),(await k.FactoryOfContract({tx:t.tx,env:this})).erase()}}}catch(e){this.emit("error",e)}}),this.client.hook("chain.reset",async t=>{try{await this.resetChain(t)}catch(t){this.emit("error",t)}}),this.jsonp&&this.jsonp.hook("error",t=>{this.emit("error",t)}))}async disconnect(){this.client&&await this.client._close(),this.jsonp&&await this.jsonp._close()}async flushCP(t,e=!1){this.client&&(t=t||[],e||(t=this.cpList.excludeCids(t),e=e||0<t.length),e&&await this.client.execute("cp.remoteQuery",[[["cid","include",t]]]))}async watch(){let t=this.db.iterator({gte:h.p(N.NULL_HASH),lte:h.p(N.HIGH_HASH)}),e=0,r=0;for(;;){var i=await t.next();if(!i)break;try{var s=h.pp(i.key);this.filter.add(s,"hex")}catch(e){throw await t.end(),e}e++}for(t=this.db.iterator({gte:h.o(N.NULL_HASH,0),lte:h.o(N.HIGH_HASH,4294967295)});;){var n=await t.next();if(!n)break;try{var[a,o]=h.oo(n.key);var c=new y(a,o).toRaw();this.filter.add(c)}catch(e){throw await t.end(),e}r++}this.logger.info("Filter: Added %d hashes to AccountDB filter.",e),this.logger.info("Filter: Added %d outpoints to AccountDB filter.",r),await this.setFilter()}async sync(){if(this.client){let e,r=this.curHeight;for(;0<=r;){var t=await this.getBlock(r);if(!t)break;if(e=await this.client.getEntry(t.hash))break;r--}e||(r=this.state.startHeight,(e=await this.client.getEntry(this.state.startHash))||(r=0)),await this.cpList.loadHistory(),await this.cpMemList.loadHistory(),await this.propList.loadHistory(),await this.htlcList.loadHistory(),await this.commentList.loadHistory(),await this.accountList.loadHistory(),await this.transactionList.loadHistory(),await this.loadContact(),await this.erList.loadHistory(),await this.auditList.loadHistory(),await this.erAbList.loadHistory(),await this.accountCoinList.loadHistory(),await this.scan(r,!1)}}async scan(t,e=!0){if(this.client){null==t&&(t=this.state.startHeight),s(t>>>0===t,"WDB: Must pass in a height.");var r=this.curHeight;e=(await this.rollback(t,e),this.logger.info("AccountDB is scanning %d blocks.",r-t+1),await this.getTip());try{this.rescanning=!0,await this.client.rescan(e.hash)}finally{this.rescanning=!1}}}async rescan(t){const e=await this.txLock.lock();try{return await this.scan(t,!1)}finally{e()}}async send(t){if(this.client)return this.client.send(t);this.emit("send",t)}async getTX(t){for(const r of this.wallets.values()){var e=await r.getTX(t);if(e)return e.tx}return null}async getTXFromDb(t){for(const r of this.wallets.values()){var e=await r.getTX(t);if(e)return e.tx}return null}async getExtendTX(t){for(const r of this.wallets.values()){var e=await r.getTX(t);if(e)return e}return null}async removeTX(t){this.client?await this.client.removeTX(t):this.emit("remove",t)}async estimateFee(t){return 0<this.feeRate?this.feeRate:!this.client||(t=await this.client.estimateFee(t))<this.network.feeRate?this.network.feeRate:t>this.network.maxFeeRate?this.network.maxFeeRate:t}setFilter(){return this.client?this.client.setFilter(this.filter):(this.emit("filter.set",this.filter),Promise.resolve())}addFilter(t){return this.client?this.client.addFilter(t):(this.emit("filter.add",t),Promise.resolve())}resetFilter(){return this.client?this.client.resetFilter():(this.emit("filter.reset"),Promise.resolve())}backup(t){return this.db.backup(t)}async wipe(){this.logger.warning("Wiping AccountDB TXDB..."),this.logger.warning("I hope you know what you're doing.");const t=this.db.iterator({gte:Buffer.from([0]),lte:Buffer.from([255])}),e=this.db.batch();let r=0;for(;;){var i=await t.next();if(!i)break;try{switch(i.key[0]){case 98:case 99:case 101:case 116:case 111:case 104:case 82:e.del(i.key),r++}}catch(e){throw await t.end(),e}}this.logger.warning("Wiped %d txdb records.",r),await e.write()}async getDepth(){const t=this.db.iterator({gte:h.w(0),lte:h.w(4294967295),reverse:!0,limit:1});var e=await t.next();return e?(await t.end(),h.ww(e.key)+1):1}start(t){return s(!t.current,"WDB: Batch already started."),t.current=this.db.batch(),t.accountCache.start(),t.pathCache.start(),t.current}drop(t){const e=this.batch(t);t.current=null,t.accountCache.drop(),t.pathCache.drop(),e.clear()}clear(t){const e=this.batch(t);t.accountCache.clear(),t.pathCache.clear(),e.clear()}batch(t){return s(t.current,"WDB: Batch does not exist."),t.current}async commit(t){const e=this.batch(t);try{await e.write()}catch(t){throw this.drop(),t}t.current=null,t.accountCache.commit(),t.pathCache.commit()}testFilter(t){return this.filter.test(t,"hex")}addHash(t){return this.filter.add(t,"hex"),this.addFilter(t)}addOutpoint(t,e){const r=new y(t,e);this.filter.add(r.toRaw())}dump(){return this.db.dump()}register(t){s(!this.wallets.has(t.wid)),this.wallets.set(t.wid,t)}unregister(t){s(this.wallets.has(t.wid)),this.wallets.delete(t.wid)}async getWalletID(t){if(!t)return null;if("number"==typeof t)return t;var e=this.widCache.get(t);if(e)return e;const r=await this.db.get(h.l(t));return r?(e=r.readUInt32LE(0,!0),this.widCache.set(t,e),e):null}async get(t){if(!(t=await this.getWalletID(t)))return null;const e=await this.readLock.lock(t);try{return await this._get(t)}finally{e()}}async _get(t){var e=this.wallets.get(t);if(e)return e;if(!(e=await this.db.get(h.w(t))))return null;const r=a.fromRaw(this,e);return await r.open(),this.register(r),r}async loadBackup(t){if(ft.unsupported)throw new gt(mt.INTERNAL_ERROR,"FS not available.");let e=await this.get("primary");const r=await ft.readFile(t,"utf8");var i;for(i of r.split(/\n+/))if(0!==(i=i.trim()).length&&!/^\s*#/.test(i)){const t=i.split(/\s+/);if(t.length<4)throw new gt(mt.DESERIALIZATION_ERROR,"Malformed wallet Data File.");switch(t[0]){case"W":var n=Buffer.from(t[1],"base64");n=a.fromRaw(e.db,n);if(e.wid!=n.wid)throw new 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(t[1],"base64");const r=o.fromRaw(e.db,n);r.wallet=e,r.wid=e.wid,r.id=e.id,r.initialized=!0,r.watchOnly=e.watchOnly,r.receive=r.deriveReceive(r.receiveDepth-1),r.change=r.deriveChange(r.changeDepth-1),r.witness&&(r.nested=r.deriveNested(r.nestedDepth-1));let i=e.master.key.deriveAccount(44,r.accountIndex);i.publicKey.toString("hex")!==r.accountKey.publicKey.toString("hex")&&s(i.publicKey.toString("hex")==r.accountKey.publicKey.toString("hex")),await e.saveAccount(r),this.logger.info("Import Account %s(%s)",r.name,r.accountIndex);break}case"A":{var c=parseInt(t[5]),u=parseInt(t[7]),h=parseInt(t[9]),l=t[11].trim();let r=await e.deriveKey(c,u,h),i=await e.deriveKey(c,u,h,e.master);r.getAddress("string")!==i.getAddress("string")&&s(r.getAddress("string")==i.getAddress("string")),r.getAddress("string")!==l&&s(r.getAddress("string")==l),this.logger.info("Import Address %s %s %s %s",c,u,h,r.getAddress("string"));break}}}return e.accountCache.reset(),e}save(t){var e=t.wid,r=t.id;const i=this.batch(t);this.widCache.set(r,e),i.put(h.w(e),t.toRaw()),i.put(h.l(r),D(e))}async rename(t,e){const r=await this.writeLock.lock();try{return await this._rename(t,e)}finally{r()}}async _rename(t,e){var r=t.id;if(!n.isName(e))throw new Error("WDB: Bad wallet ID.");if(await this.has(e))throw new Error("WDB: ID not available.");this.start(t).del(h.l(r)),t.id=e,this.save(t),await this.commit(t),this.widCache.remove(r);for(const r of t.pathCache.values())r.id=e}async replace(t){const e=await this.writeLock.lock();try{return await this._replace(t)}finally{e()}}async _replace(t){const e=this.start(t);e.del(h.l(t.id)),e.del(h.w(t.wid)),this.save(t),await this.commit(t),this.widCache.remove(t.id),this.wallets.delete(t.wid)}renameAccount(t,e){var r=t.wallet;this.batch(r).del(h.i(t.wid,t.name)),t.name=e,this.saveAccount(t)}async auth(t,e){if("string"==typeof e){if(!C.isHex256(e))throw new Error("WDB Authentication: Invalid Token.");e=Buffer.from(e,"hex")}t=x.getHmac(t.toString(),this.keys.hmacSalt);const r=i.createHmac("sha256",t.random);if(t=Buffer.from(r.update(t.token).digest("hex"),"hex"),!p(e,t))throw new Error("WDB Authentication: CRC Error.")}async create(t){const e=await this.writeLock.lock();t=t||{};try{return await this._create(t)}finally{e()}}async _create(t){if(await this.has(t.id))throw new Error("WDB: Wallet already exists.");"string"==typeof t.mnemonic&&(t.mnemonic={phrase:t.mnemonic}),t.mnemonic=t.mnemonic||{},!t.mnemonic.language&&this.options.mnemonic&&this.options.mnemonic.language&&(t.mnemonic.language=this.options.mnemonic.language);const e=a.fromOptions(this,t);return e.wid=this.depth++,await e.init(t),this.register(e),this.logger.info("Created wallet %s in AccountDB.",e.id),e}async has(t){return null!=await this.getWalletID(t)}async ensure(t){return await this.get(t.id)||this.create(t)}async getAccount(t,e){return(t=await this.db.get(h.a(t,e)))?o.fromRaw(this,t):null}getAccounts(t){return this.db.values({gte:h.n(t,0),lte:h.n(t,4294967295),parse:t=>t.toString("ascii")})}async getAccountIndex(t,e){const r=await this.db.get(h.i(t,e));return r?r.readUInt32LE(0,!0):-1}async getGuider(t){return t=v.fromString(t,this.network.type).getHash("hex"),(t=await this.db.get(h.g(t)))?v.fromRaw(t).toString():null}async setGuider(t,e,r){if(r=v.fromString(r,this.network.type).getHash("hex"),!await this.db.has(h.g(r))){t=v.fromString(t,this.network.type);const i=this.db.batch();i.put(h.g(r),t.toRaw()),i.put(h.gs(t.getHash("hex"),Buffer.from(e,"ascii").toString("hex"),r),null),await i.write()}}async unsetGuider(t,e,r){t=v.fromString(t,this.network.type).getHash("hex"),r=v.fromString(r,this.network.type).getHash("hex");const i=this.db.batch();i.del(h.g(r)),i.del(h.gs(t,Buffer.from(e,"ascii").toString("hex"),r)),await i.write()}async getAccountName(t,e){const r=await this.db.get(h.n(t,e));return r?r.toString("ascii"):null}saveAccount(t){var e=t.wid;const r=t.wallet;var i=t.accountIndex,s=t.name;const n=this.batch(r);n.put(h.a(e,i),t.toRaw()),n.put(h.i(e,s),D(i)),n.put(h.n(e,i),Buffer.from(s,"ascii")),r.accountCache.push(i,t)}hasAccount(t,e){return"number"==typeof t&&"number"==typeof e&&this.db.has(h.a(t,e))}async getPathMap(t){var e=this.pathMapCache.get(t);return e||((e=await this.db.get(h.p(t)))?(e=ht.fromRaw(t,e),this.pathMapCache.set(t,e),e):null)}saveKey(t,e){return this.savePath(t,e.toPath())}async savePath(t,e){var r=t.wid,i=e.hash;const s=this.batch(t);await this.addHash(i);let n=await this.getPathMap(i);(n=n||new ht(i)).add(r)&&(this.pathMapCache.set(i,n),t.pathCache.push(i,e),s.put(h.p(i),n.toRaw()),s.put(h.P(r,i),e.toRaw()),s.put(h.r(r,e.account,i),null))}async getPath(t,e){var r=await this.db.get(h.P(t,e));if(!r)return null;const i=at.fromRaw(r);return i.wid=t,i.hash=e,i}hasPath(t,e){return this.db.has(h.P(t,e))}getHashes(){return this.db.keys({gte:h.p(N.NULL_HASH),lte:h.p(N.HIGH_HASH),parse:h.pp})}getOutpoints(){return this.db.keys({gte:h.o(N.NULL_HASH,0),lte:h.o(N.HIGH_HASH,4294967295),parse:t=>{var[t,e]=h.oo(t);return new y(t,e)}})}getWalletHashes(t){return this.db.keys({gte:h.P(t,N.NULL_HASH),lte:h.P(t,N.HIGH_HASH),parse:h.Pp})}getAccountHashes(t,e){return this.db.keys({gte:h.r(t,e,N.NULL_HASH),lte:h.r(t,e,N.HIGH_HASH),parse:h.rr})}async getWalletPaths(t){const e=[];for(const i of await this.db.range({gte:h.P(t,N.NULL_HASH),lte:h.P(t,N.HIGH_HASH)})){var r=h.Pp(i.key);const s=at.fromRaw(i.value);s.hash=r,s.wid=t,e.push(s)}return e}async encryptKeys(t,e){var r,i=t.wid,n=await t.getPaths();const a=this.batch(t);for(r of n)if(r.data){s(!r.encrypted);var o=Buffer.from(r.hash,"hex").slice(0,16);(r=r.clone()).data=d.encipher(r.data,e,o),r.encrypted=!0,t.pathCache.push(r.hash,r),a.put(h.P(i,r.hash),r.toRaw())}}async decryptKeys(t,e){var r,i=t.wid,n=await t.getPaths();const a=this.batch(t);for(r of n)if(r.data){s(r.encrypted);var o=Buffer.from(r.hash,"hex").slice(0,16);(r=r.clone()).data=d.decipher(r.data,e,o),r.encrypted=!1,t.pathCache.push(r.hash,r),a.put(h.P(i,r.hash),r.toRaw())}}async resend(){let t={};var e;for(const e of await this.db.keys({gte:h.w(0),lte:h.w(4294967295)})){var r,i=h.ww(e);!i||(r=await this.resendPending(i))&&Array.isArray(r)&&(t[i]=r)}for(e of Object.keys(t)){let r=await this.get(parseInt(e));if(r)for(const i of t[e]){try{await this.send(i)}catch(t){this.logger.warning("wdb resend:",t.message);try{await r.abandon(i.hash("hex"))}catch(t){this.logger.warning("wdb abandon:",t.message)}}await dt.timeout(50)}}}async resendPending(t){const e=await this.get(t);var r=await this.db.keys({gte:u.txdb.prefix(t,u.txdb.p(N.NULL_HASH)),lte:u.txdb.prefix(t,u.txdb.p(N.HIGH_HASH))});if(0!==r.length){this.logger.info("Rebroadcasting %d transactions for %d.",r.length,t);const n=[];for(const a of r){var i=u.txdb.pp(a),s=u.txdb.prefix(t,u.txdb.t(i));if(s=await this.db.get(s)){const r=lt.fromRaw(s);if(!r.tx.isCoinbase())try{let t=await k.FactoryOfContract({tx:r.tx,env:this});"notify"!=t.oper&&(await t.isBlockFinal()==E.Expired?e&&(await this.removeTX(r.tx),await e.remove(i),await t.erase()):n.push(r.tx))}catch(t){this.logger.error("TX(%s) Smart Contract Error: %s",r.tx.txid(),t.message)}}}return await P(n,this)}}getWallets(){return this.db.keys({gte:h.l("\0"),lte:h.l("ÿ"),parse:h.ll})}async getWalletsByTX(t){const e=new Set;if(!t.isCoinbase())for(const i of t.inputs){const t=i.prevout;if(this.testFilter(t.toRaw())){var r=await this.getOutpointMap(t.hash,t.index);if(r)for(const t of r.wids)e.add(t)}}for(const r of t.getOutputHashes("hex"))if(this.testFilter(r)){var i=await this.getPathMap(r);if(i)for(const t of i.wids)e.add(t)}return 0===e.size?null:e}async getState(){var t=await this.db.get(h.R);return t?ot.fromRaw(t):null}async init(t){var e=this.options.startHeight;let r;if(this.client){if(null!=e){if(!(r=await this.client.getEntry(e)))throw new Error("WDB: Could not find start block.")}else r=await this.client.getTip();r=ut.fromEntry(r)}else r=ut.fromEntry(this.network.genesis);this.logger.info("Initializing AccountDB chain state (height %d).",r.height),(e=await this.getState())?this.state=e:await this.resetState(r,!1),await this.ensure({id:"primary",witness:!0,mnemonic:this.options.mnemonic}),t&&t.backup&&await this.loadBackup(t.backup)}async resetState(t,e){const r=this.state.clone(),i=(r.startHeight=t.height,r.startHash=t.hash,r.height=t.height,r.marked=e,this.db.batch()),s=this.db.iterator({gte:h.h(t.height),lte:h.h(4294967295),values:!1});for(;;){var n=await s.next();if(!n)break;try{i.del(n.key)}catch(t){throw await s.end(),t}}i.put(h.h(t.height),t.toHash()),i.put(h.R,r.toRaw()),await i.write(),this.state=r}async syncState(t){const e=this.state.clone(),r=this.db.batch();if(t.height<e.height){let s=e.height;var i=s-t.height;for(let t=0;t<i;t++)r.del(h.h(s--))}else t.height>e.height&&s(t.height===e.height+1,`Bad chain sync tip ${t.height} while state `+e.height);e.height=t.height,r.put(h.h(t.height),t.toHash()),r.put(h.R,e.toRaw()),await r.write(),this.state=e,X("block/tips",e)}get curHeight(){return this.state.height}get tidCreator(){return u.txdb.tx}get finder(){return this.getTXFromDb.bind(this)}rpcExecute(){return this.rpc.execute.apply(this.rpc,arguments)}async getBlockMap(t){var e=await this.db.get(h.b(t));return e?ct.fromRaw(t,e):null}writeBlockMap(t,e,r){this.batch(t).put(h.b(e),r.toRaw())}unwriteBlockMap(t,e){this.batch(t).del(h.b(e))}async getOutpointMap(t,e){var r=await this.db.get(h.o(t,e));return r?nt.fromRaw(t,e,r):null}writeOutpointMap(t,e,r,i){const s=this.batch(t);this.addOutpoint(e,r),s.put(h.o(e,r),i.toRaw())}unwriteOutpointMap(t,e,r){this.batch(t).del(h.o(e,r))}async writeBalanceLog(t,e){var r=h.log(t.wid,e.aidx,e.height,e.hash);e=Buffer.from(JSON.stringify(e));const i=await this.writeLock.lock();try{this.start(t).put(r,e),await this.commit(t)}finally{i()}}async queryBalanceLog(t,e,r=0){return this.db.values({gte:h.log(t,e,r,N.NULL_HASH),lte:h.log(t,e,this.curHeight,N.HIGH_HASH),parse:t=>JSON.parse(t.toString())})}async getBlock(t){const e=await this.db.get(h.h(t));if(!e)return null;const r=new ut;return r.hash=e.toString("hex"),r.height=t,r}async getTip(){var t=await this.getBlock(this.curHeight);if(t)return t;throw new Error("WDB: Tip not found!")}async rollback(t,e=!0){if(t>this.curHeight)throw new Error("WDB: Cannot rollback to the future.");if(t===this.curHeight)return this.logger.debug("Rolled back to same height (%d).",t),!0;this.logger.info("Rolling back %d AccountDB blocks to height %d.",this.curHeight-t,t);let r=await this.getBlock(t),i=!1;return r?(await this.revert(r.height),await this.syncState(r),e):(r=new ut,t>=this.state.startHeight?(r.height=this.state.startHeight,r.hash=this.state.startHash,i=this.state.marked,this.logger.warning("Rolling back AccountDB to start block (%d).",r.height)):(r.height=0,r.hash=this.network.genesis.hash,i=!1,this.logger.warning("Rolling back AccountDB to genesis block.")),await this.revert(r.height),await this.resetState(r,i),!1)}async revert(t){const e=this.db.iterator({gte:h.b(t+1),lte:h.b(4294967295),reverse:!0,values:!0});let r=0;for(;;){var i=await e.next();if(!i)break;try{var s=h.bb(i.key);var n=ct.fromRaw(s,i.value).toArray();r+=n.length;for(let t=n.length-1;0<=t;t--)await this._unconfirm(n[t])}catch(t){throw await e.end(),t}}this.logger.info("Rolled back %d AccountDB transactions.",r)}async addBlock(t,e){const r=await this.txLock.lock();try{return await this._addBlock(t,e)}finally{r()}}async _addBlock(t,e){var r=ut.fromEntry(t);let i=0;if(r.height<this.curHeight)this.logger.warning("AccountDB is connecting low blocks (%d).",r.height);else{if(r.height===this.curHeight)this.logger.warning("Already saw AccountDB block (%d).",r.height);else if(r.height!==this.curHeight+1)throw new Error(`WDB(addBlock): Bad disconnection (height mismatch, tip ${r.height} while state ${this.curHeight})`);if(await this.syncState(r),!(this.options.checkpoints&&r.height<=this.network.lastCheckpoint)){for(const t of e)await this._insert(t,r)&&i++;0<i&&this.logger.info("Connected AccountDB block %s (tx=%d).",C.revHex(r.hash),i)}}return i}async removeBlock(t,e){const r=await this.txLock.lock();try{return await this._removeBlock(t,e)}finally{r()}}async _removeBlock(t,e){if((t=ut.fromEntry(t)).height>this.curHeight)return this.logger.warning("AccountDB is disconnecting high blocks (%d).",t.height),0;if(t.height!==this.curHeight)throw new Error(`WDB(removeBlock): Bad disconnection (height mismatch, tip ${t.height} / ${C.revHex(t.hash)} while state ${this.curHeight})`);var r=await this.getBlock(t.height-1);if(!r)throw new Error(`WDB(removeBlock): Bad disconnection (no previous block of ${t.height} / ${C.revHex(t.hash)}).`);var i=await this.getBlockMap(t.height);if(i){for(let t=e.length-1;0<=t;t--){var s=e[t];await this._unconfirm(s,i)}this.logger.warning("Disconnected wallet block %s (tx=%d).",C.revHex(t.hash),i.txs.size)}return await this.syncState(r),i?i.txs.size:0}async rescanBlock(t,e){if(this.rescanning){const r=await this.scanLock.lock();try{await this._addBlock(t,e)}catch(t){throw this.emit("error",t),t}finally{r()}}else this.logger.warning("Unsolicited rescan block: %s.",t.height)}async addTX(t,e,r){const i=await this.txLock.lock();try{return await this._insert(t,e,r)}finally{i()}}listNotify(t){return this.NotifyList.deletes([["h","<",this.curHeight-12]]),this.NotifyList.query(t)}listContact(t,e,r){return this.$contacts.query(t,e,r)}async setCp(t){await this.batchPut(u.txdb.cp(t.cid),t.toRaw())}async delCp(t){await this.batchDel(u.txdb.cp(t))}async delVp(t){let e=this.db.batch();e.del(u.txdb.VP(t.pid)),await e.write()}async setVp(t,e){let r=this.db.batch();r.put(u.txdb.VP(t.pid),t.toRaw()),await r.write()}async getVp(t){return(t=await this.db.get(u.txdb.VP(t)))?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:u.txdb.VP(N.ZERO_CID,"hex"),lte:u.txdb.VP(N.MAX_CID,"hex"),parse:t=>Z.fromRaw(t)})}async saveContact(t){let e=this.db.batch();e.put(u.txdb.CT(t.getAddress()),t.toRaw()),await e.write()}async loadContact(t){var e;for(e of await this.db.values({gte:u.txdb.CT(N.ZERO_HASH160_HEX),lte:u.txdb.CT(N.MAX_HASH160_HEX),parse:t=>R.fromRaw(t,this)}))e.sender&&(e.sender.wallet=await this.get(e.sender.wid)),this.$contacts.set(e.address,e)}async delHtlc(t){if((t=new M(t)).id){this.htlcList.delete(t.id),this.htlcList.delAccount(t);let e=this.db.batch();e.del(u.txdb.VH(t.shash,t.sidx)),await e.write()}}async setSuggest(t){let e=new M(t);this.htlcList.set(e.id,e);var[t,r]=await this.getAccountByAddress(e.aa),[t,r]=(t&&this.htlcList.setAccount(e,t,r),await this.getAccountByAddress(e.ba));t&&this.htlcList.setAccount(e,t,r);let i=this.db.batch();i.put(u.txdb.VH(e.shash,e.sidx),e.toRaw()),await i.write()}async setAssent(t){let e=new M(t);this.htlcList.set(e.id,e);var[t,r]=await this.getAccountByAddress(e.ab),[t,r]=(t&&this.htlcList.setAccount(e,t,r),await this.getAccountByAddress(e.bb));t&&this.htlcList.setAccount(e,t,r);let i=this.db.batch();i.put(u.txdb.VH(e.shash,e.sidx),e.toRaw()),await i.write()}async loadHtlcList(){return this.db.values({gte:u.txdb.VH(N.ZERO_CID,0),lte:u.txdb.VH(N.MAX_CID,4294967295),parse:t=>M.fromRaw(t)})}async delComment(t){if((t=new q(t)).id){this.commentList.delete(t.id),this.commentList.delAccount(t);let e=this.db.batch();e.del(u.txdb.VC(t.shash,t.sidx)),await e.write()}}async setComment(t){let e=new q(t);this.commentList.set(e.id,e);var[t,r]=await this.getAccountByAddress(e.bob);t&&(this.commentList.setAccount(e,t,r),this.emit("comm.comment",e));let i=this.db.batch();i.put(u.txdb.VC(e.shash,e.sidx),e.toRaw()),await i.write()}async loadCommentList(){return this.db.values({gte:u.txdb.VC(N.ZERO_CID,0),lte:u.txdb.VC(N.MAX_CID,4294967295),parse:t=>q.fromRaw(t)})}async setStockRecord(t){let e=this.db.batch();switch(e.put(t.itemNo,t.toRaw()),t.type){case G.RecordType.Offer:break;case G.RecordType.Bid:{let r=this.accountList.getStockAccount(t.cid,t.addr);if(!r)break;r.stock.sum=t.sum,r.stock.price=t.price,r.stock.period=this.curHeight+10*m.BLOCK_DAY,r.seq=t.seq,e.put(r.getItemNo(),r.toRaw());break}case G.RecordType.Auction:{let i=this.accountList.getStockAccount(t.cid,t.addr);i?(r=i.sum+t.sum,i.price=(t.sum*t.price+i.sum*i.price)/r|0,i.sum=r,i.seq=t.seq):((i=new tt(t.cid,t.addr,t.sum,t.price,0)).seq=t.seq,this.accountList.setStockAccount(i)),e.put(i.getItemNo(),i.toRaw());let s=this.accountList.getStockAccount(t.cid,t.to);if(!s)break;var r=s.sum-t.sum;s.sum=r,s.stock.sum-=t.sum,e.put(s.getItemNo(),s.toRaw());break}case G.RecordType.Purchase:{let i=this.accountList.getStockAccount(t.cid,t.addr);i?(r=i.sum+t.sum,i.price=(t.sum*t.price+i.sum*i.price)/r,i.sum=r,i.seq=t.seq):((i=new 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:{let i=this.accountList.getStockAccount(t.cid,t.addr);if(i){i.sum-=t.sum,i.seq=t.seq;let s=this.accountList.getStockAccount(t.cid,t.to);s||(s=new 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){let e=this.db.batch();switch(e.del(t.itemNo),t.type){case G.RecordType.Offer:break;case G.RecordType.Bid:{let r=this.accountList.getStockAccount(t.cid,t.addr);if(!r)break;r.stock.sum=0,r.stock.price=0,r.stock.period=0,r.seq=t.seq-1,e.put(r.getItemNo(),r.toRaw());break}case G.RecordType.Auction:{let i=this.accountList.getStockAccount(t.cid,t.addr);if(!i)break;var r=i.sum-t.sum;i.price=(i.sum*i.price-t.sum*t.price)/r|0,i.sum=r,i.seq=t.seq-1,e.put(i.getItemNo(),i.toRaw());let s=this.accountList.getStockAccount(t.cid,t.to);if(!s)break;r=s.sum+t.sum,s.sum=r,s.stock.sum+=t.sum,e.put(s.getItemNo(),s.toRaw());break}case G.RecordType.Purchase:{let i=this.accountList.getStockAccount(t.cid,t.addr);i&&(r=i.sum-t.sum,i.price=(i.sum*i.price-t.sum*t.price)/r,i.sum=r,i.seq=t.seq-1,e.put(i.getItemNo(),i.toRaw()));break}case G.RecordType.Send:{let i=this.accountList.getStockAccount(t.cid,t.addr);if(i){i.sum+=t.sum,i.seq=t.seq-1,e.put(i.getItemNo(),i.toRaw());let s=this.accountList.getStockAccount(t.cid,t.to);s&&(r=s.sum-t.sum,s.price=(s.sum*s.price-t.sum*i.price)/r|0,s.sum=r,e.put(s.getItemNo(),s.toRaw()))}break}case G.RecordType.Bonus:}await e.write()}async getStockRecordById(t){return(t=await this.db.get(t))?G.fromRaw(t):null}async verifyClsTx(t,e){if(!this.spv){let r=await k.FactoryOfContract({env:this,block:e,tx:t});if(1!=(e=await r.verify()))throw new g(t,S(e),"bad-contract-verify",100)}return!0}async getStockRecord(t,e,r){let i=6,s=N.ZERO_CID_BUF,n=N.MAX_CID_BUF,a=0;return t&&(i=t,e&&(s=e,n=e,a=r||0)),t=new I,(await this.db.values({gte:G.itemNo(i,s,a,N.NULL_HASH,0),lte:G.itemNo(i,n,4294967295,N.HIGH_HASH,4294967295),parse:G.fromRaw})).reduce((t,e)=>(t.set(e.itemNo,e),t),t),t}async getStockRecordByCid(t,e){let r=new I;for(var i of Object.keys(G.RecordType))i=await this.getStockRecord(G.RecordType[i],t,e),r.merge(i);return r}async getStockAccountList(t){var e;return t?(e=tt.SN(t,N.NULL_HASH),t=tt.SN(t,N.HIGH_HASH),this.db.values({gte:e,lte:t,parse:tt.fromRaw})):this.db.values({gte:tt.SN(N.ZERO_CID_BUF,N.NULL_HASH),lte:tt.SN(N.MAX_CID_BUF,N.HIGH_HASH),parse:tt.fromRaw})}async delEr(t){let e=this.db.batch();e.del(u.txdb.ER(t.erid)),e.del(u.txdb.ERR(t.witness,t.erid)),await e.write()}async setEr(t,e){e&&t.source&&(i=v.fromWitnessPubkeyhash(l.hash160(Buffer.from(t.source.pubkey,"hex")),this.network),[i,e]=await this.getAccountByAddress(i,e),t.wid=i,t.account=e);let r=this.db.batch();var i=u.txdb.ERR(t.witness,t.erid);r.put(i,t.toRaw()),r.put(u.txdb.ER(t.erid),i),await r.write()}async getEr(t){return(t=(t=await this.db.get(u.txdb.ER(t)))&&await this.db.get(t))?rt.fromRaw(t):null}async byPubkey(t,e,r=!1){let i=new I;var s;t=await this.db.values({gte:u.txdb.ERR(t,N.ZERO_CID),lte:u.txdb.ERR(t,N.MAX_CID),parse:t=>rt.fromRaw(t)});let n=[],a=new Map;if(r){for(var o of t)(!a.get(o.source.cluster)||o.startHeight>a.get(o.source.cluster).startHeight)&&a.set(o.source.cluster,await this.caVerifyObj(o));n=a.values()}else n=t;for(s of n)i.set(s.erid,s);return i.query(e)}async caVerifyObj(t){var e={verify:!1};if(!t||t.validHeight<=this.curHeight)return e;var r=await this.erAbList.getErAb(t.erid);return r&&r.abolishHeight<this.curHeight?e:(r=pt.fromPublic(Buffer.from(t.witness,"hex"),this.network.type),t.verify(r)?(t.verify=!0,0<(r=this.cpList.query([["pubKey",t.witness]])).list.length&&(t.cpid=r.list[0].cid),t):e)}async delErAbolish(t){let e=this.db.batch();e.del(u.txdb.ERA(t.erid)),await e.write()}async setErAbolish(t){let e=this.db.batch();e.put(u.txdb.ERA(t.erid),t.toRaw()),await e.write()}async getErAbolish(t){return(t=await this.db.get(u.txdb.ERA(t)))?Y.fromRaw(t):null}loadErAbolishList(){return this.db.values({gte:u.txdb.ERA(N.ZERO_CID),lte:u.txdb.ERA(N.MAX_CID),parse:t=>Y.fromRaw(t)})}async delAudit(t){let e=this.db.batch();e.del(u.txdb.AU(t.erid)),await e.write()}async setAudit(t){let e=this.db.batch();e.put(u.txdb.AU(t.erid),t.toRaw()),await e.write()}async getAudit(t){return(t=await this.db.get(u.txdb.AU(t)))?st.fromRaw(t):null}async loadAuditList(){return this.db.values({gte:u.txdb.AU(N.NULL_HASH),lte:u.txdb.AU(N.HIGH_HASH),parse:t=>st.fromRaw(t)})}async batchPut(t,e){const r=this.db.batch();r.put(t,e),await r.write()}async batchDel(t){const e=this.db.batch();e.del(t),await e.write()}async _insert(t,e,r){s(!t.mutable,"WDB: Cannot add mutable TX.");let i=await this.getWalletsByTX(t);if(i){this.logger.info("Incoming transaction for %d wallets in AccountDB (%s).",i.size,t.txid()),!e||this.state.marked||(this.logger.info("Marking AccountDB start block at %s (%d).",C.revHex(e.hash),e.height),await this.resetState(e,!0));let n=!1;for(const a of i){const i=await this.get(a);s(i),await i.add(t,e,r)&&(this.logger.info("Added transaction to wallet in AccountDB: %s (%d).",i.id,a),n=!0)}n||(i=null)}try{let r=await k.FactoryOfContract({env:this,block:e,tx:t});e?await r.confirm():await r.insert()}catch(r){e?this.logger.error("TX(%s) Smart Contract Confirm Error: %s",t.txid(),r.message):this.logger.error("TX(%s) Smart Contract Insert Error: %s",t.txid(),r.message)}return i}async _unconfirm(t,e){if(e)try{let r=await k.FactoryOfContract({env:this,block:e,tx:t});await r.unconfirm()}catch(i){this.logger.error("TX(%s) Smart Contract Unconfirm Error: %s",t.txid(),i.message)}let r,i=null;if(r=t.wids?(i=t.wids,t.hash):(i=await this.getWalletsByTX(t),t.hash("hex")),!i)return null;for(const t of i){const e=await this.get(t);s(e),await e.unconfirm(r)}for(const t of i){const e=await this.get(t);s(e),await e.abandon(r)}}async resetChain(t){const e=await this.txLock.lock();try{return await this._resetChain(t)}finally{e()}}async _resetChain(t){if(t.height>this.curHeight)throw new Error(`WDB: Bad reset height ${t.height} while curHeight `+this.curHeight);var e;for(e of(await this.rollback(t.height)||await this.scan(),await this.getWallets())){const r=await this.get(e);for(const e of await r.getPending())try{await r.abandon(e.hash)}catch(t){}await r.resetBalance()}}async saveMSTrans(t){const e=await this.writeLock.lock();try{return await this._saveMSTrans(t)}finally{e()}}async _saveMSTrans(t){const e=this.db.batch();e.put(h.ms(v.getHash(t.addr,"hex"),t.txid),Buffer.from(JSON.stringify(t))),await e.write()}async listMSTrans(t){return t=v.getHash(t,"hex"),this.db.values({gte:h.ms(t,N.NULL_HASH),lte:h.ms(t,N.HIGH_HASH),parse:t=>JSON.parse(t.toString())})}async delMSTrans(t,e){const r=await this.writeLock.lock();try{return await this._delMSTrans(t,e)}finally{r()}}async _delMSTrans(t,e){t=v.getHash(t,"hex");const r=this.db.batch();r.del(h.ms(t,e)),await r.write()}}yt.layout=h,t.exports=yt},function(t,e,r){"use strict";
839
+ */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),z=r(342),H=r(343),M=H.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),tt=Q.stockAccount,et=r(157),rt=et.ErItem,it=r(618),st=it.AuditItem,nt=r(315),at=r(110),ot=r(619),ct=r(316),ut=r(123),ht=r(620),lt=r(222),pt=r(39),dt=r(35),ft=r(59),mt=r(78).errors,gt=r(77);class yt extends j{constructor(t){super(),this.readyLoad=!1,this.options=new c(t),this.network=this.options.network,this.logger=this.options.logger.context("wallet"),this.workers=this.options.workers,this.keys={hmacSalt:N.DefaultChainCode},t.keys&&t.keys.hmacSalt&&(s(Buffer.isBuffer(t.keys.hmacSalt)),this.keys.hmacSalt=t.keys.hmacSalt),this.client=this.options.client,this.client&&(this.client.wdb=this),this.jsonp=this.options.jsonp,this.jsonp&&(this.jsonp.wdb=this),this.spv=this.options.spv,this.feeRate=this.options.feeRate,this.db=f(this.options),this.rpc=new L(this),this.primary=null,this.state=new ot,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 z(this),this.htlcList=new H(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 it(this),this.erList=new et(this),this.erAbList=new $(this),this.hmacConnection=[],this._init()}async logAudit(t){t.height=this.curHeight,t.time=C.now(),t.erid=l.sha256(C.stringify(t)).toString("hex"),t=new st(t),await this.auditList.setAudit(t)}async getAccountByAddress(t,e){if(t){let i=null;if(i=e?await this.getWalletsByTX(e):await this.getWallets())for(const e of i){const i=await this.get(e);if(i){var r=await i.getPath(t);if(r)return[i.wid,r.name,i.id]}}}return[0,"",""]}_init(){let t=1e6,e=-1;this.spv&&(t=2e4,e=B.flags.ALL),this.filter=B.fromRate(t,.001,e)}async getCpSnap(){return{}}get mode(){return _.Wallet}async getTXFromAll(t){return this.getTXFromDb(t)}async checkNewRecord(){var t={createIfMissing:this.db.options.createIfMissing,errorIfExists:this.db.options.errorIfExists};this.db.options.createIfMissing=!1,this.db.options.errorIfExists=!0;try{await this.db.open();var e=await this.db.checkVersion(h,6);this.newRecord="new"==e}catch(t){if(-1!=t.message.indexOf("does not exist (create_if_missing is false)"))this.newRecord=!0;else{if(-1==t.message.indexOf("exists (error_if_exists is true)"))throw t;this.newRecord=!1}}try{await this.db.close()}catch(t){}this.db.options.createIfMissing=t.createIfMissing,this.db.options.errorIfExists=t.errorIfExists}async isNewRecord(){return await this.checkNewRecord(),this.newRecord}setmnemonic(t){if(this.options.mnemonic=this.options.mnemonic||{},t.bits)this.options.mnemonic={bits:t.bits};else if(t.entropy)this.options.mnemonic={entropy:Buffer.from(t.entropy,"hex")};else if(t.phrase){var e=this.testmnemonic(t.phrase);if(0!=e.code)throw e.msg;this.options.mnemonic={phrase:t.phrase}}t.passphrase&&(this.options.mnemonic.passphrase=t.passphrase),t.language&&(this.options.mnemonic.language=t.language)}testmnemonic(t){try{return new w(t),{code:0}}catch(t){return{code:-1,msg:t.message}}}async getContracts(t){let e=await this.db.values({gte:u.txdb.tx(N.NULL_HASH),lte:u.txdb.tx(N.HIGH_HASH),parse:t=>C.parseJson(t.toString())});return t?e.filter(e=>e.srcact==t||e.dstact==t):e}isFull(){return this.spv||this.synced||!1}async _open(t){}async handleNotify(t,e=!1){if(!e){let r=t.body.content;if("string"==typeof r)try{r=JSON.parse(t.body.content)}catch(e){return}if("object"==typeof r&&"secret"===r.type){let e={contact:t.body.src,messenger:t.body.dst};r.init&&(e.init=Buffer.from(r.init,"hex")),r.packet&&(e.packet=Buffer.from(r.packet)),await this.handleSecret(e)}}}async handleSecret(t){if(t.contact&&t.messenger&&t.contact!=t.messenger){try{v.fromString(t.contact,this.network.type),v.fromString(t.messenger,this.network.type)}catch(t){return}let e=await this.ensureContact(t);e&&await e.ensureMessenger(t).answer(t)}}async scanContact(t,e=-1){var r=async t=>{var e;t.witness&&"witnesspubkeyhash"==t.getType()&&(e=t.witness.getPubkeyhashInput()[1],t=v.fromWitness(t.witness).toString(),e&&t&&await this.ensureContact({contact:t,publicKey:e}))};if(0<=e&&e<t.inputs.length)await r(t.inputs[e]);else for(var i of t.inputs)await r(i)}async ensureContact(t){if(!t.contact||t.contact==t.messenger)return null;try{v.fromString(t.contact,this.network.type),t.messenger&&v.fromString(t.messenger,this.network.type)}catch(t){return null}t.network=this.network.type,this.$contacts.get(t.contact)||this.$contacts.set(t.contact,new R(t));let e=this.$contacts.get(t.contact);if(t.messenger){let i=e.ensureMessenger(t);if(!i.wallet){var[t,r]=await this.getAccountByAddress(i.address);if(!(t=await this.get(t)))return;i.wallet=t,i.account=r}}return e}getCps(){return this.db.values({gte:u.txdb.cp(N.ZERO_CID,"hex"),lte:u.txdb.cp(N.MAX_CID,"hex"),parse:t=>W.fromRaw(t)})}async _close(){await this.disconnect(),this.http&&this.options.listen&&await this.http.close();for(const t of this.wallets.values())await t.destroy();await this.db.close(),this.options.listen&&await this.logger.close()}async destroy(){await this.db.destroy(),this.widCache.reset(),this.pathMapCache.reset()}async load(t){if(this.readyLoad){const e=await this.ensure({id:"primary",witness:!0,mnemonic:this.options.mnemonic}),r=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{r()}setTimeout(()=>{this.resend()},5e3)}}bind(){!this.client||this.bound||(this.bound=!0,this.client.hook("htlcassent.cancel",t=>{this.setAssent(t),this.emit("htlcassent.cancel",t)}),this.client.hook("htlcassent.deal",t=>{this.setAssent(t),this.emit("htlcassent.deal",t)}),this.client.hook("htlcassent.receive",t=>{this.setAssent(t),this.emit("htlcassent.receive",t)}),this.client.hook("htlcsuggest.cancel",t=>{this.setSuggest(t),this.emit("htlcsuggest.cancel",t)}),this.client.hook("htlcsuggest.deal",t=>{this.setSuggest(t),this.emit("htlcsuggest.deal",t)}),this.client.hook("htlcsuggest.receive",t=>{this.setSuggest(t),this.emit("htlcsuggest.receive",t)}),this.on("mssendpubk/receive",async t=>{let e=await this.get(t.addr);if(!e){e=await this.ensure({id:t.addr,type:"multisig",m:t.m,n:t.n,witness:!0});var[r,i]=await this.getAccountByAddress(t.addr);let s=await this.get(r);s&&await s.send({subtractFee:!1,sort:!1,outputs:[{address:t.contract,value:1e4}],comment:JSON.stringify({oper:"scrun",params:{oper:"pubk",addr:t.addr,puba:e.account.accountKey}})},i)}if(e.account.keys.length<e.account.n-1){var s;for(s of t.data.split(","))try{await e.addSharedKey(s)}catch(s){}if(e.account.keys.length==e.account.n-1){var[r,i]=await this.getAccountByAddress(t.addr);let s=await this.get(r);s&&await s.send({subtractFee:!1,sort:!1,outputs:[{address:t.contract,value:1e4}],comment:JSON.stringify({oper:"scrun",params:{oper:"puba",addr:t.addr,puba:e.account.receive.getAddress().toString()}})},i)}}}),this.on("mssendtx/receive",async t=>{let e=await this.get(t.addr);if(e&&e.account.type==o.types.MULTISIG){const r=b.fromRaw(t.data,"hex");r.view=await e.getCoinView(r),r.isSigned()||(t.txid=r.txid(),await this.saveMSTrans(t))}}),this.client.hook("onConnect",async()=>{await this.load()}),this.client.hook("error",t=>{this.emit("error",t)}),this.client.hook("block.connect",async(t,e)=>{try{await this.addBlock(t,e)}catch(t){this.emit("error",t)}}),this.client.hook("block.disconnect",async(t,e)=>{try{await this.removeBlock(t,e)}catch(t){this.emit("error",t)}}),this.client.hook("chain.full",()=>{this.synced=!0}),this.client.hook("block.rescan",async(t,e)=>{try{await this.rescanBlock(t,e)}catch(t){this.emit("error",t)}}),this.client.hook("tx",async(t,e,r)=>{try{await this.addTX(t,null,r)}catch(t){this.emit("error",t)}}),this.client.hook("entry.remove",async(t,e)=>{try{if(e){var r=t.tx.hash("hex"),i=await this.getWalletsByTX(t.tx);if(i)for(const e of i){const i=await this.get(e);s(i),await i.remove(r),(await k.FactoryOfContract({tx:t.tx,env:this})).erase()}}}catch(e){this.emit("error",e)}}),this.client.hook("chain.reset",async t=>{try{await this.resetChain(t)}catch(t){this.emit("error",t)}}),this.jsonp&&this.jsonp.hook("error",t=>{this.emit("error",t)}))}async disconnect(){this.client&&await this.client._close(),this.jsonp&&await this.jsonp._close()}async flushCP(t,e=!1){this.client&&(t=t||[],e||(t=this.cpList.excludeCids(t),e=e||0<t.length),e&&await this.client.execute("cp.remoteQuery",[[["cid","include",t]]]))}async watch(){let t=this.db.iterator({gte:h.p(N.NULL_HASH),lte:h.p(N.HIGH_HASH)}),e=0,r=0;for(;;){var i=await t.next();if(!i)break;try{var s=h.pp(i.key);this.filter.add(s,"hex")}catch(e){throw await t.end(),e}e++}for(t=this.db.iterator({gte:h.o(N.NULL_HASH,0),lte:h.o(N.HIGH_HASH,4294967295)});;){var n=await t.next();if(!n)break;try{var[a,o]=h.oo(n.key);var c=new y(a,o).toRaw();this.filter.add(c)}catch(e){throw await t.end(),e}r++}this.logger.info("Filter: Added %d hashes to AccountDB filter.",e),this.logger.info("Filter: Added %d outpoints to AccountDB filter.",r),await this.setFilter()}async sync(){if(this.client){let e,r=this.curHeight;for(;0<=r;){var t=await this.getBlock(r);if(!t)break;if(e=await this.client.getEntry(t.hash))break;r--}e||(r=this.state.startHeight,(e=await this.client.getEntry(this.state.startHash))||(r=0)),await this.cpList.loadHistory(),await this.cpMemList.loadHistory(),await this.propList.loadHistory(),await this.htlcList.loadHistory(),await this.commentList.loadHistory(),await this.accountList.loadHistory(),await this.transactionList.loadHistory(),await this.loadContact(),await this.erList.loadHistory(),await this.auditList.loadHistory(),await this.erAbList.loadHistory(),await this.accountCoinList.loadHistory(),await this.scan(r,!1)}}async scan(t,e=!0){if(this.client){null==t&&(t=this.state.startHeight),s(t>>>0===t,"WDB: Must pass in a height.");var r=this.curHeight;e=(await this.rollback(t,e),this.logger.info("AccountDB is scanning %d blocks.",r-t+1),await this.getTip());try{this.rescanning=!0,await this.client.rescan(e.hash)}finally{this.rescanning=!1}}}async rescan(t){const e=await this.txLock.lock();try{return await this.scan(t,!1)}finally{e()}}async send(t){if(this.client)return this.client.send(t);this.emit("send",t)}async getTX(t){for(const r of this.wallets.values()){var e=await r.getTX(t);if(e)return e.tx}return null}async getTXFromDb(t){for(const r of this.wallets.values()){var e=await r.getTX(t);if(e)return e.tx}return null}async getExtendTX(t){for(const r of this.wallets.values()){var e=await r.getTX(t);if(e)return e}return null}async removeTX(t){this.client?await this.client.removeTX(t):this.emit("remove",t)}async estimateFee(t){return 0<this.feeRate?this.feeRate:!this.client||(t=await this.client.estimateFee(t))<this.network.feeRate?this.network.feeRate:t>this.network.maxFeeRate?this.network.maxFeeRate:t}setFilter(){return this.client?this.client.setFilter(this.filter):(this.emit("filter.set",this.filter),Promise.resolve())}addFilter(t){return this.client?this.client.addFilter(t):(this.emit("filter.add",t),Promise.resolve())}resetFilter(){return this.client?this.client.resetFilter():(this.emit("filter.reset"),Promise.resolve())}backup(t){return this.db.backup(t)}async wipe(){this.logger.warning("Wiping AccountDB TXDB..."),this.logger.warning("I hope you know what you're doing.");const t=this.db.iterator({gte:Buffer.from([0]),lte:Buffer.from([255])}),e=this.db.batch();let r=0;for(;;){var i=await t.next();if(!i)break;try{switch(i.key[0]){case 98:case 99:case 101:case 116:case 111:case 104:case 82:e.del(i.key),r++}}catch(e){throw await t.end(),e}}this.logger.warning("Wiped %d txdb records.",r),await e.write()}async getDepth(){const t=this.db.iterator({gte:h.w(0),lte:h.w(4294967295),reverse:!0,limit:1});var e=await t.next();return e?(await t.end(),h.ww(e.key)+1):1}start(t){return s(!t.current,"WDB: Batch already started."),t.current=this.db.batch(),t.accountCache.start(),t.pathCache.start(),t.current}drop(t){const e=this.batch(t);t.current=null,t.accountCache.drop(),t.pathCache.drop(),e.clear()}clear(t){const e=this.batch(t);t.accountCache.clear(),t.pathCache.clear(),e.clear()}batch(t){return s(t.current,"WDB: Batch does not exist."),t.current}async commit(t){const e=this.batch(t);try{await e.write()}catch(t){throw this.drop(),t}t.current=null,t.accountCache.commit(),t.pathCache.commit()}testFilter(t){return this.filter.test(t,"hex")}addHash(t){return this.filter.add(t,"hex"),this.addFilter(t)}addOutpoint(t,e){const r=new y(t,e);this.filter.add(r.toRaw())}dump(){return this.db.dump()}register(t){s(!this.wallets.has(t.wid)),this.wallets.set(t.wid,t)}unregister(t){s(this.wallets.has(t.wid)),this.wallets.delete(t.wid)}async getWalletID(t){if(!t)return null;if("number"==typeof t)return t;var e=this.widCache.get(t);if(e)return e;const r=await this.db.get(h.l(t));return r?(e=r.readUInt32LE(0,!0),this.widCache.set(t,e),e):null}async get(t){if(!(t=await this.getWalletID(t)))return null;const e=await this.readLock.lock(t);try{return await this._get(t)}finally{e()}}async _get(t){var e=this.wallets.get(t);if(e)return e;if(!(e=await this.db.get(h.w(t))))return null;const r=a.fromRaw(this,e);return await r.open(),this.register(r),r}async loadBackup(t){if(ft.unsupported)throw new gt(mt.INTERNAL_ERROR,"FS not available.");let e=await this.get("primary");const r=await ft.readFile(t,"utf8");var i;for(i of r.split(/\n+/))if(0!==(i=i.trim()).length&&!/^\s*#/.test(i)){const t=i.split(/\s+/);if(t.length<4)throw new gt(mt.DESERIALIZATION_ERROR,"Malformed wallet Data File.");switch(t[0]){case"W":var n=Buffer.from(t[1],"base64");n=a.fromRaw(e.db,n);if(e.wid!=n.wid)throw new 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(t[1],"base64");const r=o.fromRaw(e.db,n);r.wallet=e,r.wid=e.wid,r.id=e.id,r.initialized=!0,r.watchOnly=e.watchOnly,r.receive=r.deriveReceive(r.receiveDepth-1),r.change=r.deriveChange(r.changeDepth-1),r.witness&&(r.nested=r.deriveNested(r.nestedDepth-1));let i=e.master.key.deriveAccount(44,r.accountIndex);i.publicKey.toString("hex")!==r.accountKey.publicKey.toString("hex")&&s(i.publicKey.toString("hex")==r.accountKey.publicKey.toString("hex")),await e.saveAccount(r),this.logger.info("Import Account %s(%s)",r.name,r.accountIndex);break}case"A":{var c=parseInt(t[5]),u=parseInt(t[7]),h=parseInt(t[9]),l=t[11].trim();let r=await e.deriveKey(c,u,h),i=await e.deriveKey(c,u,h,e.master);r.getAddress("string")!==i.getAddress("string")&&s(r.getAddress("string")==i.getAddress("string")),r.getAddress("string")!==l&&s(r.getAddress("string")==l),this.logger.info("Import Address %s %s %s %s",c,u,h,r.getAddress("string"));break}}}return e.accountCache.reset(),e}save(t){var e=t.wid,r=t.id;const i=this.batch(t);this.widCache.set(r,e),i.put(h.w(e),t.toRaw()),i.put(h.l(r),D(e))}async rename(t,e){const r=await this.writeLock.lock();try{return await this._rename(t,e)}finally{r()}}async _rename(t,e){var r=t.id;if(!n.isName(e))throw new Error("WDB: Bad wallet ID.");if(await this.has(e))throw new Error("WDB: ID not available.");this.start(t).del(h.l(r)),t.id=e,this.save(t),await this.commit(t),this.widCache.remove(r);for(const r of t.pathCache.values())r.id=e}async replace(t){const e=await this.writeLock.lock();try{return await this._replace(t)}finally{e()}}async _replace(t){const e=this.start(t);e.del(h.l(t.id)),e.del(h.w(t.wid)),this.save(t),await this.commit(t),this.widCache.remove(t.id),this.wallets.delete(t.wid)}renameAccount(t,e){var r=t.wallet;this.batch(r).del(h.i(t.wid,t.name)),t.name=e,this.saveAccount(t)}async auth(t,e){if("string"==typeof e){if(!C.isHex256(e))throw new Error("WDB Authentication: Invalid Token.");e=Buffer.from(e,"hex")}t=x.getHmac(t.toString(),this.keys.hmacSalt);const r=i.createHmac("sha256",t.random);if(t=Buffer.from(r.update(t.token).digest("hex"),"hex"),!p(e,t))throw new Error("WDB Authentication: CRC Error.")}async create(t){const e=await this.writeLock.lock();t=t||{};try{return await this._create(t)}finally{e()}}async _create(t){if(await this.has(t.id))throw new Error("WDB: Wallet already exists.");"string"==typeof t.mnemonic&&(t.mnemonic={phrase:t.mnemonic}),t.mnemonic=t.mnemonic||{},!t.mnemonic.language&&this.options.mnemonic&&this.options.mnemonic.language&&(t.mnemonic.language=this.options.mnemonic.language);const e=a.fromOptions(this,t);return e.wid=this.depth++,await e.init(t),this.register(e),this.logger.info("Created wallet %s in AccountDB.",e.id),e}async has(t){return null!=await this.getWalletID(t)}async ensure(t){return await this.get(t.id)||this.create(t)}async getAccount(t,e){return(t=await this.db.get(h.a(t,e)))?o.fromRaw(this,t):null}getAccounts(t){return this.db.values({gte:h.n(t,0),lte:h.n(t,4294967295),parse:t=>t.toString("ascii")})}async getAccountIndex(t,e){const r=await this.db.get(h.i(t,e));return r?r.readUInt32LE(0,!0):-1}async getGuider(t){return t=v.fromString(t,this.network.type).getHash("hex"),(t=await this.db.get(h.g(t)))?v.fromRaw(t).toString():null}async setGuider(t,e,r){if(r=v.fromString(r,this.network.type).getHash("hex"),!await this.db.has(h.g(r))){t=v.fromString(t,this.network.type);const i=this.db.batch();i.put(h.g(r),t.toRaw()),i.put(h.gs(t.getHash("hex"),Buffer.from(e,"ascii").toString("hex"),r),null),await i.write()}}async unsetGuider(t,e,r){t=v.fromString(t,this.network.type).getHash("hex"),r=v.fromString(r,this.network.type).getHash("hex");const i=this.db.batch();i.del(h.g(r)),i.del(h.gs(t,Buffer.from(e,"ascii").toString("hex"),r)),await i.write()}async getAccountName(t,e){const r=await this.db.get(h.n(t,e));return r?r.toString("ascii"):null}saveAccount(t){var e=t.wid;const r=t.wallet;var i=t.accountIndex,s=t.name;const n=this.batch(r);n.put(h.a(e,i),t.toRaw()),n.put(h.i(e,s),D(i)),n.put(h.n(e,i),Buffer.from(s,"ascii")),r.accountCache.push(i,t)}hasAccount(t,e){return"number"==typeof t&&"number"==typeof e&&this.db.has(h.a(t,e))}async getPathMap(t){var e=this.pathMapCache.get(t);return e||((e=await this.db.get(h.p(t)))?(e=ht.fromRaw(t,e),this.pathMapCache.set(t,e),e):null)}saveKey(t,e){return this.savePath(t,e.toPath())}async savePath(t,e){var r=t.wid,i=e.hash;const s=this.batch(t);await this.addHash(i);let n=await this.getPathMap(i);(n=n||new ht(i)).add(r)&&(this.pathMapCache.set(i,n),t.pathCache.push(i,e),s.put(h.p(i),n.toRaw()),s.put(h.P(r,i),e.toRaw()),s.put(h.r(r,e.account,i),null))}async getPath(t,e){var r=await this.db.get(h.P(t,e));if(!r)return null;const i=at.fromRaw(r);return i.wid=t,i.hash=e,i}hasPath(t,e){return this.db.has(h.P(t,e))}getHashes(){return this.db.keys({gte:h.p(N.NULL_HASH),lte:h.p(N.HIGH_HASH),parse:h.pp})}getOutpoints(){return this.db.keys({gte:h.o(N.NULL_HASH,0),lte:h.o(N.HIGH_HASH,4294967295),parse:t=>{var[t,e]=h.oo(t);return new y(t,e)}})}getWalletHashes(t){return this.db.keys({gte:h.P(t,N.NULL_HASH),lte:h.P(t,N.HIGH_HASH),parse:h.Pp})}getAccountHashes(t,e){return this.db.keys({gte:h.r(t,e,N.NULL_HASH),lte:h.r(t,e,N.HIGH_HASH),parse:h.rr})}async getWalletPaths(t){const e=[];for(const i of await this.db.range({gte:h.P(t,N.NULL_HASH),lte:h.P(t,N.HIGH_HASH)})){var r=h.Pp(i.key);const s=at.fromRaw(i.value);s.hash=r,s.wid=t,e.push(s)}return e}async encryptKeys(t,e){var r,i=t.wid,n=await t.getPaths();const a=this.batch(t);for(r of n)if(r.data){s(!r.encrypted);var o=Buffer.from(r.hash,"hex").slice(0,16);(r=r.clone()).data=d.encipher(r.data,e,o),r.encrypted=!0,t.pathCache.push(r.hash,r),a.put(h.P(i,r.hash),r.toRaw())}}async decryptKeys(t,e){var r,i=t.wid,n=await t.getPaths();const a=this.batch(t);for(r of n)if(r.data){s(r.encrypted);var o=Buffer.from(r.hash,"hex").slice(0,16);(r=r.clone()).data=d.decipher(r.data,e,o),r.encrypted=!1,t.pathCache.push(r.hash,r),a.put(h.P(i,r.hash),r.toRaw())}}async resend(){let t={};var e;for(const e of await this.db.keys({gte:h.w(0),lte:h.w(4294967295)})){var r,i=h.ww(e);!i||(r=await this.resendPending(i))&&Array.isArray(r)&&(t[i]=r)}for(e of Object.keys(t)){let r=await this.get(parseInt(e));if(r)for(const i of t[e]){try{await this.send(i)}catch(t){this.logger.warning("wdb resend:",t.message);try{await r.abandon(i.hash("hex"))}catch(t){this.logger.warning("wdb abandon:",t.message)}}await dt.timeout(50)}}}async resendPending(t){const e=await this.get(t);var r=await this.db.keys({gte:u.txdb.prefix(t,u.txdb.p(N.NULL_HASH)),lte:u.txdb.prefix(t,u.txdb.p(N.HIGH_HASH))});if(0!==r.length){this.logger.info("Rebroadcasting %d transactions for %d.",r.length,t);const n=[];for(const a of r){var i=u.txdb.pp(a),s=u.txdb.prefix(t,u.txdb.t(i));if(s=await this.db.get(s)){const r=lt.fromRaw(s);if(!r.tx.isCoinbase())try{let t=await k.FactoryOfContract({tx:r.tx,env:this});"notify"!=t.oper&&(await t.isBlockFinal()==E.Expired?e&&(await this.removeTX(r.tx),await e.remove(i),await t.erase()):n.push(r.tx))}catch(t){this.logger.error("TX(%s) Smart Contract Error: %s",r.tx.txid(),t.message)}}}return await P(n,this)}}getWallets(){return this.db.keys({gte:h.l("\0"),lte:h.l("ÿ"),parse:h.ll})}async getWalletsByTX(t){const e=new Set;if(!t.isCoinbase())for(const i of t.inputs){const t=i.prevout;if(this.testFilter(t.toRaw())){var r=await this.getOutpointMap(t.hash,t.index);if(r)for(const t of r.wids)e.add(t)}}for(const r of t.getOutputHashes("hex"))if(this.testFilter(r)){var i=await this.getPathMap(r);if(i)for(const t of i.wids)e.add(t)}return 0===e.size?null:e}async getState(){var t=await this.db.get(h.R);return t?ot.fromRaw(t):null}async init(t){var e=this.options.startHeight;let r;if(this.client){if(null!=e){if(!(r=await this.client.getEntry(e)))throw new Error("WDB: Could not find start block.")}else r=await this.client.getTip();r=ut.fromEntry(r)}else r=ut.fromEntry(this.network.genesis);this.logger.info("Initializing AccountDB chain state (height %d).",r.height),(e=await this.getState())?this.state=e:await this.resetState(r,!1),await this.ensure({id:"primary",witness:!0,mnemonic:this.options.mnemonic}),t&&t.backup&&await this.loadBackup(t.backup)}async resetState(t,e){const r=this.state.clone(),i=(r.startHeight=t.height,r.startHash=t.hash,r.height=t.height,r.marked=e,this.db.batch()),s=this.db.iterator({gte:h.h(t.height),lte:h.h(4294967295),values:!1});for(;;){var n=await s.next();if(!n)break;try{i.del(n.key)}catch(t){throw await s.end(),t}}i.put(h.h(t.height),t.toHash()),i.put(h.R,r.toRaw()),await i.write(),this.state=r}async syncState(t){const e=this.state.clone(),r=this.db.batch();if(t.height<e.height){let s=e.height;var i=s-t.height;for(let t=0;t<i;t++)r.del(h.h(s--))}else t.height>e.height&&s(t.height===e.height+1,`Bad chain sync tip ${t.height} while state `+e.height);e.height=t.height,r.put(h.h(t.height),t.toHash()),r.put(h.R,e.toRaw()),await r.write(),this.state=e,X("block/tips",e)}get curHeight(){return this.state.height}get tidCreator(){return u.txdb.tx}get finder(){return this.getTXFromDb.bind(this)}rpcExecute(){return this.rpc.execute.apply(this.rpc,arguments)}async getBlockMap(t){var e=await this.db.get(h.b(t));return e?ct.fromRaw(t,e):null}writeBlockMap(t,e,r){this.batch(t).put(h.b(e),r.toRaw())}unwriteBlockMap(t,e){this.batch(t).del(h.b(e))}async getOutpointMap(t,e){var r=await this.db.get(h.o(t,e));return r?nt.fromRaw(t,e,r):null}writeOutpointMap(t,e,r,i){const s=this.batch(t);this.addOutpoint(e,r),s.put(h.o(e,r),i.toRaw())}unwriteOutpointMap(t,e,r){this.batch(t).del(h.o(e,r))}async writeBalanceLog(t,e){var r=h.log(t.wid,e.aidx,e.height,e.hash);e=Buffer.from(JSON.stringify(e));const i=await this.writeLock.lock();try{this.start(t).put(r,e),await this.commit(t)}finally{i()}}async queryBalanceLog(t,e,r=0){return this.db.values({gte:h.log(t,e,r,N.NULL_HASH),lte:h.log(t,e,this.curHeight,N.HIGH_HASH),parse:t=>JSON.parse(t.toString())})}async getBlock(t){const e=await this.db.get(h.h(t));if(!e)return null;const r=new ut;return r.hash=e.toString("hex"),r.height=t,r}async getTip(){var t=await this.getBlock(this.curHeight);if(t)return t;throw new Error("WDB: Tip not found!")}async rollback(t,e=!0){if(t>this.curHeight)throw new Error("WDB: Cannot rollback to the future.");if(t===this.curHeight)return this.logger.debug("Rolled back to same height (%d).",t),!0;this.logger.info("Rolling back %d AccountDB blocks to height %d.",this.curHeight-t,t);let r=await this.getBlock(t),i=!1;return r?(await this.revert(r.height),await this.syncState(r),e):(r=new ut,t>=this.state.startHeight?(r.height=this.state.startHeight,r.hash=this.state.startHash,i=this.state.marked,this.logger.warning("Rolling back AccountDB to start block (%d).",r.height)):(r.height=0,r.hash=this.network.genesis.hash,i=!1,this.logger.warning("Rolling back AccountDB to genesis block.")),await this.revert(r.height),await this.resetState(r,i),!1)}async revert(t){const e=this.db.iterator({gte:h.b(t+1),lte:h.b(4294967295),reverse:!0,values:!0});let r=0;for(;;){var i=await e.next();if(!i)break;try{var s=h.bb(i.key);var n=ct.fromRaw(s,i.value).toArray();r+=n.length;for(let t=n.length-1;0<=t;t--)await this._unconfirm(n[t])}catch(t){throw await e.end(),t}}this.logger.info("Rolled back %d AccountDB transactions.",r)}async addBlock(t,e){const r=await this.txLock.lock();try{return await this._addBlock(t,e)}finally{r()}}async _addBlock(t,e){var r=ut.fromEntry(t);let i=0;if(r.height<this.curHeight)this.logger.warning("AccountDB is connecting low blocks (%d).",r.height);else{if(r.height===this.curHeight)this.logger.warning("Already saw AccountDB block (%d).",r.height);else if(r.height!==this.curHeight+1)throw new Error(`WDB(addBlock): Bad disconnection (height mismatch, tip ${r.height} while state ${this.curHeight})`);if(await this.syncState(r),!(this.options.checkpoints&&r.height<=this.network.lastCheckpoint)){for(const t of e)await this._insert(t,r)&&i++;0<i&&this.logger.info("Connected AccountDB block %s (tx=%d).",C.revHex(r.hash),i)}}return i}async removeBlock(t,e){const r=await this.txLock.lock();try{return await this._removeBlock(t,e)}finally{r()}}async _removeBlock(t,e){if((t=ut.fromEntry(t)).height>this.curHeight)return this.logger.warning("AccountDB is disconnecting high blocks (%d).",t.height),0;if(t.height!==this.curHeight)throw new Error(`WDB(removeBlock): Bad disconnection (height mismatch, tip ${t.height} / ${C.revHex(t.hash)} while state ${this.curHeight})`);var r=await this.getBlock(t.height-1);if(!r)throw new Error(`WDB(removeBlock): Bad disconnection (no previous block of ${t.height} / ${C.revHex(t.hash)}).`);var i=await this.getBlockMap(t.height);if(i){for(let t=e.length-1;0<=t;t--){var s=e[t];await this._unconfirm(s,i)}this.logger.warning("Disconnected wallet block %s (tx=%d).",C.revHex(t.hash),i.txs.size)}return await this.syncState(r),i?i.txs.size:0}async rescanBlock(t,e){if(this.rescanning){const r=await this.scanLock.lock();try{await this._addBlock(t,e)}catch(t){throw this.emit("error",t),t}finally{r()}}else this.logger.warning("Unsolicited rescan block: %s.",t.height)}async addTX(t,e,r){const i=await this.txLock.lock();try{return await this._insert(t,e,r)}finally{i()}}listNotify(t){return this.NotifyList.deletes([["h","<",this.curHeight-12]]),this.NotifyList.query(t)}listContact(t,e,r){return this.$contacts.query(t,e,r)}async setCp(t){await this.batchPut(u.txdb.cp(t.cid),t.toRaw())}async delCp(t){await this.batchDel(u.txdb.cp(t))}async delVp(t){let e=this.db.batch();e.del(u.txdb.VP(t.pid)),await e.write()}async setVp(t,e){let r=this.db.batch();r.put(u.txdb.VP(t.pid),t.toRaw()),await r.write()}async getVp(t){return(t=await this.db.get(u.txdb.VP(t)))?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:u.txdb.VP(N.ZERO_CID,"hex"),lte:u.txdb.VP(N.MAX_CID,"hex"),parse:t=>Z.fromRaw(t)})}async saveContact(t){let e=this.db.batch();e.put(u.txdb.CT(t.getAddress()),t.toRaw()),await e.write()}async loadContact(t){var e;for(e of await this.db.values({gte:u.txdb.CT(N.ZERO_HASH160_HEX),lte:u.txdb.CT(N.MAX_HASH160_HEX),parse:t=>R.fromRaw(t,this)}))e.sender&&(e.sender.wallet=await this.get(e.sender.wid)),this.$contacts.set(e.address,e)}async delHtlc(t){if((t=new M(t)).id){this.htlcList.delete(t.id),this.htlcList.delAccount(t);let e=this.db.batch();e.del(u.txdb.VH(t.shash,t.sidx)),await e.write()}}async setSuggest(t){let e=new M(t);this.htlcList.set(e.id,e);var[t,r]=await this.getAccountByAddress(e.aa),[t,r]=(t&&this.htlcList.setAccount(e,t,r),await this.getAccountByAddress(e.ba));t&&this.htlcList.setAccount(e,t,r);let i=this.db.batch();i.put(u.txdb.VH(e.shash,e.sidx),e.toRaw()),await i.write()}async setAssent(t){let e=new M(t);this.htlcList.set(e.id,e);var[t,r]=await this.getAccountByAddress(e.ab),[t,r]=(t&&this.htlcList.setAccount(e,t,r),await this.getAccountByAddress(e.bb));t&&this.htlcList.setAccount(e,t,r);let i=this.db.batch();i.put(u.txdb.VH(e.shash,e.sidx),e.toRaw()),await i.write()}async loadHtlcList(){return this.db.values({gte:u.txdb.VH(N.ZERO_CID,0),lte:u.txdb.VH(N.MAX_CID,4294967295),parse:t=>M.fromRaw(t)})}async delComment(t){if((t=new q(t)).id){this.commentList.delete(t.id),this.commentList.delAccount(t);let e=this.db.batch();e.del(u.txdb.VC(t.shash,t.sidx)),await e.write()}}async setComment(t){let e=new q(t);this.commentList.set(e.id,e);var[t,r]=await this.getAccountByAddress(e.bob);t&&(this.commentList.setAccount(e,t,r),this.emit("comm.comment",e));let i=this.db.batch();i.put(u.txdb.VC(e.shash,e.sidx),e.toRaw()),await i.write()}async loadCommentList(){return this.db.values({gte:u.txdb.VC(N.ZERO_CID,0),lte:u.txdb.VC(N.MAX_CID,4294967295),parse:t=>q.fromRaw(t)})}async setStockRecord(t){let e=this.db.batch();switch(e.put(t.itemNo,t.toRaw()),t.type){case G.RecordType.Offer:break;case G.RecordType.Bid:{let r=this.accountList.getStockAccount(t.cid,t.addr);if(!r)break;r.stock.sum=t.sum,r.stock.price=t.price,r.stock.period=this.curHeight+10*m.BLOCK_DAY,r.seq=t.seq,e.put(r.getItemNo(),r.toRaw());break}case G.RecordType.Auction:{let i=this.accountList.getStockAccount(t.cid,t.addr);i?(r=i.sum+t.sum,i.price=(t.sum*t.price+i.sum*i.price)/r|0,i.sum=r,i.seq=t.seq):((i=new tt(t.cid,t.addr,t.sum,t.price,0)).seq=t.seq,this.accountList.setStockAccount(i)),e.put(i.getItemNo(),i.toRaw());let s=this.accountList.getStockAccount(t.cid,t.to);if(!s)break;var r=s.sum-t.sum;s.sum=r,s.stock.sum-=t.sum,e.put(s.getItemNo(),s.toRaw());break}case G.RecordType.Purchase:{let i=this.accountList.getStockAccount(t.cid,t.addr);i?(r=i.sum+t.sum,i.price=(t.sum*t.price+i.sum*i.price)/r,i.sum=r,i.seq=t.seq):((i=new 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:{let i=this.accountList.getStockAccount(t.cid,t.addr);if(i){i.sum-=t.sum,i.seq=t.seq;let s=this.accountList.getStockAccount(t.cid,t.to);s||(s=new 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){let e=this.db.batch();switch(e.del(t.itemNo),t.type){case G.RecordType.Offer:break;case G.RecordType.Bid:{let r=this.accountList.getStockAccount(t.cid,t.addr);if(!r)break;r.stock.sum=0,r.stock.price=0,r.stock.period=0,r.seq=t.seq-1,e.put(r.getItemNo(),r.toRaw());break}case G.RecordType.Auction:{let i=this.accountList.getStockAccount(t.cid,t.addr);if(!i)break;var r=i.sum-t.sum;i.price=(i.sum*i.price-t.sum*t.price)/r|0,i.sum=r,i.seq=t.seq-1,e.put(i.getItemNo(),i.toRaw());let s=this.accountList.getStockAccount(t.cid,t.to);if(!s)break;r=s.sum+t.sum,s.sum=r,s.stock.sum+=t.sum,e.put(s.getItemNo(),s.toRaw());break}case G.RecordType.Purchase:{let i=this.accountList.getStockAccount(t.cid,t.addr);i&&(r=i.sum-t.sum,i.price=(i.sum*i.price-t.sum*t.price)/r,i.sum=r,i.seq=t.seq-1,e.put(i.getItemNo(),i.toRaw()));break}case G.RecordType.Send:{let i=this.accountList.getStockAccount(t.cid,t.addr);if(i){i.sum+=t.sum,i.seq=t.seq-1,e.put(i.getItemNo(),i.toRaw());let s=this.accountList.getStockAccount(t.cid,t.to);s&&(r=s.sum-t.sum,s.price=(s.sum*s.price-t.sum*i.price)/r|0,s.sum=r,e.put(s.getItemNo(),s.toRaw()))}break}case G.RecordType.Bonus:}await e.write()}async getStockRecordById(t){return(t=await this.db.get(t))?G.fromRaw(t):null}async verifyClsTx(t,e){if(!this.spv){let r=await k.FactoryOfContract({env:this,block:e,tx:t});if(1!=(e=await r.verify()))throw new g(t,S(e),"bad-contract-verify",100)}return!0}async getStockRecord(t,e,r){let i=6,s=N.ZERO_CID_BUF,n=N.MAX_CID_BUF,a=0;return t&&(i=t,e&&(s=e,n=e,a=r||0)),t=new I,(await this.db.values({gte:G.itemNo(i,s,a,N.NULL_HASH,0),lte:G.itemNo(i,n,4294967295,N.HIGH_HASH,4294967295),parse:G.fromRaw})).reduce((t,e)=>(t.set(e.itemNo,e),t),t),t}async getStockRecordByCid(t,e){let r=new I;for(var i of Object.keys(G.RecordType))i=await this.getStockRecord(G.RecordType[i],t,e),r.merge(i);return r}async getStockAccountList(t){var e;return t?(e=tt.SN(t,N.NULL_HASH),t=tt.SN(t,N.HIGH_HASH),this.db.values({gte:e,lte:t,parse:tt.fromRaw})):this.db.values({gte:tt.SN(N.ZERO_CID_BUF,N.NULL_HASH),lte:tt.SN(N.MAX_CID_BUF,N.HIGH_HASH),parse:tt.fromRaw})}async delEr(t){let e=this.db.batch();e.del(u.txdb.ER(t.erid)),e.del(u.txdb.ERR(t.witness,t.erid)),await e.write()}async setEr(t,e){e&&t.source&&(i=v.fromWitnessPubkeyhash(l.hash160(Buffer.from(t.source.pubkey,"hex")),this.network),[i,e]=await this.getAccountByAddress(i,e),t.wid=i,t.account=e);let r=this.db.batch();var i=u.txdb.ERR(t.witness,t.erid);r.put(i,t.toRaw()),r.put(u.txdb.ER(t.erid),i),await r.write()}async getEr(t){return(t=(t=await this.db.get(u.txdb.ER(t)))&&await this.db.get(t))?rt.fromRaw(t):null}async byPubkey(t,e,r=!1){let i=new I;var s;t=await this.db.values({gte:u.txdb.ERR(t,N.ZERO_CID),lte:u.txdb.ERR(t,N.MAX_CID),parse:t=>rt.fromRaw(t)});let n=[],a=new Map;if(r){for(var o of t)(!a.get(o.source.cluster)||o.startHeight>a.get(o.source.cluster).startHeight)&&a.set(o.source.cluster,await this.caVerifyObj(o));n=a.values()}else n=t;for(s of n)i.set(s.erid,s);return i.query(e)}async caVerifyObj(t){var e={verify:!1};if(!t||t.validHeight<=this.curHeight)return e;var r=await this.erAbList.getErAb(t.erid);return r&&r.abolishHeight<this.curHeight?e:(r=pt.fromPublic(Buffer.from(t.witness,"hex"),this.network.type),t.verify(r)?(t.verify=!0,0<(r=this.cpList.query([["pubKey",t.witness]])).list.length&&(t.cpid=r.list[0].cid),t):e)}async delErAbolish(t){let e=this.db.batch();e.del(u.txdb.ERA(t.erid)),await e.write()}async setErAbolish(t){let e=this.db.batch();e.put(u.txdb.ERA(t.erid),t.toRaw()),await e.write()}async getErAbolish(t){return(t=await this.db.get(u.txdb.ERA(t)))?Y.fromRaw(t):null}loadErAbolishList(){return this.db.values({gte:u.txdb.ERA(N.ZERO_CID),lte:u.txdb.ERA(N.MAX_CID),parse:t=>Y.fromRaw(t)})}async delAudit(t){let e=this.db.batch();e.del(u.txdb.AU(t.erid)),await e.write()}async setAudit(t){let e=this.db.batch();e.put(u.txdb.AU(t.erid),t.toRaw()),await e.write()}async getAudit(t){return(t=await this.db.get(u.txdb.AU(t)))?st.fromRaw(t):null}async loadAuditList(){return this.db.values({gte:u.txdb.AU(N.NULL_HASH),lte:u.txdb.AU(N.HIGH_HASH),parse:t=>st.fromRaw(t)})}async batchPut(t,e){const r=this.db.batch();r.put(t,e),await r.write()}async batchDel(t){const e=this.db.batch();e.del(t),await e.write()}async _insert(t,e,r){s(!t.mutable,"WDB: Cannot add mutable TX.");let i=await this.getWalletsByTX(t);if(i){this.logger.info("Incoming transaction for %d wallets in AccountDB (%s).",i.size,t.txid()),!e||this.state.marked||(this.logger.info("Marking AccountDB start block at %s (%d).",C.revHex(e.hash),e.height),await this.resetState(e,!0));let n=!1;for(const a of i){const i=await this.get(a);s(i),await i.add(t,e,r)&&(this.logger.info("Added transaction to wallet in AccountDB: %s (%d).",i.id,a),n=!0)}n||(i=null)}try{let r=await k.FactoryOfContract({env:this,block:e,tx:t});e?await r.confirm():await r.insert()}catch(r){e?this.logger.error("TX(%s) Smart Contract Confirm Error: %s",t.txid(),r.message):this.logger.error("TX(%s) Smart Contract Insert Error: %s",t.txid(),r.message)}return i}async _unconfirm(t,e){if(e)try{let r=await k.FactoryOfContract({env:this,block:e,tx:t});await r.unconfirm()}catch(i){this.logger.error("TX(%s) Smart Contract Unconfirm Error: %s",t.txid(),i.message)}let r,i=null;if(r=t.wids?(i=t.wids,t.hash):(i=await this.getWalletsByTX(t),t.hash("hex")),!i)return null;for(const t of i){const e=await this.get(t);s(e),await e.unconfirm(r)}for(const t of i){const e=await this.get(t);s(e),await e.abandon(r)}}async resetChain(t){const e=await this.txLock.lock();try{return await this._resetChain(t)}finally{e()}}async _resetChain(t){if(t.height>this.curHeight)throw new Error(`WDB: Bad reset height ${t.height} while curHeight `+this.curHeight);var e;for(e of(await this.rollback(t.height)||await this.scan(),await this.getWallets())){const r=await this.get(e);for(const e of await r.getPending())try{await r.abandon(e.hash)}catch(t){}await r.resetBalance()}}async saveMSTrans(t){const e=await this.writeLock.lock();try{return await this._saveMSTrans(t)}finally{e()}}async _saveMSTrans(t){const e=this.db.batch();e.put(h.ms(v.getHash(t.addr,"hex"),t.txid),Buffer.from(JSON.stringify(t))),await e.write()}async listMSTrans(t){return t=v.getHash(t,"hex"),this.db.values({gte:h.ms(t,N.NULL_HASH),lte:h.ms(t,N.HIGH_HASH),parse:t=>JSON.parse(t.toString())})}async delMSTrans(t,e){const r=await this.writeLock.lock();try{return await this._delMSTrans(t,e)}finally{r()}}async _delMSTrans(t,e){t=v.getHash(t,"hex");const r=this.db.batch();r.del(h.ms(t,e)),await r.write()}}yt.layout=h,t.exports=yt},function(t,e,r){"use strict";
840
840
  /*!
841
841
  * txdb.js - persistent transaction pool
842
842
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
package/lib/gamegold.js CHANGED
@@ -204,7 +204,7 @@ let r=[];[i(561),i(562),i(563),i(564),i(565),i(566),i(567),i(568),i(569),i(570),
204
204
  * pkg.js - package constants
205
205
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
206
206
  * https://github.com/bookmansoft/gamegold
207
- */e.protocol="vallnet",e.version="v4.0.10",e.url="https://github.com/bookmansoft/gamegold"},function(t,e,i){"use strict";
207
+ */e.protocol="vallnet",e.version="v4.0.11",e.url="https://github.com/bookmansoft/gamegold"},function(t,e,i){"use strict";
208
208
  /*!
209
209
  * common.js - p2p constants for vallnet
210
210
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -906,7 +906,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(
906
906
  /*!
907
907
  * accountdb.js - storage for account management
908
908
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
909
- */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),w=i(12);i(19);const v=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 r=null;if(r=e?await this.getWalletsByTX(e):await this.getWallets())for(const e of r){const r=await this.get(e);if(r){var i=await r.getPath(t);if(i)return[r.wid,i.name,r.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){let 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(e){return}if("object"==typeof i&&"secret"===i.type){let 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{w.fromString(t.contact,this.network.type),w.fromString(t.messenger,this.network.type)}catch(t){return}let e=await this.ensureContact(t);e&&await e.ensureMessenger(t).answer(t)}}async scanContact(t,e=-1){var i=async t=>{var e;t.witness&&"witnesspubkeyhash"==t.getType()&&(e=t.witness.getPubkeyhashInput()[1],t=w.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{w.fromString(t.contact,this.network.type),t.messenger&&w.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));let e=this.$contacts.get(t.contact);if(t.messenger){let r=e.ensureMessenger(t);if(!r.wallet){var[t,i]=await this.getAccountByAddress(r.address);if(!(t=await this.get(t)))return;r.wallet=t,r.account=i}}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){await this.txLock.lock();try{await this.init(t),await this.watch();let e=await this.ensure({id:"primary",witness:!0,mnemonic:this.options.mnemonic});await e.createReceive(0,1,e.master,this.network.type),await e.ensureNotifyKey(),await this.sync()}finally{e()}setTimeout(()=>{this.resend()},5e3)}}bind(){!this.client||this.bound||(this.bound=!0,this.client.hook("htlcassent.cancel",t=>{this.setAssent(t),this.emit("htlcassent.cancel",t)}),this.client.hook("htlcassent.deal",t=>{this.setAssent(t),this.emit("htlcassent.deal",t)}),this.client.hook("htlcassent.receive",t=>{this.setAssent(t),this.emit("htlcassent.receive",t)}),this.client.hook("htlcsuggest.cancel",t=>{this.setSuggest(t),this.emit("htlcsuggest.cancel",t)}),this.client.hook("htlcsuggest.deal",t=>{this.setSuggest(t),this.emit("htlcsuggest.deal",t)}),this.client.hook("htlcsuggest.receive",t=>{this.setSuggest(t),this.emit("htlcsuggest.receive",t)}),this.on("mssendpubk/receive",async t=>{let e=await this.get(t.addr);if(!e){e=await this.ensure({id:t.addr,type:"multisig",m:t.m,n:t.n,witness:!0});var[i,r]=await this.getAccountByAddress(t.addr);let s=await this.get(i);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)}if(e.account.keys.length<e.account.n-1){var s;for(s of t.data.split(","))try{await e.addSharedKey(s)}catch(s){}if(e.account.keys.length==e.account.n-1){var[i,r]=await this.getAccountByAddress(t.addr);let s=await this.get(i);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=>{let e=await this.get(t.addr);if(e&&e.account.type==o.types.MULTISIG){const i=v.fromRaw(t.data,"hex");i.view=await e.getCoinView(i),i.isSigned()||(t.txid=i.txid(),await this.saveMSTrans(t))}}),this.client.hook("onConnect",async()=>{await this.load()}),this.client.hook("error",t=>{this.emit("error",t)}),this.client.hook("block.connect",async(t,e)=>{try{await this.addBlock(t,e)}catch(t){this.emit("error",t)}}),this.client.hook("block.disconnect",async(t,e)=>{try{await this.removeBlock(t,e)}catch(t){this.emit("error",t)}}),this.client.hook("chain.full",()=>{this.synced=!0}),this.client.hook("block.rescan",async(t,e)=>{try{await this.rescanBlock(t,e)}catch(t){this.emit("error",t)}}),this.client.hook("tx",async(t,e,i)=>{try{await this.addTX(t,null,i)}catch(t){this.emit("error",t)}}),this.client.hook("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){const r=await this.get(e);s(r),await r.remove(i),(await x.FactoryOfContract({tx:t.tx,env:this})).erase()}}}catch(e){this.emit("error",e)}}),this.client.hook("chain.reset",async t=>{try{await this.resetChain(t)}catch(t){this.emit("error",t)}}),this.jsonp&&this.jsonp.hook("error",t=>{this.emit("error",t)}))}async disconnect(){this.client&&await this.client._close(),this.jsonp&&await this.jsonp._close()}async flushCP(t,e=!1){this.client&&(t=t||[],e||(t=this.cpList.excludeCids(t),e=e||0<t.length),e&&await this.client.execute("cp.remoteQuery",[[["cid","include",t]]]))}async watch(){let t=this.db.iterator({gte: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);var 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){const e=await this.txLock.lock();try{return await this.scan(t,!1)}finally{e()}}async send(t){if(this.client)return this.client.send(t);this.emit("send",t)}async getTX(t){for(const 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.");const 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(){const t=this.db.iterator({gte:u.w(0),lte:u.w(4294967295),reverse:!0,limit:1});var 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){const e=this.batch(t);t.current=null,t.accountCache.drop(),t.pathCache.drop(),e.clear()}clear(t){const e=this.batch(t);t.accountCache.clear(),t.pathCache.clear(),e.clear()}batch(t){return s(t.current,"WDB: Batch does not exist."),t.current}async commit(t){const e=this.batch(t);try{await e.write()}catch(t){throw this.drop(),t}t.current=null,t.accountCache.commit(),t.pathCache.commit()}testFilter(t){return this.filter.test(t,"hex")}addHash(t){return this.filter.add(t,"hex"),this.addFilter(t)}addOutpoint(t,e){const i=new y(t,e);this.filter.add(i.toRaw())}dump(){return this.db.dump()}register(t){s(!this.wallets.has(t.wid)),this.wallets.set(t.wid,t)}unregister(t){s(this.wallets.has(t.wid)),this.wallets.delete(t.wid)}async getWalletID(t){if(!t)return null;if("number"==typeof t)return t;var e=this.widCache.get(t);if(e)return e;const i=await this.db.get(u.l(t));return i?(e=i.readUInt32LE(0,!0),this.widCache.set(t,e),e):null}async get(t){if(!(t=await this.getWalletID(t)))return null;const e=await this.readLock.lock(t);try{return await this._get(t)}finally{e()}}async _get(t){var e=this.wallets.get(t);if(e)return e;if(!(e=await this.db.get(u.w(t))))return null;const i=a.fromRaw(this,e);return await i.open(),this.register(i),i}async loadBackup(t){if(ft.unsupported)throw new gt(mt.INTERNAL_ERROR,"FS not available.");let e=await this.get("primary");const i=await ft.readFile(t,"utf8");var r;for(r of i.split(/\n+/))if(0!==(r=r.trim()).length&&!/^\s*#/.test(r)){const t=r.split(/\s+/);if(t.length<4)throw new gt(mt.DESERIALIZATION_ERROR,"Malformed wallet Data File.");switch(t[0]){case"W":var n=Buffer.from(t[1],"base64");n=a.fromRaw(e.db,n);if(e.wid!=n.wid)throw new 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(t[1],"base64");const i=o.fromRaw(e.db,n);i.wallet=e,i.wid=e.wid,i.id=e.id,i.initialized=!0,i.watchOnly=e.watchOnly,i.receive=i.deriveReceive(i.receiveDepth-1),i.change=i.deriveChange(i.changeDepth-1),i.witness&&(i.nested=i.deriveNested(i.nestedDepth-1));let r=e.master.key.deriveAccount(44,i.accountIndex);r.publicKey.toString("hex")!==i.accountKey.publicKey.toString("hex")&&s(r.publicKey.toString("hex")==i.accountKey.publicKey.toString("hex")),await e.saveAccount(i),this.logger.info("Import Account %s(%s)",i.name,i.accountIndex);break}case"A":{var c=parseInt(t[5]),h=parseInt(t[7]),u=parseInt(t[9]),l=t[11].trim();let i=await e.deriveKey(c,h,u),r=await e.deriveKey(c,h,u,e.master);i.getAddress("string")!==r.getAddress("string")&&s(i.getAddress("string")==r.getAddress("string")),i.getAddress("string")!==l&&s(i.getAddress("string")==l),this.logger.info("Import Address %s %s %s %s",c,h,u,i.getAddress("string"));break}}}return e.accountCache.reset(),e}save(t){var e=t.wid,i=t.id;const 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){const 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);for(const i of t.pathCache.values())i.id=e}async replace(t){const e=await this.writeLock.lock();try{return await this._replace(t)}finally{e()}}async _replace(t){const e=this.start(t);e.del(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);const i=r.createHmac("sha256",t.random);if(t=Buffer.from(i.update(t.token).digest("hex"),"hex"),!p(e,t))throw new Error("WDB Authentication: CRC Error.")}async create(t){const e=await this.writeLock.lock();t=t||{};try{return await this._create(t)}finally{e()}}async _create(t){if(await this.has(t.id))throw new Error("WDB: Wallet already exists.");"string"==typeof t.mnemonic&&(t.mnemonic={phrase:t.mnemonic}),t.mnemonic=t.mnemonic||{},!t.mnemonic.language&&this.options.mnemonic&&this.options.mnemonic.language&&(t.mnemonic.language=this.options.mnemonic.language);const e=a.fromOptions(this,t);return e.wid=this.depth++,await e.init(t),this.register(e),this.logger.info("Created wallet %s in AccountDB.",e.id),e}async has(t){return null!=await this.getWalletID(t)}async ensure(t){return await this.get(t.id)||this.create(t)}async getAccount(t,e){return(t=await this.db.get(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){const i=await this.db.get(u.i(t,e));return i?i.readUInt32LE(0,!0):-1}async getGuider(t){return t=w.fromString(t,this.network.type).getHash("hex"),(t=await this.db.get(u.g(t)))?w.fromRaw(t).toString():null}async setGuider(t,e,i){if(i=w.fromString(i,this.network.type).getHash("hex"),!await this.db.has(u.g(i))){t=w.fromString(t,this.network.type);const r=this.db.batch();r.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=w.fromString(t,this.network.type).getHash("hex"),i=w.fromString(i,this.network.type).getHash("hex");const 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){const i=await this.db.get(u.n(t,e));return i?i.toString("ascii"):null}saveAccount(t){var e=t.wid;const i=t.wallet;var r=t.accountIndex,s=t.name;const 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;const 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));if(!i)return null;const r=at.fromRaw(i);return r.wid=t,r.hash=e,r}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){const e=[];for(const r of await this.db.range({gte:u.P(t,F.NULL_HASH),lte:u.P(t,F.HIGH_HASH)})){var i=u.Pp(r.key);const s=at.fromRaw(r.value);s.hash=i,s.wid=t,e.push(s)}return e}async encryptKeys(t,e){var i,r=t.wid,n=await t.getPaths();const a=this.batch(t);for(i of n)if(i.data){s(!i.encrypted);var o=Buffer.from(i.hash,"hex").slice(0,16);(i=i.clone()).data=d.encipher(i.data,e,o),i.encrypted=!0,t.pathCache.push(i.hash,i),a.put(u.P(r,i.hash),i.toRaw())}}async decryptKeys(t,e){var i,r=t.wid,n=await t.getPaths();const a=this.batch(t);for(i of n)if(i.data){s(i.encrypted);var o=Buffer.from(i.hash,"hex").slice(0,16);(i=i.clone()).data=d.decipher(i.data,e,o),i.encrypted=!1,t.pathCache.push(i.hash,i),a.put(u.P(r,i.hash),i.toRaw())}}async resend(){let t={};var e;for(const e of await this.db.keys({gte:u.w(0),lte:u.w(4294967295)})){var i,r=u.ww(e);!r||(i=await this.resendPending(r))&&Array.isArray(i)&&(t[r]=i)}for(e of Object.keys(t)){let i=await this.get(parseInt(e));if(i)for(const r of t[e]){try{await this.send(r)}catch(t){this.logger.warning("wdb resend:",t.message);try{await i.abandon(r.hash("hex"))}catch(t){this.logger.warning("wdb abandon:",t.message)}}await dt.timeout(50)}}}async resendPending(t){const e=await this.get(t);var 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);const n=[];for(const a of i){var r=h.txdb.pp(a),s=h.txdb.prefix(t,h.txdb.t(r));if(s=await this.db.get(s)){const i=lt.fromRaw(s);if(!i.tx.isCoinbase())try{let t=await x.FactoryOfContract({tx:i.tx,env:this});"notify"!=t.oper&&(await t.isBlockFinal()==E.Expired?e&&(await this.removeTX(i.tx),await e.remove(r),await t.erase()):n.push(i.tx))}catch(t){this.logger.error("TX(%s) Smart Contract Error: %s",i.tx.txid(),t.message)}}}return await P(n,this)}}getWallets(){return this.db.keys({gte:u.l("\0"),lte:u.l("ÿ"),parse:u.ll})}async getWalletsByTX(t){const e=new Set;if(!t.isCoinbase())for(const r of t.inputs){const t=r.prevout;if(this.testFilter(t.toRaw())){var i=await this.getOutpointMap(t.hash,t.index);if(i)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){const 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});for(;;){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){const 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){const s=this.batch(t);this.addOutpoint(e,i),s.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);e=Buffer.from(JSON.stringify(e));const r=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){const e=await this.db.get(u.h(t));if(!e)return null;const i=new ht;return i.hash=e.toString("hex"),i.height=t,i}async getTip(){var t=await this.getBlock(this.curHeight);if(t)return t;throw new Error("WDB: Tip not found!")}async rollback(t,e=!0){if(t>this.curHeight)throw new Error("WDB: Cannot rollback to the future.");if(t===this.curHeight)return this.logger.debug("Rolled back to same height (%d).",t),!0;this.logger.info("Rolling back %d AccountDB blocks to height %d.",this.curHeight-t,t);let i=await this.getBlock(t),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){const 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);var 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){const 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){const 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){const 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){const 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){let e=this.db.batch();e.del(h.txdb.VP(t.pid)),await e.write()}async setVp(t,e){let 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){let 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){if((t=new z(t)).id){this.htlcList.delete(t.id),this.htlcList.delAccount(t);let e=this.db.batch();e.del(h.txdb.VH(t.shash,t.sidx)),await e.write()}}async setSuggest(t){let e=new z(t);this.htlcList.set(e.id,e);var[t,i]=await this.getAccountByAddress(e.aa),[t,i]=(t&&this.htlcList.setAccount(e,t,i),await this.getAccountByAddress(e.ba));t&&this.htlcList.setAccount(e,t,i);let r=this.db.batch();r.put(h.txdb.VH(e.shash,e.sidx),e.toRaw()),await r.write()}async setAssent(t){let e=new z(t);this.htlcList.set(e.id,e);var[t,i]=await this.getAccountByAddress(e.ab),[t,i]=(t&&this.htlcList.setAccount(e,t,i),await this.getAccountByAddress(e.bb));t&&this.htlcList.setAccount(e,t,i);let r=this.db.batch();r.put(h.txdb.VH(e.shash,e.sidx),e.toRaw()),await r.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){if((t=new q(t)).id){this.commentList.delete(t.id),this.commentList.delAccount(t);let e=this.db.batch();e.del(h.txdb.VC(t.shash,t.sidx)),await e.write()}}async setComment(t){let e=new q(t);this.commentList.set(e.id,e);var[t,i]=await this.getAccountByAddress(e.bob);t&&(this.commentList.setAccount(e,t,i),this.emit("comm.comment",e));let r=this.db.batch();r.put(h.txdb.VC(e.shash,e.sidx),e.toRaw()),await r.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){let e=this.db.batch();switch(e.put(t.itemNo,t.toRaw()),t.type){case G.RecordType.Offer:break;case G.RecordType.Bid:{let i=this.accountList.getStockAccount(t.cid,t.addr);if(!i)break;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 r=this.accountList.getStockAccount(t.cid,t.addr);r?(i=r.sum+t.sum,r.price=(t.sum*t.price+r.sum*r.price)/i|0,r.sum=i,r.seq=t.seq):((r=new tt(t.cid,t.addr,t.sum,t.price,0)).seq=t.seq,this.accountList.setStockAccount(r)),e.put(r.getItemNo(),r.toRaw());let s=this.accountList.getStockAccount(t.cid,t.to);if(!s)break;var i=s.sum-t.sum;s.sum=i,s.stock.sum-=t.sum,e.put(s.getItemNo(),s.toRaw());break}case G.RecordType.Purchase:{let r=this.accountList.getStockAccount(t.cid,t.addr);r?(i=r.sum+t.sum,r.price=(t.sum*t.price+r.sum*r.price)/i,r.sum=i,r.seq=t.seq):((r=new tt(t.cid,t.addr,t.sum,t.price,0)).seq=t.seq,this.accountList.setStockAccount(r)),e.put(r.getItemNo(),r.toRaw());break}case G.RecordType.Send:{let r=this.accountList.getStockAccount(t.cid,t.addr);if(r){r.sum-=t.sum,r.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)),i=s.sum+t.sum,s.price=(t.sum*r.price+s.sum*s.price)/i,s.sum=i,e.put(r.getItemNo(),r.toRaw()),e.put(s.getItemNo(),s.toRaw())}break}case G.RecordType.Bonus:case G.RecordType.Ads:}await e.write()}async unsetStockRecord(t){let e=this.db.batch();switch(e.del(t.itemNo),t.type){case G.RecordType.Offer:break;case G.RecordType.Bid:{let i=this.accountList.getStockAccount(t.cid,t.addr);if(!i)break;i.stock.sum=0,i.stock.price=0,i.stock.period=0,i.seq=t.seq-1,e.put(i.getItemNo(),i.toRaw());break}case G.RecordType.Auction:{let r=this.accountList.getStockAccount(t.cid,t.addr);if(!r)break;var i=r.sum-t.sum;r.price=(r.sum*r.price-t.sum*t.price)/i|0,r.sum=i,r.seq=t.seq-1,e.put(r.getItemNo(),r.toRaw());let s=this.accountList.getStockAccount(t.cid,t.to);if(!s)break;i=s.sum+t.sum,s.sum=i,s.stock.sum+=t.sum,e.put(s.getItemNo(),s.toRaw());break}case G.RecordType.Purchase:{let r=this.accountList.getStockAccount(t.cid,t.addr);r&&(i=r.sum-t.sum,r.price=(r.sum*r.price-t.sum*t.price)/i,r.sum=i,r.seq=t.seq-1,e.put(r.getItemNo(),r.toRaw()));break}case G.RecordType.Send:{let r=this.accountList.getStockAccount(t.cid,t.addr);if(r){r.sum+=t.sum,r.seq=t.seq-1,e.put(r.getItemNo(),r.toRaw());let s=this.accountList.getStockAccount(t.cid,t.to);s&&(i=s.sum-t.sum,s.price=(s.sum*s.price-t.sum*r.price)/i|0,s.sum=i,e.put(s.getItemNo(),s.toRaw()))}break}case G.RecordType.Bonus:}await e.write()}async getStockRecordById(t){return(t=await this.db.get(t))?G.fromRaw(t):null}async verifyClsTx(t,e){if(!this.spv){let i=await x.FactoryOfContract({env:this,block:e,tx:t});if(1!=(e=await i.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){let i=new C;for(var r of Object.keys(G.RecordType))r=await this.getStockRecord(G.RecordType[r],t,e),i.merge(r);return i}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){let e=this.db.batch();e.del(h.txdb.ER(t.erid)),e.del(h.txdb.ERR(t.witness,t.erid)),await e.write()}async setEr(t,e){e&&t.source&&(r=w.fromWitnessPubkeyhash(l.hash160(Buffer.from(t.source.pubkey,"hex")),this.network),[r,e]=await this.getAccountByAddress(r,e),t.wid=r,t.account=e);let i=this.db.batch();var r=h.txdb.ERR(t.witness,t.erid);i.put(r,t.toRaw()),i.put(h.txdb.ER(t.erid),r),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){let r=new C;var s;t=await this.db.values({gte:h.txdb.ERR(t,F.ZERO_CID),lte:h.txdb.ERR(t,F.MAX_CID),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(s of n)r.set(s.erid,s);return r.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){let e=this.db.batch();e.del(h.txdb.ERA(t.erid)),await e.write()}async setErAbolish(t){let 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){let e=this.db.batch();e.del(h.txdb.AU(t.erid)),await e.write()}async setAudit(t){let 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){const i=this.db.batch();i.put(t,e),await i.write()}async batchDel(t){const 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 n=!1;for(const a of r){const r=await this.get(a);s(r),await r.add(t,e,i)&&(this.logger.info("Added transaction to wallet in AccountDB: %s (%d).",r.id,a),n=!0)}n||(r=null)}try{let i=await x.FactoryOfContract({env:this,block:e,tx:t});e?await i.confirm():await i.insert()}catch(i){e?this.logger.error("TX(%s) Smart Contract Confirm Error: %s",t.txid(),i.message):this.logger.error("TX(%s) Smart Contract Insert Error: %s",t.txid(),i.message)}return r}async _unconfirm(t,e){if(e)try{let i=await x.FactoryOfContract({env:this,block:e,tx:t});await i.unconfirm()}catch(r){this.logger.error("TX(%s) Smart Contract Unconfirm Error: %s",t.txid(),r.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){const e=await this.get(t);s(e),await e.unconfirm(i)}for(const t of r){const e=await this.get(t);s(e),await e.abandon(i)}}async resetChain(t){const e=await this.txLock.lock();try{return await this._resetChain(t)}finally{e()}}async _resetChain(t){if(t.height>this.curHeight)throw new Error(`WDB: Bad reset height ${t.height} while curHeight `+this.curHeight);var e;for(e of(await this.rollback(t.height)||await this.scan(),await this.getWallets())){const 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){const e=await this.writeLock.lock();try{return await this._saveMSTrans(t)}finally{e()}}async _saveMSTrans(t){const e=this.db.batch();e.put(u.ms(w.getHash(t.addr,"hex"),t.txid),Buffer.from(JSON.stringify(t))),await e.write()}async listMSTrans(t){return t=w.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){const i=await this.writeLock.lock();try{return await this._delMSTrans(t,e)}finally{i()}}async _delMSTrans(t,e){t=w.getHash(t,"hex");const 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";
909
+ */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),w=i(12);i(19);const v=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 r=null;if(r=e?await this.getWalletsByTX(e):await this.getWallets())for(const e of r){const r=await this.get(e);if(r){var i=await r.getPath(t);if(i)return[r.wid,i.name,r.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){let 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(e){return}if("object"==typeof i&&"secret"===i.type){let 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{w.fromString(t.contact,this.network.type),w.fromString(t.messenger,this.network.type)}catch(t){return}let e=await this.ensureContact(t);e&&await e.ensureMessenger(t).answer(t)}}async scanContact(t,e=-1){var i=async t=>{var e;t.witness&&"witnesspubkeyhash"==t.getType()&&(e=t.witness.getPubkeyhashInput()[1],t=w.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{w.fromString(t.contact,this.network.type),t.messenger&&w.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));let e=this.$contacts.get(t.contact);if(t.messenger){let r=e.ensureMessenger(t);if(!r.wallet){var[t,i]=await this.getAccountByAddress(r.address);if(!(t=await this.get(t)))return;r.wallet=t,r.account=i}}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){const 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);if(!e){e=await this.ensure({id:t.addr,type:"multisig",m:t.m,n:t.n,witness:!0});var[i,r]=await this.getAccountByAddress(t.addr);let s=await this.get(i);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)}if(e.account.keys.length<e.account.n-1){var s;for(s of t.data.split(","))try{await e.addSharedKey(s)}catch(s){}if(e.account.keys.length==e.account.n-1){var[i,r]=await this.getAccountByAddress(t.addr);let s=await this.get(i);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=>{let e=await this.get(t.addr);if(e&&e.account.type==o.types.MULTISIG){const i=v.fromRaw(t.data,"hex");i.view=await e.getCoinView(i),i.isSigned()||(t.txid=i.txid(),await this.saveMSTrans(t))}}),this.client.hook("onConnect",async()=>{await this.load()}),this.client.hook("error",t=>{this.emit("error",t)}),this.client.hook("block.connect",async(t,e)=>{try{await this.addBlock(t,e)}catch(t){this.emit("error",t)}}),this.client.hook("block.disconnect",async(t,e)=>{try{await this.removeBlock(t,e)}catch(t){this.emit("error",t)}}),this.client.hook("chain.full",()=>{this.synced=!0}),this.client.hook("block.rescan",async(t,e)=>{try{await this.rescanBlock(t,e)}catch(t){this.emit("error",t)}}),this.client.hook("tx",async(t,e,i)=>{try{await this.addTX(t,null,i)}catch(t){this.emit("error",t)}}),this.client.hook("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){const r=await this.get(e);s(r),await r.remove(i),(await x.FactoryOfContract({tx:t.tx,env:this})).erase()}}}catch(e){this.emit("error",e)}}),this.client.hook("chain.reset",async t=>{try{await this.resetChain(t)}catch(t){this.emit("error",t)}}),this.jsonp&&this.jsonp.hook("error",t=>{this.emit("error",t)}))}async disconnect(){this.client&&await this.client._close(),this.jsonp&&await this.jsonp._close()}async flushCP(t,e=!1){this.client&&(t=t||[],e||(t=this.cpList.excludeCids(t),e=e||0<t.length),e&&await this.client.execute("cp.remoteQuery",[[["cid","include",t]]]))}async watch(){let t=this.db.iterator({gte: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);var 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){const e=await this.txLock.lock();try{return await this.scan(t,!1)}finally{e()}}async send(t){if(this.client)return this.client.send(t);this.emit("send",t)}async getTX(t){for(const 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.");const 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(){const t=this.db.iterator({gte:u.w(0),lte:u.w(4294967295),reverse:!0,limit:1});var 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){const e=this.batch(t);t.current=null,t.accountCache.drop(),t.pathCache.drop(),e.clear()}clear(t){const e=this.batch(t);t.accountCache.clear(),t.pathCache.clear(),e.clear()}batch(t){return s(t.current,"WDB: Batch does not exist."),t.current}async commit(t){const e=this.batch(t);try{await e.write()}catch(t){throw this.drop(),t}t.current=null,t.accountCache.commit(),t.pathCache.commit()}testFilter(t){return this.filter.test(t,"hex")}addHash(t){return this.filter.add(t,"hex"),this.addFilter(t)}addOutpoint(t,e){const i=new y(t,e);this.filter.add(i.toRaw())}dump(){return this.db.dump()}register(t){s(!this.wallets.has(t.wid)),this.wallets.set(t.wid,t)}unregister(t){s(this.wallets.has(t.wid)),this.wallets.delete(t.wid)}async getWalletID(t){if(!t)return null;if("number"==typeof t)return t;var e=this.widCache.get(t);if(e)return e;const i=await this.db.get(u.l(t));return i?(e=i.readUInt32LE(0,!0),this.widCache.set(t,e),e):null}async get(t){if(!(t=await this.getWalletID(t)))return null;const e=await this.readLock.lock(t);try{return await this._get(t)}finally{e()}}async _get(t){var e=this.wallets.get(t);if(e)return e;if(!(e=await this.db.get(u.w(t))))return null;const i=a.fromRaw(this,e);return await i.open(),this.register(i),i}async loadBackup(t){if(ft.unsupported)throw new gt(mt.INTERNAL_ERROR,"FS not available.");let e=await this.get("primary");const i=await ft.readFile(t,"utf8");var r;for(r of i.split(/\n+/))if(0!==(r=r.trim()).length&&!/^\s*#/.test(r)){const t=r.split(/\s+/);if(t.length<4)throw new gt(mt.DESERIALIZATION_ERROR,"Malformed wallet Data File.");switch(t[0]){case"W":var n=Buffer.from(t[1],"base64");n=a.fromRaw(e.db,n);if(e.wid!=n.wid)throw new 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(t[1],"base64");const i=o.fromRaw(e.db,n);i.wallet=e,i.wid=e.wid,i.id=e.id,i.initialized=!0,i.watchOnly=e.watchOnly,i.receive=i.deriveReceive(i.receiveDepth-1),i.change=i.deriveChange(i.changeDepth-1),i.witness&&(i.nested=i.deriveNested(i.nestedDepth-1));let r=e.master.key.deriveAccount(44,i.accountIndex);r.publicKey.toString("hex")!==i.accountKey.publicKey.toString("hex")&&s(r.publicKey.toString("hex")==i.accountKey.publicKey.toString("hex")),await e.saveAccount(i),this.logger.info("Import Account %s(%s)",i.name,i.accountIndex);break}case"A":{var c=parseInt(t[5]),h=parseInt(t[7]),u=parseInt(t[9]),l=t[11].trim();let i=await e.deriveKey(c,h,u),r=await e.deriveKey(c,h,u,e.master);i.getAddress("string")!==r.getAddress("string")&&s(i.getAddress("string")==r.getAddress("string")),i.getAddress("string")!==l&&s(i.getAddress("string")==l),this.logger.info("Import Address %s %s %s %s",c,h,u,i.getAddress("string"));break}}}return e.accountCache.reset(),e}save(t){var e=t.wid,i=t.id;const 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){const 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);for(const i of t.pathCache.values())i.id=e}async replace(t){const e=await this.writeLock.lock();try{return await this._replace(t)}finally{e()}}async _replace(t){const e=this.start(t);e.del(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);const i=r.createHmac("sha256",t.random);if(t=Buffer.from(i.update(t.token).digest("hex"),"hex"),!p(e,t))throw new Error("WDB Authentication: CRC Error.")}async create(t){const e=await this.writeLock.lock();t=t||{};try{return await this._create(t)}finally{e()}}async _create(t){if(await this.has(t.id))throw new Error("WDB: Wallet already exists.");"string"==typeof t.mnemonic&&(t.mnemonic={phrase:t.mnemonic}),t.mnemonic=t.mnemonic||{},!t.mnemonic.language&&this.options.mnemonic&&this.options.mnemonic.language&&(t.mnemonic.language=this.options.mnemonic.language);const e=a.fromOptions(this,t);return e.wid=this.depth++,await e.init(t),this.register(e),this.logger.info("Created wallet %s in AccountDB.",e.id),e}async has(t){return null!=await this.getWalletID(t)}async ensure(t){return await this.get(t.id)||this.create(t)}async getAccount(t,e){return(t=await this.db.get(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){const i=await this.db.get(u.i(t,e));return i?i.readUInt32LE(0,!0):-1}async getGuider(t){return t=w.fromString(t,this.network.type).getHash("hex"),(t=await this.db.get(u.g(t)))?w.fromRaw(t).toString():null}async setGuider(t,e,i){if(i=w.fromString(i,this.network.type).getHash("hex"),!await this.db.has(u.g(i))){t=w.fromString(t,this.network.type);const r=this.db.batch();r.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=w.fromString(t,this.network.type).getHash("hex"),i=w.fromString(i,this.network.type).getHash("hex");const 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){const i=await this.db.get(u.n(t,e));return i?i.toString("ascii"):null}saveAccount(t){var e=t.wid;const i=t.wallet;var r=t.accountIndex,s=t.name;const 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;const 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));if(!i)return null;const r=at.fromRaw(i);return r.wid=t,r.hash=e,r}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){const e=[];for(const r of await this.db.range({gte:u.P(t,F.NULL_HASH),lte:u.P(t,F.HIGH_HASH)})){var i=u.Pp(r.key);const s=at.fromRaw(r.value);s.hash=i,s.wid=t,e.push(s)}return e}async encryptKeys(t,e){var i,r=t.wid,n=await t.getPaths();const a=this.batch(t);for(i of n)if(i.data){s(!i.encrypted);var o=Buffer.from(i.hash,"hex").slice(0,16);(i=i.clone()).data=d.encipher(i.data,e,o),i.encrypted=!0,t.pathCache.push(i.hash,i),a.put(u.P(r,i.hash),i.toRaw())}}async decryptKeys(t,e){var i,r=t.wid,n=await t.getPaths();const a=this.batch(t);for(i of n)if(i.data){s(i.encrypted);var o=Buffer.from(i.hash,"hex").slice(0,16);(i=i.clone()).data=d.decipher(i.data,e,o),i.encrypted=!1,t.pathCache.push(i.hash,i),a.put(u.P(r,i.hash),i.toRaw())}}async resend(){let t={};var e;for(const e of await this.db.keys({gte:u.w(0),lte:u.w(4294967295)})){var i,r=u.ww(e);!r||(i=await this.resendPending(r))&&Array.isArray(i)&&(t[r]=i)}for(e of Object.keys(t)){let i=await this.get(parseInt(e));if(i)for(const r of t[e]){try{await this.send(r)}catch(t){this.logger.warning("wdb resend:",t.message);try{await i.abandon(r.hash("hex"))}catch(t){this.logger.warning("wdb abandon:",t.message)}}await dt.timeout(50)}}}async resendPending(t){const e=await this.get(t);var 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);const n=[];for(const a of i){var r=h.txdb.pp(a),s=h.txdb.prefix(t,h.txdb.t(r));if(s=await this.db.get(s)){const i=lt.fromRaw(s);if(!i.tx.isCoinbase())try{let t=await x.FactoryOfContract({tx:i.tx,env:this});"notify"!=t.oper&&(await t.isBlockFinal()==E.Expired?e&&(await this.removeTX(i.tx),await e.remove(r),await t.erase()):n.push(i.tx))}catch(t){this.logger.error("TX(%s) Smart Contract Error: %s",i.tx.txid(),t.message)}}}return await P(n,this)}}getWallets(){return this.db.keys({gte:u.l("\0"),lte:u.l("ÿ"),parse:u.ll})}async getWalletsByTX(t){const e=new Set;if(!t.isCoinbase())for(const r of t.inputs){const t=r.prevout;if(this.testFilter(t.toRaw())){var i=await this.getOutpointMap(t.hash,t.index);if(i)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){const 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});for(;;){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){const 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){const s=this.batch(t);this.addOutpoint(e,i),s.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);e=Buffer.from(JSON.stringify(e));const r=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){const e=await this.db.get(u.h(t));if(!e)return null;const i=new ht;return i.hash=e.toString("hex"),i.height=t,i}async getTip(){var t=await this.getBlock(this.curHeight);if(t)return t;throw new Error("WDB: Tip not found!")}async rollback(t,e=!0){if(t>this.curHeight)throw new Error("WDB: Cannot rollback to the future.");if(t===this.curHeight)return this.logger.debug("Rolled back to same height (%d).",t),!0;this.logger.info("Rolling back %d AccountDB blocks to height %d.",this.curHeight-t,t);let i=await this.getBlock(t),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){const 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);var 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){const 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){const 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){const 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){const 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){let e=this.db.batch();e.del(h.txdb.VP(t.pid)),await e.write()}async setVp(t,e){let 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){let 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){if((t=new z(t)).id){this.htlcList.delete(t.id),this.htlcList.delAccount(t);let e=this.db.batch();e.del(h.txdb.VH(t.shash,t.sidx)),await e.write()}}async setSuggest(t){let e=new z(t);this.htlcList.set(e.id,e);var[t,i]=await this.getAccountByAddress(e.aa),[t,i]=(t&&this.htlcList.setAccount(e,t,i),await this.getAccountByAddress(e.ba));t&&this.htlcList.setAccount(e,t,i);let r=this.db.batch();r.put(h.txdb.VH(e.shash,e.sidx),e.toRaw()),await r.write()}async setAssent(t){let e=new z(t);this.htlcList.set(e.id,e);var[t,i]=await this.getAccountByAddress(e.ab),[t,i]=(t&&this.htlcList.setAccount(e,t,i),await this.getAccountByAddress(e.bb));t&&this.htlcList.setAccount(e,t,i);let r=this.db.batch();r.put(h.txdb.VH(e.shash,e.sidx),e.toRaw()),await r.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){if((t=new q(t)).id){this.commentList.delete(t.id),this.commentList.delAccount(t);let e=this.db.batch();e.del(h.txdb.VC(t.shash,t.sidx)),await e.write()}}async setComment(t){let e=new q(t);this.commentList.set(e.id,e);var[t,i]=await this.getAccountByAddress(e.bob);t&&(this.commentList.setAccount(e,t,i),this.emit("comm.comment",e));let r=this.db.batch();r.put(h.txdb.VC(e.shash,e.sidx),e.toRaw()),await r.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){let e=this.db.batch();switch(e.put(t.itemNo,t.toRaw()),t.type){case G.RecordType.Offer:break;case G.RecordType.Bid:{let i=this.accountList.getStockAccount(t.cid,t.addr);if(!i)break;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 r=this.accountList.getStockAccount(t.cid,t.addr);r?(i=r.sum+t.sum,r.price=(t.sum*t.price+r.sum*r.price)/i|0,r.sum=i,r.seq=t.seq):((r=new tt(t.cid,t.addr,t.sum,t.price,0)).seq=t.seq,this.accountList.setStockAccount(r)),e.put(r.getItemNo(),r.toRaw());let s=this.accountList.getStockAccount(t.cid,t.to);if(!s)break;var i=s.sum-t.sum;s.sum=i,s.stock.sum-=t.sum,e.put(s.getItemNo(),s.toRaw());break}case G.RecordType.Purchase:{let r=this.accountList.getStockAccount(t.cid,t.addr);r?(i=r.sum+t.sum,r.price=(t.sum*t.price+r.sum*r.price)/i,r.sum=i,r.seq=t.seq):((r=new tt(t.cid,t.addr,t.sum,t.price,0)).seq=t.seq,this.accountList.setStockAccount(r)),e.put(r.getItemNo(),r.toRaw());break}case G.RecordType.Send:{let r=this.accountList.getStockAccount(t.cid,t.addr);if(r){r.sum-=t.sum,r.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)),i=s.sum+t.sum,s.price=(t.sum*r.price+s.sum*s.price)/i,s.sum=i,e.put(r.getItemNo(),r.toRaw()),e.put(s.getItemNo(),s.toRaw())}break}case G.RecordType.Bonus:case G.RecordType.Ads:}await e.write()}async unsetStockRecord(t){let e=this.db.batch();switch(e.del(t.itemNo),t.type){case G.RecordType.Offer:break;case G.RecordType.Bid:{let i=this.accountList.getStockAccount(t.cid,t.addr);if(!i)break;i.stock.sum=0,i.stock.price=0,i.stock.period=0,i.seq=t.seq-1,e.put(i.getItemNo(),i.toRaw());break}case G.RecordType.Auction:{let r=this.accountList.getStockAccount(t.cid,t.addr);if(!r)break;var i=r.sum-t.sum;r.price=(r.sum*r.price-t.sum*t.price)/i|0,r.sum=i,r.seq=t.seq-1,e.put(r.getItemNo(),r.toRaw());let s=this.accountList.getStockAccount(t.cid,t.to);if(!s)break;i=s.sum+t.sum,s.sum=i,s.stock.sum+=t.sum,e.put(s.getItemNo(),s.toRaw());break}case G.RecordType.Purchase:{let r=this.accountList.getStockAccount(t.cid,t.addr);r&&(i=r.sum-t.sum,r.price=(r.sum*r.price-t.sum*t.price)/i,r.sum=i,r.seq=t.seq-1,e.put(r.getItemNo(),r.toRaw()));break}case G.RecordType.Send:{let r=this.accountList.getStockAccount(t.cid,t.addr);if(r){r.sum+=t.sum,r.seq=t.seq-1,e.put(r.getItemNo(),r.toRaw());let s=this.accountList.getStockAccount(t.cid,t.to);s&&(i=s.sum-t.sum,s.price=(s.sum*s.price-t.sum*r.price)/i|0,s.sum=i,e.put(s.getItemNo(),s.toRaw()))}break}case G.RecordType.Bonus:}await e.write()}async getStockRecordById(t){return(t=await this.db.get(t))?G.fromRaw(t):null}async verifyClsTx(t,e){if(!this.spv){let i=await x.FactoryOfContract({env:this,block:e,tx:t});if(1!=(e=await i.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){let i=new C;for(var r of Object.keys(G.RecordType))r=await this.getStockRecord(G.RecordType[r],t,e),i.merge(r);return i}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){let e=this.db.batch();e.del(h.txdb.ER(t.erid)),e.del(h.txdb.ERR(t.witness,t.erid)),await e.write()}async setEr(t,e){e&&t.source&&(r=w.fromWitnessPubkeyhash(l.hash160(Buffer.from(t.source.pubkey,"hex")),this.network),[r,e]=await this.getAccountByAddress(r,e),t.wid=r,t.account=e);let i=this.db.batch();var r=h.txdb.ERR(t.witness,t.erid);i.put(r,t.toRaw()),i.put(h.txdb.ER(t.erid),r),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){let r=new C;var s;t=await this.db.values({gte:h.txdb.ERR(t,F.ZERO_CID),lte:h.txdb.ERR(t,F.MAX_CID),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(s of n)r.set(s.erid,s);return r.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){let e=this.db.batch();e.del(h.txdb.ERA(t.erid)),await e.write()}async setErAbolish(t){let 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){let e=this.db.batch();e.del(h.txdb.AU(t.erid)),await e.write()}async setAudit(t){let 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){const i=this.db.batch();i.put(t,e),await i.write()}async batchDel(t){const 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 n=!1;for(const a of r){const r=await this.get(a);s(r),await r.add(t,e,i)&&(this.logger.info("Added transaction to wallet in AccountDB: %s (%d).",r.id,a),n=!0)}n||(r=null)}try{let i=await x.FactoryOfContract({env:this,block:e,tx:t});e?await i.confirm():await i.insert()}catch(i){e?this.logger.error("TX(%s) Smart Contract Confirm Error: %s",t.txid(),i.message):this.logger.error("TX(%s) Smart Contract Insert Error: %s",t.txid(),i.message)}return r}async _unconfirm(t,e){if(e)try{let i=await x.FactoryOfContract({env:this,block:e,tx:t});await i.unconfirm()}catch(r){this.logger.error("TX(%s) Smart Contract Unconfirm Error: %s",t.txid(),r.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){const e=await this.get(t);s(e),await e.unconfirm(i)}for(const t of r){const e=await this.get(t);s(e),await e.abandon(i)}}async resetChain(t){const e=await this.txLock.lock();try{return await this._resetChain(t)}finally{e()}}async _resetChain(t){if(t.height>this.curHeight)throw new Error(`WDB: Bad reset height ${t.height} while curHeight `+this.curHeight);var e;for(e of(await this.rollback(t.height)||await this.scan(),await this.getWallets())){const 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){const e=await this.writeLock.lock();try{return await this._saveMSTrans(t)}finally{e()}}async _saveMSTrans(t){const e=this.db.batch();e.put(u.ms(w.getHash(t.addr,"hex"),t.txid),Buffer.from(JSON.stringify(t))),await e.write()}async listMSTrans(t){return t=w.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){const i=await this.writeLock.lock();try{return await this._delMSTrans(t,e)}finally{i()}}async _delMSTrans(t,e){t=w.getHash(t,"hex");const 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";
910
910
  /*!
911
911
  * txdb.js - persistent transaction pool
912
912
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
@@ -1615,7 +1615,7 @@ const r=i(0),s=i(2),n=i(4),a=i(3);function o(t){if(!(this instanceof o))return n
1615
1615
  * fullnode.js - full node for vallnet
1616
1616
  * Copyright (c) 2019-2022, Bookman Software (MIT License).
1617
1617
  * https://github.com/bookmansoft/gamegold
1618
- */const r=i(345),s=i(353),n=i(629),a=i(357),o=i(630),c=i(351),h=i(352);var u=i(225);const l=i(5).PropStatus;i(53);const p=i(125),d=i(717),f=i(3),m=i(83),g=i(150);t.exports=class extends u{constructor(t){t.spv=!1,t.nodeType="full",super(t),this.chain=new r({node:this,network:this.network,logger:this.logger,workers:this.workers,db:this.config.str("db"),prefix:this.config.prefix,maxFiles:this.config.uint("max-files"),cacheSize:this.config.mb("cache-size"),forceFlags:this.config.bool("force-flags"),prune:this.config.bool("prune"),checkpoints:this.config.bool("checkpoints"),coinCache:this.config.uint("coin-cache"),entryCache:this.config.uint("entry-cache"),indexTX:this.config.bool("index-tx"),indexAddress:this.config.bool("index-address")}),this.fees=new s(this.logger),this.fees.init(),this.mempool=new n({node:this,network:this.network,logger:this.logger,workers:this.workers,fees:this.fees,db:this.config.str("db"),prefix:this.config.prefix,persistent:this.config.bool("persistent-mempool"),maxSize:this.config.mb("mempool-size"),limitFree:this.config.bool("limit-free"),limitFreeRelay:this.config.uint("limit-free-relay"),requireStandard:this.config.bool("require-standard"),rejectAbsurdFees:this.config.bool("reject-absurd-fees"),replaceByFee:this.config.bool("replace-by-fee"),indexAddress:this.config.bool("index-address")}),this.pool=new a({node:this,network:this.network,logger:this.logger,prefix:this.config.prefix,selfish:this.config.bool("selfish"),compact:this.config.bool("compact"),bip37:this.config.bool("bip37"),bip151:this.config.bool("bip151"),bip150:this.config.bool("bip150"),identityKey:this.config.buf("identity-key"),knownPeers:this.config.array("known-peers"),maxOutbound:this.config.uint("max-outbound"),maxInbound:this.config.uint("max-inbound"),proxy:this.config.str("proxy"),onion:this.config.bool("onion"),upnp:this.config.bool("upnp"),seeds:this.config.array("seeds"),nodes:this.config.array("nodes"),only:this.config.array("only"),publicHost:this.config.str("public-host"),publicPort:this.config.uint("public-port"),host:this.config.str("host"),port:this.config.uint("port"),wsport:this.config.uint("wsport"),listen:this.config.bool("listen"),persistent:this.config.bool("persistent")}),this.miner=new o({node:this,network:this.network,logger:this.logger,workers:this.workers,addresses:this.config.array("coinbase-address"),coinbaseFlags:this.config.str("coinbase-flags"),preverify:this.config.bool("preverify"),maxWeight:this.config.uint("max-weight"),reservedWeight:this.config.uint("reserved-weight"),reservedSigops:this.config.uint("reserved-sigops")}),this.rpc=new h(this),this._init(),c.unsupported||(this.http=new c({network:this.network,logger:this.logger,node:this,prefix:this.config.prefix,ssl:this.config.bool("ssl"),keyFile:this.config.path("ssl-key"),certFile:this.config.path("ssl-cert"),host:this.config.str("http-host"),port:this.config.httpPort,apiKey:this.config.str("api-key")}),this.http.on("error",t=>this.error(t)),this.http.init())}_init(){this.conn_s2local=new d(this),this.chain.on("error",t=>this.error(t)),this.mempool.on("error",t=>this.error(t)),this.pool.on("error",t=>this.error(t)),this.miner.on("error",t=>this.error(t)),this.mempool.on("tx",(t,e,i)=>{this.miner.cpu.notifyEntry(),this.emit("tx",t,e,i)}),this.mempool.on("entry.remove",(t,e)=>{this.miner.cpu.notifyEntry(),this.emit("entry.remove",t,e)}),this.chain.hook("block.connect",async(t,e)=>{try{await this.mempool._addBlock(t,e.txs)}catch(t){this.error(t)}await this.fire("block.connect",t,e),this.emit("block",e)}),this.chain.hook("block.disconnect",async(t,e)=>{await this.fire("block.disconnect",t,e);try{await this.mempool._removeBlock(t,e.txs)}catch(t){this.error(t)}}),this.chain.hook("chain.reorganize.begin",async(t,e)=>{try{await this.mempool._handleReorgBegin()}catch(t){this.error(t)}this.emit("chain.reorganize.begin",t,e)}),this.chain.hook("chain.reorganize.end",async(t,e)=>{try{await this.mempool._handleReorgEnd()}catch(t){this.error(t)}this.emit("chain.reorganize.end",t,e)}),this.chain.hook("chain.reset",async t=>{try{await this.mempool._reset()}catch(t){this.error(t)}await this.fire("chain.reset",t)}),this.loadPlugins();try{this.cdb=this.require("contractdb")}catch(t){this.logger.error("cdb loading failed.",t.message)}}async _open(){g.localhost=this.config.bool("localhost",!1);let t=this.config.str("genesis");t&&"string"==typeof(t="true"==t?[]:t.split(","))[2]&&(t[2]=parseInt(t[2]));var e=this.config.str("keystore"),i=this.config.str("password"),r=this.config.str("backup");let s=await p.readFile(`./${this.config.network}-genesis.params`),n=(s&&s.notifyAddress&&(this.config.notifyAddress=s.notifyAddress,this.config[this.config.network+"Addresses"]=s[this.config.network+"Addresses"],e||this.config.coinbaseAddress||await this.rpc.setMinerAddr([s.coinbaseAddress])),!t||s||((s=(s=await p.readEncryptFile({password:i,network:this.config.network,file:e||`./${this.config.network}-genesis.keystore`}))||{password:i,passphrase:t[0]||f.MNEMONIC_SALT,language:t[1]||"english",bits:parseInt(t[2])||256}).network=this.network.type),await this.pool.open(s),await this.miner.open(),this.config.obj("mnemonic")),a=((n=n||{}).password=n.password||i,n.network=this.network.type,n.file=e,n.backup=r,t?(n.passphrase=t[0]||n.passphrase||f.MNEMONIC_SALT,n.language=t[1]||n.language||"english",n.bits=t[2]||n.bits||256):(n.passphrase=n.passphrase||f.MNEMONIC_SALT,n.language=n.language||"english",n.bits=n.bits||256),await this.openPlugins(n),await p.readEncryptFile({password:i,network:this.config.network,file:e||`./${this.config.network}-genesis.keystore`}));if(a){if(this.config.alliancePrivateKey=a.alliancePrivateKey,this.config.allianceName=a.allianceName,this.config.allianceNodeId=a.allianceNodeId,this.config.notifyAddress=a.notifyAddress,this.pool.options.agent=""+m.USER_AGENT+this.config.allianceName+"."+this.config.allianceNodeId,a.allianceNodeToken&&!this.config.identityKey&&(this.config.identityKey=a.allianceNodeToken.prv,this.pool.options.identityKey=Buffer.from(a.allianceNodeToken.prv,"hex")),"string"==typeof a.authorized)for(var o of a.authorized.split(","))o=o.split(" "),this.pool.authdb.addKnown(o[0],Buffer.from(o[1],"hex"));e&&a.awardAddress&&await this.rpc.setMinerAddr([a.awardAddress])}await this.config.saveAsync(),this.http&&await this.http.open(),this.logger.info("Full Node is loaded.")}async _close(){this.http&&await this.http.close(),await this.closePlugins(),await this.pool.close(),await this.miner.close(),await this.mempool.close(),await this.chain.close(),this.logger.info("Node is closed.")}scan(t,e,i){return this.chain.scan(t,e,i)}async broadcast(t){try{await this.pool.broadcast(t)}catch(t){this.emit("error",t)}}async queryProps(t,e,i,r,s){let n=[["pst","!=",l.Delete]],a=(t&&n.push(["cid",t]),e&&n.push(["current.address",e]),i&&n.push(["pid","like",i]),r&&n.push(["oid","like",r]),!s||s<0?(n.push(["page",1]),n.push(["size",10])):n.push(["page",s]),this.chain.db.propList.query(n));return t=a.list.map(t=>(t.confirm=0<t.height?this.chain.height-t.height+1:0,t)),{count:a.count,cur:a.cur,countCur:a.countCur,page:a.page,list:t}}async queryStockHolder(t,e){let i=[["sum",">",0]];return t&&i.push(["cid",t]),!e||e<0?(i.push(["page",1]),i.push(["size",10])):i.push(["page",e]),this.chain.db.accountList.query(i)}async queryStockRecord(t,e,i){let r=[];!i||i<0?(r.push(["page",1]),r.push(["size",10])):r.push(["page",i]),i=this.chain.height;let s=null;return(t?await this.chain.db.getStockRecord(t,e,i):await this.chain.db.getStockRecordByCid(e,i)).query(r)}async sendTX(t){if(!t.opr.isDerived){let e;try{e=await this.mempool.addTX(t)}catch(t){throw t}e?this.logger.warning("TX was orphaned in mempool: %s.",t.txid()):this.pool.options.selfish&&this.pool.broadcast(t)}}async relay(t){return this.sendTX(t)}async removeTX(t){try{await this.mempool.removeTX(t)}catch(t){throw t}}getBlock(t){return this.chain.getBlock(t)}async getCoin(t,e){return this.mempool.getCoin(t,e)||(this.mempool.isSpent(t,e)?null:this.chain.getCoin(t,e))}async getCoinsByAddress(t){var e=this.mempool.getCoinsByAddress(t);const i=[];for(const e of await this.chain.getCoinsByAddress(t))this.mempool.isSpent(e.hash,e.index)||i.push(e);for(const t of e)i.push(t);return i}async getMetaByAddress(t){var e=this.mempool.getMetaByAddress(t);return(await this.chain.getMetaByAddress(t)).concat(e)}async getMeta(t){if(this.mempool){var e=this.mempool.getMeta(t);if(e)return e}return this.chain.getMeta(t)}async getMetaView(t){return(-1===t.height?this.mempool:this.chain).getSpentView(t.tx)}async getTXByAddress(t){const e=[];for(const i of await this.getMetaByAddress(t))e.push(i.tx);return e}async getTX(t){return(t=await this.getMeta(t))?t.tx:null}async hasTX(t){return!!this.mempool.hasEntry(t)||this.chain.hasTX(t)}}},function(t,e,i){"use strict";
1618
+ */const r=i(345),s=i(353),n=i(629),a=i(357),o=i(630),c=i(351),h=i(352);var u=i(225);const l=i(5).PropStatus;i(53);const p=i(125),d=i(717),f=i(3),m=i(83),g=i(150);t.exports=class extends u{constructor(t){t.spv=!1,t.nodeType="full",super(t),this.chain=new r({node:this,network:this.network,logger:this.logger,workers:this.workers,db:this.config.str("db"),prefix:this.config.prefix,maxFiles:this.config.uint("max-files"),cacheSize:this.config.mb("cache-size"),forceFlags:this.config.bool("force-flags"),prune:this.config.bool("prune"),checkpoints:this.config.bool("checkpoints"),coinCache:this.config.uint("coin-cache"),entryCache:this.config.uint("entry-cache"),indexTX:this.config.bool("index-tx"),indexAddress:this.config.bool("index-address")}),this.fees=new s(this.logger),this.fees.init(),this.mempool=new n({node:this,network:this.network,logger:this.logger,workers:this.workers,fees:this.fees,db:this.config.str("db"),prefix:this.config.prefix,persistent:this.config.bool("persistent-mempool"),maxSize:this.config.mb("mempool-size"),limitFree:this.config.bool("limit-free"),limitFreeRelay:this.config.uint("limit-free-relay"),requireStandard:this.config.bool("require-standard"),rejectAbsurdFees:this.config.bool("reject-absurd-fees"),replaceByFee:this.config.bool("replace-by-fee"),indexAddress:this.config.bool("index-address")}),this.pool=new a({node:this,network:this.network,logger:this.logger,prefix:this.config.prefix,selfish:this.config.bool("selfish"),compact:this.config.bool("compact"),bip37:this.config.bool("bip37"),bip151:this.config.bool("bip151"),bip150:this.config.bool("bip150"),identityKey:this.config.buf("identity-key"),knownPeers:this.config.array("known-peers"),maxOutbound:this.config.uint("max-outbound"),maxInbound:this.config.uint("max-inbound"),proxy:this.config.str("proxy"),onion:this.config.bool("onion"),upnp:this.config.bool("upnp"),seeds:this.config.array("seeds"),nodes:this.config.array("nodes"),only:this.config.array("only"),publicHost:this.config.str("public-host"),publicPort:this.config.uint("public-port"),host:this.config.str("host"),port:this.config.uint("port"),wsport:this.config.uint("wsport"),listen:this.config.bool("listen"),persistent:this.config.bool("persistent")}),this.miner=new o({node:this,network:this.network,logger:this.logger,workers:this.workers,addresses:this.config.array("coinbase-address"),coinbaseFlags:this.config.str("coinbase-flags"),preverify:this.config.bool("preverify"),maxWeight:this.config.uint("max-weight"),reservedWeight:this.config.uint("reserved-weight"),reservedSigops:this.config.uint("reserved-sigops")}),this.rpc=new h(this),this._init(),c.unsupported||(this.http=new c({network:this.network,logger:this.logger,node:this,prefix:this.config.prefix,ssl:this.config.bool("ssl"),keyFile:this.config.path("ssl-key"),certFile:this.config.path("ssl-cert"),host:this.config.str("http-host"),port:this.config.httpPort,apiKey:this.config.str("api-key")}),this.http.on("error",t=>this.error(t)),this.http.init())}_init(){this.conn_s2local=new d(this),this.chain.on("error",t=>this.error(t)),this.mempool.on("error",t=>this.error(t)),this.pool.on("error",t=>this.error(t)),this.miner.on("error",t=>this.error(t)),this.mempool.on("tx",(t,e,i)=>{this.miner.cpu.notifyEntry(),this.emit("tx",t,e,i)}),this.mempool.on("entry.remove",(t,e)=>{this.miner.cpu.notifyEntry(),this.emit("entry.remove",t,e)}),this.chain.hook("block.connect",async(t,e)=>{try{await this.mempool._addBlock(t,e.txs)}catch(t){this.error(t)}await this.fire("block.connect",t,e),this.emit("block",e)}),this.chain.hook("block.disconnect",async(t,e)=>{await this.fire("block.disconnect",t,e);try{await this.mempool._removeBlock(t,e.txs)}catch(t){this.error(t)}}),this.chain.hook("chain.reorganize.begin",async(t,e)=>{try{await this.mempool._handleReorgBegin()}catch(t){this.error(t)}this.emit("chain.reorganize.begin",t,e)}),this.chain.hook("chain.reorganize.end",async(t,e)=>{try{await this.mempool._handleReorgEnd()}catch(t){this.error(t)}this.emit("chain.reorganize.end",t,e)}),this.chain.hook("chain.reset",async t=>{try{await this.mempool._reset()}catch(t){this.error(t)}await this.fire("chain.reset",t)}),this.loadPlugins();try{this.cdb=this.require("contractdb")}catch(t){this.logger.error("cdb loading failed.",t.message)}}async _open(){g.localhost=this.config.bool("localhost",!1);let t=this.config.str("genesis");t&&"string"==typeof(t="true"==t?[]:t.split(","))[2]&&(t[2]=parseInt(t[2]));var e=this.config.str("keystore"),i=this.config.str("password"),r=this.config.str("backup");let s=await p.readFile(`./${this.config.network}-genesis.params`),n=(s&&s.notifyAddress&&(this.config.notifyAddress=s.notifyAddress,this.config[this.config.network+"Addresses"]=s[this.config.network+"Addresses"],e||this.config.coinbaseAddress||await this.rpc.setMinerAddr([s.coinbaseAddress])),!t||s||((s=(s=await p.readEncryptFile({password:i,network:this.config.network,file:e||`./${this.config.network}-genesis.keystore`}))||{password:i,passphrase:t[0]||f.MNEMONIC_SALT,language:t[1]||"english",bits:parseInt(t[2])||256}).network=this.network.type),await this.pool.open(s),await this.miner.open(),this.config.obj("mnemonic")),a=((n=n||{}).password=n.password||i,n.network=this.network.type,n.file=e,n.backup=r,t?(n.passphrase=t[0]||n.passphrase||f.MNEMONIC_SALT,n.language=t[1]||n.language||"english",n.bits=t[2]||n.bits||256):(n.passphrase=n.passphrase||f.MNEMONIC_SALT,n.language=n.language||"english",n.bits=n.bits||256),await this.openPlugins(n),await p.readEncryptFile({password:i,network:this.config.network,file:e||`./${this.config.network}-genesis.keystore`}));if(a){if(this.config.alliancePrivateKey=a.alliancePrivateKey,this.config.allianceName=a.allianceName,this.config.allianceNodeId=a.allianceNodeId,this.config.notifyAddress=a.notifyAddress,this.pool.options.agent=""+m.USER_AGENT+this.config.allianceName+"."+this.config.allianceNodeId,a.allianceNodeToken&&!this.config.identityKey&&(this.config.identityKey=a.allianceNodeToken.prv,this.pool.options.identityKey=Buffer.from(a.allianceNodeToken.prv,"hex")),"string"==typeof a.authorized)for(var o of a.authorized.split(","))if(o&&(o=o.split(" "))&&2<=o.length)try{this.pool.authdb.addKnown(o[0],Buffer.from(o[1],"hex"))}catch(t){this.logger.error("cert with bad format.")}e&&a.awardAddress&&await this.rpc.setMinerAddr([a.awardAddress])}await this.config.saveAsync(),this.http&&await this.http.open(),this.logger.info("Full Node is loaded.")}async _close(){this.http&&await this.http.close(),await this.closePlugins(),await this.pool.close(),await this.miner.close(),await this.mempool.close(),await this.chain.close(),this.logger.info("Node is closed.")}scan(t,e,i){return this.chain.scan(t,e,i)}async broadcast(t){try{await this.pool.broadcast(t)}catch(t){this.emit("error",t)}}async queryProps(t,e,i,r,s){let n=[["pst","!=",l.Delete]],a=(t&&n.push(["cid",t]),e&&n.push(["current.address",e]),i&&n.push(["pid","like",i]),r&&n.push(["oid","like",r]),!s||s<0?(n.push(["page",1]),n.push(["size",10])):n.push(["page",s]),this.chain.db.propList.query(n));return t=a.list.map(t=>(t.confirm=0<t.height?this.chain.height-t.height+1:0,t)),{count:a.count,cur:a.cur,countCur:a.countCur,page:a.page,list:t}}async queryStockHolder(t,e){let i=[["sum",">",0]];return t&&i.push(["cid",t]),!e||e<0?(i.push(["page",1]),i.push(["size",10])):i.push(["page",e]),this.chain.db.accountList.query(i)}async queryStockRecord(t,e,i){let r=[];!i||i<0?(r.push(["page",1]),r.push(["size",10])):r.push(["page",i]),i=this.chain.height;let s=null;return(t?await this.chain.db.getStockRecord(t,e,i):await this.chain.db.getStockRecordByCid(e,i)).query(r)}async sendTX(t){if(!t.opr.isDerived){let e;try{e=await this.mempool.addTX(t)}catch(t){throw t}e?this.logger.warning("TX was orphaned in mempool: %s.",t.txid()):this.pool.options.selfish&&this.pool.broadcast(t)}}async relay(t){return this.sendTX(t)}async removeTX(t){try{await this.mempool.removeTX(t)}catch(t){throw t}}getBlock(t){return this.chain.getBlock(t)}async getCoin(t,e){return this.mempool.getCoin(t,e)||(this.mempool.isSpent(t,e)?null:this.chain.getCoin(t,e))}async getCoinsByAddress(t){var e=this.mempool.getCoinsByAddress(t);const i=[];for(const e of await this.chain.getCoinsByAddress(t))this.mempool.isSpent(e.hash,e.index)||i.push(e);for(const t of e)i.push(t);return i}async getMetaByAddress(t){var e=this.mempool.getMetaByAddress(t);return(await this.chain.getMetaByAddress(t)).concat(e)}async getMeta(t){if(this.mempool){var e=this.mempool.getMeta(t);if(e)return e}return this.chain.getMeta(t)}async getMetaView(t){return(-1===t.height?this.mempool:this.chain).getSpentView(t.tx)}async getTXByAddress(t){const e=[];for(const i of await this.getMetaByAddress(t))e.push(i.tx);return e}async getTX(t){return(t=await this.getMeta(t))?t.tx:null}async hasTX(t){return!!this.mempool.hasEntry(t)||this.chain.hasTX(t)}}},function(t,e,i){"use strict";
1619
1619
  /*!
1620
1620
  * conn_s2local.js - 全节点/SPV节点中,钱包对象和节点对象间的通信组件,以实现消息订阅功能
1621
1621
  * 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.0.10",
3
+ "version": "4.0.11",
4
4
  "description": "Vallnet Core",
5
5
  "license": "MIT",
6
6
  "repository": "git://github.com/bookmansoft/gamegold",