gamegold 5.0.5 → 5.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/gamegold-worker.js +3 -3
- package/lib/gamegold.js +3 -3
- package/package.json +1 -1
package/lib/gamegold-worker.js
CHANGED
|
@@ -2,7 +2,7 @@ const path = require('path');var gpath = path.join(__dirname, '../../../', 'node
|
|
|
2
2
|
/*!
|
|
3
3
|
* reader.js - buffer reader for vallnet
|
|
4
4
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
5
|
-
*/const i=r(0),a=r(3),s=r(6),n=Buffer.alloc(0);function o(e,t){if(!(this instanceof o))return new o(e,t);i(Buffer.isBuffer(e),"Must pass a Buffer."),this.data=e,this.offset=0,this.zeroCopy=t||!1,this.stack=[]}o.prototype.assert=function e(t){if(!t)throw new a.EncodingError(this.offset,"Out of bounds read",e)},o.prototype.enforce=function e(t,r){if(!t)throw new a.EncodingError(this.offset,r,e)},o.prototype.getSize=function(){return this.data.length},o.prototype.left=function(){return this.assert(this.offset<=this.data.length),this.data.length-this.offset},o.prototype.seek=function(e){return this.assert(0<=this.offset+e),this.assert(this.offset+e<=this.data.length),this.offset+=e,e},o.prototype.start=function(){return this.stack.push(this.offset),this.offset},o.prototype.end=function(){i(0<this.stack.length);var e=this.stack.pop();return this.offset-e},o.prototype.endData=function(e){i(0<this.stack.length);var t=this.stack.pop(),r=this.offset,a=r-t,s=this.data;return a===s.length?s:this.zeroCopy||e?s.slice(t,r):(e=Buffer.allocUnsafe(a),s.copy(e,0,t,r),e)},o.prototype.destroy=function(){this.data=n,this.offset=0,this.stack.length=0},o.prototype.readU8=function(){this.assert(this.offset+1<=this.data.length);var e=this.data[this.offset];return this.offset+=1,e},o.prototype.readU16=function(){this.assert(this.offset+2<=this.data.length);var e=this.data.readUInt16LE(this.offset,!0);return this.offset+=2,e},o.prototype.readU16BE=function(){this.assert(this.offset+2<=this.data.length);var e=this.data.readUInt16BE(this.offset,!0);return this.offset+=2,e},o.prototype.readU32=function(){this.assert(this.offset+4<=this.data.length);var e=this.data.readUInt32LE(this.offset,!0);return this.offset+=4,e},o.prototype.readU32BE=function(){this.assert(this.offset+4<=this.data.length);var e=this.data.readUInt32BE(this.offset,!0);return this.offset+=4,e},o.prototype.readU64=function(){this.assert(this.offset+8<=this.data.length);var e=a.readU64(this.data,this.offset);return this.offset+=8,e},o.prototype.readU64BE=function(){this.assert(this.offset+8<=this.data.length);var e=a.readU64BE(this.data,this.offset);return this.offset+=8,e},o.prototype.readI8=function(){this.assert(this.offset+1<=this.data.length);var e=this.data.readInt8(this.offset,!0);return this.offset+=1,e},o.prototype.readI16=function(){this.assert(this.offset+2<=this.data.length);var e=this.data.readInt16LE(this.offset,!0);return this.offset+=2,e},o.prototype.readI16BE=function(){this.assert(this.offset+2<=this.data.length);var e=this.data.readInt16BE(this.offset,!0);return this.offset+=2,e},o.prototype.readI32=function(){this.assert(this.offset+4<=this.data.length);var e=this.data.readInt32LE(this.offset,!0);return this.offset+=4,e},o.prototype.readI32BE=function(){this.assert(this.offset+4<=this.data.length);var e=this.data.readInt32BE(this.offset,!0);return this.offset+=4,e},o.prototype.readI64=function(){this.assert(this.offset+8<=this.data.length);var e=a.readI64(this.data,this.offset);return this.offset+=8,e},o.prototype.readI64BE=function(){this.assert(this.offset+8<=this.data.length);var e=a.readI64BE(this.data,this.offset);return this.offset+=8,e},o.prototype.readU64N=function(){this.assert(this.offset+8<=this.data.length);var e=a.readU64N(this.data,this.offset);return this.offset+=8,e},o.prototype.readU64BEN=function(){this.assert(this.offset+8<=this.data.length);var e=a.readU64BEN(this.data,this.offset);return this.offset+=8,e},o.prototype.readI64N=function(){this.assert(this.offset+8<=this.data.length);var e=a.readI64N(this.data,this.offset);return this.offset+=8,e},o.prototype.readI64BEN=function(){this.assert(this.offset+8<=this.data.length);var e=a.readI64BEN(this.data,this.offset);return this.offset+=8,e},o.prototype.readFloat=function(){this.assert(this.offset+4<=this.data.length);var e=this.data.readFloatLE(this.offset,!0);return this.offset+=4,e},o.prototype.readFloatBE=function(){this.assert(this.offset+4<=this.data.length);var e=this.data.readFloatBE(this.offset,!0);return this.offset+=4,e},o.prototype.readDouble=function(){this.assert(this.offset+8<=this.data.length);var e=this.data.readDoubleLE(this.offset,!0);return this.offset+=8,e},o.prototype.readDoubleBE=function(){this.assert(this.offset+8<=this.data.length);var e=this.data.readDoubleBE(this.offset,!0);return this.offset+=8,e},o.prototype.readVarint=function(){var{size:e,value:t}=a.readVarint(this.data,this.offset);return this.offset+=e,t},o.prototype.readVarintN=function(){var{size:e,value:t}=a.readVarintN(this.data,this.offset);return this.offset+=e,t},o.prototype.readVarint2=function(){var{size:e,value:t}=a.readVarint2(this.data,this.offset);return this.offset+=e,t},o.prototype.readVarint2N=function(){var{size:e,value:t}=a.readVarint2N(this.data,this.offset);return this.offset+=e,t},o.prototype.readBytes=function(e,t){let r;return i(0<=e),this.assert(this.offset+e<=this.data.length),this.zeroCopy||t?r=this.data.slice(this.offset,this.offset+e):(r=Buffer.allocUnsafe(e),this.data.copy(r,0,this.offset,this.offset+e)),this.offset+=e,r},o.prototype.readVarBytes=function(e){return this.readBytes(this.readVarint(),e)},o.prototype.readString=function(e,t){return i(0<=t),this.assert(this.offset+t<=this.data.length),e=this.data.toString(e,this.offset,this.offset+t),this.offset+=t,e},o.prototype.readHash=function(e){return e?this.readString(e,32):this.readBytes(32)},o.prototype.readVarString=function(e,t){var r=this.readVarint();return this.enforce(!t||r<=t,"String exceeds limit."),this.readString(e,r)},o.prototype.readNullString=function(e){this.assert(this.offset+1<=this.data.length);let t=this.offset;for(;t<this.data.length&&0!==this.data[t];t++);return this.assert(t!==this.data.length),e=this.readString(e,t-this.offset),this.offset=t+1,e},o.prototype.createChecksum=function(){let e=0;0<this.stack.length&&(e=this.stack[this.stack.length-1]);var t=this.data.slice(e,this.offset);return s.hash256(t).readUInt32LE(0,!0)},o.prototype.verifyChecksum=function(){var e=this.createChecksum(),t=this.readU32();return this.enforce(e===t,"Checksum mismatch."),t},e.exports=o},function(e,t,r){"use strict";
|
|
5
|
+
*/const i=r(0),a=r(3),s=r(6),n=Buffer.alloc(0);function o(e,t){if(!(this instanceof o))return new o(e,t);"ArrayBuffer"==e.constructor.name&&(e=Buffer.from(e)),i(Buffer.isBuffer(e),"Must pass a Buffer."),this.data=e,this.offset=0,this.zeroCopy=t||!1,this.stack=[]}o.prototype.assert=function e(t){if(!t)throw new a.EncodingError(this.offset,"Out of bounds read",e)},o.prototype.enforce=function e(t,r){if(!t)throw new a.EncodingError(this.offset,r,e)},o.prototype.getSize=function(){return this.data.length},o.prototype.left=function(){return this.assert(this.offset<=this.data.length),this.data.length-this.offset},o.prototype.seek=function(e){return this.assert(0<=this.offset+e),this.assert(this.offset+e<=this.data.length),this.offset+=e,e},o.prototype.start=function(){return this.stack.push(this.offset),this.offset},o.prototype.end=function(){i(0<this.stack.length);var e=this.stack.pop();return this.offset-e},o.prototype.endData=function(e){i(0<this.stack.length);var t=this.stack.pop(),r=this.offset,a=r-t,s=this.data;return a===s.length?s:this.zeroCopy||e?s.slice(t,r):(e=Buffer.allocUnsafe(a),s.copy(e,0,t,r),e)},o.prototype.destroy=function(){this.data=n,this.offset=0,this.stack.length=0},o.prototype.readU8=function(){this.assert(this.offset+1<=this.data.length);var e=this.data[this.offset];return this.offset+=1,e},o.prototype.readU16=function(){this.assert(this.offset+2<=this.data.length);var e=this.data.readUInt16LE(this.offset,!0);return this.offset+=2,e},o.prototype.readU16BE=function(){this.assert(this.offset+2<=this.data.length);var e=this.data.readUInt16BE(this.offset,!0);return this.offset+=2,e},o.prototype.readU32=function(){this.assert(this.offset+4<=this.data.length);var e=this.data.readUInt32LE(this.offset,!0);return this.offset+=4,e},o.prototype.readU32BE=function(){this.assert(this.offset+4<=this.data.length);var e=this.data.readUInt32BE(this.offset,!0);return this.offset+=4,e},o.prototype.readU64=function(){this.assert(this.offset+8<=this.data.length);var e=a.readU64(this.data,this.offset);return this.offset+=8,e},o.prototype.readU64BE=function(){this.assert(this.offset+8<=this.data.length);var e=a.readU64BE(this.data,this.offset);return this.offset+=8,e},o.prototype.readI8=function(){this.assert(this.offset+1<=this.data.length);var e=this.data.readInt8(this.offset,!0);return this.offset+=1,e},o.prototype.readI16=function(){this.assert(this.offset+2<=this.data.length);var e=this.data.readInt16LE(this.offset,!0);return this.offset+=2,e},o.prototype.readI16BE=function(){this.assert(this.offset+2<=this.data.length);var e=this.data.readInt16BE(this.offset,!0);return this.offset+=2,e},o.prototype.readI32=function(){this.assert(this.offset+4<=this.data.length);var e=this.data.readInt32LE(this.offset,!0);return this.offset+=4,e},o.prototype.readI32BE=function(){this.assert(this.offset+4<=this.data.length);var e=this.data.readInt32BE(this.offset,!0);return this.offset+=4,e},o.prototype.readI64=function(){this.assert(this.offset+8<=this.data.length);var e=a.readI64(this.data,this.offset);return this.offset+=8,e},o.prototype.readI64BE=function(){this.assert(this.offset+8<=this.data.length);var e=a.readI64BE(this.data,this.offset);return this.offset+=8,e},o.prototype.readU64N=function(){this.assert(this.offset+8<=this.data.length);var e=a.readU64N(this.data,this.offset);return this.offset+=8,e},o.prototype.readU64BEN=function(){this.assert(this.offset+8<=this.data.length);var e=a.readU64BEN(this.data,this.offset);return this.offset+=8,e},o.prototype.readI64N=function(){this.assert(this.offset+8<=this.data.length);var e=a.readI64N(this.data,this.offset);return this.offset+=8,e},o.prototype.readI64BEN=function(){this.assert(this.offset+8<=this.data.length);var e=a.readI64BEN(this.data,this.offset);return this.offset+=8,e},o.prototype.readFloat=function(){this.assert(this.offset+4<=this.data.length);var e=this.data.readFloatLE(this.offset,!0);return this.offset+=4,e},o.prototype.readFloatBE=function(){this.assert(this.offset+4<=this.data.length);var e=this.data.readFloatBE(this.offset,!0);return this.offset+=4,e},o.prototype.readDouble=function(){this.assert(this.offset+8<=this.data.length);var e=this.data.readDoubleLE(this.offset,!0);return this.offset+=8,e},o.prototype.readDoubleBE=function(){this.assert(this.offset+8<=this.data.length);var e=this.data.readDoubleBE(this.offset,!0);return this.offset+=8,e},o.prototype.readVarint=function(){var{size:e,value:t}=a.readVarint(this.data,this.offset);return this.offset+=e,t},o.prototype.readVarintN=function(){var{size:e,value:t}=a.readVarintN(this.data,this.offset);return this.offset+=e,t},o.prototype.readVarint2=function(){var{size:e,value:t}=a.readVarint2(this.data,this.offset);return this.offset+=e,t},o.prototype.readVarint2N=function(){var{size:e,value:t}=a.readVarint2N(this.data,this.offset);return this.offset+=e,t},o.prototype.readBytes=function(e,t){let r;return i(0<=e),this.assert(this.offset+e<=this.data.length),this.zeroCopy||t?r=this.data.slice(this.offset,this.offset+e):(r=Buffer.allocUnsafe(e),this.data.copy(r,0,this.offset,this.offset+e)),this.offset+=e,r},o.prototype.readVarBytes=function(e){return this.readBytes(this.readVarint(),e)},o.prototype.readString=function(e,t){return i(0<=t),this.assert(this.offset+t<=this.data.length),e=this.data.toString(e,this.offset,this.offset+t),this.offset+=t,e},o.prototype.readHash=function(e){return e?this.readString(e,32):this.readBytes(32)},o.prototype.readVarString=function(e,t){var r=this.readVarint();return this.enforce(!t||r<=t,"String exceeds limit."),this.readString(e,r)},o.prototype.readNullString=function(e){this.assert(this.offset+1<=this.data.length);let t=this.offset;for(;t<this.data.length&&0!==this.data[t];t++);return this.assert(t!==this.data.length),e=this.readString(e,t-this.offset),this.offset=t+1,e},o.prototype.createChecksum=function(){let e=0;0<this.stack.length&&(e=this.stack[this.stack.length-1]);var t=this.data.slice(e,this.offset);return s.hash256(t).readUInt32LE(0,!0)},o.prototype.verifyChecksum=function(){var e=this.createChecksum(),t=this.readU32();return this.enforce(e===t,"Checksum mismatch."),t},e.exports=o},function(e,t,r){"use strict";
|
|
6
6
|
/*!
|
|
7
7
|
* util.js - utils for vallnet
|
|
8
8
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -196,7 +196,7 @@ let i=[];[r(557),r(558),r(559),r(560),r(561),r(562),r(563),r(564),r(565),r(566),
|
|
|
196
196
|
* pkg.js - package constants
|
|
197
197
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
198
198
|
* https://github.com/bookmansoft/gamegold
|
|
199
|
-
*/t.protocol="vallnet",t.version="v5.0.
|
|
199
|
+
*/t.protocol="vallnet",t.version="v5.0.6",t.url="https://github.com/bookmansoft/gamegold"},function(e,t,r){"use strict";
|
|
200
200
|
/*!
|
|
201
201
|
* common.js - p2p constants for vallnet
|
|
202
202
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -830,7 +830,7 @@ const i=r(5).ContractType;e.exports=function(e){if(!e)return r(188);switch(e.ope
|
|
|
830
830
|
/*!
|
|
831
831
|
* accountdb.js - storage for account management
|
|
832
832
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
833
|
-
*/const i=r(8),a=r(0),s=r(73),n=r(118),o=r(157),c=r(608),u=r(85),h=u.walletdb,l=r(6),p=r(158),d=r(124),f=r(167),m=r(36).VerifyError,g=r(45),y=r(13);r(19),r(68);const v=r(196),b=r(67),w=r(50),{getVerifyMsg:k,BlockFinalType:x,ContractEnvType:S}=r(5),_=r(159),E=r(610),j=r(35);var R=r(71);const A=r(2),I=r(140).sortWithSeq,O=r(33),C=r(197),P=r(63),T=r(100),B=r(3),N=B.U32,z=r(336),F=r(337),L=r(338),M=L.vpItem,D=r(611),H=D.vpItem,U=r(312);r(612);const q=U.cpItem,V=r(154),K=V.ErAbolishItem,W=r(43).broadcast,$=r(131),Y=$.vpItem,G=r(153),X=G.ErItem,J=r(613),Q=J.AuditItem,Z=r(305),ee=r(109),te=r(614),re=r(306),ie=r(119),ae=r(615),se=r(217),ne=r(38),oe=r(34),ce=r(59),ue=r(78),he=ue.errors,le=r(77);class pe extends R{constructor(e){super(),this.readyLoad=!1,this.options=new c(e),this.network=this.options.network,this.logger=this.options.logger.context("wallet"),this.workers=this.options.workers,this.keys={hmacSalt:B.DefaultChainCode},e.keys&&e.keys.hmacSalt&&(a(Buffer.isBuffer(e.keys.hmacSalt)),this.keys.hmacSalt=e.keys.hmacSalt),this.client=this.options.client,this.client&&(this.client.wdb=this),this.jsonp=this.options.jsonp,this.jsonp&&(this.jsonp.wdb=this),this.spv=this.options.spv,this.feeRate=this.options.feeRate,this.db=f(this.options),this.rpc=new z(this),this.primary=null,this.state=new te,this.wallets=new Map,this.depth=0,this.rescanning=!1,this.bound=!1,this.newRecord=!0,this.readLock=new C,this.writeLock=new O,this.txLock=new O,this.scanLock=new O,this.widCache=new P(1e4),this.pathMapCache=new P(1e5),this.filter=new T,this.middleHashMem=new Set,this.middleHashChain=new Set,this.autoTaskMgr=new _(this),this.transactionList=new F(this),this.htlcList=new L(this),this.commentList=new D(this),this.NotifyList=new j,this.propList=new $(this),this.$contacts=new j,this.cpList=new U(this),this.cpMemList=new U(this),this.auditList=new J(this),this.erList=new G(this),this.erAbList=new V(this),this.hmacConnection=[],this._init()}async logAudit(e){e.height=this.curHeight,e.time=A.now(),e.erid=l.sha256(A.stringify(e)).toString("hex"),e=new Q(e),await this.auditList.setAudit(e)}async getAccountByAddress(e,t){if(e){let a=null;if(a=t?await this.getWalletsByTX(t):await this.getWallets())for(const t of a){var r=await this.get(t);if(r){var i=await r.getPath(e);if(i)return[r.wid,i.name,r.id]}}}return[0,"",""]}_init(){let e=1e6,t=-1;this.spv&&(e=2e4,t=T.flags.ALL),this.filter=T.fromRate(e,.001,t)}get mode(){return S.Wallet}async getTXFromAll(e){return this.getTXFromDb(e)}async checkNewRecord(){var e={createIfMissing:this.db.options.createIfMissing,errorIfExists:this.db.options.errorIfExists};this.db.options.createIfMissing=!1,this.db.options.errorIfExists=!0;try{await this.db.open();var t=await this.db.checkVersion(h,6);this.newRecord="new"==t}catch(e){if(-1!=e.message.indexOf("does not exist (create_if_missing is false)"))this.newRecord=!0;else{if(-1==e.message.indexOf("exists (error_if_exists is true)"))throw e;this.newRecord=!1}}try{await this.db.close()}catch(e){}this.db.options.createIfMissing=e.createIfMissing,this.db.options.errorIfExists=e.errorIfExists}async isNewRecord(){return await this.checkNewRecord(),this.newRecord}setmnemonic(e){if(this.options.mnemonic=this.options.mnemonic||{},e.bits)this.options.mnemonic={bits:e.bits};else if(e.entropy)this.options.mnemonic={entropy:Buffer.from(e.entropy,"hex")};else if(e.phrase){var t=this.testmnemonic(e.phrase);if(0!=t.code)throw t.msg;this.options.mnemonic={phrase:e.phrase}}e.passphrase&&(this.options.mnemonic.passphrase=e.passphrase),e.language&&(this.options.mnemonic.language=e.language)}testmnemonic(e){try{return new v(e),{code:0}}catch(e){return{code:-1,msg:e.message}}}async getContracts(e){var t=await this.db.values({gte:u.txdb.tx(B.NULL_HASH),lte:u.txdb.tx(B.HIGH_HASH),parse:e=>A.parseJson(e.toString())});return e?t.filter(t=>t.srcact==e||t.dstact==e):t}isFull(){return this.spv||this.synced||!1}async _open(e){}async handleNotify(e,t=!1){if(!t){let r=e.body.content;if("string"==typeof r)try{r=JSON.parse(e.body.content)}catch(e){return}"object"==typeof r&&"secret"===r.type&&(t={contact:e.body.src,messenger:e.body.dst},r.init&&(t.init=Buffer.from(r.init,"hex")),r.packet&&(t.packet=Buffer.from(r.packet)),await this.handleSecret(t))}}async handleSecret(e){if(e.contact&&e.messenger&&e.contact!=e.messenger){try{y.fromString(e.contact,this.network.type),y.fromString(e.messenger,this.network.type)}catch(e){return}var t=await this.ensureContact(e);t&&await t.ensureMessenger(e).answer(e)}}async scanContact(e,t=-1){var r=async e=>{var t;e.witness&&"witnesspubkeyhash"==e.getType()&&(t=e.witness.getPubkeyhashInput()[1],e=y.fromWitness(e.witness).toString(),t)&&e&&await this.ensureContact({contact:e,publicKey:t})};if(0<=t&&t<e.inputs.length)await r(e.inputs[t]);else for(var i of e.inputs)await r(i)}async ensureContact(e){if(!e.contact||e.contact==e.messenger)return null;try{y.fromString(e.contact,this.network.type),e.messenger&&y.fromString(e.messenger,this.network.type)}catch(e){return null}e.network=this.network.type,this.$contacts.get(e.contact)||this.$contacts.set(e.contact,new E(e));var t=this.$contacts.get(e.contact);if(e.messenger&&!(e=t.ensureMessenger(e)).wallet){var r,[r,i]=await this.getAccountByAddress(e.address);if(!(r=await this.get(r)))return;e.wallet=r,e.account=i}return t}getCps(){return this.db.values({gte:u.txdb.cp(B.ZERO_CID,"hex"),lte:u.txdb.cp(B.MAX_CID,"hex"),parse:e=>q.fromRaw(e)})}async _close(){await this.disconnect(),this.http&&this.options.listen&&await this.http.close();for(const e of this.wallets.values())await e.destroy();await this.db.close(),this.options.listen&&await this.logger.close()}async destroy(){await this.db.destroy(),this.widCache.reset(),this.pathMapCache.reset()}async load(e){if(this.readyLoad){var t=await this.ensure({id:"primary",witness:!0,mnemonic:this.options.mnemonic}),r=await this.txLock.lock();try{await this.init(e),await this.watch(),await t.createReceive(0,1,t.master,this.network.type),await t.ensureNotifyKey(),await this.sync()}finally{r()}setTimeout(()=>{this.resend()},5e3)}}async disconnect(){this.client&&await this.client._close(),this.jsonp&&await this.jsonp._close()}async flushCP(e,t=!1){this.client&&(e=e||[],t||(e=this.cpList.excludeCids(e),t=t||0<e.length),t)&&await this.client.execute("cp.remoteQuery",[[["cid","include",e]]])}async watch(){let e=this.db.iterator({gte:h.p(B.NULL_HASH),lte:h.p(B.HIGH_HASH)}),t=0,r=0;for(;;){var i=await e.next();if(!i)break;try{var a=h.pp(i.key);this.addHash(a,!1)}catch(t){throw await e.end(),t}t++}for(e=this.db.iterator({gte:h.o(B.NULL_HASH,0),lte:h.o(B.HIGH_HASH,4294967295)});;){var s=await e.next();if(!s)break;try{var[n,o]=h.oo(s.key);this.addOutpoint(n,o)}catch(t){throw await e.end(),t}r++}this.logger.info("Filter: Added %d hashes to AccountDB filter.",t),this.logger.info("Filter: Added %d outpoints to AccountDB filter.",r),await this.setFilter()}async sync(){if(this.client){let t,r=this.curHeight;for(;0<=r;){var e=await this.getBlock(r);if(!e)break;if(t=await this.client.getEntry(e.hash))break;r--}t||(r=this.state.startHeight,t=await this.client.getEntry(this.state.startHash))||(r=0),await this.cpList.loadHistory(),await this.cpMemList.loadHistory(),await this.propList.loadHistory(),await this.htlcList.loadHistory(),await this.commentList.loadHistory(),await this.transactionList.loadHistory(),await this.loadContact(),await this.erList.loadHistory(),await this.auditList.loadHistory(),await this.erAbList.loadHistory(),await this._rescan(r,!1)}}async _rescan(e,t=!0){if(this.client){null==e&&(e=this.state.startHeight),a(e>>>0===e,"WDB: Must pass in a height.");var r=this.curHeight;t=(await this.rollback(e,t),this.logger.info("AccountDB is scanning %d blocks.",r-e+1),await this.getTip());try{this.rescanning=!0,await this.client.rescan(t.hash,this.eid)}finally{this.rescanning=!1}}}async rescan(e){var t=await this.txLock.lock();try{return await this._rescan(e,!1)}finally{t()}}async send(e){if(this.client)return this.client.send(e);this.emit("send",e)}async getTX(e){for(const r of this.wallets.values()){var t=await r.getTX(e);if(t)return t.tx}return null}async getTXFromDb(e){for(const r of this.wallets.values()){var t=await r.getTX(e);if(t)return t.tx}return null}async getExtendTX(e){for(const r of this.wallets.values()){var t=await r.getTX(e);if(t)return t}return null}async removeTX(e){this.client?await this.client.removeTX(e):this.emit("remove",e)}async estimateFee(e){return 0<this.feeRate?this.feeRate:!this.client||(e=await this.client.estimateFee(e))<this.network.feeRate?this.network.feeRate:e>this.network.maxFeeRate?this.network.maxFeeRate:e}setFilter(){return this.client?this.client.setFilter(this.filter):(this.emit("filter.set",this.filter),Promise.resolve())}resetFilter(){return this.client?this.client.resetFilter():(this.emit("filter.reset"),Promise.resolve())}backup(e){return this.db.backup(e)}async wipe(){this.logger.warning("Wiping AccountDB TXDB..."),this.logger.warning("I hope you know what you're doing.");var e=this.db.iterator({gte:Buffer.from([0]),lte:Buffer.from([255])}),t=this.db.batch();let r=0;for(;;){var i=await e.next();if(!i)break;try{switch(i.key[0]){case 98:case 99:case 101:case 116:case 111:case 104:case 82:t.del(i.key),r++}}catch(t){throw await e.end(),t}}this.logger.warning("Wiped %d txdb records.",r),await t.write()}async getDepth(){var e=this.db.iterator({gte:h.w(0),lte:h.w(4294967295),reverse:!0,limit:1}),t=await e.next();return t?(await e.end(),h.ww(t.key)+1):1}start(e){return a(!e.current,"WDB: Batch already started."),e.current=this.db.batch(),e.accountCache.start(),e.pathCache.start(),e.current}drop(e){var t=this.batch(e);e.current=null,e.accountCache.drop(),e.pathCache.drop(),t.clear()}clear(e){var t=this.batch(e);e.accountCache.clear(),e.pathCache.clear(),t.clear()}batch(e){return a(e.current,"WDB: Batch does not exist."),e.current}async commit(e){var t=this.batch(e);try{await t.write()}catch(e){throw this.drop(),e}e.current=null,e.accountCache.commit(),e.pathCache.commit()}testFilter(e){return this.filter.test(e,"hex")}addHash(e,t=!0){this.filter.add(e,"hex"),t&&(t=Buffer.from(e,"hex"),this.client?this.client.addFilter(t):this.emit("filter.add",t))}addOutpoint(e,t){e=new g(e,t),this.filter.add(e.toRaw())}dump(){return this.db.dump()}register(e){a(!this.wallets.has(e.wid)),this.wallets.set(e.wid,e)}unregister(e){a(this.wallets.has(e.wid)),this.wallets.delete(e.wid)}async getWalletID(e){var t;return e?"number"==typeof e?e:this.widCache.get(e)||((t=await this.db.get(h.l(e)))?(t=t.readUInt32LE(0,!0),this.widCache.set(e,t),t):null):null}async get(e){if(!(e=await this.getWalletID(e)))return null;var t=await this.readLock.lock(e);try{return await this._get(e)}finally{t()}}async _get(e){var t=this.wallets.get(e);return t||((t=await this.db.get(h.w(e)))?(await(e=n.fromRaw(this,t)).open(),this.register(e),e):null)}async loadBackup(e){if(ce.unsupported)throw new le(he.INTERNAL_ERROR,"FS not available.");let t=null;var r;for(r of(await ce.readFile(e,"utf8")).split(/\n+/))if(0!==(r=r.trim()).length&&!/^\s*#/.test(r)){var i=r.split(/\s+/);if(i.length<4)throw new le(he.DESERIALIZATION_ERROR,"Malformed wallet Data File.");switch(i[0]){case"W":var s=Buffer.from(i[1],"base64");s=n.fromRaw(this,s);await this.replace(s),t=await this.get(s.id),this.logger.info("Import Wallet %s(%s)",t.id,t.wid);break;case"C":s=Buffer.from(i[1],"base64");(c=((u=o.fromRaw(this,s)).wallet=t,u.wid=t.wid,u.id=t.id,u.initialized=!0,u.watchOnly=t.watchOnly,u.receive=u.deriveReceive(u.receiveDepth-1),u.change=u.deriveChange(u.changeDepth-1),u.witness&&(u.nested=u.deriveNested(u.nestedDepth-1)),t.master.key.deriveAccount(44,u.accountIndex))).publicKey.toString("hex")!==u.accountKey.publicKey.toString("hex")&&a(c.publicKey.toString("hex")==u.accountKey.publicKey.toString("hex")),await t.saveAccount(u),this.logger.info("Import Account %s(%s)",u.name,u.accountIndex);break;case"A":var c=ue.parseSecret(i[1],this.network),u=parseInt(i[5]),h=parseInt(i[7]),l=parseInt(i[9]),p=i[11].trim();if(h<0||l<0)try{await t.importKey(u,c)}catch(e){this.logger.error(`loadBackup: ${e.message} account/secret: ${u}/`+p)}else{var d=await t.deriveKey(u,h,l),f=await t.deriveKey(u,h,l,t.master);d.getAddress("string")!==f.getAddress("string")&&this.logger.error(`loadBackup: not-equal-1: ${d.getAddress("string")} != `+f.getAddress("string")),d.getAddress("string")!==p&&this.logger.error(`loadBackup: not-equal-2: ${d.getAddress("string")} != `+p)}this.logger.info("Import Address %s %s %s %s",u,h,l,p)}}return t.accountCache.reset(),t}save(e){var t=e.wid,r=e.id,i=this.batch(e);this.widCache.set(r,t),i.put(h.w(t),e.toRaw()),i.put(h.l(r),N(t))}async rename(e,t){var r=await this.writeLock.lock();try{return await this._rename(e,t)}finally{r()}}async _rename(e,t){var r=e.id;if(!s.isName(t))throw new Error("WDB: Bad wallet ID.");if(await this.has(t))throw new Error("WDB: ID not available.");this.start(e).del(h.l(r)),e.id=t,this.save(e),await this.commit(e),this.widCache.remove(r),r=e.pathCache.values();for(const e of r)e.id=t}async replace(e){var t=await this.writeLock.lock();try{return await this._replace(e)}finally{t()}}async _replace(e){var t=this.start(e);t.del(h.l(e.id)),t.del(h.w(e.wid)),this.save(e),await this.commit(e),this.widCache.remove(e.id),this.wallets.delete(e.wid)}renameAccount(e,t){var r=e.wallet;this.batch(r).del(h.i(e.wid,e.name)),e.name=t,this.saveAccount(e)}async auth(e,t){if("string"==typeof t){if(!A.isHex256(t))throw new Error("WDB Authentication: Invalid Token.");t=Buffer.from(t,"hex")}e=b.getHmac(e.toString(),this.keys.hmacSalt);var r=i.createHmac("sha256",e.random);r=Buffer.from(r.update(e.token).digest("hex"),"hex");if(!p(t,r))throw new Error("WDB Authentication: CRC Error.")}async create(e){var t=await this.writeLock.lock();e=e||{};try{return await this._create(e)}finally{t()}}async _create(e){if(await this.has(e.id))throw new Error("WDB: Wallet already exists.");"string"==typeof e.mnemonic&&(e.mnemonic={phrase:e.mnemonic}),e.mnemonic=e.mnemonic||{},!e.mnemonic.language&&this.options.mnemonic&&this.options.mnemonic.language&&(e.mnemonic.language=this.options.mnemonic.language);var t=n.fromOptions(this,e);return t.wid=this.depth++,await t.init(e),this.register(t),this.logger.info("Created wallet %s in AccountDB.",t.id),t}async has(e){return null!=await this.getWalletID(e)}async ensure(e){return await this.get(e.id)||this.create(e)}async getAccount(e,t){return(e=await this.db.get(h.a(e,t)))?o.fromRaw(this,e):null}getAccounts(e){return this.db.values({gte:h.n(e,0),lte:h.n(e,4294967295),parse:e=>e.toString("ascii")})}async getAccountIndex(e,t){return(e=await this.db.get(h.i(e,t)))?e.readUInt32LE(0,!0):-1}async getAccountName(e,t){return(e=await this.db.get(h.n(e,t)))?e.toString("ascii"):null}saveAccount(e){var t=e.wid,r=e.wallet,i=e.accountIndex,a=e.name,s=this.batch(r);s.put(h.a(t,i),e.toRaw()),s.put(h.i(t,a),N(i)),s.put(h.n(t,i),Buffer.from(a,"ascii")),r.accountCache.push(i,e)}hasAccount(e,t){return"number"==typeof e&&"number"==typeof t&&this.db.has(h.a(e,t))}async getPathMap(e){var t=this.pathMapCache.get(e);return t||((t=await this.db.get(h.p(e)))?(t=ae.fromRaw(e,t),this.pathMapCache.set(e,t),t):null)}saveKey(e,t){return this.savePath(e,t.toPath())}async savePath(e,t){var r=e.wid,i=t.hash,a=this.batch(e);this.addHash(i);let s=await this.getPathMap(i);(s=s||new ae(i)).add(r)&&(this.pathMapCache.set(i,s),e.pathCache.push(i,t),a.put(h.p(i),s.toRaw()),a.put(h.P(r,i),t.toRaw()),a.put(h.r(r,t.account,i),null))}async getPath(e,t){var r=await this.db.get(h.P(e,t));return r?((r=ee.fromRaw(r)).wid=e,r.hash=t,r):null}hasPath(e,t){return this.db.has(h.P(e,t))}getHashes(){return this.db.keys({gte:h.p(B.NULL_HASH),lte:h.p(B.HIGH_HASH),parse:h.pp})}getOutpoints(){return this.db.keys({gte:h.o(B.NULL_HASH,0),lte:h.o(B.HIGH_HASH,4294967295),parse:e=>{var[e,t]=h.oo(e);return new g(e,t)}})}getWalletHashes(e){return this.db.keys({gte:h.P(e,B.NULL_HASH),lte:h.P(e,B.HIGH_HASH),parse:h.Pp})}getAccountHashes(e,t){return this.db.keys({gte:h.r(e,t,B.NULL_HASH),lte:h.r(e,t,B.HIGH_HASH),parse:h.rr})}async getWalletPaths(e){var t=[];for(const a of await this.db.range({gte:h.P(e,B.NULL_HASH),lte:h.P(e,B.HIGH_HASH)})){var r=h.Pp(a.key),i=ee.fromRaw(a.value);i.hash=r,i.wid=e,t.push(i)}return t}async encryptKeys(e,t){var r,i,s=e.wid,n=await e.getPaths(),o=this.batch(e);for(r of n)r.data&&(a(!r.encrypted),i=Buffer.from(r.hash,"hex").slice(0,16),(r=r.clone()).data=d.encipher(r.data,t,i),r.encrypted=!0,e.pathCache.push(r.hash,r),o.put(h.P(s,r.hash),r.toRaw()))}async decryptKeys(e,t){var r,i,s=e.wid,n=await e.getPaths(),o=this.batch(e);for(r of n)r.data&&(a(r.encrypted),i=Buffer.from(r.hash,"hex").slice(0,16),(r=r.clone()).data=d.decipher(r.data,t,i),r.encrypted=!1,e.pathCache.push(r.hash,r),o.put(h.P(s,r.hash),r.toRaw()))}async resend(){var e,t={};for(const e of await this.db.keys({gte:h.w(0),lte:h.w(4294967295)})){var r=h.ww(e),i=await this.resendPending(r);i&&Array.isArray(i)&&(t[r]=i)}for(e of Object.keys(t))if(await this.get(parseInt(e)))for(const r of t[e]){try{await this.send(r)}catch(e){this.logger.warning("wdb resend:",e.message)}await oe.timeout(50)}}async resendPending(e){var t=await this.get(e),r=await this.db.keys({gte:u.txdb.prefix(e,u.txdb.p(B.NULL_HASH)),lte:u.txdb.prefix(e,u.txdb.p(B.HIGH_HASH))});if(0!==r.length){this.logger.info("Rebroadcasting %d transactions for %d.",r.length,e);var i=[];for(const o of r){var a=u.txdb.pp(o),s=u.txdb.prefix(e,u.txdb.t(a));if((s=await this.db.get(s))&&!(s=se.fromRaw(s)).tx.isCoinbase())try{var n=await w.FactoryOfContract({tx:s.tx,env:this});await n.isBlockFinal()==x.Expired?t&&(await this.removeTX(s.tx),await t.remove(a),await n.erase()):"notify"!=n.oper&&i.push(s.tx)}catch(e){this.logger.error("TX(%s) Smart Contract Error: %s",s.tx.txid(),e.message)}}return I(i)}}getWallets(){return this.db.keys({gte:h.l("\0"),lte:h.l("ÿ"),parse:h.ll})}async getWalletsByTX(e){var t=new Set;if(!e.isCoinbase())for(const i of e.inputs){var r=i.prevout;if(this.testFilter(r.toRaw())&&(r=await this.getOutpointMap(r.hash,r.index)))for(const e of r.wids)t.add(e)}for(const r of e.getOutputHashes("hex"))if(this.testFilter(r)){var i=await this.getPathMap(r);if(i)for(const e of i.wids)t.add(e)}return 0===t.size?null:t}async getState(){var e=await this.db.get(h.R);return e?te.fromRaw(e):null}async init(e){var t=this.options.startHeight;let r;if(this.client){if(null!=t){if(!(r=await this.client.getEntry(t)))throw new Error("WDB: Could not find start block.")}else r=await this.client.getTip();r=ie.fromEntry(r)}else r=ie.fromEntry(this.network.genesis);this.logger.info("Initializing AccountDB chain state (height %d).",r.height),(t=await this.getState())?this.state=t:await this.resetState(r,!1),await this.ensure({id:"primary",witness:!0,mnemonic:this.options.mnemonic}),e&&e.backup&&await this.loadBackup(e.backup)}async resetState(e,t){for(var r=this.state.clone(),i=(r.startHeight=e.height,r.startHash=e.hash,r.height=e.height,r.marked=t,this.db.batch()),a=this.db.iterator({gte:h.h(e.height),lte:h.h(4294967295),values:!1});;){var s=await a.next();if(!s)break;try{i.del(s.key)}catch(e){throw await a.end(),e}}i.put(h.h(e.height),e.toHash()),i.put(h.R,r.toRaw()),await i.write(),this.state=r}async syncState(e){var t=this.state.clone(),r=this.db.batch();if(e.height<t.height){let a=t.height;var i=a-e.height;for(let e=0;e<i;e++)r.del(h.h(a--))}else e.height>t.height&&a(e.height===t.height+1,`Bad chain sync tip ${e.height} while state `+t.height);t.height=e.height,r.put(h.h(e.height),e.toHash()),r.put(h.R,t.toRaw()),await r.write(),this.state=t,W("block/tips",t)}get curHeight(){return this.state.height}get tidCreator(){return u.txdb.tx}get finder(){return this.getTXFromDb.bind(this)}rpcExecute(){return this.rpc.execute.apply(this.rpc,arguments)}async getBlockMap(e){var t=await this.db.get(h.b(e));return t?re.fromRaw(e,t):null}writeBlockMap(e,t,r){this.batch(e).put(h.b(t),r.toRaw())}unwriteBlockMap(e,t){this.batch(e).del(h.b(t))}async getOutpointMap(e,t){var r=await this.db.get(h.o(e,t));return r?Z.fromRaw(e,t,r):null}writeOutpointMap(e,t,r,i){e=this.batch(e),this.addOutpoint(t,r),e.put(h.o(t,r),i.toRaw())}unwriteOutpointMap(e,t,r){this.batch(e).del(h.o(t,r))}async writeBalanceLog(e,t){var r=h.log(e.wid,t.aidx,t.height,t.hash),i=(t=Buffer.from(JSON.stringify(t)),await this.writeLock.lock());try{this.start(e).put(r,t),await this.commit(e)}finally{i()}}async queryBalanceLog(e,t,r=0){return this.db.values({gte:h.log(e,t,r,B.NULL_HASH),lte:h.log(e,t,this.curHeight,B.HIGH_HASH),parse:e=>JSON.parse(e.toString())})}async getBlock(e){var t,r=await this.db.get(h.h(e));return r?((t=new ie).hash=r.toString("hex"),t.height=e,t):null}async getTip(){var e=await this.getBlock(this.curHeight);if(e)return e;throw new Error("WDB: Tip not found!")}async rollback(e,t=!0){if(e>this.curHeight)throw new Error("WDB: Cannot rollback to the future.");if(e===this.curHeight)return this.logger.debug("Rolled back to same height (%d).",e),!0;this.logger.info("Rolling back %d AccountDB blocks to height %d.",this.curHeight-e,e);var r=await this.getBlock(e);let i=!1;return r?(await this.revert(r.height),await this.syncState(r),t):(r=new ie,e>=this.state.startHeight?(r.height=this.state.startHeight,r.hash=this.state.startHash,i=this.state.marked,this.logger.warning("Rolling back AccountDB to start block (%d).",r.height)):(r.height=0,r.hash=this.network.genesis.hash,i=!1,this.logger.warning("Rolling back AccountDB to genesis block.")),await this.revert(r.height),await this.resetState(r,i),!1)}async revert(e){var t=this.db.iterator({gte:h.b(e+1),lte:h.b(4294967295),reverse:!0,values:!0});let r=0;for(;;){var i=await t.next();if(!i)break;try{var a=h.bb(i.key),s=re.fromRaw(a,i.value).toArray();r+=s.length;for(let e=s.length-1;0<=e;e--)await this._unconfirm(s[e])}catch(e){throw await t.end(),e}}this.logger.info("Rolled back %d AccountDB transactions.",r)}async addBlock(e,t){var r=await this.txLock.lock();try{return await this._addBlock(e,t)}finally{r()}}async _addBlock(e,t){var r=ie.fromEntry(e);let i=0;if(r.height<this.curHeight)this.logger.warning("AccountDB is connecting low blocks (%d).",r.height);else{if(r.height===this.curHeight)this.logger.warning("Already saw AccountDB block (%d).",r.height);else if(r.height!==this.curHeight+1)throw new Error(`WDB(addBlock): Bad disconnection (height mismatch, tip ${r.height} while state ${this.curHeight})`);if(await this.syncState(r),!(this.options.checkpoints&&r.height<=this.network.lastCheckpoint)){for(const e of t)await this._insert(e,r)&&i++;0<i&&this.logger.info("Connected AccountDB block %s (tx=%d).",A.revHex(r.hash),i)}}return i}async removeBlock(e,t){var r=await this.txLock.lock();try{return await this._removeBlock(e,t)}finally{r()}}async _removeBlock(e,t){if((e=ie.fromEntry(e)).height>this.curHeight)return this.logger.warning("AccountDB is disconnecting high blocks (%d).",e.height),0;if(e.height!==this.curHeight)throw new Error(`WDB(removeBlock): Bad disconnection (height mismatch, tip ${e.height} / ${A.revHex(e.hash)} while state ${this.curHeight})`);var r=await this.getBlock(e.height-1);if(!r)throw new Error(`WDB(removeBlock): Bad disconnection (no previous block of ${e.height} / ${A.revHex(e.hash)}).`);var i=await this.getBlockMap(e.height);if(i){for(let e=t.length-1;0<=e;e--){var a=t[e];await this._unconfirm(a,i)}this.logger.warning("Disconnected wallet block %s (tx=%d).",A.revHex(e.hash),i.txs.size)}return await this.syncState(r),i?i.txs.size:0}async rescanBlock(e,t){if(this.rescanning){var r=await this.scanLock.lock();try{await this._addBlock(e,t)}catch(e){throw this.emit("error",e),e}finally{r()}}else this.logger.warning("Unsolicited rescan block: %s.",e.height)}async addTX(e,t,r){var i=await this.txLock.lock();try{return await this._insert(e,t,r)}finally{i()}}listNotify(e){return this.NotifyList.deletes([["h","<",this.curHeight-12]]),this.NotifyList.query(e)}listContact(e,t,r){return this.$contacts.query(e,t,r)}async setCp(e){await this.batchPut(u.txdb.cp(e.cid),e.toRaw())}async delCp(e){await this.batchDel(u.txdb.cp(e))}async delVp(e){var t=this.db.batch();t.del(u.txdb.VP(e.pid)),await t.write()}async setVp(e,t){var r=this.db.batch();r.put(u.txdb.VP(e.pid),e.toRaw()),await r.write()}async getVp(e){return(e=await this.db.get(u.txdb.VP(e)))?Y.fromRaw(e):null}async getVpByAddress(e){return{list:[],count:0}}async getVpByOid(e){return{list:[],count:0}}async loadVpList(){return this.db.values({gte:u.txdb.VP(B.ZERO_CID,"hex"),lte:u.txdb.VP(B.MAX_CID,"hex"),parse:e=>Y.fromRaw(e)})}async saveContact(e){var t=this.db.batch();t.put(u.txdb.CT(e.getAddress()),e.toRaw()),await t.write()}async loadContact(e){var t;for(t of await this.db.values({gte:u.txdb.CT(B.ZERO_HASH160_HEX),lte:u.txdb.CT(B.MAX_HASH160_HEX),parse:e=>E.fromRaw(e,this)}))t.sender&&(t.sender.wallet=await this.get(t.sender.wid)),this.$contacts.set(t.address,t)}async delHtlc(e){var t;(e=new M(e)).id&&(this.htlcList.delete(e.id),this.htlcList.delAccount(e),(t=this.db.batch()).del(u.txdb.VH(e.shash,e.sidx)),await t.write())}async setSuggest(e){e=new M(e);var t,[t,r]=(this.htlcList.set(e.id,e),await this.getAccountByAddress(e.aa)),[t,r]=(t&&this.htlcList.setAccount(e,t,r),await this.getAccountByAddress(e.ba));(t=(t&&this.htlcList.setAccount(e,t,r),this.db.batch())).put(u.txdb.VH(e.shash,e.sidx),e.toRaw()),await t.write()}async setAssent(e){e=new M(e);var t,[t,r]=(this.htlcList.set(e.id,e),await this.getAccountByAddress(e.ab)),[t,r]=(t&&this.htlcList.setAccount(e,t,r),await this.getAccountByAddress(e.bb));(t=(t&&this.htlcList.setAccount(e,t,r),this.db.batch())).put(u.txdb.VH(e.shash,e.sidx),e.toRaw()),await t.write()}async loadHtlcList(){return this.db.values({gte:u.txdb.VH(B.ZERO_CID,0),lte:u.txdb.VH(B.MAX_CID,4294967295),parse:e=>M.fromRaw(e)})}async delComment(e){var t;(e=new H(e)).id&&(this.commentList.delete(e.id),this.commentList.delAccount(e),(t=this.db.batch()).del(u.txdb.VC(e.shash,e.sidx)),await t.write())}async setComment(e){e=new H(e);var t,[t,r]=(this.commentList.set(e.id,e),await this.getAccountByAddress(e.bob));(t=(t&&(this.commentList.setAccount(e,t,r),this.emit("comm.comment",e)),this.db.batch())).put(u.txdb.VC(e.shash,e.sidx),e.toRaw()),await t.write()}async loadCommentList(){return this.db.values({gte:u.txdb.VC(B.ZERO_CID,0),lte:u.txdb.VC(B.MAX_CID,4294967295),parse:e=>H.fromRaw(e)})}async verifyClsTx(e,t){if(!this.spv&&1!=(t=await(await w.FactoryOfContract({env:this,block:t,tx:e})).verify()))throw new m(e,k(t),"bad-contract-verify",100);return!0}async delEr(e){var t=this.db.batch();t.del(u.txdb.ER(e.erid)),t.del(u.txdb.ERR(e.witness,e.erid,e.txid)),await t.write()}async setEr(e,t){t&&e.source&&(r=y.fromWitnessPubkeyhash(l.hash160(Buffer.from(e.source.pubkey,"hex")),this.network),[r,t]=await this.getAccountByAddress(r,t),e.wid=r,e.account=t);var r=this.db.batch();t=u.txdb.ERR(e.witness,e.erid,e.txid);r.put(t,e.toRaw()),r.put(u.txdb.ER(e.erid),t),await r.write()}async getEr(e){var t;return(e=await this.db.get(u.txdb.ER(e)))&&([,,t]=u.txdb.ERRR(e),e=await this.db.get(e))?((e=X.fromRaw(e)).txid=t,e):null}async byPubkey(e,t,r=!1){var i,a=new j;e=await this.db.values({gte:u.txdb.ERR(e,B.NULL_HASH,B.NULL_HASH),lte:u.txdb.ERR(e,B.HIGH_HASH,B.HIGH_HASH),parse:e=>X.fromRaw(e)});let s=[],n=new Map;if(r){for(var o of e)(!n.get(o.source.cluster)||o.startHeight>n.get(o.source.cluster).startHeight)&&n.set(o.source.cluster,await this.caVerifyObj(o));s=n.values()}else s=e;for(i of s)a.set(i.erid,i);return a.query(t)}async caVerifyObj(e){var t={verify:!1};if(!e||e.validHeight<=this.curHeight)return t;var r=await this.erAbList.getErAb(e.erid);return r&&r.abolishHeight<this.curHeight?t:(r=ne.fromPublic(Buffer.from(e.witness,"hex"),this.network.type),e.verify(r)?(e.verify=!0,0<(r=this.cpList.query([["pubKey",e.witness]])).list.length&&(e.cpid=r.list[0].cid),e):t)}async delErAbolish(e){var t=this.db.batch();t.del(u.txdb.ERA(e.erid)),await t.write()}async setErAbolish(e){var t=this.db.batch();t.put(u.txdb.ERA(e.erid),e.toRaw()),await t.write()}async getErAbolish(e){return(e=await this.db.get(u.txdb.ERA(e)))?K.fromRaw(e):null}loadErAbolishList(){return this.db.values({gte:u.txdb.ERA(B.ZERO_CID),lte:u.txdb.ERA(B.MAX_CID),parse:e=>K.fromRaw(e)})}async delAudit(e){var t=this.db.batch();t.del(u.txdb.AU(e.erid)),await t.write()}async setAudit(e){var t=this.db.batch();t.put(u.txdb.AU(e.erid),e.toRaw()),await t.write()}async getAudit(e){return(e=await this.db.get(u.txdb.AU(e)))?Q.fromRaw(e):null}async loadAuditList(){return this.db.values({gte:u.txdb.AU(B.NULL_HASH),lte:u.txdb.AU(B.HIGH_HASH),parse:e=>Q.fromRaw(e)})}async batchPut(e,t){var r=this.db.batch();r.put(e,t),await r.write()}async batchDel(e){var t=this.db.batch();t.del(e),await t.write()}async _insert(e,t,r){a(!e.mutable,"WDB: Cannot add mutable TX.");let i=await this.getWalletsByTX(e);if(i){this.logger.info("Incoming transaction for %d wallets in AccountDB (%s).",i.size,e.txid()),!t||this.state.marked||(this.logger.info("Marking AccountDB start block at %s (%d).",A.revHex(t.hash),t.height),await this.resetState(t,!0));let n=!1;for(const o of i){var s=await this.get(o);a(s),await s.add(e,t,r)&&(this.logger.info("Added transaction to wallet in AccountDB: %s (%d).",s.id,o),n=!0)}n||(i=null)}try{var n=await w.FactoryOfContract({env:this,block:t,tx:e});t?await n.confirm():await n.insert()}catch(n){t?this.logger.error("TX(%s) Smart Contract Confirm Error: %s",e.txid(),n.message):this.logger.error("TX(%s) Smart Contract Insert Error: %s",e.txid(),n.message)}return i}async _unconfirm(e,t){if(t)try{await(await w.FactoryOfContract({env:this,block:t,tx:e})).unconfirm()}catch(t){this.logger.error("TX(%s) Smart Contract Unconfirm Error: %s",e.txid(),t.message)}let r,i=null;if(r=e.wids?(i=e.wids,e.hash):(i=await this.getWalletsByTX(e),e.hash("hex")),!i)return null;for(const e of i){var s=await this.get(e);a(s),await s.unconfirm(r)}}async resetChain(e){var t=await this.txLock.lock();try{return await this._resetChain(e)}finally{t()}}async _resetChain(e){if(e.height>this.curHeight)throw new Error(`WDB: Bad reset height ${e.height} while curHeight `+this.curHeight);var t;for(t of(await this.rollback(e.height)||await this._rescan(),await this.getWallets())){var r=await this.get(t);for(const t of await r.getPending())try{await r.abandon(t.hash)}catch(e){}}}async saveMSTrans(e){var t=await this.writeLock.lock();try{return await this._saveMSTrans(e)}finally{t()}}async _saveMSTrans(e){var t=this.db.batch();t.put(h.ms(y.getHash(e.addr,"hex"),e.txid),Buffer.from(JSON.stringify(e))),await t.write()}async listMSTrans(e){return e=y.getHash(e,"hex"),this.db.values({gte:h.ms(e,B.NULL_HASH),lte:h.ms(e,B.HIGH_HASH),parse:e=>JSON.parse(e.toString())})}async delMSTrans(e,t){var r=await this.writeLock.lock();try{return await this._delMSTrans(e,t)}finally{r()}}async _delMSTrans(e,t){e=y.getHash(e,"hex");var r=this.db.batch();r.del(h.ms(e,t)),await r.write()}}pe.layout=h,e.exports=pe},function(e,t,r){"use strict";
|
|
833
|
+
*/const i=r(8),a=r(0),s=r(73),n=r(118),o=r(157),c=r(608),u=r(85),h=u.walletdb,l=r(6),p=r(158),d=r(124),f=r(167),m=r(36).VerifyError,g=r(45),y=r(13);r(19),r(68);const v=r(196),b=r(67),w=r(50),{getVerifyMsg:k,BlockFinalType:x,ContractEnvType:S}=r(5),_=r(159),E=r(610),j=r(35);var R=r(71);const A=r(2),I=r(140).sortWithSeq,O=r(33),C=r(197),P=r(63),T=r(100),B=r(3),N=B.U32,z=r(336),F=r(337),L=r(338),M=L.vpItem,D=r(611),H=D.vpItem,U=r(312);r(612);const q=U.cpItem,V=r(154),K=V.ErAbolishItem,W=r(43).broadcast,$=r(131),Y=$.vpItem,G=r(153),X=G.ErItem,J=r(613),Q=J.AuditItem,Z=r(305),ee=r(109),te=r(614),re=r(306),ie=r(119),ae=r(615),se=r(217),ne=r(38),oe=r(34),ce=r(59),ue=r(78),he=ue.errors,le=r(77);class pe extends R{constructor(e){super(),this.readyLoad=!1,this.options=new c(e),this.network=this.options.network,this.logger=this.options.logger.context("wallet"),this.workers=this.options.workers,this.keys={hmacSalt:B.DefaultChainCode},e.keys&&e.keys.hmacSalt&&(a(Buffer.isBuffer(e.keys.hmacSalt)),this.keys.hmacSalt=e.keys.hmacSalt),this.client=this.options.client,this.client&&(this.client.wdb=this),this.jsonp=this.options.jsonp,this.jsonp&&(this.jsonp.wdb=this),this.spv=this.options.spv,this.feeRate=this.options.feeRate,this.db=f(this.options),this.rpc=new z(this),this.primary=null,this.state=new te,this.wallets=new Map,this.depth=0,this.rescanning=!1,this.bound=!1,this.newRecord=!0,this.readLock=new C,this.writeLock=new O,this.txLock=new O,this.scanLock=new O,this.widCache=new P(1e4),this.pathMapCache=new P(1e5),this.filter=new T,this.middleHashMem=new Set,this.middleHashChain=new Set,this.autoTaskMgr=new _(this),this.transactionList=new F(this),this.htlcList=new L(this),this.commentList=new D(this),this.NotifyList=new j,this.propList=new $(this),this.$contacts=new j,this.cpList=new U(this),this.cpMemList=new U(this),this.auditList=new J(this),this.erList=new G(this),this.erAbList=new V(this),this.hmacConnection=[],this._init()}async logAudit(e){e.height=this.curHeight,e.time=A.now(),e.erid=l.sha256(A.stringify(e)).toString("hex"),e=new Q(e),await this.auditList.setAudit(e)}async getAccountByAddress(e,t){if(e){let a=null;if(a=t?await this.getWalletsByTX(t):await this.getWallets())for(const t of a){var r=await this.get(t);if(r){var i=await r.getPath(e);if(i)return[r.wid,i.name,r.id]}}}return[0,"",""]}_init(){let e=1e6,t=-1;this.spv&&(e=2e4,t=T.flags.ALL),this.filter=T.fromRate(e,.001,t)}get mode(){return S.Wallet}async getTXFromAll(e){return this.getTXFromDb(e)}async checkNewRecord(){var e={createIfMissing:this.db.options.createIfMissing,errorIfExists:this.db.options.errorIfExists};this.db.options.createIfMissing=!1,this.db.options.errorIfExists=!0;try{await this.db.open();var t=await this.db.checkVersion(h,6);this.newRecord="new"==t}catch(e){if(-1!=e.message.indexOf("does not exist (create_if_missing is false)"))this.newRecord=!0;else{if(-1==e.message.indexOf("exists (error_if_exists is true)"))throw e;this.newRecord=!1}}try{await this.db.close()}catch(e){}this.db.options.createIfMissing=e.createIfMissing,this.db.options.errorIfExists=e.errorIfExists}async isNewRecord(){return await this.checkNewRecord(),this.newRecord}setmnemonic(e){if(this.options.mnemonic=this.options.mnemonic||{},e.bits)this.options.mnemonic={bits:e.bits};else if(e.entropy)this.options.mnemonic={entropy:Buffer.from(e.entropy,"hex")};else if(e.phrase){var t=this.testmnemonic(e.phrase);if(0!=t.code)throw t.msg;this.options.mnemonic={phrase:e.phrase}}e.passphrase&&(this.options.mnemonic.passphrase=e.passphrase),e.language&&(this.options.mnemonic.language=e.language)}testmnemonic(e){try{return new v(e),{code:0}}catch(e){return{code:-1,msg:e.message}}}async getContracts(e){var t=await this.db.values({gte:u.txdb.tx(B.NULL_HASH),lte:u.txdb.tx(B.HIGH_HASH),parse:e=>A.parseJson(e.toString())});return e?t.filter(t=>t.srcact==e||t.dstact==e):t}isFull(){return this.spv||this.synced||!1}async _open(e){}async handleNotify(e,t=!1){if(!t){let r=e.body.content;if("string"==typeof r)try{r=JSON.parse(e.body.content)}catch(e){return}"object"==typeof r&&"secret"===r.type&&(t={contact:e.body.src,messenger:e.body.dst},r.init&&(t.init=Buffer.from(r.init,"hex")),r.packet&&(t.packet=Buffer.from(r.packet)),await this.handleSecret(t))}}async handleSecret(e){if(e.contact&&e.messenger&&e.contact!=e.messenger){try{y.fromString(e.contact,this.network.type),y.fromString(e.messenger,this.network.type)}catch(e){return}var t=await this.ensureContact(e);t&&await t.ensureMessenger(e).answer(e)}}async scanContact(e,t=-1){var r=async e=>{var t;e.witness&&"witnesspubkeyhash"==e.getType()&&(t=e.witness.getPubkeyhashInput()[1],e=y.fromWitness(e.witness).toString(),t)&&e&&await this.ensureContact({contact:e,publicKey:t})};if(0<=t&&t<e.inputs.length)await r(e.inputs[t]);else for(var i of e.inputs)await r(i)}async ensureContact(e){if(!e.contact||e.contact==e.messenger)return null;try{y.fromString(e.contact,this.network.type),e.messenger&&y.fromString(e.messenger,this.network.type)}catch(e){return null}e.network=this.network.type,this.$contacts.get(e.contact)||this.$contacts.set(e.contact,new E(e));var t=this.$contacts.get(e.contact);if(e.messenger&&!(e=t.ensureMessenger(e)).wallet){var r,[r,i]=await this.getAccountByAddress(e.address);if(!(r=await this.get(r)))return;e.wallet=r,e.account=i}return t}getCps(){return this.db.values({gte:u.txdb.cp(B.ZERO_CID,"hex"),lte:u.txdb.cp(B.MAX_CID,"hex"),parse:e=>q.fromRaw(e)})}async _close(){await this.disconnect(),this.http&&this.options.listen&&await this.http.close();for(const e of this.wallets.values())await e.destroy();await this.db.close(),this.options.listen&&await this.logger.close()}async destroy(){await this.db.destroy(),this.widCache.reset(),this.pathMapCache.reset()}async load(e){if(this.readyLoad){var t=await this.ensure({id:"primary",witness:!0,mnemonic:this.options.mnemonic}),r=await this.txLock.lock();try{await this.init(e),await this.watch(),await t.createReceive(0,1,t.master,this.network.type),await t.ensureNotifyKey(),await this.sync()}finally{r()}setTimeout(()=>{this.resend()},5e3)}}async disconnect(){this.client&&await this.client._close(),this.jsonp&&await this.jsonp._close()}async flushCP(e,t=!1){this.client&&(e=e||[],t||(e=this.cpList.excludeCids(e),t=t||0<e.length),t)&&await this.client.execute("cp.remoteQuery",[[["cid","include",e]]])}async watch(){let e=this.db.iterator({gte:h.p(B.NULL_HASH),lte:h.p(B.HIGH_HASH)}),t=0,r=0;for(;;){var i=await e.next();if(!i)break;try{var a=h.pp(i.key);this.addHash(a,!1)}catch(t){throw await e.end(),t}t++}for(e=this.db.iterator({gte:h.o(B.NULL_HASH,0),lte:h.o(B.HIGH_HASH,4294967295)});;){var s=await e.next();if(!s)break;try{var[n,o]=h.oo(s.key);this.addOutpoint(n,o)}catch(t){throw await e.end(),t}r++}this.logger.info("Filter: Added %d hashes to AccountDB filter.",t),this.logger.info("Filter: Added %d outpoints to AccountDB filter.",r),await this.setFilter()}async sync(){if(this.client){let t,r=this.curHeight;for(;0<=r;){var e=await this.getBlock(r);if(!e)break;if(t=await this.client.getEntry(e.hash))break;r--}t||(r=this.state.startHeight,t=await this.client.getEntry(this.state.startHash))||(r=0),await this.cpList.loadHistory(),await this.cpMemList.loadHistory(),await this.propList.loadHistory(),await this.htlcList.loadHistory(),await this.commentList.loadHistory(),await this.transactionList.loadHistory(),await this.loadContact(),await this.erList.loadHistory(),await this.auditList.loadHistory(),await this.erAbList.loadHistory(),await this._rescan(r,!1)}}async _rescan(e,t=!0){if(this.client){null==e&&(e=this.state.startHeight),a(e>>>0===e,"WDB: Must pass in a height.");var r=this.curHeight;t=(await this.rollback(e,t),this.logger.info("AccountDB is scanning %d blocks.",r-e+1),await this.getTip());try{this.rescanning=!0,await this.client.rescan(t.hash,this.eid)}finally{this.rescanning=!1}}}async rescan(e){var t=await this.txLock.lock();try{return await this._rescan(e,!1)}finally{t()}}async send(e){return this.client?this.client.send(e):(this.emit("send",e),Promise.resolve())}async getTX(e){for(const r of this.wallets.values()){var t=await r.getTX(e);if(t)return t.tx}return null}async getTXFromDb(e){for(const r of this.wallets.values()){var t=await r.getTX(e);if(t)return t.tx}return null}async getExtendTX(e){for(const r of this.wallets.values()){var t=await r.getTX(e);if(t)return t}return null}async removeTX(e){this.client?await this.client.removeTX(e):this.emit("remove",e)}async estimateFee(e){return 0<this.feeRate?this.feeRate:!this.client||(e=await this.client.estimateFee(e))<this.network.feeRate?this.network.feeRate:e>this.network.maxFeeRate?this.network.maxFeeRate:e}setFilter(){return this.client?this.client.setFilter(this.filter):(this.emit("filter.set",this.filter),Promise.resolve())}resetFilter(){return this.client?this.client.resetFilter():(this.emit("filter.reset"),Promise.resolve())}backup(e){return this.db.backup(e)}async wipe(){this.logger.warning("Wiping AccountDB TXDB..."),this.logger.warning("I hope you know what you're doing.");var e=this.db.iterator({gte:Buffer.from([0]),lte:Buffer.from([255])}),t=this.db.batch();let r=0;for(;;){var i=await e.next();if(!i)break;try{switch(i.key[0]){case 98:case 99:case 101:case 116:case 111:case 104:case 82:t.del(i.key),r++}}catch(t){throw await e.end(),t}}this.logger.warning("Wiped %d txdb records.",r),await t.write()}async getDepth(){var e=this.db.iterator({gte:h.w(0),lte:h.w(4294967295),reverse:!0,limit:1}),t=await e.next();return t?(await e.end(),h.ww(t.key)+1):1}start(e){return a(!e.current,"WDB: Batch already started."),e.current=this.db.batch(),e.accountCache.start(),e.pathCache.start(),e.current}drop(e){var t=this.batch(e);e.current=null,e.accountCache.drop(),e.pathCache.drop(),t.clear()}clear(e){var t=this.batch(e);e.accountCache.clear(),e.pathCache.clear(),t.clear()}batch(e){return a(e.current,"WDB: Batch does not exist."),e.current}async commit(e){var t=this.batch(e);try{await t.write()}catch(e){throw this.drop(),e}e.current=null,e.accountCache.commit(),e.pathCache.commit()}testFilter(e){return this.filter.test(e,"hex")}addHash(e,t=!0){this.filter.add(e,"hex"),t&&(t=Buffer.from(e,"hex"),this.client?this.client.addFilter(t):this.emit("filter.add",t))}addOutpoint(e,t){e=new g(e,t),this.filter.add(e.toRaw())}dump(){return this.db.dump()}register(e){a(!this.wallets.has(e.wid)),this.wallets.set(e.wid,e)}unregister(e){a(this.wallets.has(e.wid)),this.wallets.delete(e.wid)}async getWalletID(e){var t;return e?"number"==typeof e?e:this.widCache.get(e)||((t=await this.db.get(h.l(e)))?(t=t.readUInt32LE(0,!0),this.widCache.set(e,t),t):null):null}async get(e){if(!(e=await this.getWalletID(e)))return null;var t=await this.readLock.lock(e);try{return await this._get(e)}finally{t()}}async _get(e){var t=this.wallets.get(e);return t||((t=await this.db.get(h.w(e)))?(await(e=n.fromRaw(this,t)).open(),this.register(e),e):null)}async loadBackup(e){if(ce.unsupported)throw new le(he.INTERNAL_ERROR,"FS not available.");let t=null;var r;for(r of(await ce.readFile(e,"utf8")).split(/\n+/))if(0!==(r=r.trim()).length&&!/^\s*#/.test(r)){var i=r.split(/\s+/);if(i.length<4)throw new le(he.DESERIALIZATION_ERROR,"Malformed wallet Data File.");switch(i[0]){case"W":var s=Buffer.from(i[1],"base64");s=n.fromRaw(this,s);await this.replace(s),t=await this.get(s.id),this.logger.info("Import Wallet %s(%s)",t.id,t.wid);break;case"C":s=Buffer.from(i[1],"base64");(c=((u=o.fromRaw(this,s)).wallet=t,u.wid=t.wid,u.id=t.id,u.initialized=!0,u.watchOnly=t.watchOnly,u.receive=u.deriveReceive(u.receiveDepth-1),u.change=u.deriveChange(u.changeDepth-1),u.witness&&(u.nested=u.deriveNested(u.nestedDepth-1)),t.master.key.deriveAccount(44,u.accountIndex))).publicKey.toString("hex")!==u.accountKey.publicKey.toString("hex")&&a(c.publicKey.toString("hex")==u.accountKey.publicKey.toString("hex")),await t.saveAccount(u),this.logger.info("Import Account %s(%s)",u.name,u.accountIndex);break;case"A":var c=ue.parseSecret(i[1],this.network),u=parseInt(i[5]),h=parseInt(i[7]),l=parseInt(i[9]),p=i[11].trim();if(h<0||l<0)try{await t.importKey(u,c)}catch(e){this.logger.error(`loadBackup: ${e.message} account/secret: ${u}/`+p)}else{var d=await t.deriveKey(u,h,l),f=await t.deriveKey(u,h,l,t.master);d.getAddress("string")!==f.getAddress("string")&&this.logger.error(`loadBackup: not-equal-1: ${d.getAddress("string")} != `+f.getAddress("string")),d.getAddress("string")!==p&&this.logger.error(`loadBackup: not-equal-2: ${d.getAddress("string")} != `+p)}this.logger.info("Import Address %s %s %s %s",u,h,l,p)}}return t.accountCache.reset(),t}save(e){var t=e.wid,r=e.id,i=this.batch(e);this.widCache.set(r,t),i.put(h.w(t),e.toRaw()),i.put(h.l(r),N(t))}async rename(e,t){var r=await this.writeLock.lock();try{return await this._rename(e,t)}finally{r()}}async _rename(e,t){var r=e.id;if(!s.isName(t))throw new Error("WDB: Bad wallet ID.");if(await this.has(t))throw new Error("WDB: ID not available.");this.start(e).del(h.l(r)),e.id=t,this.save(e),await this.commit(e),this.widCache.remove(r),r=e.pathCache.values();for(const e of r)e.id=t}async replace(e){var t=await this.writeLock.lock();try{return await this._replace(e)}finally{t()}}async _replace(e){var t=this.start(e);t.del(h.l(e.id)),t.del(h.w(e.wid)),this.save(e),await this.commit(e),this.widCache.remove(e.id),this.wallets.delete(e.wid)}renameAccount(e,t){var r=e.wallet;this.batch(r).del(h.i(e.wid,e.name)),e.name=t,this.saveAccount(e)}async auth(e,t){if("string"==typeof t){if(!A.isHex256(t))throw new Error("WDB Authentication: Invalid Token.");t=Buffer.from(t,"hex")}e=b.getHmac(e.toString(),this.keys.hmacSalt);var r=i.createHmac("sha256",e.random);r=Buffer.from(r.update(e.token).digest("hex"),"hex");if(!p(t,r))throw new Error("WDB Authentication: CRC Error.")}async create(e){var t=await this.writeLock.lock();e=e||{};try{return await this._create(e)}finally{t()}}async _create(e){if(await this.has(e.id))throw new Error("WDB: Wallet already exists.");"string"==typeof e.mnemonic&&(e.mnemonic={phrase:e.mnemonic}),e.mnemonic=e.mnemonic||{},!e.mnemonic.language&&this.options.mnemonic&&this.options.mnemonic.language&&(e.mnemonic.language=this.options.mnemonic.language);var t=n.fromOptions(this,e);return t.wid=this.depth++,await t.init(e),this.register(t),this.logger.info("Created wallet %s in AccountDB.",t.id),t}async has(e){return null!=await this.getWalletID(e)}async ensure(e){return await this.get(e.id)||this.create(e)}async getAccount(e,t){return(e=await this.db.get(h.a(e,t)))?o.fromRaw(this,e):null}getAccounts(e){return this.db.values({gte:h.n(e,0),lte:h.n(e,4294967295),parse:e=>e.toString("ascii")})}async getAccountIndex(e,t){return(e=await this.db.get(h.i(e,t)))?e.readUInt32LE(0,!0):-1}async getAccountName(e,t){return(e=await this.db.get(h.n(e,t)))?e.toString("ascii"):null}saveAccount(e){var t=e.wid,r=e.wallet,i=e.accountIndex,a=e.name,s=this.batch(r);s.put(h.a(t,i),e.toRaw()),s.put(h.i(t,a),N(i)),s.put(h.n(t,i),Buffer.from(a,"ascii")),r.accountCache.push(i,e)}hasAccount(e,t){return"number"==typeof e&&"number"==typeof t&&this.db.has(h.a(e,t))}async getPathMap(e){var t=this.pathMapCache.get(e);return t||((t=await this.db.get(h.p(e)))?(t=ae.fromRaw(e,t),this.pathMapCache.set(e,t),t):null)}saveKey(e,t){return this.savePath(e,t.toPath())}async savePath(e,t){var r=e.wid,i=t.hash,a=this.batch(e);this.addHash(i);let s=await this.getPathMap(i);(s=s||new ae(i)).add(r)&&(this.pathMapCache.set(i,s),e.pathCache.push(i,t),a.put(h.p(i),s.toRaw()),a.put(h.P(r,i),t.toRaw()),a.put(h.r(r,t.account,i),null))}async getPath(e,t){var r=await this.db.get(h.P(e,t));return r?((r=ee.fromRaw(r)).wid=e,r.hash=t,r):null}hasPath(e,t){return this.db.has(h.P(e,t))}getHashes(){return this.db.keys({gte:h.p(B.NULL_HASH),lte:h.p(B.HIGH_HASH),parse:h.pp})}getOutpoints(){return this.db.keys({gte:h.o(B.NULL_HASH,0),lte:h.o(B.HIGH_HASH,4294967295),parse:e=>{var[e,t]=h.oo(e);return new g(e,t)}})}getWalletHashes(e){return this.db.keys({gte:h.P(e,B.NULL_HASH),lte:h.P(e,B.HIGH_HASH),parse:h.Pp})}getAccountHashes(e,t){return this.db.keys({gte:h.r(e,t,B.NULL_HASH),lte:h.r(e,t,B.HIGH_HASH),parse:h.rr})}async getWalletPaths(e){var t=[];for(const a of await this.db.range({gte:h.P(e,B.NULL_HASH),lte:h.P(e,B.HIGH_HASH)})){var r=h.Pp(a.key),i=ee.fromRaw(a.value);i.hash=r,i.wid=e,t.push(i)}return t}async encryptKeys(e,t){var r,i,s=e.wid,n=await e.getPaths(),o=this.batch(e);for(r of n)r.data&&(a(!r.encrypted),i=Buffer.from(r.hash,"hex").slice(0,16),(r=r.clone()).data=d.encipher(r.data,t,i),r.encrypted=!0,e.pathCache.push(r.hash,r),o.put(h.P(s,r.hash),r.toRaw()))}async decryptKeys(e,t){var r,i,s=e.wid,n=await e.getPaths(),o=this.batch(e);for(r of n)r.data&&(a(r.encrypted),i=Buffer.from(r.hash,"hex").slice(0,16),(r=r.clone()).data=d.decipher(r.data,t,i),r.encrypted=!1,e.pathCache.push(r.hash,r),o.put(h.P(s,r.hash),r.toRaw()))}async resend(){var e,t={};for(const e of await this.db.keys({gte:h.w(0),lte:h.w(4294967295)})){var r=h.ww(e),i=await this.resendPending(r);i&&Array.isArray(i)&&(t[r]=i)}for(e of Object.keys(t))if(await this.get(parseInt(e)))for(const r of t[e]){try{await this.send(r)}catch(e){this.logger.warning("wdb resend:",e.message)}await oe.timeout(50)}}async resendPending(e){var t=await this.get(e),r=await this.db.keys({gte:u.txdb.prefix(e,u.txdb.p(B.NULL_HASH)),lte:u.txdb.prefix(e,u.txdb.p(B.HIGH_HASH))});if(0!==r.length){this.logger.info("Rebroadcasting %d transactions for %d.",r.length,e);var i=[];for(const o of r){var a=u.txdb.pp(o),s=u.txdb.prefix(e,u.txdb.t(a));if((s=await this.db.get(s))&&!(s=se.fromRaw(s)).tx.isCoinbase())try{var n=await w.FactoryOfContract({tx:s.tx,env:this});await n.isBlockFinal()==x.Expired?t&&(await this.removeTX(s.tx),await t.remove(a),await n.erase()):"notify"!=n.oper&&i.push(s.tx)}catch(e){this.logger.error("TX(%s) Smart Contract Error: %s",s.tx.txid(),e.message)}}return I(i)}}getWallets(){return this.db.keys({gte:h.l("\0"),lte:h.l("ÿ"),parse:h.ll})}async getWalletsByTX(e){var t=new Set;if(!e.isCoinbase())for(const i of e.inputs){var r=i.prevout;if(this.testFilter(r.toRaw())&&(r=await this.getOutpointMap(r.hash,r.index)))for(const e of r.wids)t.add(e)}for(const r of e.getOutputHashes("hex"))if(this.testFilter(r)){var i=await this.getPathMap(r);if(i)for(const e of i.wids)t.add(e)}return 0===t.size?null:t}async getState(){var e=await this.db.get(h.R);return e?te.fromRaw(e):null}async init(e){var t=this.options.startHeight;let r;if(this.client){if(null!=t){if(!(r=await this.client.getEntry(t)))throw new Error("WDB: Could not find start block.")}else r=await this.client.getTip();r=ie.fromEntry(r)}else r=ie.fromEntry(this.network.genesis);this.logger.info("Initializing AccountDB chain state (height %d).",r.height),(t=await this.getState())?this.state=t:await this.resetState(r,!1),await this.ensure({id:"primary",witness:!0,mnemonic:this.options.mnemonic}),e&&e.backup&&await this.loadBackup(e.backup)}async resetState(e,t){for(var r=this.state.clone(),i=(r.startHeight=e.height,r.startHash=e.hash,r.height=e.height,r.marked=t,this.db.batch()),a=this.db.iterator({gte:h.h(e.height),lte:h.h(4294967295),values:!1});;){var s=await a.next();if(!s)break;try{i.del(s.key)}catch(e){throw await a.end(),e}}i.put(h.h(e.height),e.toHash()),i.put(h.R,r.toRaw()),await i.write(),this.state=r}async syncState(e){var t=this.state.clone(),r=this.db.batch();if(e.height<t.height){let a=t.height;var i=a-e.height;for(let e=0;e<i;e++)r.del(h.h(a--))}else e.height>t.height&&a(e.height===t.height+1,`Bad chain sync tip ${e.height} while state `+t.height);t.height=e.height,r.put(h.h(e.height),e.toHash()),r.put(h.R,t.toRaw()),await r.write(),this.state=t,W("block/tips",t)}get curHeight(){return this.state.height}get tidCreator(){return u.txdb.tx}get finder(){return this.getTXFromDb.bind(this)}rpcExecute(){return this.rpc.execute.apply(this.rpc,arguments)}async getBlockMap(e){var t=await this.db.get(h.b(e));return t?re.fromRaw(e,t):null}writeBlockMap(e,t,r){this.batch(e).put(h.b(t),r.toRaw())}unwriteBlockMap(e,t){this.batch(e).del(h.b(t))}async getOutpointMap(e,t){var r=await this.db.get(h.o(e,t));return r?Z.fromRaw(e,t,r):null}writeOutpointMap(e,t,r,i){e=this.batch(e),this.addOutpoint(t,r),e.put(h.o(t,r),i.toRaw())}unwriteOutpointMap(e,t,r){this.batch(e).del(h.o(t,r))}async writeBalanceLog(e,t){var r=h.log(e.wid,t.aidx,t.height,t.hash),i=(t=Buffer.from(JSON.stringify(t)),await this.writeLock.lock());try{this.start(e).put(r,t),await this.commit(e)}finally{i()}}async queryBalanceLog(e,t,r=0){return this.db.values({gte:h.log(e,t,r,B.NULL_HASH),lte:h.log(e,t,this.curHeight,B.HIGH_HASH),parse:e=>JSON.parse(e.toString())})}async getBlock(e){var t,r=await this.db.get(h.h(e));return r?((t=new ie).hash=r.toString("hex"),t.height=e,t):null}async getTip(){var e=await this.getBlock(this.curHeight);if(e)return e;throw new Error("WDB: Tip not found!")}async rollback(e,t=!0){if(e>this.curHeight)throw new Error("WDB: Cannot rollback to the future.");if(e===this.curHeight)return this.logger.debug("Rolled back to same height (%d).",e),!0;this.logger.info("Rolling back %d AccountDB blocks to height %d.",this.curHeight-e,e);var r=await this.getBlock(e);let i=!1;return r?(await this.revert(r.height),await this.syncState(r),t):(r=new ie,e>=this.state.startHeight?(r.height=this.state.startHeight,r.hash=this.state.startHash,i=this.state.marked,this.logger.warning("Rolling back AccountDB to start block (%d).",r.height)):(r.height=0,r.hash=this.network.genesis.hash,i=!1,this.logger.warning("Rolling back AccountDB to genesis block.")),await this.revert(r.height),await this.resetState(r,i),!1)}async revert(e){var t=this.db.iterator({gte:h.b(e+1),lte:h.b(4294967295),reverse:!0,values:!0});let r=0;for(;;){var i=await t.next();if(!i)break;try{var a=h.bb(i.key),s=re.fromRaw(a,i.value).toArray();r+=s.length;for(let e=s.length-1;0<=e;e--)await this._unconfirm(s[e])}catch(e){throw await t.end(),e}}this.logger.info("Rolled back %d AccountDB transactions.",r)}async addBlock(e,t){var r=await this.txLock.lock();try{return await this._addBlock(e,t)}finally{r()}}async _addBlock(e,t){var r=ie.fromEntry(e);let i=0;if(r.height<this.curHeight)this.logger.warning("AccountDB is connecting low blocks (%d).",r.height);else{if(r.height===this.curHeight)this.logger.warning("Already saw AccountDB block (%d).",r.height);else if(r.height!==this.curHeight+1)throw new Error(`WDB(addBlock): Bad disconnection (height mismatch, tip ${r.height} while state ${this.curHeight})`);if(await this.syncState(r),!(this.options.checkpoints&&r.height<=this.network.lastCheckpoint)){for(const e of t)await this._insert(e,r)&&i++;0<i&&this.logger.info("Connected AccountDB block %s (tx=%d).",A.revHex(r.hash),i)}}return i}async removeBlock(e,t){var r=await this.txLock.lock();try{return await this._removeBlock(e,t)}finally{r()}}async _removeBlock(e,t){if((e=ie.fromEntry(e)).height>this.curHeight)return this.logger.warning("AccountDB is disconnecting high blocks (%d).",e.height),0;if(e.height!==this.curHeight)throw new Error(`WDB(removeBlock): Bad disconnection (height mismatch, tip ${e.height} / ${A.revHex(e.hash)} while state ${this.curHeight})`);var r=await this.getBlock(e.height-1);if(!r)throw new Error(`WDB(removeBlock): Bad disconnection (no previous block of ${e.height} / ${A.revHex(e.hash)}).`);var i=await this.getBlockMap(e.height);if(i){for(let e=t.length-1;0<=e;e--){var a=t[e];await this._unconfirm(a,i)}this.logger.warning("Disconnected wallet block %s (tx=%d).",A.revHex(e.hash),i.txs.size)}return await this.syncState(r),i?i.txs.size:0}async rescanBlock(e,t){if(this.rescanning){var r=await this.scanLock.lock();try{await this._addBlock(e,t)}catch(e){throw this.emit("error",e),e}finally{r()}}else this.logger.warning("Unsolicited rescan block: %s.",e.height)}async addTX(e,t,r){var i=await this.txLock.lock();try{return await this._insert(e,t,r)}finally{i()}}listNotify(e){return this.NotifyList.deletes([["h","<",this.curHeight-12]]),this.NotifyList.query(e)}listContact(e,t,r){return this.$contacts.query(e,t,r)}async setCp(e){await this.batchPut(u.txdb.cp(e.cid),e.toRaw())}async delCp(e){await this.batchDel(u.txdb.cp(e))}async delVp(e){var t=this.db.batch();t.del(u.txdb.VP(e.pid)),await t.write()}async setVp(e,t){var r=this.db.batch();r.put(u.txdb.VP(e.pid),e.toRaw()),await r.write()}async getVp(e){return(e=await this.db.get(u.txdb.VP(e)))?Y.fromRaw(e):null}async getVpByAddress(e){return{list:[],count:0}}async getVpByOid(e){return{list:[],count:0}}async loadVpList(){return this.db.values({gte:u.txdb.VP(B.ZERO_CID,"hex"),lte:u.txdb.VP(B.MAX_CID,"hex"),parse:e=>Y.fromRaw(e)})}async saveContact(e){var t=this.db.batch();t.put(u.txdb.CT(e.getAddress()),e.toRaw()),await t.write()}async loadContact(e){var t;for(t of await this.db.values({gte:u.txdb.CT(B.ZERO_HASH160_HEX),lte:u.txdb.CT(B.MAX_HASH160_HEX),parse:e=>E.fromRaw(e,this)}))t.sender&&(t.sender.wallet=await this.get(t.sender.wid)),this.$contacts.set(t.address,t)}async delHtlc(e){var t;(e=new M(e)).id&&(this.htlcList.delete(e.id),this.htlcList.delAccount(e),(t=this.db.batch()).del(u.txdb.VH(e.shash,e.sidx)),await t.write())}async setSuggest(e){e=new M(e);var t,[t,r]=(this.htlcList.set(e.id,e),await this.getAccountByAddress(e.aa)),[t,r]=(t&&this.htlcList.setAccount(e,t,r),await this.getAccountByAddress(e.ba));(t=(t&&this.htlcList.setAccount(e,t,r),this.db.batch())).put(u.txdb.VH(e.shash,e.sidx),e.toRaw()),await t.write()}async setAssent(e){e=new M(e);var t,[t,r]=(this.htlcList.set(e.id,e),await this.getAccountByAddress(e.ab)),[t,r]=(t&&this.htlcList.setAccount(e,t,r),await this.getAccountByAddress(e.bb));(t=(t&&this.htlcList.setAccount(e,t,r),this.db.batch())).put(u.txdb.VH(e.shash,e.sidx),e.toRaw()),await t.write()}async loadHtlcList(){return this.db.values({gte:u.txdb.VH(B.ZERO_CID,0),lte:u.txdb.VH(B.MAX_CID,4294967295),parse:e=>M.fromRaw(e)})}async delComment(e){var t;(e=new H(e)).id&&(this.commentList.delete(e.id),this.commentList.delAccount(e),(t=this.db.batch()).del(u.txdb.VC(e.shash,e.sidx)),await t.write())}async setComment(e){e=new H(e);var t,[t,r]=(this.commentList.set(e.id,e),await this.getAccountByAddress(e.bob));(t=(t&&(this.commentList.setAccount(e,t,r),this.emit("comm.comment",e)),this.db.batch())).put(u.txdb.VC(e.shash,e.sidx),e.toRaw()),await t.write()}async loadCommentList(){return this.db.values({gte:u.txdb.VC(B.ZERO_CID,0),lte:u.txdb.VC(B.MAX_CID,4294967295),parse:e=>H.fromRaw(e)})}async verifyClsTx(e,t){if(!this.spv&&1!=(t=await(await w.FactoryOfContract({env:this,block:t,tx:e})).verify()))throw new m(e,k(t),"bad-contract-verify",100);return!0}async delEr(e){var t=this.db.batch();t.del(u.txdb.ER(e.erid)),t.del(u.txdb.ERR(e.witness,e.erid,e.txid)),await t.write()}async setEr(e,t){t&&e.source&&(r=y.fromWitnessPubkeyhash(l.hash160(Buffer.from(e.source.pubkey,"hex")),this.network),[r,t]=await this.getAccountByAddress(r,t),e.wid=r,e.account=t);var r=this.db.batch();t=u.txdb.ERR(e.witness,e.erid,e.txid);r.put(t,e.toRaw()),r.put(u.txdb.ER(e.erid),t),await r.write()}async getEr(e){var t;return(e=await this.db.get(u.txdb.ER(e)))&&([,,t]=u.txdb.ERRR(e),e=await this.db.get(e))?((e=X.fromRaw(e)).txid=t,e):null}async byPubkey(e,t,r=!1){var i,a=new j;e=await this.db.values({gte:u.txdb.ERR(e,B.NULL_HASH,B.NULL_HASH),lte:u.txdb.ERR(e,B.HIGH_HASH,B.HIGH_HASH),parse:e=>X.fromRaw(e)});let s=[],n=new Map;if(r){for(var o of e)(!n.get(o.source.cluster)||o.startHeight>n.get(o.source.cluster).startHeight)&&n.set(o.source.cluster,await this.caVerifyObj(o));s=n.values()}else s=e;for(i of s)a.set(i.erid,i);return a.query(t)}async caVerifyObj(e){var t={verify:!1};if(!e||e.validHeight<=this.curHeight)return t;var r=await this.erAbList.getErAb(e.erid);return r&&r.abolishHeight<this.curHeight?t:(r=ne.fromPublic(Buffer.from(e.witness,"hex"),this.network.type),e.verify(r)?(e.verify=!0,0<(r=this.cpList.query([["pubKey",e.witness]])).list.length&&(e.cpid=r.list[0].cid),e):t)}async delErAbolish(e){var t=this.db.batch();t.del(u.txdb.ERA(e.erid)),await t.write()}async setErAbolish(e){var t=this.db.batch();t.put(u.txdb.ERA(e.erid),e.toRaw()),await t.write()}async getErAbolish(e){return(e=await this.db.get(u.txdb.ERA(e)))?K.fromRaw(e):null}loadErAbolishList(){return this.db.values({gte:u.txdb.ERA(B.ZERO_CID),lte:u.txdb.ERA(B.MAX_CID),parse:e=>K.fromRaw(e)})}async delAudit(e){var t=this.db.batch();t.del(u.txdb.AU(e.erid)),await t.write()}async setAudit(e){var t=this.db.batch();t.put(u.txdb.AU(e.erid),e.toRaw()),await t.write()}async getAudit(e){return(e=await this.db.get(u.txdb.AU(e)))?Q.fromRaw(e):null}async loadAuditList(){return this.db.values({gte:u.txdb.AU(B.NULL_HASH),lte:u.txdb.AU(B.HIGH_HASH),parse:e=>Q.fromRaw(e)})}async batchPut(e,t){var r=this.db.batch();r.put(e,t),await r.write()}async batchDel(e){var t=this.db.batch();t.del(e),await t.write()}async _insert(e,t,r){a(!e.mutable,"WDB: Cannot add mutable TX.");let i=await this.getWalletsByTX(e);if(i){this.logger.info("Incoming transaction for %d wallets in AccountDB (%s).",i.size,e.txid()),!t||this.state.marked||(this.logger.info("Marking AccountDB start block at %s (%d).",A.revHex(t.hash),t.height),await this.resetState(t,!0));let n=!1;for(const o of i){var s=await this.get(o);a(s),await s.add(e,t,r)&&(this.logger.info("Added transaction to wallet in AccountDB: %s (%d).",s.id,o),n=!0)}n||(i=null)}try{var n=await w.FactoryOfContract({env:this,block:t,tx:e});t?await n.confirm():await n.insert()}catch(n){t?this.logger.error("TX(%s) Smart Contract Confirm Error: %s",e.txid(),n.message):this.logger.error("TX(%s) Smart Contract Insert Error: %s",e.txid(),n.message)}return i}async _unconfirm(e,t){if(t)try{await(await w.FactoryOfContract({env:this,block:t,tx:e})).unconfirm()}catch(t){this.logger.error("TX(%s) Smart Contract Unconfirm Error: %s",e.txid(),t.message)}let r,i=null;if(r=e.wids?(i=e.wids,e.hash):(i=await this.getWalletsByTX(e),e.hash("hex")),!i)return null;for(const e of i){var s=await this.get(e);a(s),await s.unconfirm(r)}}async resetChain(e){var t=await this.txLock.lock();try{return await this._resetChain(e)}finally{t()}}async _resetChain(e){if(e.height>this.curHeight)throw new Error(`WDB: Bad reset height ${e.height} while curHeight `+this.curHeight);var t;for(t of(await this.rollback(e.height)||await this._rescan(),await this.getWallets())){var r=await this.get(t);for(const t of await r.getPending())try{await r.abandon(t.hash)}catch(e){}}}async saveMSTrans(e){var t=await this.writeLock.lock();try{return await this._saveMSTrans(e)}finally{t()}}async _saveMSTrans(e){var t=this.db.batch();t.put(h.ms(y.getHash(e.addr,"hex"),e.txid),Buffer.from(JSON.stringify(e))),await t.write()}async listMSTrans(e){return e=y.getHash(e,"hex"),this.db.values({gte:h.ms(e,B.NULL_HASH),lte:h.ms(e,B.HIGH_HASH),parse:e=>JSON.parse(e.toString())})}async delMSTrans(e,t){var r=await this.writeLock.lock();try{return await this._delMSTrans(e,t)}finally{r()}}async _delMSTrans(e,t){e=y.getHash(e,"hex");var r=this.db.batch();r.del(h.ms(e,t)),await r.write()}}pe.layout=h,e.exports=pe},function(e,t,r){"use strict";
|
|
834
834
|
/*!
|
|
835
835
|
* txdb.js - persistent transaction pool
|
|
836
836
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
package/lib/gamegold.js
CHANGED
|
@@ -2,7 +2,7 @@ const path = require('path');var gpath = path.join(__dirname, '../../../', 'node
|
|
|
2
2
|
/*!
|
|
3
3
|
* reader.js - buffer reader for vallnet
|
|
4
4
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
5
|
-
*/const r=i(0),s=i(3),n=i(6),a=Buffer.alloc(0);function o(e,t){if(!(this instanceof o))return new o(e,t);r(Buffer.isBuffer(e),"Must pass a Buffer."),this.data=e,this.offset=0,this.zeroCopy=t||!1,this.stack=[]}o.prototype.assert=function e(t){if(!t)throw new s.EncodingError(this.offset,"Out of bounds read",e)},o.prototype.enforce=function e(t,i){if(!t)throw new s.EncodingError(this.offset,i,e)},o.prototype.getSize=function(){return this.data.length},o.prototype.left=function(){return this.assert(this.offset<=this.data.length),this.data.length-this.offset},o.prototype.seek=function(e){return this.assert(0<=this.offset+e),this.assert(this.offset+e<=this.data.length),this.offset+=e,e},o.prototype.start=function(){return this.stack.push(this.offset),this.offset},o.prototype.end=function(){r(0<this.stack.length);var e=this.stack.pop();return this.offset-e},o.prototype.endData=function(e){r(0<this.stack.length);var t=this.stack.pop(),i=this.offset,s=i-t,n=this.data;return s===n.length?n:this.zeroCopy||e?n.slice(t,i):(e=Buffer.allocUnsafe(s),n.copy(e,0,t,i),e)},o.prototype.destroy=function(){this.data=a,this.offset=0,this.stack.length=0},o.prototype.readU8=function(){this.assert(this.offset+1<=this.data.length);var e=this.data[this.offset];return this.offset+=1,e},o.prototype.readU16=function(){this.assert(this.offset+2<=this.data.length);var e=this.data.readUInt16LE(this.offset,!0);return this.offset+=2,e},o.prototype.readU16BE=function(){this.assert(this.offset+2<=this.data.length);var e=this.data.readUInt16BE(this.offset,!0);return this.offset+=2,e},o.prototype.readU32=function(){this.assert(this.offset+4<=this.data.length);var e=this.data.readUInt32LE(this.offset,!0);return this.offset+=4,e},o.prototype.readU32BE=function(){this.assert(this.offset+4<=this.data.length);var e=this.data.readUInt32BE(this.offset,!0);return this.offset+=4,e},o.prototype.readU64=function(){this.assert(this.offset+8<=this.data.length);var e=s.readU64(this.data,this.offset);return this.offset+=8,e},o.prototype.readU64BE=function(){this.assert(this.offset+8<=this.data.length);var e=s.readU64BE(this.data,this.offset);return this.offset+=8,e},o.prototype.readI8=function(){this.assert(this.offset+1<=this.data.length);var e=this.data.readInt8(this.offset,!0);return this.offset+=1,e},o.prototype.readI16=function(){this.assert(this.offset+2<=this.data.length);var e=this.data.readInt16LE(this.offset,!0);return this.offset+=2,e},o.prototype.readI16BE=function(){this.assert(this.offset+2<=this.data.length);var e=this.data.readInt16BE(this.offset,!0);return this.offset+=2,e},o.prototype.readI32=function(){this.assert(this.offset+4<=this.data.length);var e=this.data.readInt32LE(this.offset,!0);return this.offset+=4,e},o.prototype.readI32BE=function(){this.assert(this.offset+4<=this.data.length);var e=this.data.readInt32BE(this.offset,!0);return this.offset+=4,e},o.prototype.readI64=function(){this.assert(this.offset+8<=this.data.length);var e=s.readI64(this.data,this.offset);return this.offset+=8,e},o.prototype.readI64BE=function(){this.assert(this.offset+8<=this.data.length);var e=s.readI64BE(this.data,this.offset);return this.offset+=8,e},o.prototype.readU64N=function(){this.assert(this.offset+8<=this.data.length);var e=s.readU64N(this.data,this.offset);return this.offset+=8,e},o.prototype.readU64BEN=function(){this.assert(this.offset+8<=this.data.length);var e=s.readU64BEN(this.data,this.offset);return this.offset+=8,e},o.prototype.readI64N=function(){this.assert(this.offset+8<=this.data.length);var e=s.readI64N(this.data,this.offset);return this.offset+=8,e},o.prototype.readI64BEN=function(){this.assert(this.offset+8<=this.data.length);var e=s.readI64BEN(this.data,this.offset);return this.offset+=8,e},o.prototype.readFloat=function(){this.assert(this.offset+4<=this.data.length);var e=this.data.readFloatLE(this.offset,!0);return this.offset+=4,e},o.prototype.readFloatBE=function(){this.assert(this.offset+4<=this.data.length);var e=this.data.readFloatBE(this.offset,!0);return this.offset+=4,e},o.prototype.readDouble=function(){this.assert(this.offset+8<=this.data.length);var e=this.data.readDoubleLE(this.offset,!0);return this.offset+=8,e},o.prototype.readDoubleBE=function(){this.assert(this.offset+8<=this.data.length);var e=this.data.readDoubleBE(this.offset,!0);return this.offset+=8,e},o.prototype.readVarint=function(){var{size:e,value:t}=s.readVarint(this.data,this.offset);return this.offset+=e,t},o.prototype.readVarintN=function(){var{size:e,value:t}=s.readVarintN(this.data,this.offset);return this.offset+=e,t},o.prototype.readVarint2=function(){var{size:e,value:t}=s.readVarint2(this.data,this.offset);return this.offset+=e,t},o.prototype.readVarint2N=function(){var{size:e,value:t}=s.readVarint2N(this.data,this.offset);return this.offset+=e,t},o.prototype.readBytes=function(e,t){let i;return r(0<=e),this.assert(this.offset+e<=this.data.length),this.zeroCopy||t?i=this.data.slice(this.offset,this.offset+e):(i=Buffer.allocUnsafe(e),this.data.copy(i,0,this.offset,this.offset+e)),this.offset+=e,i},o.prototype.readVarBytes=function(e){return this.readBytes(this.readVarint(),e)},o.prototype.readString=function(e,t){return r(0<=t),this.assert(this.offset+t<=this.data.length),e=this.data.toString(e,this.offset,this.offset+t),this.offset+=t,e},o.prototype.readHash=function(e){return e?this.readString(e,32):this.readBytes(32)},o.prototype.readVarString=function(e,t){var i=this.readVarint();return this.enforce(!t||i<=t,"String exceeds limit."),this.readString(e,i)},o.prototype.readNullString=function(e){this.assert(this.offset+1<=this.data.length);let t=this.offset;for(;t<this.data.length&&0!==this.data[t];t++);return this.assert(t!==this.data.length),e=this.readString(e,t-this.offset),this.offset=t+1,e},o.prototype.createChecksum=function(){let e=0;0<this.stack.length&&(e=this.stack[this.stack.length-1]);var t=this.data.slice(e,this.offset);return n.hash256(t).readUInt32LE(0,!0)},o.prototype.verifyChecksum=function(){var e=this.createChecksum(),t=this.readU32();return this.enforce(e===t,"Checksum mismatch."),t},e.exports=o},function(e,t,i){"use strict";
|
|
5
|
+
*/const r=i(0),s=i(3),n=i(6),a=Buffer.alloc(0);function o(e,t){if(!(this instanceof o))return new o(e,t);"ArrayBuffer"==e.constructor.name&&(e=Buffer.from(e)),r(Buffer.isBuffer(e),"Must pass a Buffer."),this.data=e,this.offset=0,this.zeroCopy=t||!1,this.stack=[]}o.prototype.assert=function e(t){if(!t)throw new s.EncodingError(this.offset,"Out of bounds read",e)},o.prototype.enforce=function e(t,i){if(!t)throw new s.EncodingError(this.offset,i,e)},o.prototype.getSize=function(){return this.data.length},o.prototype.left=function(){return this.assert(this.offset<=this.data.length),this.data.length-this.offset},o.prototype.seek=function(e){return this.assert(0<=this.offset+e),this.assert(this.offset+e<=this.data.length),this.offset+=e,e},o.prototype.start=function(){return this.stack.push(this.offset),this.offset},o.prototype.end=function(){r(0<this.stack.length);var e=this.stack.pop();return this.offset-e},o.prototype.endData=function(e){r(0<this.stack.length);var t=this.stack.pop(),i=this.offset,s=i-t,n=this.data;return s===n.length?n:this.zeroCopy||e?n.slice(t,i):(e=Buffer.allocUnsafe(s),n.copy(e,0,t,i),e)},o.prototype.destroy=function(){this.data=a,this.offset=0,this.stack.length=0},o.prototype.readU8=function(){this.assert(this.offset+1<=this.data.length);var e=this.data[this.offset];return this.offset+=1,e},o.prototype.readU16=function(){this.assert(this.offset+2<=this.data.length);var e=this.data.readUInt16LE(this.offset,!0);return this.offset+=2,e},o.prototype.readU16BE=function(){this.assert(this.offset+2<=this.data.length);var e=this.data.readUInt16BE(this.offset,!0);return this.offset+=2,e},o.prototype.readU32=function(){this.assert(this.offset+4<=this.data.length);var e=this.data.readUInt32LE(this.offset,!0);return this.offset+=4,e},o.prototype.readU32BE=function(){this.assert(this.offset+4<=this.data.length);var e=this.data.readUInt32BE(this.offset,!0);return this.offset+=4,e},o.prototype.readU64=function(){this.assert(this.offset+8<=this.data.length);var e=s.readU64(this.data,this.offset);return this.offset+=8,e},o.prototype.readU64BE=function(){this.assert(this.offset+8<=this.data.length);var e=s.readU64BE(this.data,this.offset);return this.offset+=8,e},o.prototype.readI8=function(){this.assert(this.offset+1<=this.data.length);var e=this.data.readInt8(this.offset,!0);return this.offset+=1,e},o.prototype.readI16=function(){this.assert(this.offset+2<=this.data.length);var e=this.data.readInt16LE(this.offset,!0);return this.offset+=2,e},o.prototype.readI16BE=function(){this.assert(this.offset+2<=this.data.length);var e=this.data.readInt16BE(this.offset,!0);return this.offset+=2,e},o.prototype.readI32=function(){this.assert(this.offset+4<=this.data.length);var e=this.data.readInt32LE(this.offset,!0);return this.offset+=4,e},o.prototype.readI32BE=function(){this.assert(this.offset+4<=this.data.length);var e=this.data.readInt32BE(this.offset,!0);return this.offset+=4,e},o.prototype.readI64=function(){this.assert(this.offset+8<=this.data.length);var e=s.readI64(this.data,this.offset);return this.offset+=8,e},o.prototype.readI64BE=function(){this.assert(this.offset+8<=this.data.length);var e=s.readI64BE(this.data,this.offset);return this.offset+=8,e},o.prototype.readU64N=function(){this.assert(this.offset+8<=this.data.length);var e=s.readU64N(this.data,this.offset);return this.offset+=8,e},o.prototype.readU64BEN=function(){this.assert(this.offset+8<=this.data.length);var e=s.readU64BEN(this.data,this.offset);return this.offset+=8,e},o.prototype.readI64N=function(){this.assert(this.offset+8<=this.data.length);var e=s.readI64N(this.data,this.offset);return this.offset+=8,e},o.prototype.readI64BEN=function(){this.assert(this.offset+8<=this.data.length);var e=s.readI64BEN(this.data,this.offset);return this.offset+=8,e},o.prototype.readFloat=function(){this.assert(this.offset+4<=this.data.length);var e=this.data.readFloatLE(this.offset,!0);return this.offset+=4,e},o.prototype.readFloatBE=function(){this.assert(this.offset+4<=this.data.length);var e=this.data.readFloatBE(this.offset,!0);return this.offset+=4,e},o.prototype.readDouble=function(){this.assert(this.offset+8<=this.data.length);var e=this.data.readDoubleLE(this.offset,!0);return this.offset+=8,e},o.prototype.readDoubleBE=function(){this.assert(this.offset+8<=this.data.length);var e=this.data.readDoubleBE(this.offset,!0);return this.offset+=8,e},o.prototype.readVarint=function(){var{size:e,value:t}=s.readVarint(this.data,this.offset);return this.offset+=e,t},o.prototype.readVarintN=function(){var{size:e,value:t}=s.readVarintN(this.data,this.offset);return this.offset+=e,t},o.prototype.readVarint2=function(){var{size:e,value:t}=s.readVarint2(this.data,this.offset);return this.offset+=e,t},o.prototype.readVarint2N=function(){var{size:e,value:t}=s.readVarint2N(this.data,this.offset);return this.offset+=e,t},o.prototype.readBytes=function(e,t){let i;return r(0<=e),this.assert(this.offset+e<=this.data.length),this.zeroCopy||t?i=this.data.slice(this.offset,this.offset+e):(i=Buffer.allocUnsafe(e),this.data.copy(i,0,this.offset,this.offset+e)),this.offset+=e,i},o.prototype.readVarBytes=function(e){return this.readBytes(this.readVarint(),e)},o.prototype.readString=function(e,t){return r(0<=t),this.assert(this.offset+t<=this.data.length),e=this.data.toString(e,this.offset,this.offset+t),this.offset+=t,e},o.prototype.readHash=function(e){return e?this.readString(e,32):this.readBytes(32)},o.prototype.readVarString=function(e,t){var i=this.readVarint();return this.enforce(!t||i<=t,"String exceeds limit."),this.readString(e,i)},o.prototype.readNullString=function(e){this.assert(this.offset+1<=this.data.length);let t=this.offset;for(;t<this.data.length&&0!==this.data[t];t++);return this.assert(t!==this.data.length),e=this.readString(e,t-this.offset),this.offset=t+1,e},o.prototype.createChecksum=function(){let e=0;0<this.stack.length&&(e=this.stack[this.stack.length-1]);var t=this.data.slice(e,this.offset);return n.hash256(t).readUInt32LE(0,!0)},o.prototype.verifyChecksum=function(){var e=this.createChecksum(),t=this.readU32();return this.enforce(e===t,"Checksum mismatch."),t},e.exports=o},function(e,t,i){"use strict";
|
|
6
6
|
/*!
|
|
7
7
|
* util.js - utils for vallnet
|
|
8
8
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -206,7 +206,7 @@ let r=[];[i(557),i(558),i(559),i(560),i(561),i(562),i(563),i(564),i(565),i(566),
|
|
|
206
206
|
* pkg.js - package constants
|
|
207
207
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
208
208
|
* https://github.com/bookmansoft/gamegold
|
|
209
|
-
*/t.protocol="vallnet",t.version="v5.0.
|
|
209
|
+
*/t.protocol="vallnet",t.version="v5.0.6",t.url="https://github.com/bookmansoft/gamegold"},function(e,t,i){"use strict";
|
|
210
210
|
/*!
|
|
211
211
|
* common.js - p2p constants for vallnet
|
|
212
212
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -900,7 +900,7 @@ var r=i(770),s=i(772),n=i(773),a=i(774),o=i(775),c=i(776),h=i(777);i=i(778),s=[]
|
|
|
900
900
|
/*!
|
|
901
901
|
* accountdb.js - storage for account management
|
|
902
902
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
903
|
-
*/const r=i(8),s=i(0),n=i(73),a=i(118),o=i(157),c=i(608),h=i(85),u=h.walletdb,l=i(6),p=i(158),d=i(124),f=i(167),m=i(36).VerifyError,g=i(45),y=i(13);i(19),i(68);const v=i(196),b=i(67),w=i(50),{getVerifyMsg:k,BlockFinalType:x,ContractEnvType:S}=i(5),_=i(159),E=i(610),R=i(35);var A=i(71);const O=i(2),C=i(140).sortWithSeq,I=i(33),P=i(197),j=i(63),T=i(100),B=i(3),N=B.U32,M=i(336),L=i(337),F=i(338),z=F.vpItem,H=i(611),D=H.vpItem,U=i(312);i(612);const q=U.cpItem,V=i(154),K=V.ErAbolishItem,W=i(43).broadcast,$=i(131),X=$.vpItem,G=i(153),Y=G.ErItem,J=i(613),Z=J.AuditItem,Q=i(305),ee=i(109),te=i(614),ie=i(306),re=i(119),se=i(615),ne=i(217),ae=i(38),oe=i(34),ce=i(59),he=i(78),ue=he.errors,le=i(77);class pe extends A{constructor(e){super(),this.readyLoad=!1,this.options=new c(e),this.network=this.options.network,this.logger=this.options.logger.context("wallet"),this.workers=this.options.workers,this.keys={hmacSalt:B.DefaultChainCode},e.keys&&e.keys.hmacSalt&&(s(Buffer.isBuffer(e.keys.hmacSalt)),this.keys.hmacSalt=e.keys.hmacSalt),this.client=this.options.client,this.client&&(this.client.wdb=this),this.jsonp=this.options.jsonp,this.jsonp&&(this.jsonp.wdb=this),this.spv=this.options.spv,this.feeRate=this.options.feeRate,this.db=f(this.options),this.rpc=new M(this),this.primary=null,this.state=new te,this.wallets=new Map,this.depth=0,this.rescanning=!1,this.bound=!1,this.newRecord=!0,this.readLock=new P,this.writeLock=new I,this.txLock=new I,this.scanLock=new I,this.widCache=new j(1e4),this.pathMapCache=new j(1e5),this.filter=new T,this.middleHashMem=new Set,this.middleHashChain=new Set,this.autoTaskMgr=new _(this),this.transactionList=new L(this),this.htlcList=new F(this),this.commentList=new H(this),this.NotifyList=new R,this.propList=new $(this),this.$contacts=new R,this.cpList=new U(this),this.cpMemList=new U(this),this.auditList=new J(this),this.erList=new G(this),this.erAbList=new V(this),this.hmacConnection=[],this._init()}async logAudit(e){e.height=this.curHeight,e.time=O.now(),e.erid=l.sha256(O.stringify(e)).toString("hex"),e=new Z(e),await this.auditList.setAudit(e)}async getAccountByAddress(e,t){if(e){let s=null;if(s=t?await this.getWalletsByTX(t):await this.getWallets())for(const t of s){var i=await this.get(t);if(i){var r=await i.getPath(e);if(r)return[i.wid,r.name,i.id]}}}return[0,"",""]}_init(){let e=1e6,t=-1;this.spv&&(e=2e4,t=T.flags.ALL),this.filter=T.fromRate(e,.001,t)}get mode(){return S.Wallet}async getTXFromAll(e){return this.getTXFromDb(e)}async checkNewRecord(){var e={createIfMissing:this.db.options.createIfMissing,errorIfExists:this.db.options.errorIfExists};this.db.options.createIfMissing=!1,this.db.options.errorIfExists=!0;try{await this.db.open();var t=await this.db.checkVersion(u,6);this.newRecord="new"==t}catch(e){if(-1!=e.message.indexOf("does not exist (create_if_missing is false)"))this.newRecord=!0;else{if(-1==e.message.indexOf("exists (error_if_exists is true)"))throw e;this.newRecord=!1}}try{await this.db.close()}catch(e){}this.db.options.createIfMissing=e.createIfMissing,this.db.options.errorIfExists=e.errorIfExists}async isNewRecord(){return await this.checkNewRecord(),this.newRecord}setmnemonic(e){if(this.options.mnemonic=this.options.mnemonic||{},e.bits)this.options.mnemonic={bits:e.bits};else if(e.entropy)this.options.mnemonic={entropy:Buffer.from(e.entropy,"hex")};else if(e.phrase){var t=this.testmnemonic(e.phrase);if(0!=t.code)throw t.msg;this.options.mnemonic={phrase:e.phrase}}e.passphrase&&(this.options.mnemonic.passphrase=e.passphrase),e.language&&(this.options.mnemonic.language=e.language)}testmnemonic(e){try{return new v(e),{code:0}}catch(e){return{code:-1,msg:e.message}}}async getContracts(e){var t=await this.db.values({gte:h.txdb.tx(B.NULL_HASH),lte:h.txdb.tx(B.HIGH_HASH),parse:e=>O.parseJson(e.toString())});return e?t.filter(t=>t.srcact==e||t.dstact==e):t}isFull(){return this.spv||this.synced||!1}async _open(e){}async handleNotify(e,t=!1){if(!t){let i=e.body.content;if("string"==typeof i)try{i=JSON.parse(e.body.content)}catch(e){return}"object"==typeof i&&"secret"===i.type&&(t={contact:e.body.src,messenger:e.body.dst},i.init&&(t.init=Buffer.from(i.init,"hex")),i.packet&&(t.packet=Buffer.from(i.packet)),await this.handleSecret(t))}}async handleSecret(e){if(e.contact&&e.messenger&&e.contact!=e.messenger){try{y.fromString(e.contact,this.network.type),y.fromString(e.messenger,this.network.type)}catch(e){return}var t=await this.ensureContact(e);t&&await t.ensureMessenger(e).answer(e)}}async scanContact(e,t=-1){var i=async e=>{var t;e.witness&&"witnesspubkeyhash"==e.getType()&&(t=e.witness.getPubkeyhashInput()[1],e=y.fromWitness(e.witness).toString(),t)&&e&&await this.ensureContact({contact:e,publicKey:t})};if(0<=t&&t<e.inputs.length)await i(e.inputs[t]);else for(var r of e.inputs)await i(r)}async ensureContact(e){if(!e.contact||e.contact==e.messenger)return null;try{y.fromString(e.contact,this.network.type),e.messenger&&y.fromString(e.messenger,this.network.type)}catch(e){return null}e.network=this.network.type,this.$contacts.get(e.contact)||this.$contacts.set(e.contact,new E(e));var t=this.$contacts.get(e.contact);if(e.messenger&&!(e=t.ensureMessenger(e)).wallet){var i,[i,r]=await this.getAccountByAddress(e.address);if(!(i=await this.get(i)))return;e.wallet=i,e.account=r}return t}getCps(){return this.db.values({gte:h.txdb.cp(B.ZERO_CID,"hex"),lte:h.txdb.cp(B.MAX_CID,"hex"),parse:e=>q.fromRaw(e)})}async _close(){await this.disconnect(),this.http&&this.options.listen&&await this.http.close();for(const e of this.wallets.values())await e.destroy();await this.db.close(),this.options.listen&&await this.logger.close()}async destroy(){await this.db.destroy(),this.widCache.reset(),this.pathMapCache.reset()}async load(e){if(this.readyLoad){var t=await this.ensure({id:"primary",witness:!0,mnemonic:this.options.mnemonic}),i=await this.txLock.lock();try{await this.init(e),await this.watch(),await t.createReceive(0,1,t.master,this.network.type),await t.ensureNotifyKey(),await this.sync()}finally{i()}setTimeout(()=>{this.resend()},5e3)}}async disconnect(){this.client&&await this.client._close(),this.jsonp&&await this.jsonp._close()}async flushCP(e,t=!1){this.client&&(e=e||[],t||(e=this.cpList.excludeCids(e),t=t||0<e.length),t)&&await this.client.execute("cp.remoteQuery",[[["cid","include",e]]])}async watch(){let e=this.db.iterator({gte:u.p(B.NULL_HASH),lte:u.p(B.HIGH_HASH)}),t=0,i=0;for(;;){var r=await e.next();if(!r)break;try{var s=u.pp(r.key);this.addHash(s,!1)}catch(t){throw await e.end(),t}t++}for(e=this.db.iterator({gte:u.o(B.NULL_HASH,0),lte:u.o(B.HIGH_HASH,4294967295)});;){var n=await e.next();if(!n)break;try{var[a,o]=u.oo(n.key);this.addOutpoint(a,o)}catch(t){throw await e.end(),t}i++}this.logger.info("Filter: Added %d hashes to AccountDB filter.",t),this.logger.info("Filter: Added %d outpoints to AccountDB filter.",i),await this.setFilter()}async sync(){if(this.client){let t,i=this.curHeight;for(;0<=i;){var e=await this.getBlock(i);if(!e)break;if(t=await this.client.getEntry(e.hash))break;i--}t||(i=this.state.startHeight,t=await this.client.getEntry(this.state.startHash))||(i=0),await this.cpList.loadHistory(),await this.cpMemList.loadHistory(),await this.propList.loadHistory(),await this.htlcList.loadHistory(),await this.commentList.loadHistory(),await this.transactionList.loadHistory(),await this.loadContact(),await this.erList.loadHistory(),await this.auditList.loadHistory(),await this.erAbList.loadHistory(),await this._rescan(i,!1)}}async _rescan(e,t=!0){if(this.client){null==e&&(e=this.state.startHeight),s(e>>>0===e,"WDB: Must pass in a height.");var i=this.curHeight;t=(await this.rollback(e,t),this.logger.info("AccountDB is scanning %d blocks.",i-e+1),await this.getTip());try{this.rescanning=!0,await this.client.rescan(t.hash,this.eid)}finally{this.rescanning=!1}}}async rescan(e){var t=await this.txLock.lock();try{return await this._rescan(e,!1)}finally{t()}}async send(e){if(this.client)return this.client.send(e);this.emit("send",e)}async getTX(e){for(const i of this.wallets.values()){var t=await i.getTX(e);if(t)return t.tx}return null}async getTXFromDb(e){for(const i of this.wallets.values()){var t=await i.getTX(e);if(t)return t.tx}return null}async getExtendTX(e){for(const i of this.wallets.values()){var t=await i.getTX(e);if(t)return t}return null}async removeTX(e){this.client?await this.client.removeTX(e):this.emit("remove",e)}async estimateFee(e){return 0<this.feeRate?this.feeRate:!this.client||(e=await this.client.estimateFee(e))<this.network.feeRate?this.network.feeRate:e>this.network.maxFeeRate?this.network.maxFeeRate:e}setFilter(){return this.client?this.client.setFilter(this.filter):(this.emit("filter.set",this.filter),Promise.resolve())}resetFilter(){return this.client?this.client.resetFilter():(this.emit("filter.reset"),Promise.resolve())}backup(e){return this.db.backup(e)}async wipe(){this.logger.warning("Wiping AccountDB TXDB..."),this.logger.warning("I hope you know what you're doing.");var e=this.db.iterator({gte:Buffer.from([0]),lte:Buffer.from([255])}),t=this.db.batch();let i=0;for(;;){var r=await e.next();if(!r)break;try{switch(r.key[0]){case 98:case 99:case 101:case 116:case 111:case 104:case 82:t.del(r.key),i++}}catch(t){throw await e.end(),t}}this.logger.warning("Wiped %d txdb records.",i),await t.write()}async getDepth(){var e=this.db.iterator({gte:u.w(0),lte:u.w(4294967295),reverse:!0,limit:1}),t=await e.next();return t?(await e.end(),u.ww(t.key)+1):1}start(e){return s(!e.current,"WDB: Batch already started."),e.current=this.db.batch(),e.accountCache.start(),e.pathCache.start(),e.current}drop(e){var t=this.batch(e);e.current=null,e.accountCache.drop(),e.pathCache.drop(),t.clear()}clear(e){var t=this.batch(e);e.accountCache.clear(),e.pathCache.clear(),t.clear()}batch(e){return s(e.current,"WDB: Batch does not exist."),e.current}async commit(e){var t=this.batch(e);try{await t.write()}catch(e){throw this.drop(),e}e.current=null,e.accountCache.commit(),e.pathCache.commit()}testFilter(e){return this.filter.test(e,"hex")}addHash(e,t=!0){this.filter.add(e,"hex"),t&&(t=Buffer.from(e,"hex"),this.client?this.client.addFilter(t):this.emit("filter.add",t))}addOutpoint(e,t){e=new g(e,t),this.filter.add(e.toRaw())}dump(){return this.db.dump()}register(e){s(!this.wallets.has(e.wid)),this.wallets.set(e.wid,e)}unregister(e){s(this.wallets.has(e.wid)),this.wallets.delete(e.wid)}async getWalletID(e){var t;return e?"number"==typeof e?e:this.widCache.get(e)||((t=await this.db.get(u.l(e)))?(t=t.readUInt32LE(0,!0),this.widCache.set(e,t),t):null):null}async get(e){if(!(e=await this.getWalletID(e)))return null;var t=await this.readLock.lock(e);try{return await this._get(e)}finally{t()}}async _get(e){var t=this.wallets.get(e);return t||((t=await this.db.get(u.w(e)))?(await(e=a.fromRaw(this,t)).open(),this.register(e),e):null)}async loadBackup(e){if(ce.unsupported)throw new le(ue.INTERNAL_ERROR,"FS not available.");let t=null;var i;for(i of(await ce.readFile(e,"utf8")).split(/\n+/))if(0!==(i=i.trim()).length&&!/^\s*#/.test(i)){var r=i.split(/\s+/);if(r.length<4)throw new le(ue.DESERIALIZATION_ERROR,"Malformed wallet Data File.");switch(r[0]){case"W":var n=Buffer.from(r[1],"base64");n=a.fromRaw(this,n);await this.replace(n),t=await this.get(n.id),this.logger.info("Import Wallet %s(%s)",t.id,t.wid);break;case"C":n=Buffer.from(r[1],"base64");(c=((h=o.fromRaw(this,n)).wallet=t,h.wid=t.wid,h.id=t.id,h.initialized=!0,h.watchOnly=t.watchOnly,h.receive=h.deriveReceive(h.receiveDepth-1),h.change=h.deriveChange(h.changeDepth-1),h.witness&&(h.nested=h.deriveNested(h.nestedDepth-1)),t.master.key.deriveAccount(44,h.accountIndex))).publicKey.toString("hex")!==h.accountKey.publicKey.toString("hex")&&s(c.publicKey.toString("hex")==h.accountKey.publicKey.toString("hex")),await t.saveAccount(h),this.logger.info("Import Account %s(%s)",h.name,h.accountIndex);break;case"A":var c=he.parseSecret(r[1],this.network),h=parseInt(r[5]),u=parseInt(r[7]),l=parseInt(r[9]),p=r[11].trim();if(u<0||l<0)try{await t.importKey(h,c)}catch(e){this.logger.error(`loadBackup: ${e.message} account/secret: ${h}/`+p)}else{var d=await t.deriveKey(h,u,l),f=await t.deriveKey(h,u,l,t.master);d.getAddress("string")!==f.getAddress("string")&&this.logger.error(`loadBackup: not-equal-1: ${d.getAddress("string")} != `+f.getAddress("string")),d.getAddress("string")!==p&&this.logger.error(`loadBackup: not-equal-2: ${d.getAddress("string")} != `+p)}this.logger.info("Import Address %s %s %s %s",h,u,l,p)}}return t.accountCache.reset(),t}save(e){var t=e.wid,i=e.id,r=this.batch(e);this.widCache.set(i,t),r.put(u.w(t),e.toRaw()),r.put(u.l(i),N(t))}async rename(e,t){var i=await this.writeLock.lock();try{return await this._rename(e,t)}finally{i()}}async _rename(e,t){var i=e.id;if(!n.isName(t))throw new Error("WDB: Bad wallet ID.");if(await this.has(t))throw new Error("WDB: ID not available.");this.start(e).del(u.l(i)),e.id=t,this.save(e),await this.commit(e),this.widCache.remove(i),i=e.pathCache.values();for(const e of i)e.id=t}async replace(e){var t=await this.writeLock.lock();try{return await this._replace(e)}finally{t()}}async _replace(e){var t=this.start(e);t.del(u.l(e.id)),t.del(u.w(e.wid)),this.save(e),await this.commit(e),this.widCache.remove(e.id),this.wallets.delete(e.wid)}renameAccount(e,t){var i=e.wallet;this.batch(i).del(u.i(e.wid,e.name)),e.name=t,this.saveAccount(e)}async auth(e,t){if("string"==typeof t){if(!O.isHex256(t))throw new Error("WDB Authentication: Invalid Token.");t=Buffer.from(t,"hex")}e=b.getHmac(e.toString(),this.keys.hmacSalt);var i=r.createHmac("sha256",e.random);i=Buffer.from(i.update(e.token).digest("hex"),"hex");if(!p(t,i))throw new Error("WDB Authentication: CRC Error.")}async create(e){var t=await this.writeLock.lock();e=e||{};try{return await this._create(e)}finally{t()}}async _create(e){if(await this.has(e.id))throw new Error("WDB: Wallet already exists.");"string"==typeof e.mnemonic&&(e.mnemonic={phrase:e.mnemonic}),e.mnemonic=e.mnemonic||{},!e.mnemonic.language&&this.options.mnemonic&&this.options.mnemonic.language&&(e.mnemonic.language=this.options.mnemonic.language);var t=a.fromOptions(this,e);return t.wid=this.depth++,await t.init(e),this.register(t),this.logger.info("Created wallet %s in AccountDB.",t.id),t}async has(e){return null!=await this.getWalletID(e)}async ensure(e){return await this.get(e.id)||this.create(e)}async getAccount(e,t){return(e=await this.db.get(u.a(e,t)))?o.fromRaw(this,e):null}getAccounts(e){return this.db.values({gte:u.n(e,0),lte:u.n(e,4294967295),parse:e=>e.toString("ascii")})}async getAccountIndex(e,t){return(e=await this.db.get(u.i(e,t)))?e.readUInt32LE(0,!0):-1}async getAccountName(e,t){return(e=await this.db.get(u.n(e,t)))?e.toString("ascii"):null}saveAccount(e){var t=e.wid,i=e.wallet,r=e.accountIndex,s=e.name,n=this.batch(i);n.put(u.a(t,r),e.toRaw()),n.put(u.i(t,s),N(r)),n.put(u.n(t,r),Buffer.from(s,"ascii")),i.accountCache.push(r,e)}hasAccount(e,t){return"number"==typeof e&&"number"==typeof t&&this.db.has(u.a(e,t))}async getPathMap(e){var t=this.pathMapCache.get(e);return t||((t=await this.db.get(u.p(e)))?(t=se.fromRaw(e,t),this.pathMapCache.set(e,t),t):null)}saveKey(e,t){return this.savePath(e,t.toPath())}async savePath(e,t){var i=e.wid,r=t.hash,s=this.batch(e);this.addHash(r);let n=await this.getPathMap(r);(n=n||new se(r)).add(i)&&(this.pathMapCache.set(r,n),e.pathCache.push(r,t),s.put(u.p(r),n.toRaw()),s.put(u.P(i,r),t.toRaw()),s.put(u.r(i,t.account,r),null))}async getPath(e,t){var i=await this.db.get(u.P(e,t));return i?((i=ee.fromRaw(i)).wid=e,i.hash=t,i):null}hasPath(e,t){return this.db.has(u.P(e,t))}getHashes(){return this.db.keys({gte:u.p(B.NULL_HASH),lte:u.p(B.HIGH_HASH),parse:u.pp})}getOutpoints(){return this.db.keys({gte:u.o(B.NULL_HASH,0),lte:u.o(B.HIGH_HASH,4294967295),parse:e=>{var[e,t]=u.oo(e);return new g(e,t)}})}getWalletHashes(e){return this.db.keys({gte:u.P(e,B.NULL_HASH),lte:u.P(e,B.HIGH_HASH),parse:u.Pp})}getAccountHashes(e,t){return this.db.keys({gte:u.r(e,t,B.NULL_HASH),lte:u.r(e,t,B.HIGH_HASH),parse:u.rr})}async getWalletPaths(e){var t=[];for(const s of await this.db.range({gte:u.P(e,B.NULL_HASH),lte:u.P(e,B.HIGH_HASH)})){var i=u.Pp(s.key),r=ee.fromRaw(s.value);r.hash=i,r.wid=e,t.push(r)}return t}async encryptKeys(e,t){var i,r,n=e.wid,a=await e.getPaths(),o=this.batch(e);for(i of a)i.data&&(s(!i.encrypted),r=Buffer.from(i.hash,"hex").slice(0,16),(i=i.clone()).data=d.encipher(i.data,t,r),i.encrypted=!0,e.pathCache.push(i.hash,i),o.put(u.P(n,i.hash),i.toRaw()))}async decryptKeys(e,t){var i,r,n=e.wid,a=await e.getPaths(),o=this.batch(e);for(i of a)i.data&&(s(i.encrypted),r=Buffer.from(i.hash,"hex").slice(0,16),(i=i.clone()).data=d.decipher(i.data,t,r),i.encrypted=!1,e.pathCache.push(i.hash,i),o.put(u.P(n,i.hash),i.toRaw()))}async resend(){var e,t={};for(const e of await this.db.keys({gte:u.w(0),lte:u.w(4294967295)})){var i=u.ww(e),r=await this.resendPending(i);r&&Array.isArray(r)&&(t[i]=r)}for(e of Object.keys(t))if(await this.get(parseInt(e)))for(const i of t[e]){try{await this.send(i)}catch(e){this.logger.warning("wdb resend:",e.message)}await oe.timeout(50)}}async resendPending(e){var t=await this.get(e),i=await this.db.keys({gte:h.txdb.prefix(e,h.txdb.p(B.NULL_HASH)),lte:h.txdb.prefix(e,h.txdb.p(B.HIGH_HASH))});if(0!==i.length){this.logger.info("Rebroadcasting %d transactions for %d.",i.length,e);var r=[];for(const o of i){var s=h.txdb.pp(o),n=h.txdb.prefix(e,h.txdb.t(s));if((n=await this.db.get(n))&&!(n=ne.fromRaw(n)).tx.isCoinbase())try{var a=await w.FactoryOfContract({tx:n.tx,env:this});await a.isBlockFinal()==x.Expired?t&&(await this.removeTX(n.tx),await t.remove(s),await a.erase()):"notify"!=a.oper&&r.push(n.tx)}catch(e){this.logger.error("TX(%s) Smart Contract Error: %s",n.tx.txid(),e.message)}}return C(r)}}getWallets(){return this.db.keys({gte:u.l("\0"),lte:u.l("ÿ"),parse:u.ll})}async getWalletsByTX(e){var t=new Set;if(!e.isCoinbase())for(const r of e.inputs){var i=r.prevout;if(this.testFilter(i.toRaw())&&(i=await this.getOutpointMap(i.hash,i.index)))for(const e of i.wids)t.add(e)}for(const i of e.getOutputHashes("hex"))if(this.testFilter(i)){var r=await this.getPathMap(i);if(r)for(const e of r.wids)t.add(e)}return 0===t.size?null:t}async getState(){var e=await this.db.get(u.R);return e?te.fromRaw(e):null}async init(e){var t=this.options.startHeight;let i;if(this.client){if(null!=t){if(!(i=await this.client.getEntry(t)))throw new Error("WDB: Could not find start block.")}else i=await this.client.getTip();i=re.fromEntry(i)}else i=re.fromEntry(this.network.genesis);this.logger.info("Initializing AccountDB chain state (height %d).",i.height),(t=await this.getState())?this.state=t:await this.resetState(i,!1),await this.ensure({id:"primary",witness:!0,mnemonic:this.options.mnemonic}),e&&e.backup&&await this.loadBackup(e.backup)}async resetState(e,t){for(var i=this.state.clone(),r=(i.startHeight=e.height,i.startHash=e.hash,i.height=e.height,i.marked=t,this.db.batch()),s=this.db.iterator({gte:u.h(e.height),lte:u.h(4294967295),values:!1});;){var n=await s.next();if(!n)break;try{r.del(n.key)}catch(e){throw await s.end(),e}}r.put(u.h(e.height),e.toHash()),r.put(u.R,i.toRaw()),await r.write(),this.state=i}async syncState(e){var t=this.state.clone(),i=this.db.batch();if(e.height<t.height){let s=t.height;var r=s-e.height;for(let e=0;e<r;e++)i.del(u.h(s--))}else e.height>t.height&&s(e.height===t.height+1,`Bad chain sync tip ${e.height} while state `+t.height);t.height=e.height,i.put(u.h(e.height),e.toHash()),i.put(u.R,t.toRaw()),await i.write(),this.state=t,W("block/tips",t)}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(e){var t=await this.db.get(u.b(e));return t?ie.fromRaw(e,t):null}writeBlockMap(e,t,i){this.batch(e).put(u.b(t),i.toRaw())}unwriteBlockMap(e,t){this.batch(e).del(u.b(t))}async getOutpointMap(e,t){var i=await this.db.get(u.o(e,t));return i?Q.fromRaw(e,t,i):null}writeOutpointMap(e,t,i,r){e=this.batch(e),this.addOutpoint(t,i),e.put(u.o(t,i),r.toRaw())}unwriteOutpointMap(e,t,i){this.batch(e).del(u.o(t,i))}async writeBalanceLog(e,t){var i=u.log(e.wid,t.aidx,t.height,t.hash),r=(t=Buffer.from(JSON.stringify(t)),await this.writeLock.lock());try{this.start(e).put(i,t),await this.commit(e)}finally{r()}}async queryBalanceLog(e,t,i=0){return this.db.values({gte:u.log(e,t,i,B.NULL_HASH),lte:u.log(e,t,this.curHeight,B.HIGH_HASH),parse:e=>JSON.parse(e.toString())})}async getBlock(e){var t,i=await this.db.get(u.h(e));return i?((t=new re).hash=i.toString("hex"),t.height=e,t):null}async getTip(){var e=await this.getBlock(this.curHeight);if(e)return e;throw new Error("WDB: Tip not found!")}async rollback(e,t=!0){if(e>this.curHeight)throw new Error("WDB: Cannot rollback to the future.");if(e===this.curHeight)return this.logger.debug("Rolled back to same height (%d).",e),!0;this.logger.info("Rolling back %d AccountDB blocks to height %d.",this.curHeight-e,e);var i=await this.getBlock(e);let r=!1;return i?(await this.revert(i.height),await this.syncState(i),t):(i=new re,e>=this.state.startHeight?(i.height=this.state.startHeight,i.hash=this.state.startHash,r=this.state.marked,this.logger.warning("Rolling back AccountDB to start block (%d).",i.height)):(i.height=0,i.hash=this.network.genesis.hash,r=!1,this.logger.warning("Rolling back AccountDB to genesis block.")),await this.revert(i.height),await this.resetState(i,r),!1)}async revert(e){var t=this.db.iterator({gte:u.b(e+1),lte:u.b(4294967295),reverse:!0,values:!0});let i=0;for(;;){var r=await t.next();if(!r)break;try{var s=u.bb(r.key),n=ie.fromRaw(s,r.value).toArray();i+=n.length;for(let e=n.length-1;0<=e;e--)await this._unconfirm(n[e])}catch(e){throw await t.end(),e}}this.logger.info("Rolled back %d AccountDB transactions.",i)}async addBlock(e,t){var i=await this.txLock.lock();try{return await this._addBlock(e,t)}finally{i()}}async _addBlock(e,t){var i=re.fromEntry(e);let r=0;if(i.height<this.curHeight)this.logger.warning("AccountDB is connecting low blocks (%d).",i.height);else{if(i.height===this.curHeight)this.logger.warning("Already saw AccountDB block (%d).",i.height);else if(i.height!==this.curHeight+1)throw new Error(`WDB(addBlock): Bad disconnection (height mismatch, tip ${i.height} while state ${this.curHeight})`);if(await this.syncState(i),!(this.options.checkpoints&&i.height<=this.network.lastCheckpoint)){for(const e of t)await this._insert(e,i)&&r++;0<r&&this.logger.info("Connected AccountDB block %s (tx=%d).",O.revHex(i.hash),r)}}return r}async removeBlock(e,t){var i=await this.txLock.lock();try{return await this._removeBlock(e,t)}finally{i()}}async _removeBlock(e,t){if((e=re.fromEntry(e)).height>this.curHeight)return this.logger.warning("AccountDB is disconnecting high blocks (%d).",e.height),0;if(e.height!==this.curHeight)throw new Error(`WDB(removeBlock): Bad disconnection (height mismatch, tip ${e.height} / ${O.revHex(e.hash)} while state ${this.curHeight})`);var i=await this.getBlock(e.height-1);if(!i)throw new Error(`WDB(removeBlock): Bad disconnection (no previous block of ${e.height} / ${O.revHex(e.hash)}).`);var r=await this.getBlockMap(e.height);if(r){for(let e=t.length-1;0<=e;e--){var s=t[e];await this._unconfirm(s,r)}this.logger.warning("Disconnected wallet block %s (tx=%d).",O.revHex(e.hash),r.txs.size)}return await this.syncState(i),r?r.txs.size:0}async rescanBlock(e,t){if(this.rescanning){var i=await this.scanLock.lock();try{await this._addBlock(e,t)}catch(e){throw this.emit("error",e),e}finally{i()}}else this.logger.warning("Unsolicited rescan block: %s.",e.height)}async addTX(e,t,i){var r=await this.txLock.lock();try{return await this._insert(e,t,i)}finally{r()}}listNotify(e){return this.NotifyList.deletes([["h","<",this.curHeight-12]]),this.NotifyList.query(e)}listContact(e,t,i){return this.$contacts.query(e,t,i)}async setCp(e){await this.batchPut(h.txdb.cp(e.cid),e.toRaw())}async delCp(e){await this.batchDel(h.txdb.cp(e))}async delVp(e){var t=this.db.batch();t.del(h.txdb.VP(e.pid)),await t.write()}async setVp(e,t){var i=this.db.batch();i.put(h.txdb.VP(e.pid),e.toRaw()),await i.write()}async getVp(e){return(e=await this.db.get(h.txdb.VP(e)))?X.fromRaw(e):null}async getVpByAddress(e){return{list:[],count:0}}async getVpByOid(e){return{list:[],count:0}}async loadVpList(){return this.db.values({gte:h.txdb.VP(B.ZERO_CID,"hex"),lte:h.txdb.VP(B.MAX_CID,"hex"),parse:e=>X.fromRaw(e)})}async saveContact(e){var t=this.db.batch();t.put(h.txdb.CT(e.getAddress()),e.toRaw()),await t.write()}async loadContact(e){var t;for(t of await this.db.values({gte:h.txdb.CT(B.ZERO_HASH160_HEX),lte:h.txdb.CT(B.MAX_HASH160_HEX),parse:e=>E.fromRaw(e,this)}))t.sender&&(t.sender.wallet=await this.get(t.sender.wid)),this.$contacts.set(t.address,t)}async delHtlc(e){var t;(e=new z(e)).id&&(this.htlcList.delete(e.id),this.htlcList.delAccount(e),(t=this.db.batch()).del(h.txdb.VH(e.shash,e.sidx)),await t.write())}async setSuggest(e){e=new z(e);var t,[t,i]=(this.htlcList.set(e.id,e),await this.getAccountByAddress(e.aa)),[t,i]=(t&&this.htlcList.setAccount(e,t,i),await this.getAccountByAddress(e.ba));(t=(t&&this.htlcList.setAccount(e,t,i),this.db.batch())).put(h.txdb.VH(e.shash,e.sidx),e.toRaw()),await t.write()}async setAssent(e){e=new z(e);var t,[t,i]=(this.htlcList.set(e.id,e),await this.getAccountByAddress(e.ab)),[t,i]=(t&&this.htlcList.setAccount(e,t,i),await this.getAccountByAddress(e.bb));(t=(t&&this.htlcList.setAccount(e,t,i),this.db.batch())).put(h.txdb.VH(e.shash,e.sidx),e.toRaw()),await t.write()}async loadHtlcList(){return this.db.values({gte:h.txdb.VH(B.ZERO_CID,0),lte:h.txdb.VH(B.MAX_CID,4294967295),parse:e=>z.fromRaw(e)})}async delComment(e){var t;(e=new D(e)).id&&(this.commentList.delete(e.id),this.commentList.delAccount(e),(t=this.db.batch()).del(h.txdb.VC(e.shash,e.sidx)),await t.write())}async setComment(e){e=new D(e);var t,[t,i]=(this.commentList.set(e.id,e),await this.getAccountByAddress(e.bob));(t=(t&&(this.commentList.setAccount(e,t,i),this.emit("comm.comment",e)),this.db.batch())).put(h.txdb.VC(e.shash,e.sidx),e.toRaw()),await t.write()}async loadCommentList(){return this.db.values({gte:h.txdb.VC(B.ZERO_CID,0),lte:h.txdb.VC(B.MAX_CID,4294967295),parse:e=>D.fromRaw(e)})}async verifyClsTx(e,t){if(!this.spv&&1!=(t=await(await w.FactoryOfContract({env:this,block:t,tx:e})).verify()))throw new m(e,k(t),"bad-contract-verify",100);return!0}async delEr(e){var t=this.db.batch();t.del(h.txdb.ER(e.erid)),t.del(h.txdb.ERR(e.witness,e.erid,e.txid)),await t.write()}async setEr(e,t){t&&e.source&&(i=y.fromWitnessPubkeyhash(l.hash160(Buffer.from(e.source.pubkey,"hex")),this.network),[i,t]=await this.getAccountByAddress(i,t),e.wid=i,e.account=t);var i=this.db.batch();t=h.txdb.ERR(e.witness,e.erid,e.txid);i.put(t,e.toRaw()),i.put(h.txdb.ER(e.erid),t),await i.write()}async getEr(e){var t;return(e=await this.db.get(h.txdb.ER(e)))&&([,,t]=h.txdb.ERRR(e),e=await this.db.get(e))?((e=Y.fromRaw(e)).txid=t,e):null}async byPubkey(e,t,i=!1){var r,s=new R;e=await this.db.values({gte:h.txdb.ERR(e,B.NULL_HASH,B.NULL_HASH),lte:h.txdb.ERR(e,B.HIGH_HASH,B.HIGH_HASH),parse:e=>Y.fromRaw(e)});let n=[],a=new Map;if(i){for(var o of e)(!a.get(o.source.cluster)||o.startHeight>a.get(o.source.cluster).startHeight)&&a.set(o.source.cluster,await this.caVerifyObj(o));n=a.values()}else n=e;for(r of n)s.set(r.erid,r);return s.query(t)}async caVerifyObj(e){var t={verify:!1};if(!e||e.validHeight<=this.curHeight)return t;var i=await this.erAbList.getErAb(e.erid);return i&&i.abolishHeight<this.curHeight?t:(i=ae.fromPublic(Buffer.from(e.witness,"hex"),this.network.type),e.verify(i)?(e.verify=!0,0<(i=this.cpList.query([["pubKey",e.witness]])).list.length&&(e.cpid=i.list[0].cid),e):t)}async delErAbolish(e){var t=this.db.batch();t.del(h.txdb.ERA(e.erid)),await t.write()}async setErAbolish(e){var t=this.db.batch();t.put(h.txdb.ERA(e.erid),e.toRaw()),await t.write()}async getErAbolish(e){return(e=await this.db.get(h.txdb.ERA(e)))?K.fromRaw(e):null}loadErAbolishList(){return this.db.values({gte:h.txdb.ERA(B.ZERO_CID),lte:h.txdb.ERA(B.MAX_CID),parse:e=>K.fromRaw(e)})}async delAudit(e){var t=this.db.batch();t.del(h.txdb.AU(e.erid)),await t.write()}async setAudit(e){var t=this.db.batch();t.put(h.txdb.AU(e.erid),e.toRaw()),await t.write()}async getAudit(e){return(e=await this.db.get(h.txdb.AU(e)))?Z.fromRaw(e):null}async loadAuditList(){return this.db.values({gte:h.txdb.AU(B.NULL_HASH),lte:h.txdb.AU(B.HIGH_HASH),parse:e=>Z.fromRaw(e)})}async batchPut(e,t){var i=this.db.batch();i.put(e,t),await i.write()}async batchDel(e){var t=this.db.batch();t.del(e),await t.write()}async _insert(e,t,i){s(!e.mutable,"WDB: Cannot add mutable TX.");let r=await this.getWalletsByTX(e);if(r){this.logger.info("Incoming transaction for %d wallets in AccountDB (%s).",r.size,e.txid()),!t||this.state.marked||(this.logger.info("Marking AccountDB start block at %s (%d).",O.revHex(t.hash),t.height),await this.resetState(t,!0));let a=!1;for(const o of r){var n=await this.get(o);s(n),await n.add(e,t,i)&&(this.logger.info("Added transaction to wallet in AccountDB: %s (%d).",n.id,o),a=!0)}a||(r=null)}try{var a=await w.FactoryOfContract({env:this,block:t,tx:e});t?await a.confirm():await a.insert()}catch(a){t?this.logger.error("TX(%s) Smart Contract Confirm Error: %s",e.txid(),a.message):this.logger.error("TX(%s) Smart Contract Insert Error: %s",e.txid(),a.message)}return r}async _unconfirm(e,t){if(t)try{await(await w.FactoryOfContract({env:this,block:t,tx:e})).unconfirm()}catch(t){this.logger.error("TX(%s) Smart Contract Unconfirm Error: %s",e.txid(),t.message)}let i,r=null;if(i=e.wids?(r=e.wids,e.hash):(r=await this.getWalletsByTX(e),e.hash("hex")),!r)return null;for(const e of r){var n=await this.get(e);s(n),await n.unconfirm(i)}}async resetChain(e){var t=await this.txLock.lock();try{return await this._resetChain(e)}finally{t()}}async _resetChain(e){if(e.height>this.curHeight)throw new Error(`WDB: Bad reset height ${e.height} while curHeight `+this.curHeight);var t;for(t of(await this.rollback(e.height)||await this._rescan(),await this.getWallets())){var i=await this.get(t);for(const t of await i.getPending())try{await i.abandon(t.hash)}catch(e){}}}async saveMSTrans(e){var t=await this.writeLock.lock();try{return await this._saveMSTrans(e)}finally{t()}}async _saveMSTrans(e){var t=this.db.batch();t.put(u.ms(y.getHash(e.addr,"hex"),e.txid),Buffer.from(JSON.stringify(e))),await t.write()}async listMSTrans(e){return e=y.getHash(e,"hex"),this.db.values({gte:u.ms(e,B.NULL_HASH),lte:u.ms(e,B.HIGH_HASH),parse:e=>JSON.parse(e.toString())})}async delMSTrans(e,t){var i=await this.writeLock.lock();try{return await this._delMSTrans(e,t)}finally{i()}}async _delMSTrans(e,t){e=y.getHash(e,"hex");var i=this.db.batch();i.del(u.ms(e,t)),await i.write()}}pe.layout=u,e.exports=pe},function(e,t,i){"use strict";
|
|
903
|
+
*/const r=i(8),s=i(0),n=i(73),a=i(118),o=i(157),c=i(608),h=i(85),u=h.walletdb,l=i(6),p=i(158),d=i(124),f=i(167),m=i(36).VerifyError,g=i(45),y=i(13);i(19),i(68);const v=i(196),b=i(67),w=i(50),{getVerifyMsg:k,BlockFinalType:x,ContractEnvType:S}=i(5),_=i(159),E=i(610),R=i(35);var A=i(71);const O=i(2),C=i(140).sortWithSeq,I=i(33),P=i(197),j=i(63),T=i(100),B=i(3),N=B.U32,M=i(336),L=i(337),F=i(338),z=F.vpItem,H=i(611),D=H.vpItem,U=i(312);i(612);const q=U.cpItem,V=i(154),K=V.ErAbolishItem,W=i(43).broadcast,$=i(131),X=$.vpItem,G=i(153),Y=G.ErItem,J=i(613),Z=J.AuditItem,Q=i(305),ee=i(109),te=i(614),ie=i(306),re=i(119),se=i(615),ne=i(217),ae=i(38),oe=i(34),ce=i(59),he=i(78),ue=he.errors,le=i(77);class pe extends A{constructor(e){super(),this.readyLoad=!1,this.options=new c(e),this.network=this.options.network,this.logger=this.options.logger.context("wallet"),this.workers=this.options.workers,this.keys={hmacSalt:B.DefaultChainCode},e.keys&&e.keys.hmacSalt&&(s(Buffer.isBuffer(e.keys.hmacSalt)),this.keys.hmacSalt=e.keys.hmacSalt),this.client=this.options.client,this.client&&(this.client.wdb=this),this.jsonp=this.options.jsonp,this.jsonp&&(this.jsonp.wdb=this),this.spv=this.options.spv,this.feeRate=this.options.feeRate,this.db=f(this.options),this.rpc=new M(this),this.primary=null,this.state=new te,this.wallets=new Map,this.depth=0,this.rescanning=!1,this.bound=!1,this.newRecord=!0,this.readLock=new P,this.writeLock=new I,this.txLock=new I,this.scanLock=new I,this.widCache=new j(1e4),this.pathMapCache=new j(1e5),this.filter=new T,this.middleHashMem=new Set,this.middleHashChain=new Set,this.autoTaskMgr=new _(this),this.transactionList=new L(this),this.htlcList=new F(this),this.commentList=new H(this),this.NotifyList=new R,this.propList=new $(this),this.$contacts=new R,this.cpList=new U(this),this.cpMemList=new U(this),this.auditList=new J(this),this.erList=new G(this),this.erAbList=new V(this),this.hmacConnection=[],this._init()}async logAudit(e){e.height=this.curHeight,e.time=O.now(),e.erid=l.sha256(O.stringify(e)).toString("hex"),e=new Z(e),await this.auditList.setAudit(e)}async getAccountByAddress(e,t){if(e){let s=null;if(s=t?await this.getWalletsByTX(t):await this.getWallets())for(const t of s){var i=await this.get(t);if(i){var r=await i.getPath(e);if(r)return[i.wid,r.name,i.id]}}}return[0,"",""]}_init(){let e=1e6,t=-1;this.spv&&(e=2e4,t=T.flags.ALL),this.filter=T.fromRate(e,.001,t)}get mode(){return S.Wallet}async getTXFromAll(e){return this.getTXFromDb(e)}async checkNewRecord(){var e={createIfMissing:this.db.options.createIfMissing,errorIfExists:this.db.options.errorIfExists};this.db.options.createIfMissing=!1,this.db.options.errorIfExists=!0;try{await this.db.open();var t=await this.db.checkVersion(u,6);this.newRecord="new"==t}catch(e){if(-1!=e.message.indexOf("does not exist (create_if_missing is false)"))this.newRecord=!0;else{if(-1==e.message.indexOf("exists (error_if_exists is true)"))throw e;this.newRecord=!1}}try{await this.db.close()}catch(e){}this.db.options.createIfMissing=e.createIfMissing,this.db.options.errorIfExists=e.errorIfExists}async isNewRecord(){return await this.checkNewRecord(),this.newRecord}setmnemonic(e){if(this.options.mnemonic=this.options.mnemonic||{},e.bits)this.options.mnemonic={bits:e.bits};else if(e.entropy)this.options.mnemonic={entropy:Buffer.from(e.entropy,"hex")};else if(e.phrase){var t=this.testmnemonic(e.phrase);if(0!=t.code)throw t.msg;this.options.mnemonic={phrase:e.phrase}}e.passphrase&&(this.options.mnemonic.passphrase=e.passphrase),e.language&&(this.options.mnemonic.language=e.language)}testmnemonic(e){try{return new v(e),{code:0}}catch(e){return{code:-1,msg:e.message}}}async getContracts(e){var t=await this.db.values({gte:h.txdb.tx(B.NULL_HASH),lte:h.txdb.tx(B.HIGH_HASH),parse:e=>O.parseJson(e.toString())});return e?t.filter(t=>t.srcact==e||t.dstact==e):t}isFull(){return this.spv||this.synced||!1}async _open(e){}async handleNotify(e,t=!1){if(!t){let i=e.body.content;if("string"==typeof i)try{i=JSON.parse(e.body.content)}catch(e){return}"object"==typeof i&&"secret"===i.type&&(t={contact:e.body.src,messenger:e.body.dst},i.init&&(t.init=Buffer.from(i.init,"hex")),i.packet&&(t.packet=Buffer.from(i.packet)),await this.handleSecret(t))}}async handleSecret(e){if(e.contact&&e.messenger&&e.contact!=e.messenger){try{y.fromString(e.contact,this.network.type),y.fromString(e.messenger,this.network.type)}catch(e){return}var t=await this.ensureContact(e);t&&await t.ensureMessenger(e).answer(e)}}async scanContact(e,t=-1){var i=async e=>{var t;e.witness&&"witnesspubkeyhash"==e.getType()&&(t=e.witness.getPubkeyhashInput()[1],e=y.fromWitness(e.witness).toString(),t)&&e&&await this.ensureContact({contact:e,publicKey:t})};if(0<=t&&t<e.inputs.length)await i(e.inputs[t]);else for(var r of e.inputs)await i(r)}async ensureContact(e){if(!e.contact||e.contact==e.messenger)return null;try{y.fromString(e.contact,this.network.type),e.messenger&&y.fromString(e.messenger,this.network.type)}catch(e){return null}e.network=this.network.type,this.$contacts.get(e.contact)||this.$contacts.set(e.contact,new E(e));var t=this.$contacts.get(e.contact);if(e.messenger&&!(e=t.ensureMessenger(e)).wallet){var i,[i,r]=await this.getAccountByAddress(e.address);if(!(i=await this.get(i)))return;e.wallet=i,e.account=r}return t}getCps(){return this.db.values({gte:h.txdb.cp(B.ZERO_CID,"hex"),lte:h.txdb.cp(B.MAX_CID,"hex"),parse:e=>q.fromRaw(e)})}async _close(){await this.disconnect(),this.http&&this.options.listen&&await this.http.close();for(const e of this.wallets.values())await e.destroy();await this.db.close(),this.options.listen&&await this.logger.close()}async destroy(){await this.db.destroy(),this.widCache.reset(),this.pathMapCache.reset()}async load(e){if(this.readyLoad){var t=await this.ensure({id:"primary",witness:!0,mnemonic:this.options.mnemonic}),i=await this.txLock.lock();try{await this.init(e),await this.watch(),await t.createReceive(0,1,t.master,this.network.type),await t.ensureNotifyKey(),await this.sync()}finally{i()}setTimeout(()=>{this.resend()},5e3)}}async disconnect(){this.client&&await this.client._close(),this.jsonp&&await this.jsonp._close()}async flushCP(e,t=!1){this.client&&(e=e||[],t||(e=this.cpList.excludeCids(e),t=t||0<e.length),t)&&await this.client.execute("cp.remoteQuery",[[["cid","include",e]]])}async watch(){let e=this.db.iterator({gte:u.p(B.NULL_HASH),lte:u.p(B.HIGH_HASH)}),t=0,i=0;for(;;){var r=await e.next();if(!r)break;try{var s=u.pp(r.key);this.addHash(s,!1)}catch(t){throw await e.end(),t}t++}for(e=this.db.iterator({gte:u.o(B.NULL_HASH,0),lte:u.o(B.HIGH_HASH,4294967295)});;){var n=await e.next();if(!n)break;try{var[a,o]=u.oo(n.key);this.addOutpoint(a,o)}catch(t){throw await e.end(),t}i++}this.logger.info("Filter: Added %d hashes to AccountDB filter.",t),this.logger.info("Filter: Added %d outpoints to AccountDB filter.",i),await this.setFilter()}async sync(){if(this.client){let t,i=this.curHeight;for(;0<=i;){var e=await this.getBlock(i);if(!e)break;if(t=await this.client.getEntry(e.hash))break;i--}t||(i=this.state.startHeight,t=await this.client.getEntry(this.state.startHash))||(i=0),await this.cpList.loadHistory(),await this.cpMemList.loadHistory(),await this.propList.loadHistory(),await this.htlcList.loadHistory(),await this.commentList.loadHistory(),await this.transactionList.loadHistory(),await this.loadContact(),await this.erList.loadHistory(),await this.auditList.loadHistory(),await this.erAbList.loadHistory(),await this._rescan(i,!1)}}async _rescan(e,t=!0){if(this.client){null==e&&(e=this.state.startHeight),s(e>>>0===e,"WDB: Must pass in a height.");var i=this.curHeight;t=(await this.rollback(e,t),this.logger.info("AccountDB is scanning %d blocks.",i-e+1),await this.getTip());try{this.rescanning=!0,await this.client.rescan(t.hash,this.eid)}finally{this.rescanning=!1}}}async rescan(e){var t=await this.txLock.lock();try{return await this._rescan(e,!1)}finally{t()}}async send(e){return this.client?this.client.send(e):(this.emit("send",e),Promise.resolve())}async getTX(e){for(const i of this.wallets.values()){var t=await i.getTX(e);if(t)return t.tx}return null}async getTXFromDb(e){for(const i of this.wallets.values()){var t=await i.getTX(e);if(t)return t.tx}return null}async getExtendTX(e){for(const i of this.wallets.values()){var t=await i.getTX(e);if(t)return t}return null}async removeTX(e){this.client?await this.client.removeTX(e):this.emit("remove",e)}async estimateFee(e){return 0<this.feeRate?this.feeRate:!this.client||(e=await this.client.estimateFee(e))<this.network.feeRate?this.network.feeRate:e>this.network.maxFeeRate?this.network.maxFeeRate:e}setFilter(){return this.client?this.client.setFilter(this.filter):(this.emit("filter.set",this.filter),Promise.resolve())}resetFilter(){return this.client?this.client.resetFilter():(this.emit("filter.reset"),Promise.resolve())}backup(e){return this.db.backup(e)}async wipe(){this.logger.warning("Wiping AccountDB TXDB..."),this.logger.warning("I hope you know what you're doing.");var e=this.db.iterator({gte:Buffer.from([0]),lte:Buffer.from([255])}),t=this.db.batch();let i=0;for(;;){var r=await e.next();if(!r)break;try{switch(r.key[0]){case 98:case 99:case 101:case 116:case 111:case 104:case 82:t.del(r.key),i++}}catch(t){throw await e.end(),t}}this.logger.warning("Wiped %d txdb records.",i),await t.write()}async getDepth(){var e=this.db.iterator({gte:u.w(0),lte:u.w(4294967295),reverse:!0,limit:1}),t=await e.next();return t?(await e.end(),u.ww(t.key)+1):1}start(e){return s(!e.current,"WDB: Batch already started."),e.current=this.db.batch(),e.accountCache.start(),e.pathCache.start(),e.current}drop(e){var t=this.batch(e);e.current=null,e.accountCache.drop(),e.pathCache.drop(),t.clear()}clear(e){var t=this.batch(e);e.accountCache.clear(),e.pathCache.clear(),t.clear()}batch(e){return s(e.current,"WDB: Batch does not exist."),e.current}async commit(e){var t=this.batch(e);try{await t.write()}catch(e){throw this.drop(),e}e.current=null,e.accountCache.commit(),e.pathCache.commit()}testFilter(e){return this.filter.test(e,"hex")}addHash(e,t=!0){this.filter.add(e,"hex"),t&&(t=Buffer.from(e,"hex"),this.client?this.client.addFilter(t):this.emit("filter.add",t))}addOutpoint(e,t){e=new g(e,t),this.filter.add(e.toRaw())}dump(){return this.db.dump()}register(e){s(!this.wallets.has(e.wid)),this.wallets.set(e.wid,e)}unregister(e){s(this.wallets.has(e.wid)),this.wallets.delete(e.wid)}async getWalletID(e){var t;return e?"number"==typeof e?e:this.widCache.get(e)||((t=await this.db.get(u.l(e)))?(t=t.readUInt32LE(0,!0),this.widCache.set(e,t),t):null):null}async get(e){if(!(e=await this.getWalletID(e)))return null;var t=await this.readLock.lock(e);try{return await this._get(e)}finally{t()}}async _get(e){var t=this.wallets.get(e);return t||((t=await this.db.get(u.w(e)))?(await(e=a.fromRaw(this,t)).open(),this.register(e),e):null)}async loadBackup(e){if(ce.unsupported)throw new le(ue.INTERNAL_ERROR,"FS not available.");let t=null;var i;for(i of(await ce.readFile(e,"utf8")).split(/\n+/))if(0!==(i=i.trim()).length&&!/^\s*#/.test(i)){var r=i.split(/\s+/);if(r.length<4)throw new le(ue.DESERIALIZATION_ERROR,"Malformed wallet Data File.");switch(r[0]){case"W":var n=Buffer.from(r[1],"base64");n=a.fromRaw(this,n);await this.replace(n),t=await this.get(n.id),this.logger.info("Import Wallet %s(%s)",t.id,t.wid);break;case"C":n=Buffer.from(r[1],"base64");(c=((h=o.fromRaw(this,n)).wallet=t,h.wid=t.wid,h.id=t.id,h.initialized=!0,h.watchOnly=t.watchOnly,h.receive=h.deriveReceive(h.receiveDepth-1),h.change=h.deriveChange(h.changeDepth-1),h.witness&&(h.nested=h.deriveNested(h.nestedDepth-1)),t.master.key.deriveAccount(44,h.accountIndex))).publicKey.toString("hex")!==h.accountKey.publicKey.toString("hex")&&s(c.publicKey.toString("hex")==h.accountKey.publicKey.toString("hex")),await t.saveAccount(h),this.logger.info("Import Account %s(%s)",h.name,h.accountIndex);break;case"A":var c=he.parseSecret(r[1],this.network),h=parseInt(r[5]),u=parseInt(r[7]),l=parseInt(r[9]),p=r[11].trim();if(u<0||l<0)try{await t.importKey(h,c)}catch(e){this.logger.error(`loadBackup: ${e.message} account/secret: ${h}/`+p)}else{var d=await t.deriveKey(h,u,l),f=await t.deriveKey(h,u,l,t.master);d.getAddress("string")!==f.getAddress("string")&&this.logger.error(`loadBackup: not-equal-1: ${d.getAddress("string")} != `+f.getAddress("string")),d.getAddress("string")!==p&&this.logger.error(`loadBackup: not-equal-2: ${d.getAddress("string")} != `+p)}this.logger.info("Import Address %s %s %s %s",h,u,l,p)}}return t.accountCache.reset(),t}save(e){var t=e.wid,i=e.id,r=this.batch(e);this.widCache.set(i,t),r.put(u.w(t),e.toRaw()),r.put(u.l(i),N(t))}async rename(e,t){var i=await this.writeLock.lock();try{return await this._rename(e,t)}finally{i()}}async _rename(e,t){var i=e.id;if(!n.isName(t))throw new Error("WDB: Bad wallet ID.");if(await this.has(t))throw new Error("WDB: ID not available.");this.start(e).del(u.l(i)),e.id=t,this.save(e),await this.commit(e),this.widCache.remove(i),i=e.pathCache.values();for(const e of i)e.id=t}async replace(e){var t=await this.writeLock.lock();try{return await this._replace(e)}finally{t()}}async _replace(e){var t=this.start(e);t.del(u.l(e.id)),t.del(u.w(e.wid)),this.save(e),await this.commit(e),this.widCache.remove(e.id),this.wallets.delete(e.wid)}renameAccount(e,t){var i=e.wallet;this.batch(i).del(u.i(e.wid,e.name)),e.name=t,this.saveAccount(e)}async auth(e,t){if("string"==typeof t){if(!O.isHex256(t))throw new Error("WDB Authentication: Invalid Token.");t=Buffer.from(t,"hex")}e=b.getHmac(e.toString(),this.keys.hmacSalt);var i=r.createHmac("sha256",e.random);i=Buffer.from(i.update(e.token).digest("hex"),"hex");if(!p(t,i))throw new Error("WDB Authentication: CRC Error.")}async create(e){var t=await this.writeLock.lock();e=e||{};try{return await this._create(e)}finally{t()}}async _create(e){if(await this.has(e.id))throw new Error("WDB: Wallet already exists.");"string"==typeof e.mnemonic&&(e.mnemonic={phrase:e.mnemonic}),e.mnemonic=e.mnemonic||{},!e.mnemonic.language&&this.options.mnemonic&&this.options.mnemonic.language&&(e.mnemonic.language=this.options.mnemonic.language);var t=a.fromOptions(this,e);return t.wid=this.depth++,await t.init(e),this.register(t),this.logger.info("Created wallet %s in AccountDB.",t.id),t}async has(e){return null!=await this.getWalletID(e)}async ensure(e){return await this.get(e.id)||this.create(e)}async getAccount(e,t){return(e=await this.db.get(u.a(e,t)))?o.fromRaw(this,e):null}getAccounts(e){return this.db.values({gte:u.n(e,0),lte:u.n(e,4294967295),parse:e=>e.toString("ascii")})}async getAccountIndex(e,t){return(e=await this.db.get(u.i(e,t)))?e.readUInt32LE(0,!0):-1}async getAccountName(e,t){return(e=await this.db.get(u.n(e,t)))?e.toString("ascii"):null}saveAccount(e){var t=e.wid,i=e.wallet,r=e.accountIndex,s=e.name,n=this.batch(i);n.put(u.a(t,r),e.toRaw()),n.put(u.i(t,s),N(r)),n.put(u.n(t,r),Buffer.from(s,"ascii")),i.accountCache.push(r,e)}hasAccount(e,t){return"number"==typeof e&&"number"==typeof t&&this.db.has(u.a(e,t))}async getPathMap(e){var t=this.pathMapCache.get(e);return t||((t=await this.db.get(u.p(e)))?(t=se.fromRaw(e,t),this.pathMapCache.set(e,t),t):null)}saveKey(e,t){return this.savePath(e,t.toPath())}async savePath(e,t){var i=e.wid,r=t.hash,s=this.batch(e);this.addHash(r);let n=await this.getPathMap(r);(n=n||new se(r)).add(i)&&(this.pathMapCache.set(r,n),e.pathCache.push(r,t),s.put(u.p(r),n.toRaw()),s.put(u.P(i,r),t.toRaw()),s.put(u.r(i,t.account,r),null))}async getPath(e,t){var i=await this.db.get(u.P(e,t));return i?((i=ee.fromRaw(i)).wid=e,i.hash=t,i):null}hasPath(e,t){return this.db.has(u.P(e,t))}getHashes(){return this.db.keys({gte:u.p(B.NULL_HASH),lte:u.p(B.HIGH_HASH),parse:u.pp})}getOutpoints(){return this.db.keys({gte:u.o(B.NULL_HASH,0),lte:u.o(B.HIGH_HASH,4294967295),parse:e=>{var[e,t]=u.oo(e);return new g(e,t)}})}getWalletHashes(e){return this.db.keys({gte:u.P(e,B.NULL_HASH),lte:u.P(e,B.HIGH_HASH),parse:u.Pp})}getAccountHashes(e,t){return this.db.keys({gte:u.r(e,t,B.NULL_HASH),lte:u.r(e,t,B.HIGH_HASH),parse:u.rr})}async getWalletPaths(e){var t=[];for(const s of await this.db.range({gte:u.P(e,B.NULL_HASH),lte:u.P(e,B.HIGH_HASH)})){var i=u.Pp(s.key),r=ee.fromRaw(s.value);r.hash=i,r.wid=e,t.push(r)}return t}async encryptKeys(e,t){var i,r,n=e.wid,a=await e.getPaths(),o=this.batch(e);for(i of a)i.data&&(s(!i.encrypted),r=Buffer.from(i.hash,"hex").slice(0,16),(i=i.clone()).data=d.encipher(i.data,t,r),i.encrypted=!0,e.pathCache.push(i.hash,i),o.put(u.P(n,i.hash),i.toRaw()))}async decryptKeys(e,t){var i,r,n=e.wid,a=await e.getPaths(),o=this.batch(e);for(i of a)i.data&&(s(i.encrypted),r=Buffer.from(i.hash,"hex").slice(0,16),(i=i.clone()).data=d.decipher(i.data,t,r),i.encrypted=!1,e.pathCache.push(i.hash,i),o.put(u.P(n,i.hash),i.toRaw()))}async resend(){var e,t={};for(const e of await this.db.keys({gte:u.w(0),lte:u.w(4294967295)})){var i=u.ww(e),r=await this.resendPending(i);r&&Array.isArray(r)&&(t[i]=r)}for(e of Object.keys(t))if(await this.get(parseInt(e)))for(const i of t[e]){try{await this.send(i)}catch(e){this.logger.warning("wdb resend:",e.message)}await oe.timeout(50)}}async resendPending(e){var t=await this.get(e),i=await this.db.keys({gte:h.txdb.prefix(e,h.txdb.p(B.NULL_HASH)),lte:h.txdb.prefix(e,h.txdb.p(B.HIGH_HASH))});if(0!==i.length){this.logger.info("Rebroadcasting %d transactions for %d.",i.length,e);var r=[];for(const o of i){var s=h.txdb.pp(o),n=h.txdb.prefix(e,h.txdb.t(s));if((n=await this.db.get(n))&&!(n=ne.fromRaw(n)).tx.isCoinbase())try{var a=await w.FactoryOfContract({tx:n.tx,env:this});await a.isBlockFinal()==x.Expired?t&&(await this.removeTX(n.tx),await t.remove(s),await a.erase()):"notify"!=a.oper&&r.push(n.tx)}catch(e){this.logger.error("TX(%s) Smart Contract Error: %s",n.tx.txid(),e.message)}}return C(r)}}getWallets(){return this.db.keys({gte:u.l("\0"),lte:u.l("ÿ"),parse:u.ll})}async getWalletsByTX(e){var t=new Set;if(!e.isCoinbase())for(const r of e.inputs){var i=r.prevout;if(this.testFilter(i.toRaw())&&(i=await this.getOutpointMap(i.hash,i.index)))for(const e of i.wids)t.add(e)}for(const i of e.getOutputHashes("hex"))if(this.testFilter(i)){var r=await this.getPathMap(i);if(r)for(const e of r.wids)t.add(e)}return 0===t.size?null:t}async getState(){var e=await this.db.get(u.R);return e?te.fromRaw(e):null}async init(e){var t=this.options.startHeight;let i;if(this.client){if(null!=t){if(!(i=await this.client.getEntry(t)))throw new Error("WDB: Could not find start block.")}else i=await this.client.getTip();i=re.fromEntry(i)}else i=re.fromEntry(this.network.genesis);this.logger.info("Initializing AccountDB chain state (height %d).",i.height),(t=await this.getState())?this.state=t:await this.resetState(i,!1),await this.ensure({id:"primary",witness:!0,mnemonic:this.options.mnemonic}),e&&e.backup&&await this.loadBackup(e.backup)}async resetState(e,t){for(var i=this.state.clone(),r=(i.startHeight=e.height,i.startHash=e.hash,i.height=e.height,i.marked=t,this.db.batch()),s=this.db.iterator({gte:u.h(e.height),lte:u.h(4294967295),values:!1});;){var n=await s.next();if(!n)break;try{r.del(n.key)}catch(e){throw await s.end(),e}}r.put(u.h(e.height),e.toHash()),r.put(u.R,i.toRaw()),await r.write(),this.state=i}async syncState(e){var t=this.state.clone(),i=this.db.batch();if(e.height<t.height){let s=t.height;var r=s-e.height;for(let e=0;e<r;e++)i.del(u.h(s--))}else e.height>t.height&&s(e.height===t.height+1,`Bad chain sync tip ${e.height} while state `+t.height);t.height=e.height,i.put(u.h(e.height),e.toHash()),i.put(u.R,t.toRaw()),await i.write(),this.state=t,W("block/tips",t)}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(e){var t=await this.db.get(u.b(e));return t?ie.fromRaw(e,t):null}writeBlockMap(e,t,i){this.batch(e).put(u.b(t),i.toRaw())}unwriteBlockMap(e,t){this.batch(e).del(u.b(t))}async getOutpointMap(e,t){var i=await this.db.get(u.o(e,t));return i?Q.fromRaw(e,t,i):null}writeOutpointMap(e,t,i,r){e=this.batch(e),this.addOutpoint(t,i),e.put(u.o(t,i),r.toRaw())}unwriteOutpointMap(e,t,i){this.batch(e).del(u.o(t,i))}async writeBalanceLog(e,t){var i=u.log(e.wid,t.aidx,t.height,t.hash),r=(t=Buffer.from(JSON.stringify(t)),await this.writeLock.lock());try{this.start(e).put(i,t),await this.commit(e)}finally{r()}}async queryBalanceLog(e,t,i=0){return this.db.values({gte:u.log(e,t,i,B.NULL_HASH),lte:u.log(e,t,this.curHeight,B.HIGH_HASH),parse:e=>JSON.parse(e.toString())})}async getBlock(e){var t,i=await this.db.get(u.h(e));return i?((t=new re).hash=i.toString("hex"),t.height=e,t):null}async getTip(){var e=await this.getBlock(this.curHeight);if(e)return e;throw new Error("WDB: Tip not found!")}async rollback(e,t=!0){if(e>this.curHeight)throw new Error("WDB: Cannot rollback to the future.");if(e===this.curHeight)return this.logger.debug("Rolled back to same height (%d).",e),!0;this.logger.info("Rolling back %d AccountDB blocks to height %d.",this.curHeight-e,e);var i=await this.getBlock(e);let r=!1;return i?(await this.revert(i.height),await this.syncState(i),t):(i=new re,e>=this.state.startHeight?(i.height=this.state.startHeight,i.hash=this.state.startHash,r=this.state.marked,this.logger.warning("Rolling back AccountDB to start block (%d).",i.height)):(i.height=0,i.hash=this.network.genesis.hash,r=!1,this.logger.warning("Rolling back AccountDB to genesis block.")),await this.revert(i.height),await this.resetState(i,r),!1)}async revert(e){var t=this.db.iterator({gte:u.b(e+1),lte:u.b(4294967295),reverse:!0,values:!0});let i=0;for(;;){var r=await t.next();if(!r)break;try{var s=u.bb(r.key),n=ie.fromRaw(s,r.value).toArray();i+=n.length;for(let e=n.length-1;0<=e;e--)await this._unconfirm(n[e])}catch(e){throw await t.end(),e}}this.logger.info("Rolled back %d AccountDB transactions.",i)}async addBlock(e,t){var i=await this.txLock.lock();try{return await this._addBlock(e,t)}finally{i()}}async _addBlock(e,t){var i=re.fromEntry(e);let r=0;if(i.height<this.curHeight)this.logger.warning("AccountDB is connecting low blocks (%d).",i.height);else{if(i.height===this.curHeight)this.logger.warning("Already saw AccountDB block (%d).",i.height);else if(i.height!==this.curHeight+1)throw new Error(`WDB(addBlock): Bad disconnection (height mismatch, tip ${i.height} while state ${this.curHeight})`);if(await this.syncState(i),!(this.options.checkpoints&&i.height<=this.network.lastCheckpoint)){for(const e of t)await this._insert(e,i)&&r++;0<r&&this.logger.info("Connected AccountDB block %s (tx=%d).",O.revHex(i.hash),r)}}return r}async removeBlock(e,t){var i=await this.txLock.lock();try{return await this._removeBlock(e,t)}finally{i()}}async _removeBlock(e,t){if((e=re.fromEntry(e)).height>this.curHeight)return this.logger.warning("AccountDB is disconnecting high blocks (%d).",e.height),0;if(e.height!==this.curHeight)throw new Error(`WDB(removeBlock): Bad disconnection (height mismatch, tip ${e.height} / ${O.revHex(e.hash)} while state ${this.curHeight})`);var i=await this.getBlock(e.height-1);if(!i)throw new Error(`WDB(removeBlock): Bad disconnection (no previous block of ${e.height} / ${O.revHex(e.hash)}).`);var r=await this.getBlockMap(e.height);if(r){for(let e=t.length-1;0<=e;e--){var s=t[e];await this._unconfirm(s,r)}this.logger.warning("Disconnected wallet block %s (tx=%d).",O.revHex(e.hash),r.txs.size)}return await this.syncState(i),r?r.txs.size:0}async rescanBlock(e,t){if(this.rescanning){var i=await this.scanLock.lock();try{await this._addBlock(e,t)}catch(e){throw this.emit("error",e),e}finally{i()}}else this.logger.warning("Unsolicited rescan block: %s.",e.height)}async addTX(e,t,i){var r=await this.txLock.lock();try{return await this._insert(e,t,i)}finally{r()}}listNotify(e){return this.NotifyList.deletes([["h","<",this.curHeight-12]]),this.NotifyList.query(e)}listContact(e,t,i){return this.$contacts.query(e,t,i)}async setCp(e){await this.batchPut(h.txdb.cp(e.cid),e.toRaw())}async delCp(e){await this.batchDel(h.txdb.cp(e))}async delVp(e){var t=this.db.batch();t.del(h.txdb.VP(e.pid)),await t.write()}async setVp(e,t){var i=this.db.batch();i.put(h.txdb.VP(e.pid),e.toRaw()),await i.write()}async getVp(e){return(e=await this.db.get(h.txdb.VP(e)))?X.fromRaw(e):null}async getVpByAddress(e){return{list:[],count:0}}async getVpByOid(e){return{list:[],count:0}}async loadVpList(){return this.db.values({gte:h.txdb.VP(B.ZERO_CID,"hex"),lte:h.txdb.VP(B.MAX_CID,"hex"),parse:e=>X.fromRaw(e)})}async saveContact(e){var t=this.db.batch();t.put(h.txdb.CT(e.getAddress()),e.toRaw()),await t.write()}async loadContact(e){var t;for(t of await this.db.values({gte:h.txdb.CT(B.ZERO_HASH160_HEX),lte:h.txdb.CT(B.MAX_HASH160_HEX),parse:e=>E.fromRaw(e,this)}))t.sender&&(t.sender.wallet=await this.get(t.sender.wid)),this.$contacts.set(t.address,t)}async delHtlc(e){var t;(e=new z(e)).id&&(this.htlcList.delete(e.id),this.htlcList.delAccount(e),(t=this.db.batch()).del(h.txdb.VH(e.shash,e.sidx)),await t.write())}async setSuggest(e){e=new z(e);var t,[t,i]=(this.htlcList.set(e.id,e),await this.getAccountByAddress(e.aa)),[t,i]=(t&&this.htlcList.setAccount(e,t,i),await this.getAccountByAddress(e.ba));(t=(t&&this.htlcList.setAccount(e,t,i),this.db.batch())).put(h.txdb.VH(e.shash,e.sidx),e.toRaw()),await t.write()}async setAssent(e){e=new z(e);var t,[t,i]=(this.htlcList.set(e.id,e),await this.getAccountByAddress(e.ab)),[t,i]=(t&&this.htlcList.setAccount(e,t,i),await this.getAccountByAddress(e.bb));(t=(t&&this.htlcList.setAccount(e,t,i),this.db.batch())).put(h.txdb.VH(e.shash,e.sidx),e.toRaw()),await t.write()}async loadHtlcList(){return this.db.values({gte:h.txdb.VH(B.ZERO_CID,0),lte:h.txdb.VH(B.MAX_CID,4294967295),parse:e=>z.fromRaw(e)})}async delComment(e){var t;(e=new D(e)).id&&(this.commentList.delete(e.id),this.commentList.delAccount(e),(t=this.db.batch()).del(h.txdb.VC(e.shash,e.sidx)),await t.write())}async setComment(e){e=new D(e);var t,[t,i]=(this.commentList.set(e.id,e),await this.getAccountByAddress(e.bob));(t=(t&&(this.commentList.setAccount(e,t,i),this.emit("comm.comment",e)),this.db.batch())).put(h.txdb.VC(e.shash,e.sidx),e.toRaw()),await t.write()}async loadCommentList(){return this.db.values({gte:h.txdb.VC(B.ZERO_CID,0),lte:h.txdb.VC(B.MAX_CID,4294967295),parse:e=>D.fromRaw(e)})}async verifyClsTx(e,t){if(!this.spv&&1!=(t=await(await w.FactoryOfContract({env:this,block:t,tx:e})).verify()))throw new m(e,k(t),"bad-contract-verify",100);return!0}async delEr(e){var t=this.db.batch();t.del(h.txdb.ER(e.erid)),t.del(h.txdb.ERR(e.witness,e.erid,e.txid)),await t.write()}async setEr(e,t){t&&e.source&&(i=y.fromWitnessPubkeyhash(l.hash160(Buffer.from(e.source.pubkey,"hex")),this.network),[i,t]=await this.getAccountByAddress(i,t),e.wid=i,e.account=t);var i=this.db.batch();t=h.txdb.ERR(e.witness,e.erid,e.txid);i.put(t,e.toRaw()),i.put(h.txdb.ER(e.erid),t),await i.write()}async getEr(e){var t;return(e=await this.db.get(h.txdb.ER(e)))&&([,,t]=h.txdb.ERRR(e),e=await this.db.get(e))?((e=Y.fromRaw(e)).txid=t,e):null}async byPubkey(e,t,i=!1){var r,s=new R;e=await this.db.values({gte:h.txdb.ERR(e,B.NULL_HASH,B.NULL_HASH),lte:h.txdb.ERR(e,B.HIGH_HASH,B.HIGH_HASH),parse:e=>Y.fromRaw(e)});let n=[],a=new Map;if(i){for(var o of e)(!a.get(o.source.cluster)||o.startHeight>a.get(o.source.cluster).startHeight)&&a.set(o.source.cluster,await this.caVerifyObj(o));n=a.values()}else n=e;for(r of n)s.set(r.erid,r);return s.query(t)}async caVerifyObj(e){var t={verify:!1};if(!e||e.validHeight<=this.curHeight)return t;var i=await this.erAbList.getErAb(e.erid);return i&&i.abolishHeight<this.curHeight?t:(i=ae.fromPublic(Buffer.from(e.witness,"hex"),this.network.type),e.verify(i)?(e.verify=!0,0<(i=this.cpList.query([["pubKey",e.witness]])).list.length&&(e.cpid=i.list[0].cid),e):t)}async delErAbolish(e){var t=this.db.batch();t.del(h.txdb.ERA(e.erid)),await t.write()}async setErAbolish(e){var t=this.db.batch();t.put(h.txdb.ERA(e.erid),e.toRaw()),await t.write()}async getErAbolish(e){return(e=await this.db.get(h.txdb.ERA(e)))?K.fromRaw(e):null}loadErAbolishList(){return this.db.values({gte:h.txdb.ERA(B.ZERO_CID),lte:h.txdb.ERA(B.MAX_CID),parse:e=>K.fromRaw(e)})}async delAudit(e){var t=this.db.batch();t.del(h.txdb.AU(e.erid)),await t.write()}async setAudit(e){var t=this.db.batch();t.put(h.txdb.AU(e.erid),e.toRaw()),await t.write()}async getAudit(e){return(e=await this.db.get(h.txdb.AU(e)))?Z.fromRaw(e):null}async loadAuditList(){return this.db.values({gte:h.txdb.AU(B.NULL_HASH),lte:h.txdb.AU(B.HIGH_HASH),parse:e=>Z.fromRaw(e)})}async batchPut(e,t){var i=this.db.batch();i.put(e,t),await i.write()}async batchDel(e){var t=this.db.batch();t.del(e),await t.write()}async _insert(e,t,i){s(!e.mutable,"WDB: Cannot add mutable TX.");let r=await this.getWalletsByTX(e);if(r){this.logger.info("Incoming transaction for %d wallets in AccountDB (%s).",r.size,e.txid()),!t||this.state.marked||(this.logger.info("Marking AccountDB start block at %s (%d).",O.revHex(t.hash),t.height),await this.resetState(t,!0));let a=!1;for(const o of r){var n=await this.get(o);s(n),await n.add(e,t,i)&&(this.logger.info("Added transaction to wallet in AccountDB: %s (%d).",n.id,o),a=!0)}a||(r=null)}try{var a=await w.FactoryOfContract({env:this,block:t,tx:e});t?await a.confirm():await a.insert()}catch(a){t?this.logger.error("TX(%s) Smart Contract Confirm Error: %s",e.txid(),a.message):this.logger.error("TX(%s) Smart Contract Insert Error: %s",e.txid(),a.message)}return r}async _unconfirm(e,t){if(t)try{await(await w.FactoryOfContract({env:this,block:t,tx:e})).unconfirm()}catch(t){this.logger.error("TX(%s) Smart Contract Unconfirm Error: %s",e.txid(),t.message)}let i,r=null;if(i=e.wids?(r=e.wids,e.hash):(r=await this.getWalletsByTX(e),e.hash("hex")),!r)return null;for(const e of r){var n=await this.get(e);s(n),await n.unconfirm(i)}}async resetChain(e){var t=await this.txLock.lock();try{return await this._resetChain(e)}finally{t()}}async _resetChain(e){if(e.height>this.curHeight)throw new Error(`WDB: Bad reset height ${e.height} while curHeight `+this.curHeight);var t;for(t of(await this.rollback(e.height)||await this._rescan(),await this.getWallets())){var i=await this.get(t);for(const t of await i.getPending())try{await i.abandon(t.hash)}catch(e){}}}async saveMSTrans(e){var t=await this.writeLock.lock();try{return await this._saveMSTrans(e)}finally{t()}}async _saveMSTrans(e){var t=this.db.batch();t.put(u.ms(y.getHash(e.addr,"hex"),e.txid),Buffer.from(JSON.stringify(e))),await t.write()}async listMSTrans(e){return e=y.getHash(e,"hex"),this.db.values({gte:u.ms(e,B.NULL_HASH),lte:u.ms(e,B.HIGH_HASH),parse:e=>JSON.parse(e.toString())})}async delMSTrans(e,t){var i=await this.writeLock.lock();try{return await this._delMSTrans(e,t)}finally{i()}}async _delMSTrans(e,t){e=y.getHash(e,"hex");var i=this.db.batch();i.del(u.ms(e,t)),await i.write()}}pe.layout=u,e.exports=pe},function(e,t,i){"use strict";
|
|
904
904
|
/*!
|
|
905
905
|
* txdb.js - persistent transaction pool
|
|
906
906
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|