gamegold 5.0.3 → 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 +6 -6
- 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){if(this.filter.add(e,"hex"),t)return t=Buffer.from(e,"hex"),this.client?this.client.addFilter(t):(this.emit("filter.add",t),Promise.resolve())}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);await 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){if(this.filter.add(e,"hex"),t)return t=Buffer.from(e,"hex"),this.client?this.client.addFilter(t):(this.emit("filter.add",t),Promise.resolve())}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);await 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).
|
|
@@ -1602,7 +1602,7 @@ const r=i(0),s=i(1),n=i(4),a=i(3);e.exports=class e{constructor(e){this.hash=a.N
|
|
|
1602
1602
|
* conn_s2local.js - 全节点/SPV节点中,钱包对象和节点对象间的通信组件,以实现消息订阅功能
|
|
1603
1603
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
1604
1604
|
* https://github.com/bookmansoft/gamegold
|
|
1605
|
-
*/var r=i(71);const s=i(233).openapi;e.exports=class extends r{constructor(e){super(),this.node=e,this.network=e.network,this.filter=null,this.listen=!1,this._init()}_init(){this.node.on("block.connect",(e,t)=>{this.listen&&this.emit("block.connect",e,t.txs)}),this.node.on("block.disconnect",(e,t)=>{this.listen&&this.emit("block.disconnect",e,t.txs)}),this.node.on("chain.full",()=>{this.listen&&this.emit("chain.full")}),this.node.on("tx",async(e,t,i)=>{this.listen&&await this.emit("tx",e,t,i)}),this.node.on("entry.remove",(e,t)=>{this.emit("entry.remove",e,t)}),this.node.on("chain.reset",e=>{this.listen&&this.emit("chain.reset",e)})}_open(e){return this.listen=!0,Promise.resolve()}_close(){return this.listen=!1,Promise.resolve()}getTip(){return Promise.resolve(this.node.chain.tip)}async getEntry(e){return(e=await this.node.chain.getEntry(e))&&await this.node.chain.isMainChain(e)?e:null}async getTX(e){if(!this.node||!this.node.chain)return null;let t=null;return(t=this.node.mempool?await this.node.mempool.getTX(e):t)||await this.node.chain.getTX(e)}watchOutpoint(e){this.node.pool&&this.node.pool.watchOutpoint(e)}async execute(e,t,i){var r;if(null==t&&(t=[]),Array.isArray(t)||(t=[t]),e=s[e]){let s=null;return!this.node.spv||e.local?(s=await this.node.$localCall(e,t,i),e.remoteCb&&(r=this.node.require("walletdb"))&&(s=await e.remoteCb.call({wdb:r},s))):s=await this.node.$remoteCall(e,t,i),s}}async send(e){return this.node.relay(e)}async removeTX(e){return await this.node.removeTX(e),Promise.resolve()}setFilter(e){return this.filter=e,this.node.pool&&this.node.pool.setFilter(e),Promise.resolve()}addFilter(e){
|
|
1605
|
+
*/var r=i(71);const s=i(233).openapi;e.exports=class extends r{constructor(e){super(),this.node=e,this.network=e.network,this.filter=null,this.listen=!1,this._init()}_init(){this.node.on("block.connect",(e,t)=>{this.listen&&this.emit("block.connect",e,t.txs)}),this.node.on("block.disconnect",(e,t)=>{this.listen&&this.emit("block.disconnect",e,t.txs)}),this.node.on("chain.full",()=>{this.listen&&this.emit("chain.full")}),this.node.on("tx",async(e,t,i)=>{this.listen&&await this.emit("tx",e,t,i)}),this.node.on("entry.remove",(e,t)=>{this.emit("entry.remove",e,t)}),this.node.on("chain.reset",e=>{this.listen&&this.emit("chain.reset",e)})}_open(e){return this.listen=!0,Promise.resolve()}_close(){return this.listen=!1,Promise.resolve()}getTip(){return Promise.resolve(this.node.chain.tip)}async getEntry(e){return(e=await this.node.chain.getEntry(e))&&await this.node.chain.isMainChain(e)?e:null}async getTX(e){if(!this.node||!this.node.chain)return null;let t=null;return(t=this.node.mempool?await this.node.mempool.getTX(e):t)||await this.node.chain.getTX(e)}watchOutpoint(e){this.node.pool&&this.node.pool.watchOutpoint(e)}async execute(e,t,i){var r;if(null==t&&(t=[]),Array.isArray(t)||(t=[t]),e=s[e]){let s=null;return!this.node.spv||e.local?(s=await this.node.$localCall(e,t,i),e.remoteCb&&(r=this.node.require("walletdb"))&&(s=await e.remoteCb.call({wdb:r},s))):s=await this.node.$remoteCall(e,t,i),s}}async send(e){return this.node.relay(e)}async removeTX(e){return await this.node.removeTX(e),Promise.resolve()}setFilter(e){return this.filter=e,this.node.pool&&this.node.pool.setFilter(e),Promise.resolve()}addFilter(e){this.node.pool&&this.node.pool.watch(e)}resetFilter(){return this.node.pool.queueFilterLoad(),Promise.resolve()}async estimateFee(e){return this.node.fees?this.node.fees.estimateFee(e):this.network.feeRate}async verifyCPRegister(e){return{}}async verifyCPChange(e){return{}}rescan(e,t){return this.node.chain.scan(e,this.filter,async(e,i)=>this.fire("block.rescan."+t,e,i))}}},function(e,t,i){"use strict";
|
|
1606
1606
|
/*!
|
|
1607
1607
|
* spvnode.js - spv node for vallnet
|
|
1608
1608
|
* Copyright (c) 2017-2020, Bookman Software (MIT License).
|
|
@@ -1610,7 +1610,7 @@ const r=i(0),s=i(1),n=i(4),a=i(3);e.exports=class e{constructor(e){this.hash=a.N
|
|
|
1610
1610
|
/*!
|
|
1611
1611
|
* conn_s2remote.js - 基于 Web Socket 的客户端,为钱包系统提供主链交互功能
|
|
1612
1612
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
1613
|
-
*/const r=i(717).io,s=i(15);var n=i(71);const a=i(2),o=i(1),c=i(19),h=i(89),u=i(119),l=i(233).openapi;function p(e,t){"string"==typeof e&&(e=Buffer.from(e,"hex"));var i=h.fromHead(e),r=(e=((e=new o(e)).seek(80),e.readU32()),i.hash("hex"));return new u(r,e,i.time,i.mtp)}function d(e,t){e=p(e);var i=[];for(const e of t){var r=f(e);i.push(r)}return new m(e,i)}function f(e){return c.fromRaw(e,"hex")}function m(e,t){this.entry=e,this.txs=t}function g(e,t,i){return async function(r,s){if(r)t(new Error(r.message));else if(s&&s.result)if(s=s.result,i)try{e(await i(s))}catch(r){t(r)}else e(s);else e(null)}}e.exports=class extends n{constructor(e){super(),this.options=e="string"==typeof(e=e||{})?{uri:e}:e,this.network=s.get(e.network),this.uri=e.uri,this.apiKey=e.apiKey,this.mode=e.mode||"jsonp",this.socket=null}async _open(){this.uri&&(this.socket=r(this.uri,{transports:["websocket"],forceNew:!0}),this.socket.on("error",e=>{this.fire("error",e)}),"relay"==this.mode&&(this.socket.on("version",e=>{e.network!==this.network.type&&this.fire("error",new Error("Wrong network."))}),this.socket.on("block.connect",(e,t)=>{let i;try{i=d(e,t)}catch(e){return void this.fire("error",e)}this.emit("block.connect",i.entry,i.txs)}),this.socket.on("block.disconnect",(e,t)=>{let i;try{i=p(e)}catch(e){return void this.fire("error",e)}this.emit("block.disconnect",i,t)}),this.socket.on("block.rescan",(e,t,i)=>{let r;try{r=d(e,t)}catch(e){return this.fire("error",e),void i()}this.fire("block.rescan",r.entry,r.txs).then(i,i)}),this.socket.on("chain.full",()=>{this.emit("chain.full")}),this.socket.on("chain.reset",e=>{let t;try{t=p(e)}catch(e){return void this.fire("error",e)}this.emit("chain.reset",t)}),this.socket.on("tx",e=>{try{e=f(e)}catch(e){return void this.fire("error",e)}this.fire("tx",e)})),await this.onConnect())}_close(){return this.socket&&(this.socket.disconnect(),this.socket=null),Promise.resolve()}onConnect(){return new Promise((e,t)=>{this.socket.on("connect",async t=>{"relay"==this.mode&&(await this.watchChain(),await this.watchMempool()),await this.fireNoBubble("onConnect"),e(t)})})}async removeTX(e){return Promise.resolve()}async execute(e,t){t=t||[],Array.isArray(t)||(t=[t]);let i=l[e];return i?i.remoteCb?new Promise((e,r)=>{this.socket.emit("request",i.name,...t,g(e,r,async e=>i.remoteCb.call({wdb:this.wdb},e)))}):new Promise((e,r)=>{this.socket.emit("request",i.name,...t,g(e,r))}):null}watchChain(){return new Promise((e,t)=>{this.socket.emit("request","chain.watch",g(e,t))})}watchMempool(){return new Promise((e,t)=>{this.socket.emit("request","mempool.watch",g(e,t))})}getTip(){return new Promise((e,t)=>{this.socket.emit("request","block.tip",g(e,t,p))})}getEntry(e){return new Promise((t,i)=>{"string"==typeof e&&(e=a.revHex(e)),this.socket.emit("request","block.entry",e,g(t,i,p))})}send(e){return new Promise((t,i)=>{this.socket.emit("request","$tx.broadcast",e.toRaw(),g(t,i))})}setFilter(e){return new Promise((t,i)=>{this.socket.emit("request","filter.set",e.toRaw(),g(t,i))})}addFilter(e){
|
|
1613
|
+
*/const r=i(717).io,s=i(15);var n=i(71);const a=i(2),o=i(1),c=i(19),h=i(89),u=i(119),l=i(233).openapi;function p(e,t){"string"==typeof e&&(e=Buffer.from(e,"hex"));var i=h.fromHead(e),r=(e=((e=new o(e)).seek(80),e.readU32()),i.hash("hex"));return new u(r,e,i.time,i.mtp)}function d(e,t){e=p(e);var i=[];for(const e of t){var r=f(e);i.push(r)}return new m(e,i)}function f(e){return c.fromRaw(e,"hex")}function m(e,t){this.entry=e,this.txs=t}function g(e,t,i){return async function(r,s){if(r)t(new Error(r.message));else if(s&&s.result)if(s=s.result,i)try{e(await i(s))}catch(r){t(r)}else e(s);else e(null)}}e.exports=class extends n{constructor(e){super(),this.options=e="string"==typeof(e=e||{})?{uri:e}:e,this.network=s.get(e.network),this.uri=e.uri,this.apiKey=e.apiKey,this.mode=e.mode||"jsonp",this.socket=null}async _open(){this.uri&&(this.socket=r(this.uri,{transports:["websocket"],forceNew:!0}),this.socket.on("error",e=>{this.fire("error",e)}),"relay"==this.mode&&(this.socket.on("version",e=>{e.network!==this.network.type&&this.fire("error",new Error("Wrong network."))}),this.socket.on("block.connect",(e,t)=>{let i;try{i=d(e,t)}catch(e){return void this.fire("error",e)}this.emit("block.connect",i.entry,i.txs)}),this.socket.on("block.disconnect",(e,t)=>{let i;try{i=p(e)}catch(e){return void this.fire("error",e)}this.emit("block.disconnect",i,t)}),this.socket.on("block.rescan",(e,t,i)=>{let r;try{r=d(e,t)}catch(e){return this.fire("error",e),void i()}this.fire("block.rescan.walletdb",r.entry,r.txs).then(i,i)}),this.socket.on("chain.full",()=>{this.emit("chain.full")}),this.socket.on("chain.reset",e=>{let t;try{t=p(e)}catch(e){return void this.fire("error",e)}this.emit("chain.reset",t)}),this.socket.on("tx",e=>{try{e=f(e)}catch(e){return void this.fire("error",e)}this.fire("tx",e)})),await this.onConnect())}_close(){return this.socket&&(this.socket.disconnect(),this.socket=null),Promise.resolve()}onConnect(){return new Promise((e,t)=>{this.socket.on("connect",async t=>{"relay"==this.mode&&(await this.watchChain(),await this.watchMempool()),await this.fireNoBubble("onConnect"),e(t)})})}async removeTX(e){return Promise.resolve()}async execute(e,t){t=t||[],Array.isArray(t)||(t=[t]);let i=l[e];return i?i.remoteCb?new Promise((e,r)=>{this.socket.emit("request",i.name,...t,g(e,r,async e=>i.remoteCb.call({wdb:this.wdb},e)))}):new Promise((e,r)=>{this.socket.emit("request",i.name,...t,g(e,r))}):null}watchChain(){return new Promise((e,t)=>{this.socket.emit("request","chain.watch",g(e,t))})}watchMempool(){return new Promise((e,t)=>{this.socket.emit("request","mempool.watch",g(e,t))})}getTip(){return new Promise((e,t)=>{this.socket.emit("request","block.tip",g(e,t,p))})}getEntry(e){return new Promise((t,i)=>{"string"==typeof e&&(e=a.revHex(e)),this.socket.emit("request","block.entry",e,g(t,i,p))})}send(e){return new Promise((t,i)=>{this.socket.emit("request","$tx.broadcast",e.toRaw(),g(t,i))})}setFilter(e){return new Promise((t,i)=>{this.socket.emit("request","filter.set",e.toRaw(),g(t,i))})}addFilter(e){Array.isArray(e)||(e=[e]),this.socket.emit("request","filter.add",[e])}resetFilter(){return new Promise((e,t)=>{this.socket.emit("request","filter.reset",g(e,t))})}estimateFee(e){return new Promise((t,i)=>{this.socket.emit("request","$estimate.fee",e,g(t,i))})}rescan(e){return new Promise((t,i)=>{"string"==typeof e&&(e=a.revHex(e)),this.socket.emit("request","chain.rescan",e,g(t,i))})}}},function(e,t,i){"use strict";
|
|
1614
1614
|
/*!
|
|
1615
1615
|
* sigcache.js - signature cache for vallnet
|
|
1616
1616
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -1690,7 +1690,7 @@ object-assign
|
|
|
1690
1690
|
* vary
|
|
1691
1691
|
* Copyright(c) 2014-2017 Douglas Christopher Wilson
|
|
1692
1692
|
* MIT Licensed
|
|
1693
|
-
*/e.exports=function(e,t){if(!e||!e.getHeader||!e.setHeader)throw new TypeError("res argument is required");var i=e.getHeader("Vary")||"";(i=s(Array.isArray(i)?i.join(", "):String(i),t))&&e.setHeader("Vary",i)},e.exports.append=s;var r=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function s(e,t){if("string"!=typeof e)throw new TypeError("header argument is required");if(!t)throw new TypeError("field argument is required");for(var i=Array.isArray(t)?t:n(String(t)),s=0;s<i.length;s++)if(!r.test(i[s]))throw new TypeError("field argument contains an invalid header name");if("*"===e)return e;var a=e,o=n(e.toLowerCase());if(-1!==i.indexOf("*")||-1!==o.indexOf("*"))return"*";for(var c=0;c<i.length;c++){var h=i[c].toLowerCase();-1===o.indexOf(h)&&(o.push(h),a=a?a+", "+i[c]:i[c])}return a}function n(e){for(var t=0,i=[],r=0,s=0,n=e.length;s<n;s++)switch(e.charCodeAt(s)){case 32:r===t&&(r=t=s+1);break;case 44:i.push(e.substring(r,t)),r=t=s+1;break;default:t=s+1}return i.push(e.substring(r,t)),i}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uServer=void 0;var r=i(93);const s=i(659),n=i(757),a=(0,r.default)("engine:uws");class o extends s.BaseServer{init(){}cleanup(){}prepare(e,t){e.method=e.getMethod().toUpperCase();var i=new URLSearchParams(e.getQuery());e._query=Object.fromEntries(i.entries()),e.headers={},e.forEach((t,i)=>{e.headers[t]=i}),e.connection={remoteAddress:Buffer.from(t.getRemoteAddressAsText()).toString()},t.onAborted(()=>{a("response has been aborted")})}createTransport(e,t){return new n.default[e](t)}attach(e,t={}){var i=(t.path||"/engine.io").replace(/\/$/,"")+"/";e.any(i,this.handleRequest.bind(this)).ws(i,{compression:t.compression,idleTimeout:t.idleTimeout,maxBackpressure:t.maxBackpressure,maxPayloadLength:this.opts.maxHttpBufferSize,upgrade:this.handleUpgrade.bind(this),open:e=>{(e.transport.socket=e).transport.writable=!0,e.transport.emit("drain")},message:(e,t,i)=>{e.transport.onData(i?t:Buffer.from(t).toString())},close:(e,t,i)=>{e.transport.onClose(t,i)}})}handleRequest(e,t){a('handling "%s" http request "%s"',t.getMethod(),t.getUrl()),this.prepare(t,e),t.res=e;const i=(i,r)=>{void 0!==i?(this.emit("connection_error",{req:t,code:i,message:s.Server.errorMessages[i],context:r}),this.abortRequest(t.res,i,r)):t._query.sid?(a("setting new request for existing client"),this.clients[t._query.sid].transport.onRequest(t)):this.handshake(t._query.transport,t,(t,i)=>this.abortRequest(e,t,i))};this.corsMiddleware?(t.res=new c(e),this.corsMiddleware.call(null,t,t.res,()=>{this.verify(t,!1,i)})):this.verify(t,!1,i)}handleUpgrade(e,t,i){a("on upgrade"),this.prepare(t,e),t.res=e,this.verify(t,!0,async(r,n)=>{if(r)this.emit("connection_error",{req:t,code:r,message:s.Server.errorMessages[r],context:n}),this.abortRequest(e,r,n);else{let s;if(r=t._query.sid)(n=this.clients[r])?n.upgrading?(a("transport has already been trying to upgrade"),e.close()):n.upgraded?(a("transport had already been upgraded"),e.close()):(a("upgrading existing transport"),s=this.createTransport(t._query.transport,t),n.maybeUpgrade(s)):(a("upgrade attempt for closed client"),e.close());else if(!(s=await this.handshake(t._query.transport,t,(t,i)=>this.abortRequest(e,t,i))))return;e.upgrade({transport:s},t.getHeader("sec-websocket-key"),t.getHeader("sec-websocket-protocol"),t.getHeader("sec-websocket-extensions"),i)}})}abortRequest(e,t,i){var r=t===s.Server.errors.FORBIDDEN?"403 Forbidden":"400 Bad Request";i=i&&i.message?i.message:s.Server.errorMessages[t];e.writeStatus(r),e.writeHeader("Content-Type","application/json"),e.end(JSON.stringify({code:t,message:i}))}}t.uServer=o;class c{constructor(e){this.res=e,this.statusWritten=!1,this.headers=[]}set statusCode(e){this.writeStatus(200===e?"200 OK":"204 No Content")}setHeader(e,t){this.writeHeader(e,t)}getHeader(){}writeStatus(e){this.res.writeStatus(e),this.statusWritten=!0,this.writeBufferedHeaders()}writeHeader(e,t){"Content-Length"!==e&&(this.statusWritten?this.res.writeHeader(e,t):this.headers.push([e,t]))}writeBufferedHeaders(){this.headers.forEach(([e,t])=>{this.res.writeHeader(e,t)})}end(e){this.statusWritten||this.writeBufferedHeaders(),this.res.end(e)}onData(e){this.res.onData(e)}onAborted(e){this.res.onAborted(e)}}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(758);i=i(759);t.default={polling:r.Polling,websocket:i.WebSocket}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Polling=void 0;var r=i(313),s=i(174);const n=i(618),a=(0,i(93).default)("engine:polling"),o={gzip:s.createGzip,deflate:s.createDeflate};class c extends r.Transport{constructor(e){super(e),this.closeTimeout=3e4}get name(){return"polling"}get supportsFraming(){return!1}onRequest(e){var t=e.res;"get"===e.getMethod()?this.onPollRequest(e,t):"post"===e.getMethod()?this.onDataRequest(e,t):(t.writeStatus("500 Internal Server Error"),t.end())}onPollRequest(e,t){this.req?(a("request overlap"),this.onError("overlap from client"),t.writeStatus("500 Internal Server Error"),t.end()):(a("setting request"),this.req=e,this.res=t,e.cleanup=()=>{this.req=this.res=null},t.onAborted(()=>{this.writable=!1,this.onError("poll connection closed prematurely")}),this.writable=!0,this.emit("drain"),this.writable&&this.shouldClose&&(a("triggering empty send to append close packet"),this.send([{type:"noop"}])))}onDataRequest(e,t){if(this.dataReq)this.onError("data request overlap from client"),t.writeStatus("500 Internal Server Error"),t.end();else{const s=Number(e.headers["content-length"]);if(s)if(s>this.maxHttpBufferSize)this.onError("payload too large"),t.writeStatus("413 Payload Too Large").end();else{if("application/octet-stream"===e.headers["content-type"]&&4===this.protocol)return this.onError("invalid content");this.dataReq=e,this.dataRes=t;let n,a=0;var i,r={"Content-Type":"text/html"};for(i in this.headers(e,r),r)t.writeHeader(i,String(r[i]));const o=e=>{this.onData(e.toString()),this.onDataRequestCleanup(),t.end("ok")};t.onAborted(()=>{this.onDataRequestCleanup(),this.onError("data request connection closed prematurely")}),t.onData((e,i)=>{var r=a+e.byteLength;if(r>s)this.onError("content-length mismatch"),t.close();else{if(!n){if(i)return void o(Buffer.from(e));n=Buffer.allocUnsafe(s)}if(Buffer.from(e).copy(n,a),i)return r!=s?(this.onError("content-length mismatch"),t.writeStatus("400 Content-Length Mismatch").end(),void this.onDataRequestCleanup()):void o(n);a=r}})}else this.onError("content-length header required"),t.writeStatus("411 Length Required").end()}}onDataRequestCleanup(){this.dataReq=this.dataRes=null}onData(e){a('received "%s"',e);var t=e=>{if("close"===e.type)return a("got xhr close packet"),this.onClose(),!1;this.onPacket(e)};3===this.protocol?this.parser.decodePayload(e,t):this.parser.decodePayload(e).forEach(t)}onClose(){this.writable&&this.send([{type:"noop"}]),super.onClose()}send(e){this.writable=!1,this.shouldClose&&(a("appending close packet to payload"),e.push({type:"close"}),this.shouldClose(),this.shouldClose=null);var t=t=>{var i=e.some(e=>e.options&&e.options.compress);this.write(t,{compress:i})};3===this.protocol?this.parser.encodePayload(e,this.supportsBinary,t):this.parser.encodePayload(e,t)}write(e,t){a('writing "%s"',e),this.doWrite(e,t,()=>{this.req.cleanup()})}doWrite(e,t,i){var r="string"==typeof e;const s={"Content-Type":r?"text/plain; charset=UTF-8":"application/octet-stream"},a=e=>{this.headers(this.req,s),Object.keys(s).forEach(e=>{this.res.writeHeader(e,String(s[e]))}),this.res.end(e),i()};if(this.httpCompression&&t.compress)if((r?Buffer.byteLength(e):e.length)<this.httpCompression.threshold)a(e);else{const t=n(this.req).encodings(["gzip","deflate"]);t?this.compress(e,t,(e,r)=>{e?(this.res.writeStatus("500 Internal Server Error"),this.res.end(),i(e)):(s["Content-Encoding"]=t,a(r))}):a(e)}else a(e)}compress(e,t,i){a("compressing");const r=[];let s=0;o[t](this.httpCompression).on("error",i).on("data",(function(e){r.push(e),s+=e.length})).on("end",(function(){i(null,Buffer.concat(r,s))})).end(e)}doClose(e){let t;a("closing");var i=()=>{clearTimeout(t),e(),this.onClose()};this.writable?(a("transport writable - closing right away"),this.send([{type:"close"}]),i()):this.discarded?(a("transport discarded - closing right away"),i()):(a("transport not writable - buffering orderly close"),this.shouldClose=i,t=setTimeout(i,this.closeTimeout))}headers(e,t){t=t||{};var i=e.headers["user-agent"];return i&&(~i.indexOf(";MSIE")||~i.indexOf("Trident/"))&&(t["X-XSS-Protection"]="0"),this.emit("headers",t,e),t}}t.Polling=c},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebSocket=void 0;var r=i(313);const s=(0,i(93).default)("engine:ws");class n extends r.Transport{constructor(e){super(e),this.writable=!1,this.perMessageDeflate=null}get name(){return"websocket"}get handlesUpgrades(){return!0}get supportsFraming(){return!0}send(e){var t,i=e.shift();void 0===i?(this.writable=!0,this.emit("drain")):(i.options&&i.options.compress,t=t=>{var i="string"!=typeof t,r=this.perMessageDeflate&&Buffer.byteLength(t)>this.perMessageDeflate.threshold;s('writing "%s"',t),this.writable=!1,this.socket.send(t,i,r),this.send(e)},i.options&&"string"==typeof i.options.wsPreEncoded?t(i.options.wsPreEncoded):this.parser.encodePacket(i,this.supportsBinary,t))}doClose(e){s("closing"),e&&e(),this.socket.close()}}t.WebSocket=n},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Client=void 0;const r=i(52);var s=i(93);const n=i(42),a=s("socket.io:client");t.Client=class{constructor(e,t){this.sockets=new Map,this.nsps=new Map,this.server=e,this.conn=t,this.encoder=e.encoder,this.decoder=new e._parser.Decoder,this.id=t.id,this.setup()}get request(){return this.conn.request}setup(){this.onclose=this.onclose.bind(this),this.ondata=this.ondata.bind(this),this.onerror=this.onerror.bind(this),this.ondecoded=this.ondecoded.bind(this),this.decoder.on("decoded",this.ondecoded),this.conn.on("data",this.ondata),this.conn.on("error",this.onerror),this.conn.on("close",this.onclose),this.connectTimeout=setTimeout(()=>{0===this.nsps.size?(a("no namespace joined yet, close the client"),this.close()):a("the client has already joined a namespace, nothing to do")},this.server._connectTimeout)}connect(e,t={}){if(this.server._nsps.has(e))return a("connecting to namespace %s",e),this.doConnect(e,t);this.server._checkNamespace(e,t,i=>{i?this.doConnect(e,t):(a("creation of namespace %s was denied",e),this._packet({type:r.PacketType.CONNECT_ERROR,nsp:e,data:{message:"Invalid namespace"}}))})}doConnect(e,t){const i=this.server.of(e),r=i._add(this,t,()=>{this.sockets.set(r.id,r),this.nsps.set(i.name,r),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0)})}_disconnect(){for(const e of this.sockets.values())e.disconnect();this.sockets.clear(),this.close()}_remove(e){var t;this.sockets.has(e.id)?(t=this.sockets.get(e.id).nsp.name,this.sockets.delete(e.id),this.nsps.delete(t)):a("ignoring remove for %s",e.id)}close(){"open"===this.conn.readyState&&(a("forcing transport close"),this.conn.close(),this.onclose("forced server close"))}_packet(e,t={}){"open"!==this.conn.readyState?a("ignoring packet write %j",e):(e=t.preEncoded?e:this.encoder.encode(e),this.writeToEngine(e,t))}writeToEngine(e,t){if(t.volatile&&!this.conn.transport.writable)a("volatile packet is discarded since the transport is not currently writable");else for(const i of Array.isArray(e)?e:[e])this.conn.write(i,t)}ondata(e){try{this.decoder.add(e)}catch(e){a("invalid packet format"),this.onerror(e)}}ondecoded(e){let t,i;var s;i=3===this.conn.protocol?(t=(s=n.parse(e.nsp,!0)).pathname,s.query):(t=e.nsp,e.data);const o=this.nsps.get(t);o||e.type!==r.PacketType.CONNECT?o&&e.type!==r.PacketType.CONNECT&&e.type!==r.PacketType.CONNECT_ERROR?process.nextTick((function(){o._onpacket(e)})):(a("invalid state (packet type: %s)",e.type),this.close()):this.connect(t,i)}onerror(e){for(const t of this.sockets.values())t._onerror(e);this.conn.close()}onclose(e){a("client close with reason %s",e),this.destroy();for(const t of this.sockets.values())t._onclose(e);this.sockets.clear(),this.decoder.destroy()}destroy(){this.conn.removeListener("data",this.ondata),this.conn.removeListener("error",this.onerror),this.conn.removeListener("close",this.onclose),this.decoder.removeListener("decoded",this.ondecoded),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0)}}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ParentNamespace=void 0;const r=i(669);class s extends r.Namespace{constructor(e){super(e,"/_"+s.count++),this.children=new Set}_initAdapter(){this.adapter={broadcast:(e,t)=>{this.children.forEach(i=>{i.adapter.broadcast(e,t)})}}}emit(e,...t){return this.children.forEach(i=>{i.emit(e,...t)}),!0}createChild(e){const t=new r.Namespace(this.server,e);return t._fns=this._fns.slice(0),this.listeners("connect").forEach(e=>t.on("connect",e)),this.listeners("connection").forEach(e=>t.on("connection",e)),this.children.add(t),this.server._nsps.set(e,t),t}fetchSockets(){throw new Error("fetchSockets() is not supported on parent namespaces")}}(t.ParentNamespace=s).count=0},function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.serveFile=t.restoreAdapter=t.patchAdapter=void 0;const s=i(671),n=i(88),a=(0,r(i(93)).default)("socket.io:adapter-uws"),{addAll:o,del:c,broadcast:h}=s.Adapter.prototype;function u(e,t,i,r){const s=t.conn.id,n=t.conn.transport.socket;i&&(a("subscribe connection %s to topic %s",s,e),n.subscribe(e)),r.forEach(t=>{a("subscribe connection %s to topic %s",s,t=e+""+t),n.subscribe(t)})}t.patchAdapter=function(e){s.Adapter.prototype.addAll=function(e,t){const i=!this.sids.has(e),r=(o.call(this,e,t),this.nsp.sockets.get(e));r&&("websocket"===r.conn.transport.name?u(this.nsp.name,r,i,t):i&&r.conn.on("upgrade",()=>{var t=this.sids.get(e);t&&u(this.nsp.name,r,i,t)}))},s.Adapter.prototype.del=function(e,t){var i;c.call(this,e,t),(e=this.nsp.sockets.get(e))&&"websocket"===e.conn.transport.name&&(i=e.conn.id,e=e.conn.transport.socket,t=this.nsp.name+""+t,a("unsubscribe connection %s from topic %s",i,t),e.unsubscribe(t))},s.Adapter.prototype.broadcast=function(t,i){if(i.rooms.size<=1&&0===i.except.size){var r=i.flags||{};const s={preEncoded:!0,volatile:r.volatile,compress:r.compress},n=(t.nsp=this.nsp.name,this.encoder.encode(t)),o=0===i.rooms.size?this.nsp.name:this.nsp.name+""+i.rooms.keys().next().value;a("fast publish to %s",o),n.forEach(t=>{var i="string"!=typeof t;e.publish(o,i?t:"4"+t,i)}),this.apply(i,e=>{"websocket"!==e.conn.transport.name&&e.client.writeToEngine(n,s)})}else h.call(this,t,i)}},t.restoreAdapter=function(){s.Adapter.prototype.addAll=o,s.Adapter.prototype.del=c,s.Adapter.prototype.broadcast=h};t.serveFile=function(e,t){const i=(0,n.statSync)(t).size,r=(0,n.createReadStream)(t),s=()=>!r.destroyed&&r.destroy();e.onAborted(s),r.on("data",t=>{const s=(e=>{var{buffer:e,byteOffset:t,byteLength:i}=e;return e.slice(t,t+i)})(t),n=e.getWriteOffset();var[t,a]=e.tryEnd(s,i);a||t||(r.pause(),e.onWritable(t=>{var[t,a]=e.tryEnd(s.slice(t-n),i);return!a&&t&&r.resume(),t}))}).on("error",e=>{throw s(),e}).on("end",s)}},function(e){e.exports=JSON.parse('{"name":"socket.io","version":"4.5.4","description":"node.js realtime framework server","keywords":["realtime","framework","websocket","tcp","events","socket","io"],"files":["dist/","client-dist/","wrapper.mjs","!**/*.tsbuildinfo"],"directories":{"doc":"docs/","example":"example/","lib":"lib/","test":"test/"},"type":"commonjs","main":"./dist/index.js","exports":{"import":"./wrapper.mjs","require":"./dist/index.js","types":"./dist/index.d.ts"},"types":"./dist/index.d.ts","license":"MIT","repository":{"type":"git","url":"git://github.com/socketio/socket.io"},"scripts":{"compile":"rimraf ./dist && tsc","test":"npm run format:check && npm run compile && npm run test:types && npm run test:unit","test:types":"tsd","test:unit":"nyc mocha --require ts-node/register --reporter spec --slow 200 --bail --timeout 10000 test/index.ts","format:check":"prettier --check \\"lib/**/*.ts\\" \\"test/**/*.ts\\"","format:fix":"prettier --write \\"lib/**/*.ts\\" \\"test/**/*.ts\\"","prepack":"npm run compile"},"dependencies":{"accepts":"~1.3.4","base64id":"~2.0.0","debug":"~4.3.2","engine.io":"~6.2.1","socket.io-adapter":"~2.4.0","socket.io-parser":"~4.2.1"},"devDependencies":{"@types/mocha":"^9.0.0","expect.js":"0.3.1","mocha":"^10.0.0","nyc":"^15.1.0","prettier":"^2.3.2","rimraf":"^3.0.2","socket.io-client":"4.5.4","socket.io-client-v2":"npm:socket.io-client@^2.4.0","superagent":"^8.0.0","supertest":"^6.1.6","ts-node":"^10.2.1","tsd":"^0.21.0","typescript":"^4.4.2","uWebSockets.js":"github:uNetworking/uWebSockets.js#v20.0.0"},"contributors":[{"name":"Guillermo Rauch","email":"rauchg@gmail.com"},{"name":"Arnout Kazemier","email":"info@3rd-eden.com"},{"name":"Vladimir Dronnikov","email":"dronnikov@gmail.com"},{"name":"Einar Otto Stangvik","email":"einaros@gmail.com"}],"engines":{"node":">=10.0.0"},"tsd":{"directory":"test"}}')},function(e,t,i){const r=i(0);e.exports=class{constructor(e){this.keyLimit=100,this.bodyLimit=20<<20,this.contentType=null,this.timeout=1e4,e&&this.fromOptions(e)}fromOptions(e){return r(e),null!=e.keyLimit&&(r("number"==typeof e.keyLimit),this.keyLimit=e.keyLimit),null!=e.bodyLimit&&(r("number"==typeof e.bodyLimit),this.bodyLimit=e.bodyLimit),null!=e.contentType&&(r("string"==typeof e.contentType),this.contentType=e.contentType),this}}},function(e,t,i){const r=i(674),s=i(620).StringDecoder;e.exports=async function(e,t){let i=Object.create(null);if("GET"!==e.method){let h=e.contentType;if("bin"!==(h=t.contentType?t.contentType:h)){var n=await(a=e,o="utf8",c=t,new Promise((e,t)=>{{var i=a,r=c,n=e,h=t;const u=new s(o);let l=!1,p=0,d="";const f=()=>{i.removeListener("data",m),i.removeListener("error",g),i.removeListener("end",y),null!=v&&(v=null,clearTimeout(v))},m=e=>{p+=e.length,l=!0,p>r.bodyLimit?h(new Error("Request body overflow.")):d+=u.write(e)},g=e=>{f(),h(e)},y=()=>{f(),n(l?d:null)};let v=setTimeout(()=>{v=null,f(),h(new Error("Request body timed out."))},r.timeout);i.on("data",m),i.on("error",g),i.on("end",y)}}));if(n)switch(h){case"json":if(!(i=JSON.parse(n))||"object"!=typeof i||Array.isArray(i))throw new Error("JSON body must be an object.");break;case"form":i=r.parsePairs(n,t.keyLimit)}}}var a,o,c;return i}},function(e,t,i){const{generateKey:r,verifyObj:s}=i(72),n=i(67),a=i(6);e.exports=class{constructor(e){this.wdb=e}async call(e,t,i){try{var o,c=t.body.sig,h=n.getHmac(t.options.cid||"",this.wdb.keys.hmacSalt).token,u=r(a.hash256(Buffer.from(h)));if(!this.wdb.options.devMode&&!s({method:t.body.method,params:t.body.params,cid:t.body.cid,wid:t.body.wid},c,u.public))return o={result:null,code:404,error:{type:"HmacError",message:"Verify Error"}},i.send(404,o,"json"),{interrupt:!0,result:null};if(!(t.options.auth&&t.options.authWid==t.options.wid||(this.wdb.options.devMode||await this.wdb.auth(t.options.cid,t.options.token),t.body.method&&"wallet.create"===t.body.method))){var l=await this.wdb.get(t.options.wid);if(!l)return i.send(404,{result:null,code:404,error:{type:"HmacError",message:"Not Found Wallet"}},"json"),{interrupt:!0,result:null};this.wdb.logger.info("Successful auth for %s on %s.",t.options.cid,t.options.wid),t.options.auth=!0,t.options.authWid=t.options.wid,t.wallet=l}return{interrupt:!1}}catch(e){return this.wdb.logger.info("Auth failure for %s on %s: %s.",t.options.cid,t.options.wid,e.message),i.send(403,{result:null,code:403,error:{type:"HmacError",message:"Hmac Auth failure."}},"json"),{interrupt:!0,result:null}}}}},function(e,t){e.exports=class{async call(e,t,i){return e.node.config.devMode||e.node.acl.canAccess(t.body.method,t.options.cid)?{interrupt:!1}:(i.send(407,{result:null,code:407,error:{type:"ACLError",message:"TerminalNo Authentication Required."}},"json"),{interrupt:!0,result:null})}}},function(e,t){e.exports=class{constructor(e,t){this.routes=e,this.openapi=t}async call(e,t,i){switch(t.options.mode){case"web":if(0===t.pathname.indexOf("/public/")){var r=this.routes.getHandlers(t.method);if(!r)return{interrupt:!0,result:null};for(const n of r){var s=n.match(t.pathname);if(s){t.params=s;try{return{interrupt:!0,result:{code:0,error:null,result:await n.call(t,i)}}}catch(e){i.error(500,e)}return{interrupt:!0,result:null}}}}else if(r=this.openapi[t.body.method]){try{return{interrupt:!0,result:{code:0,error:null,result:await e.node.conn_s2local.execute(r.name,t.body.params,t)}}}catch(e){i.error(500,e)}return{interrupt:!0,result:null}}break;case"ws":if(r=this.openapi[t.body.method])return{interrupt:!0,result:{code:0,error:null,result:await e.node.conn_s2local.execute(r.name,t.body.params,t)}}}return{interrupt:!1}}}},function(e,t,i){const r=i(0),s=i(2),n=i(6),a=i(158);e.exports=class{constructor(e){r(e,"Basic auth requires options."),this.user=e.username,this.pass=e.password,this.realm=e.realm,null!=this.user&&(r("string"==typeof this.user),r(this.user.length<=255,"Username too long."),r(s.isAscii(this.user),"Username must be ASCII."),this.user=n.hash256(Buffer.from(this.user,"ascii"))),r("string"==typeof this.pass),r(this.pass.length<=255,"Password too long."),r(s.isAscii(this.pass),"Password must be ASCII."),this.pass=n.hash256(Buffer.from(this.pass,"ascii")),this.realm||(this.realm="server"),r("string"==typeof this.realm)}fail(e){e.setHeader("WWW-Authenticate",`Basic realm="${this.realm}"`),e.send(401,{result:null,code:401,error:{type:"AuthError",message:"Unauthorized."}},"json"),e.end()}async call(e,t,i){if(!e.node.config.devMode&&!t.options.auth){if(this.user){if(255<t.options.user.username.length)return this.fail(i),{interrupt:!0,result:null};const e=Buffer.from(t.options.user.username,"ascii"),r=n.hash256(e);if(!a(r,this.user))return this.fail(i),{interrupt:!0,result:null}}if(!t.options.user||!t.options.user.password||255<t.options.user.password.length)return this.fail(i),{interrupt:!0,result:null};const e=Buffer.from(t.options.user.password,"ascii"),r=n.hash256(e);if(!a(r,this.pass))return this.fail(i),{interrupt:!0,result:null};t.options.auth=!0}return{interrupt:!1}}}},function(e,t,i){const r=i(2),s=i(77),n=i(78).errors,a=i(84),o=i(120),{getBlockOverview:c,getBlockByHash:h,formatTimestamp:u}=i(621);e.exports=[{name:"blocks",method:"get",path:"/public/blocks",callback:async function(e,t){var i,r=(e=e.valid()).str("blockDate"),s=e.str("startTimestamp",""),n=(e=e.uint("limit",10),u(new Date));if(r){if(!/\d{4}-\d{2}-\d{2}/.test(r))throw new Error("Please use yyyy-mm-dd format");i=r===n}else r=n,i=!0;n=Math.round(new Date(r).getTime()/1e3),s=parseInt(s)||n+86400;var a=u(new Date(1e3*(n-86400))),o=s?u(new Date(1e3*s)):null,c=(e=parseInt(e||200),!1),l=s;try{var p,d=await this.chain.db.getTimestampHashes(s,n);let u=[];for(p of d)u.push(p.hash);u.reverse(),u.length>e&&(c=!0,u=u.slice(0,e));var f,m={blocks:[],length:u.length,pagination:{next:o,prev:a,currentTs:s-1,current:r,isToday:i,more:c,moreTs:c?l:void 0}};for(f of u){var g=await h(this,f,t);m.blocks.push(g)}return m.blocks.sort((e,t)=>t.height-e.height),m}catch(e){throw e}}},{name:"block-index",method:"get",path:"/public/block-index/:height",callback:async function(e,t){var i=this;if(-1===(e=(e=e.valid()).uint("height")))throw new s(n.TYPE_ERROR,"Invalid block height.");if(!(e=await i.chain.getEntry(e)))throw new s(n.MISC_ERROR,"Block not found");if(i=await h(i.node,e.hash,t))return i}},{name:"block-tip",method:"get",path:"/public/block-tip",callback:async function(e,t){var i=this;if(e.valid(),!(e=await i.chain.tip))throw new s(n.MISC_ERROR,"Block not found");if(i=await h(i.node,e.hash,t))return i}},{name:"block",method:"get",path:"/public/block/:blockHash",callback:async function(e,t){var i=this;if(e=(e=e.valid()).str("blockHash"),i=await h(i.node,e,t))return i}},{name:"getBlock",method:"jsonp",path:"/",callback:async function(e,t){return t=(t=new a([t])).str(0),h(e,t)}},{name:"rawblock",method:"get",path:"/public/rawblock/:param",callback:async function(e,t){var i=this;let a=(e=e.valid()).str("param");if(a=r.checkNum(a)?parseInt(a):r.revHex(a),e=await i.chain.getBlock(a))return e.toRaw().toString("hex");if(i.chain.options.spv)throw new s(n.MISC_ERROR,"Block not available (spv mode)");if(i.chain.options.prune)throw new s(n.MISC_ERROR,"Block not available (pruned data)");throw new s(n.DATABASE_ERROR,"Can't read block from disk")}},{name:"getRawBlock",method:"jsonp",path:"/",callback:async function(e,t){let i=(t=new a([t])).str(0);return r.checkNum(i)&&(i=parseInt(i)),(t=await e.chain.getBlock(i))?t.toRaw().toString("hex"):null}},{name:"isSynced",method:"jsonp",path:"/",callback:async function(e,t){return e.chain.synced}},{name:"getBlockOverview",method:"jsonp",path:"/",callback:async function(e,t){return t=(t=new a([t])).str(0),c(e,t)}},{name:"getInfo",method:"jsonp",path:"/",callback:async function(e,t){var i=await e.rpc.execute({corba:!0,method:"miner.difficulty"});return{blocks:e.chain.height,connections:e.pool.peers.size(),timeoffset:0,proxy:"",testnet:"main"!==e.network.type,errors:"",network:e.network.type,relayFee:0,version:"bitcore-1.1.2",protocolversion:700001,difficulty:i}}},{name:"getBestHeight",method:"jsonp",path:"/",callback:async function(e,t){return e.chain.height}},{name:"getBlockHeader",method:"jsonp",path:"/",callback:async function(e,t){var i=(t=new a([t])).hash(0);t=t.bool(1,!0);if(!i)throw new s(n.MISC_ERROR,"Invalid block hash.");if(!(i=await e.chain.getEntry(i)))throw new s(n.MISC_ERROR,"Block not found");if(!t)return i.toRaw().toString("hex",0,80);t=await e.chain.getMedianTime(i);var c=await e.chain.getNextHash(i.hash);return{hash:i.rhash(),confirmations:e.chain.height-i.height+1,height:i.height,version:i.version,versionHex:r.hex32(i.version),merkleroot:r.revHex(i.merkleRoot),time:i.time,mediantime:t,bits:i.bits,difficulty:o.bits2Diff(i.bits),chainwork:i.chainwork.toString("hex",64),previousblockhash:i.prevBlock!==encoding.NULL_HASH?r.revHex(i.prevBlock):null,nextblockhash:c?r.revHex(c):null}}}]},function(e){e.exports=JSON.parse('[{"poolName":"50BTC","url":"https://50btc.com/","searchStrings":["50BTC.com","50btc.com"]},{"poolName":"175btc","url":"http://www.175btc.com/","searchStrings":["Mined By 175btc.com"]},{"poolName":"ASICminer","url":"https://bitcointalk.org/index.php?topic=99497.0","searchStrings":["Mined By ASICMiner"]},{"poolName":"AntMiner","url":"https://bitmaintech.com/","searchStrings":["AntPool"]},{"poolName":"agentD","url":"http://","searchStrings":["agentD"]},{"poolName":"Bitfury","url":"http://bitfury.org/","searchStrings":["2av0id51pct"]},{"poolName":"BitMinter","url":"https://bitminter.com/","searchStrings":["BitMinter"]},{"poolName":"Bitparking","url":"http://bitparking.com/","searchStrings":["bitparking"]},{"poolName":"BTC Guild","url":"https://www.btcguild.com/","searchStrings":["Mined by BTC Guild","BTC Guild"]},{"poolName":"bcpool.io","url":"https://bcpool.io/","searchStrings":["bcpool"]},{"poolName":"Discus Fish","url":"http://f2pool.com/","searchStrings":["七彩神仙鱼","Made in China","Mined by user"]},{"poolName":"Discus Fish Solo","url":"http://f2pool.com/","searchStrings":["For Pierce and Paul"]},{"poolName":"Cointerra","url":"http://cointerra.com/","searchStrings":["cointerra"]},{"poolName":"Eligius","url":"http://eligius.st/","searchStrings":["Eligius"]},{"poolName":"EclipseMC","url":"https://eclipsemc.com/","searchStrings":["Josh Zerlan was here!","EclipseMC","Aluminum Falcon"]},{"poolName":"GIVE-ME-COINS","url":"https://give-me-coins.com/","searchStrings":["Mined at GIVE-ME-COINS.com"]},{"poolName":"ghash.io","url":"https://ghash.io/","searchStrings":["ghash.io","GHash.IO"]},{"poolName":"HHTT","url":"http://hhtt.1209k.com/","searchStrings":["HHTT"]},{"poolName":"KNCminer","url":"https://www.kncminer.com/","searchStrings":["KnCMiner"]},{"poolName":"Megabigpower","url":"http://megabigpower.com/","searchStrings":["megabigpower.com"]},{"poolName":"MultiCoin","url":"https://multicoin.co/","searchStrings":["MultiCoin.co"]},{"poolName":"Mt Red","url":"https://mtred.com/","searchStrings":["/mtred/"]},{"poolName":"MaxBTC","url":"https://www.maxbtc.com","searchStrings":["MaxBTC"]},{"poolName":"NMCbit","url":"http://nmcbit.com/","searchStrings":["nmcbit.com"]},{"poolName":"ozcoin","url":"https://ozco.in/","searchStrings":["ozco.in","ozcoin"]},{"poolName":"Polmine.pl","url":"https://polmine.pl","searchStrings":["by polmine.pl"]},{"poolName":"simplecoin","url":"http://simplecoin.us/","searchStrings":["simplecoin.us ftw"]},{"poolName":"SlushPool","url":"https://slushpool.com/","searchStrings":["/slush/"]},{"poolName":"TripleMining","url":"https://www.triplemining.com/","searchStrings":["Triplemining.com"]},{"poolName":"wizkid057","url":"http://wizkid057.com/btc","searchStrings":["wizkid057"]},{"poolName":"Yourbtc.net","url":"http://yourbtc.net/","searchStrings":["yourbtc.net"]},{"poolName":"BTCChina Pool","url":"https://pool.btcchina.com/","searchStrings":["BTCChina Pool","btcchina.com"]},{"poolName":"BTCC Pool","url":"https://pool.btcc.com/","searchStrings":["/BTCC/"]}]')},function(e,t,i){const{utxo:r,_setOutputResults:s,_setInputResults:n,transformTransaction:a,getDetailFromMeta:o,translateOutputAddress:c}=i(621),h=i(32),u=i(84),l=i(2);async function p(e,t){var i=(t=new u([t])).array(0,[]),r=t.obj(1,{}),s=(r.from=r.from||0,r.to=r.to||4294967295,[]);t=await e.getMetaByAddress(i);let n=0;for(const i of t){if(n<r.from);else{if(n>=r.to)break;var a=await o(e,i);s.push(a)}n++}return{totalCount:t.length,items:s}}async function d(e,t){let i=(r=e.valid()).str("addr");i=i||r.str("addrs");var r,s=((r={from:parseInt(e.query.from)||parseInt(e.body.from)||0}).to=parseInt(e.query.to)||parseInt(e.body.to)||parseInt(r.from)+10,e=e,{noAsm:!!parseInt(e.query.noAsm),noScriptSig:!!parseInt(e.query.noScriptSig),noSpent:!!parseInt(e.query.noSpent)});try{var n,c=await this.node.getMetaByAddress(i.split(",")),h=[];for(n of c){var u=await o(this.node,n);h.push(await a(this.node,u,s))}return{totalItems:c.length,from:r.from,to:Math.min(r.to,c.length),items:h}}catch(e){throw e}}async function f(e,t){var i=e.valid();let s=i.str("addr");s=s||i.str("addrs"),e.query.from&&e.query.to&&(parseInt(e.query.from),parseInt(e.query.to));try{var n,a=[];for(n of await r(this.node,s.split(",")))a.push(function(e,t){var i={address:c(t.address),txid:l.revHex(t.txid),vout:t.vout,scriptPubKey:t.scriptPubKey,amount:t.satoshis/1e8,satoshis:t.satoshis};return t.height&&0<t.height?(i.height=t.height,i.confirmations=e.chain.height-t.height+1):i.confirmations=0,t.timestamp&&(i.ts=t.timestamp),i}(this,n));return a}catch(e){throw e}}async function m(e,t){var i=(e=e.valid()).str("id"),r=(e=e.uint("index",1),this.node.require("walletdb"));if(r&&(r=await r.get("primary"),await r.ensureAccount({name:i,witness:!0}),r=await r.createReceive(i,e)))return r.toJSON().address}async function g(e,t,i){i=i||{};var r={totalCount:0,items:[]};let a=0;for(const s of await e.node.getMetaByAddress(t)){if(i.from&&a<i.from);else{if(i.to&&a>=i.to)break;var u=await o(e.node,s);r.items.push(u)}a++}r.totalCount=r.items.length;for(var p={addrStr:t,balance:0,balanceSat:0,totalReceived:0,totalReceivedSat:0,totalSent:0,totalSentSat:0,unconfirmedBalance:0,unconfirmedBalanceSat:0,unconfirmedTxApperances:0,txApperances:0},d=0;d<r.items.length;d++){var f=r.items[d];s(e,f,t,p),n(e,f,t,p),i.noTxList||(p.transactions||(p.transactions=[]),p.transactions.push(l.revHex(f.txid())))}return p.balance=h.fromSatoshis(p.balanceSat).toBTC(),p.totalReceived=h.fromSatoshis(p.totalReceivedSat).toBTC(),p.totalSent=h.fromSatoshis(p.totalSentSat).toBTC(),p.unconfirmedBalance=h.fromSatoshis(p.unconfirmedBalanceSat).toBTC(),p.addrStr&&(p.addrStr=c(p.addrStr)),p}e.exports=[{name:"address.reflect",method:"get",path:"/public/addr/reflect/:id",callback:m},{name:"address.reflect.index",method:"get",path:"/public/addr/reflect/:id/:index",callback:m},{name:"getInfo",method:"get",path:"/public/addr/:addr",callback:async function(e,t){var i=(i=e.valid()).str("addr"),r={noTxList:parseInt(e.query.noTxList)};e.query.from&&e.query.to?(r.from=parseInt(e.query.from),r.to=parseInt(e.query.to)):(r.from=0,r.to=10);try{return await g(this,i,r)}catch(e){throw e}}},{name:"getUTXOByAddress",method:"get",path:"/public/addr/:addr/utxo",callback:f},{name:"getUTXOByAddresses",method:"get",path:"/public/addrs/:addr/utxo",callback:f},{name:"postUTXOByAddresses",method:"post",path:"/public/addrs/utxo",callback:f},{name:"getTXSByAddresses",method:"get",path:"/public/addrs/:addrs/txs",callback:d},{name:"postTXSByAddresses",method:"post",path:"/public/addrs/txs",callback:d},{name:"getBalanceByAddress",method:"get",path:"/public/addr/:addr/balance",callback:async function(e,t){var i=this;let r=(e=e.valid()).str("addr");r=r||e.str("addrs"),e=await i.node.getCoinsByAddress(r.split(","));var s=(i=e.reduce((e,t)=>e+t.value,0))-(e=e.reduce((e,t)=>(-1==t.height&&(e+=t.value),e),0));return{confirmed:h.fromSatoshis(s).toBTC(),unconfirmed:h.fromSatoshis(e).toBTC(),balance:h.fromSatoshis(i).toBTC()}}},{name:"getUnconfirmedBalance",method:"get",path:"/public/addr/:addr/unconfirmedBalance",callback:async function(e,t){var i=this;let r=(e=e.valid()).str("addr");return r=r||e.str("addrs"),e=await i.node.getCoinsByAddress(r.split(",")),i=e.reduce((e,t)=>(-1==t.height&&(e+=t.value),e),0),h.fromSatoshis(i).toBTC()}},{name:"getTotalReceived",method:"get",path:"/public/addr/:addr/totalReceived",callback:async function(e,t){let i=(e=e.valid()).str("addr");i=i||e.str("addrs");try{return(await g(this,i)).totalReceivedSat}catch(e){throw e}}},{name:"getTotalSent",method:"get",path:"/public/addr/:addr/totalSent",callback:async function(e,t){let i=(e=e.valid()).str("addr");i=i||e.str("addrs");try{return(await g(this,i)).totalSent}catch(e){throw e}}},{name:"getAddressHistory",method:"jsonp",path:"/",callback:p},{name:"getAddressSummary",method:"jsonp",path:"/",callback:async function(e,t){var i=new u([t]),r=i.array(0,[]),a=i.obj(1,{});a.from=a.from||0,a.to=a.to||4294967295;for(var o={addrStr:r,balance:0,balanceSat:0,totalReceived:0,totalReceivedSat:0,totalSent:0,totalSentSat:0,unconfirmedBalance:0,unconfirmedBalanceSat:0,unconfirmedTxApperances:0,txApperances:0},c=(i=await p(e,t)).items,l=0;l<c.length;l++){var d=c[l];s(e,d,r,o),n(e,d,r,o),a.noTxList||(o.transactions||(o.transactions=[]),o.transactions.push(d.txid()))}return o.balance=h.fromSatoshis(o.balanceSat).toBTC(),o.totalReceived=h.fromSatoshis(o.totalReceivedSat).toBTC(),o.totalSent=h.fromSatoshis(o.totalSentSat).toBTC(),o.unconfirmedBalance=h.fromSatoshis(o.unconfirmedBalanceSat).toBTC(),o}},{name:"getAddressUnspentOutputs",method:"jsonp",path:"/",callback:async function(e,t){return t=(t=new u([t])).array(0,[]),e=await r(e,t)}},{name:"getTxidsByAddress",method:"jsonp",path:"/",callback:async function(e,t){var i=(t=new u([t])).array(0);t=t.str(1,"both");return e.chain.getHashesByAddress(i,t)}}]},function(e,t,i){var r=i(82);const s=i(32),n=i(84);var a=i(329),o=0,c=Date.now();async function h(e){var t=await e.rpc.execute({corba:!0,method:"miner.difficulty"});return{blocks:e.chain.height,connections:e.node.pool.peers.size,timeoffset:0,proxy:"",testnet:"main"!==e.node.network.type,errors:"",network:e.node.network.type,relayFee:0,version:"gamegold-"+r.version,protocolversion:700001,difficulty:t}}e.exports=[{name:"getStatus",method:"get",path:"/public/status",callback:async function(e,t){switch(e.query.q){case"getDifficulty":try{return{difficulty:(await h(this)).difficulty}}catch(e){throw e}break;case"getLastBlockHash":var i=await this.chain.db.getTip();return{syncTipHash:i.hash,lastblockhash:i.hash};case"getBestBlockHash":try{return{bestblockhash:await this.rpc.execute({corba:!0,method:"block.best"})}}catch(e){throw e}break;default:try{return{info:await h(this)}}catch(e){throw e}}}},{name:"getSync",method:"get",path:"/public/sync",callback:async function(e,t){var i="syncing";try{this.chain.synced&&(i="finished");var r=(100*this.chain.getProgress()).toFixed(2);return{status:i,blockChainHeight:this.chain.height,syncPercentage:Math.round(r),height:this.chain.height,error:null,type:"gamegold node"}}catch(e){throw e}}},{name:"getVersion",method:"get",path:"/public/version",callback:async function(e,t){return{version:r.version}}},{name:"getPeer",method:"get",path:"/public/peer",callback:function(e,t){var i=this.pool.getLoader()||{connected:!1,address:{host:null,port:null}};return{connected:i.connected,host:i.address.host,port:i.address.port}}},{name:"getEstimateFee",method:"get",path:"/public/utils/estimatefee",callback:function(e,t){e=(e.query.nbBlocks||"2").split(",");try{var i,r={};for(i of e){var n=parseInt(i);let e=this.fees.estimateFee(n,!1);0===e&&(e=-1),e=s.btc(e,!0),r[n]=e}return r}catch(e){throw e}}},{name:"estimateFee",method:"jsonp",path:"/",callback:function(e,t){t=(t=new n([t])).array(0,["2"]);try{var i,r={};for(i of t){var a=parseInt(i);let t=e.fees.estimateFee(a,!1);0===t&&(t=-1),t=s.btc(t,!0),r[a]=t}return r}catch(t){throw t}}},{name:"currency",method:"get",path:"/public/currency",callback:async function(e,t){var i=Date.now();if(!(0===o||c+6e5<=i))return{status:200,data:{bitstamp:o}};c=i;try{var r=await new Promise((e,t)=>{a("https://www.bitstamp.net/api/ticker/",(function(i,r,s){i&&t(i),i||200!==r.statusCode||e(s)}))});return{status:200,data:{bitstamp:o=parseFloat(JSON.parse(r).last)}}}catch(e){throw e}}},{name:"explorers",method:"get",path:"/public/explorers",callback:async function(e,t){return[{name:"gamegold",ticker:"GG",url:"https://insight.gamegold.xin"}]}},{name:"syncPercentage",method:"jsonp",path:"/",callback:async function(e,t){return Math.round((100*e.chain.getProgress()).toFixed(2))}},{name:"sysEcho",method:"jsonp",path:"/",callback:function(e,t){return 0}},{name:"getBestBlockHash",method:"jsonp",path:"/",callback:async function(e,t){return{bestblockhash:e=await e.rpc.execute({corba:!0,method:"block.best"})}}}]},function(e,t,i){const r=i(677),s=i(0),n=i(2),{handleErrors:a,getDetailedTransaction:o,transformTransaction:c,getDetailFromMeta:h,getBlockOverview:u,translateInputAddresses:l}=i(621),p=i(84);e.exports=[{name:"getTx",method:"get",path:"/public/tx/:txid",callback:async function(e,t){return e=(e=e.valid()).hash("txid"),(e=await o(this.node,e))?await c(this.node,e,{}):null}},{name:"getRawTx",method:"get",path:"/public/rawtx/:txid",callback:async function(e,t){return e=(e=e.valid()).str("txid"),{rawtx:e=await this.rpc.execute({method:"tx.raw.get",params:[e]})}}},{name:"getList",method:"get",path:"/public/txs",callback:async function(e,t){s(!this.chain.options.spv,"Cannot get TX in SPV mode.");var i,p=e.query.blockHash,d=l(e.query.address),f=(e=parseInt(e.query.pageNum)||0,1);if(p){if(!(p=await u(this.node,p,t)))return a(null,t);t=p.txids.length;var m,g,y=(r.isUndefined(e)?i=p.txids:(m=10*e,i=p.txids.slice(m,10+m),f=Math.ceil(t/10)),[]);for(g of i){var v=await o(this.node,n.revHex(g));v&&y.push(await c(this.node,v,{}))}return{pagesTotal:f,txs:y}}if(d){var b=10*e,w=10*(e+1),k=[];p=await this.node.getMetaByAddress(d);let t=0;for(const e of p){if(t<b);else{if(t>=w)break;var x=await h(this.node,e);k.push(await c(this.node,x,{}))}t++}return{pagesTotal:Math.ceil(p.length/10),txs:k}}throw new Error("Block hash or address expected")}},{name:"getDetailedTransaction",method:"jsonp",path:"/",callback:async function(e,t){return t=(t=new p([t])).hash(0),o(e,t,!0)}},{name:"getTransaction",method:"jsonp",path:"/",callback:async function(e,t){return t=(t=new p([t])).hash(0),e=await o(e,t,!1)}},{name:"getRawTransaction",method:"jsonp",path:"/",callback:async function(e,t){return t=(t=new p([t])).str(0),e=await e.rpc.execute({method:"tx.raw.get",params:[t]})}},{name:"getMempoolTransaction",method:"jsonp",path:"/",callback:async function(e,t){return t=(t=new p([t])).hash(0),e.mempool.getTX(t)}}]},function(e,t,i){const r=i(20).opcodes,s=i(2).revHex;e.exports=[{name:"prop.get",method:"get",path:"/public/prop/:pid",callback:async function(e,t){var i=[];e=e.valid().str("pid");if(e=await this.node.chain.db.propList.getVp(e)){var n=e.current.hash;e.oper="exchange",i.push({oper:"exchange",pid:e.pid,oid:e.oid,cid:e.cid,current:{hash:s(e.current.hash),index:e.current.index,address:e.current.address},height:e.height});let t=[n,e.current.index];for(;;){var a=await this.node.getMeta(t[0]),o=a.tx;if(!o)break;if(!(o=o.outputs[t[1]]))break;var c=o.getReturnData([r.OP_PROPCREATE,r.OP_PROPEXCHANGE]);if(!c)break;if("new"==c.oper){c.current={hash:s(t[0]),index:t[1],address:o.getAddress().toString()},c.height=a.height,i.push(c);break}if(!c.prev)break;t=[c.prev.hash,c.prev.index]}}return i}},{name:"queryProps",method:"post",path:"/public/prop/query",callback:async function(e,t){var i=(e=e.valid()).str("game_id");e=e.str("user_addr");return await this.node.queryProps(i,e)}},{name:"queryProps",method:"get",path:"/public/prop/:game_id/addr/:user_addr",callback:async function(e,t){var i=(e=e.valid()).str("game_id");e=e.str("user_addr");return await this.node.queryProps(i,e)}},{name:"queryProps",method:"get",path:"/public/props/query",callback:async function(e,t){var i=(e=e.valid()).str("pid"),r=e.str("cid"),s=e.str("oid"),n=e.str("addr");e=e.str("page");return await this.node.queryProps(r,n,i,s,e)}}]},function(e,t,i){const r=i(84);e.exports=[{name:"cp.remoteQuery",method:"jsonp",path:"/",callback:async function(e,t){return t=(t=new r([t])).array(0,[]),e.chain.db.cpList.query(t)},remoteCb:async function(e){if(e&&Array.isArray(e.list))for(var t of e.list)this.wdb.cpList.getItem(t.cid)||await this.wdb.cpList.addItem(t);return e}},{name:"cps",method:"get",path:"/public/cps",callback:async function(e,t){return e={page:e.valid().u32("page",1),pageCount:0},{list:this.chain.db.cpList.getCPList([],e),cur:e.page,page:e.pageCount}}},{name:"cpById",method:"get",path:"/public/cp/:id",callback:async function(e,t){var i=(e=e.valid()).u32("page",1);e=e.str("id");return(e=this.chain.db.cpList.getCPList(e?[e]:[],{page:i}))&&0<e.length?e[0]:null}},{name:"cpByName",method:"get",path:"/public/cp/name/:name",callback:async function(e,t){var i=(e=e.valid()).u32("page",1);e=decodeURIComponent(e.str("name"));return(e=this.chain.db.cpList.getCPListByName(e?[e]:[],{page:i}))&&0<e.length?e[0]:null}}]},function(e,t,i){const r=i(84),s=i(100),n=i(77),a=i(78).errors,o=i(67),c=i(5).ContractStatus,h=i(19),u=i(32);e.exports=[{name:"token.random",local:!0,method:"jsonp",path:"/",callback:async function(e,t,i){if(1!==t.length)throw new n(a.MISC_ERROR,"token.random clientNo: 生成令牌随机量 终端编码");return t=new r([t]).str(0),t=o.getHmac(t,e.keys.hmacSalt).random}},{name:"mempool.watch",method:"jsonp",path:"/",callback:async function(e,t,i){i&&i.join("mempool")}},{name:"mempool.unwatch",method:"jsonp",path:"/",callback:async function(e,t,i){i&&i.leave("mempool")}},{name:"chain.watch",method:"jsonp",path:"/",callback:async function(e,t,i){i&&i.join("chain")}},{name:"chain.unwatch",method:"jsonp",path:"/",callback:async function(e,t,i){i&&i.leave("chain")}},{name:"chain.rescan",method:"jsonp",path:"/",callback:async function(e,t,i){if(null==(t=new r([t]).numhash(0)))throw new Error("Invalid parameter.");return e.http.scan(i,t)}},{name:"subscribe",local:!0,method:"jsonp",path:"/",callback:async function(e,t,i){if(i&&Array.isArray(t))for(var r of t)i.bus.subscribe(r);return!0}},{name:"unsubscribe",local:!0,method:"jsonp",path:"/",callback:async function(e,t,i){if(i&&Array.isArray(t))for(var r of t)i.bus.unsubscribe(r);return!0}},{name:"filter.set",local:!0,method:"jsonp",path:"/",callback:async function(e,t,i){if(i){if(t=new r([t]).buf(0))return i.filter=s.fromRaw(t),null;throw new Error("Invalid parameter.")}}},{name:"filter.reset",local:!0,method:"jsonp",path:"/",callback:async function(e,t,i){i&&(i.filter=null)}},{name:"filter.add",local:!0,method:"jsonp",path:"/",callback:async function(e,t,i){if(i){var s=new r([t]).array(0);if(!s)throw new Error("Invalid parameter.");if(!i.filter)throw new Error("No filter set.");var n=new r([s]);for(let t=0;t<s.length;t++){var a=n.buf(t);if(!a)throw new Error("Bad data chunk.");i.filter.add(a),e.spv&&e.pool.watch(a)}}}},{name:"canExecute",method:"jsonp",path:"/",callback:async function(e,t){return(t=new r([t]).obj(0,{})).confirm||"cpChange"==t.oper?e.chain.db.cpList.canExecute(t):await e.mempool.cpMemList.canExecute(t)&&await e.chain.db.cpList.canExecute(t)}},{name:"contract.list",method:"jsonp",path:"/",callback:async function(e,t){var i,s,n,a;return 0==t.length?"contract.list type page ids size: 查询并返回交易对 交易类型 指定查询的ID数组 页码":(a=(t=new r([t])).uint(0,1),i=t.uint(1,1),s=t.array(2,[]),t=t.int(3,10),(n=[]).push(["transStatus",c.CreatedOnMem]),a&&n.push(["type",a]),0<s.length&&n.push(["id","include",s]),{pageNum:(a=e.chain.db.transactionList.where(n).paginate(t,i)).pageNum,pageCur:a.pageCur,list:a.records()})},remoteCb:async function(e){if(e&&Array.isArray(e.list))for(var t of e.list)this.wdb.transactionList.saveContract(t,!0);return e}},{name:"queryProps",method:"jsonp",path:"/",callback:async function(e,t){var i=(t=new r([t])).str(0,"");t=t.str(1,"");return e.queryProps(i,t)}},{name:"block.tip",method:"jsonp",path:"/",callback:async function(e,t){return e.chain.tip.toRaw()}},{name:"block.entry",method:"jsonp",path:"/",callback:async function(e,t){if(null==(t=new r([t]).numhash(0)))throw new Error("Invalid parameter.");return(t=await e.chain.getEntry(t))&&await e.chain.isMainChain(t)?t.toRaw():null}},{name:"$tx.broadcast",method:"jsonp",path:"/",callback:async function(e,t,i){t=new r([t]).buf(0),t=h.fromRaw(t),await e.sendTX(t)}},{name:"$estimate.fee",method:"jsonp",path:"/",callback:async function(e,t){if(t=new r([t]).u32(0,1),e.fees)return 0===(e=e.fees.estimateFee(t,!1))?-1:u.btc(e,!0);throw new n(a.MISC_ERROR,"Fee estimation not available.")}}]},function(e,t,i){const r=i(84),s=i(779);e.exports=[{name:"ca.get",method:"get",path:"/public/ca/:erid",callback:async function(e,t){return e=e.valid().str("erid"),(e=await this.node.chain.db.erList.query([["erid",e]])).height=this.node.chain.height,e}},{name:"ca.rank",method:"jsonp",path:"/",callback:async function(e,t){return t=(t=new r([t])).str(0,""),(e=await(async e=>new Promise((t,i)=>{s(e,.85,1e-4,(function(e,r){e?i(e):t(r)}))}))(e.chain.db.enCpList.rank))[t]},remoteCb:async function(e){return e}},{name:"ca.list",method:"jsonp",path:"/",callback:async function(e,t){return t=(t=new r([t])).array(0,[]),(t=await e.chain.db.erList.query(t)).height=e.chain.height,t}},{name:"ca.verify",method:"jsonp",path:"/",callback:async function(e,t){return t=(t=new r([t])).str(0,""),(t=await e.chain.db.caVerify(t))&&(t.curHeight=e.chain.height),t},remoteCb:async function(e){return e}},{name:"ca.list.ab",method:"jsonp",path:"/",callback:async function(e,t){return t=(t=new r([t])).array(0,[]),e.chain.db.erAbList.query(t)},remoteCb:async function(e){return e}}]},function(e,t,i){"use strict";class r{constructor(e,t,i,r,s){this.outgoingNodes=e,this.linkProb=t,this.tolerance=i,this.callback=r,this.pageCount=Object.keys(this.outgoingNodes).length,this.coeff=(1-t)/this.pageCount,this.probabilityNodes=e instanceof Array?[]:{},this.incomingNodes=e instanceof Array?[]:{},this.debug=s,this.startRanking()}startRanking(){var e,t,i,r=1/this.pageCount,s=this.outgoingNodes;for(e in s)for(t in this.probabilityNodes[e]=r,s[e])i=s[e][t],this.incomingNodes[i]||(this.incomingNodes[i]=[]),this.incomingNodes[i].push(e);this.debug&&this.reportDebug(1),this.iterate(1)}reportDebug(e){console.log("____ITERATION "+e+"____"),console.log("Pages: "+Object.keys(this.outgoingNodes).length),console.log("outgoing %j",this.outgoingNodes),console.log("incoming %j",this.incomingNodes),console.log("probability %j",this.probabilityNodes)}iterate(e){var t,i,r,s,n,a=[],o={};for(t in this.probabilityNodes){if(r=0,this.incomingNodes[t])for(i=0;i<this.incomingNodes[t].length;i++)r+=this.probabilityNodes[this.incomingNodes[t][i]]/this.outgoingNodes[this.incomingNodes[t][i]].length;s=this.coeff+this.linkProb*r,n=this.probabilityNodes[t]+this.tolerance,this.probabilityNodes[t]-this.tolerance<=s&&s<=n&&a.push(o[t]=s),this.probabilityNodes[t]=s}return a.length==this.pageCount?this.outgoingNodes instanceof Array?this.callback(null,a):this.callback(null,o):(this.debug&&this.reportDebug(e),this.iterate(++e))}}e.exports=function(e,t,i,s,n=!1){if(e&&t&&i&&s)return new r(e,t,i,s,n);throw new Error("Provide 4 arguments: nodeMatrix, link probability, tolerance, callback")}},function(e,t,i){"use strict";e.exports=class{constructor(e){this.config=e,this.hmacConnection=this.config.array("hmac-connection")||[],this.config.hmacConnection=this.hmacConnection}add(e){-1==this.hmacConnection.indexOf(e)&&this.hmacConnection.push(e),this.config.hmacConnection=this.hmacConnection}del(e){-1!=(e=this.hmacConnection.indexOf(e))&&(this.hmacConnection.splice(e,1),this.config.hmacConnection=this.hmacConnection)}clear(){this.hmacConnection=[],this.config.hmacConnection=this.hmacConnection}content(){return this.hmacConnection}has(e){return-1!=this.hmacConnection.indexOf(e)}}},function(e,t,i){"use strict";
|
|
1693
|
+
*/e.exports=function(e,t){if(!e||!e.getHeader||!e.setHeader)throw new TypeError("res argument is required");var i=e.getHeader("Vary")||"";(i=s(Array.isArray(i)?i.join(", "):String(i),t))&&e.setHeader("Vary",i)},e.exports.append=s;var r=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function s(e,t){if("string"!=typeof e)throw new TypeError("header argument is required");if(!t)throw new TypeError("field argument is required");for(var i=Array.isArray(t)?t:n(String(t)),s=0;s<i.length;s++)if(!r.test(i[s]))throw new TypeError("field argument contains an invalid header name");if("*"===e)return e;var a=e,o=n(e.toLowerCase());if(-1!==i.indexOf("*")||-1!==o.indexOf("*"))return"*";for(var c=0;c<i.length;c++){var h=i[c].toLowerCase();-1===o.indexOf(h)&&(o.push(h),a=a?a+", "+i[c]:i[c])}return a}function n(e){for(var t=0,i=[],r=0,s=0,n=e.length;s<n;s++)switch(e.charCodeAt(s)){case 32:r===t&&(r=t=s+1);break;case 44:i.push(e.substring(r,t)),r=t=s+1;break;default:t=s+1}return i.push(e.substring(r,t)),i}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uServer=void 0;var r=i(93);const s=i(659),n=i(757),a=(0,r.default)("engine:uws");class o extends s.BaseServer{init(){}cleanup(){}prepare(e,t){e.method=e.getMethod().toUpperCase();var i=new URLSearchParams(e.getQuery());e._query=Object.fromEntries(i.entries()),e.headers={},e.forEach((t,i)=>{e.headers[t]=i}),e.connection={remoteAddress:Buffer.from(t.getRemoteAddressAsText()).toString()},t.onAborted(()=>{a("response has been aborted")})}createTransport(e,t){return new n.default[e](t)}attach(e,t={}){var i=(t.path||"/engine.io").replace(/\/$/,"")+"/";e.any(i,this.handleRequest.bind(this)).ws(i,{compression:t.compression,idleTimeout:t.idleTimeout,maxBackpressure:t.maxBackpressure,maxPayloadLength:this.opts.maxHttpBufferSize,upgrade:this.handleUpgrade.bind(this),open:e=>{(e.transport.socket=e).transport.writable=!0,e.transport.emit("drain")},message:(e,t,i)=>{e.transport.onData(i?t:Buffer.from(t).toString())},close:(e,t,i)=>{e.transport.onClose(t,i)}})}handleRequest(e,t){a('handling "%s" http request "%s"',t.getMethod(),t.getUrl()),this.prepare(t,e),t.res=e;const i=(i,r)=>{void 0!==i?(this.emit("connection_error",{req:t,code:i,message:s.Server.errorMessages[i],context:r}),this.abortRequest(t.res,i,r)):t._query.sid?(a("setting new request for existing client"),this.clients[t._query.sid].transport.onRequest(t)):this.handshake(t._query.transport,t,(t,i)=>this.abortRequest(e,t,i))};this.corsMiddleware?(t.res=new c(e),this.corsMiddleware.call(null,t,t.res,()=>{this.verify(t,!1,i)})):this.verify(t,!1,i)}handleUpgrade(e,t,i){a("on upgrade"),this.prepare(t,e),t.res=e,this.verify(t,!0,async(r,n)=>{if(r)this.emit("connection_error",{req:t,code:r,message:s.Server.errorMessages[r],context:n}),this.abortRequest(e,r,n);else{let s;if(r=t._query.sid)(n=this.clients[r])?n.upgrading?(a("transport has already been trying to upgrade"),e.close()):n.upgraded?(a("transport had already been upgraded"),e.close()):(a("upgrading existing transport"),s=this.createTransport(t._query.transport,t),n.maybeUpgrade(s)):(a("upgrade attempt for closed client"),e.close());else if(!(s=await this.handshake(t._query.transport,t,(t,i)=>this.abortRequest(e,t,i))))return;e.upgrade({transport:s},t.getHeader("sec-websocket-key"),t.getHeader("sec-websocket-protocol"),t.getHeader("sec-websocket-extensions"),i)}})}abortRequest(e,t,i){var r=t===s.Server.errors.FORBIDDEN?"403 Forbidden":"400 Bad Request";i=i&&i.message?i.message:s.Server.errorMessages[t];e.writeStatus(r),e.writeHeader("Content-Type","application/json"),e.end(JSON.stringify({code:t,message:i}))}}t.uServer=o;class c{constructor(e){this.res=e,this.statusWritten=!1,this.headers=[]}set statusCode(e){this.writeStatus(200===e?"200 OK":"204 No Content")}setHeader(e,t){this.writeHeader(e,t)}getHeader(){}writeStatus(e){this.res.writeStatus(e),this.statusWritten=!0,this.writeBufferedHeaders()}writeHeader(e,t){"Content-Length"!==e&&(this.statusWritten?this.res.writeHeader(e,t):this.headers.push([e,t]))}writeBufferedHeaders(){this.headers.forEach(([e,t])=>{this.res.writeHeader(e,t)})}end(e){this.statusWritten||this.writeBufferedHeaders(),this.res.end(e)}onData(e){this.res.onData(e)}onAborted(e){this.res.onAborted(e)}}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(758);i=i(759);t.default={polling:r.Polling,websocket:i.WebSocket}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Polling=void 0;var r=i(313),s=i(174);const n=i(618),a=(0,i(93).default)("engine:polling"),o={gzip:s.createGzip,deflate:s.createDeflate};class c extends r.Transport{constructor(e){super(e),this.closeTimeout=3e4}get name(){return"polling"}get supportsFraming(){return!1}onRequest(e){var t=e.res;"get"===e.getMethod()?this.onPollRequest(e,t):"post"===e.getMethod()?this.onDataRequest(e,t):(t.writeStatus("500 Internal Server Error"),t.end())}onPollRequest(e,t){this.req?(a("request overlap"),this.onError("overlap from client"),t.writeStatus("500 Internal Server Error"),t.end()):(a("setting request"),this.req=e,this.res=t,e.cleanup=()=>{this.req=this.res=null},t.onAborted(()=>{this.writable=!1,this.onError("poll connection closed prematurely")}),this.writable=!0,this.emit("drain"),this.writable&&this.shouldClose&&(a("triggering empty send to append close packet"),this.send([{type:"noop"}])))}onDataRequest(e,t){if(this.dataReq)this.onError("data request overlap from client"),t.writeStatus("500 Internal Server Error"),t.end();else{const s=Number(e.headers["content-length"]);if(s)if(s>this.maxHttpBufferSize)this.onError("payload too large"),t.writeStatus("413 Payload Too Large").end();else{if("application/octet-stream"===e.headers["content-type"]&&4===this.protocol)return this.onError("invalid content");this.dataReq=e,this.dataRes=t;let n,a=0;var i,r={"Content-Type":"text/html"};for(i in this.headers(e,r),r)t.writeHeader(i,String(r[i]));const o=e=>{this.onData(e.toString()),this.onDataRequestCleanup(),t.end("ok")};t.onAborted(()=>{this.onDataRequestCleanup(),this.onError("data request connection closed prematurely")}),t.onData((e,i)=>{var r=a+e.byteLength;if(r>s)this.onError("content-length mismatch"),t.close();else{if(!n){if(i)return void o(Buffer.from(e));n=Buffer.allocUnsafe(s)}if(Buffer.from(e).copy(n,a),i)return r!=s?(this.onError("content-length mismatch"),t.writeStatus("400 Content-Length Mismatch").end(),void this.onDataRequestCleanup()):void o(n);a=r}})}else this.onError("content-length header required"),t.writeStatus("411 Length Required").end()}}onDataRequestCleanup(){this.dataReq=this.dataRes=null}onData(e){a('received "%s"',e);var t=e=>{if("close"===e.type)return a("got xhr close packet"),this.onClose(),!1;this.onPacket(e)};3===this.protocol?this.parser.decodePayload(e,t):this.parser.decodePayload(e).forEach(t)}onClose(){this.writable&&this.send([{type:"noop"}]),super.onClose()}send(e){this.writable=!1,this.shouldClose&&(a("appending close packet to payload"),e.push({type:"close"}),this.shouldClose(),this.shouldClose=null);var t=t=>{var i=e.some(e=>e.options&&e.options.compress);this.write(t,{compress:i})};3===this.protocol?this.parser.encodePayload(e,this.supportsBinary,t):this.parser.encodePayload(e,t)}write(e,t){a('writing "%s"',e),this.doWrite(e,t,()=>{this.req.cleanup()})}doWrite(e,t,i){var r="string"==typeof e;const s={"Content-Type":r?"text/plain; charset=UTF-8":"application/octet-stream"},a=e=>{this.headers(this.req,s),Object.keys(s).forEach(e=>{this.res.writeHeader(e,String(s[e]))}),this.res.end(e),i()};if(this.httpCompression&&t.compress)if((r?Buffer.byteLength(e):e.length)<this.httpCompression.threshold)a(e);else{const t=n(this.req).encodings(["gzip","deflate"]);t?this.compress(e,t,(e,r)=>{e?(this.res.writeStatus("500 Internal Server Error"),this.res.end(),i(e)):(s["Content-Encoding"]=t,a(r))}):a(e)}else a(e)}compress(e,t,i){a("compressing");const r=[];let s=0;o[t](this.httpCompression).on("error",i).on("data",(function(e){r.push(e),s+=e.length})).on("end",(function(){i(null,Buffer.concat(r,s))})).end(e)}doClose(e){let t;a("closing");var i=()=>{clearTimeout(t),e(),this.onClose()};this.writable?(a("transport writable - closing right away"),this.send([{type:"close"}]),i()):this.discarded?(a("transport discarded - closing right away"),i()):(a("transport not writable - buffering orderly close"),this.shouldClose=i,t=setTimeout(i,this.closeTimeout))}headers(e,t){t=t||{};var i=e.headers["user-agent"];return i&&(~i.indexOf(";MSIE")||~i.indexOf("Trident/"))&&(t["X-XSS-Protection"]="0"),this.emit("headers",t,e),t}}t.Polling=c},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebSocket=void 0;var r=i(313);const s=(0,i(93).default)("engine:ws");class n extends r.Transport{constructor(e){super(e),this.writable=!1,this.perMessageDeflate=null}get name(){return"websocket"}get handlesUpgrades(){return!0}get supportsFraming(){return!0}send(e){var t,i=e.shift();void 0===i?(this.writable=!0,this.emit("drain")):(i.options&&i.options.compress,t=t=>{var i="string"!=typeof t,r=this.perMessageDeflate&&Buffer.byteLength(t)>this.perMessageDeflate.threshold;s('writing "%s"',t),this.writable=!1,this.socket.send(t,i,r),this.send(e)},i.options&&"string"==typeof i.options.wsPreEncoded?t(i.options.wsPreEncoded):this.parser.encodePacket(i,this.supportsBinary,t))}doClose(e){s("closing"),e&&e(),this.socket.close()}}t.WebSocket=n},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Client=void 0;const r=i(52);var s=i(93);const n=i(42),a=s("socket.io:client");t.Client=class{constructor(e,t){this.sockets=new Map,this.nsps=new Map,this.server=e,this.conn=t,this.encoder=e.encoder,this.decoder=new e._parser.Decoder,this.id=t.id,this.setup()}get request(){return this.conn.request}setup(){this.onclose=this.onclose.bind(this),this.ondata=this.ondata.bind(this),this.onerror=this.onerror.bind(this),this.ondecoded=this.ondecoded.bind(this),this.decoder.on("decoded",this.ondecoded),this.conn.on("data",this.ondata),this.conn.on("error",this.onerror),this.conn.on("close",this.onclose),this.connectTimeout=setTimeout(()=>{0===this.nsps.size?(a("no namespace joined yet, close the client"),this.close()):a("the client has already joined a namespace, nothing to do")},this.server._connectTimeout)}connect(e,t={}){if(this.server._nsps.has(e))return a("connecting to namespace %s",e),this.doConnect(e,t);this.server._checkNamespace(e,t,i=>{i?this.doConnect(e,t):(a("creation of namespace %s was denied",e),this._packet({type:r.PacketType.CONNECT_ERROR,nsp:e,data:{message:"Invalid namespace"}}))})}doConnect(e,t){const i=this.server.of(e),r=i._add(this,t,()=>{this.sockets.set(r.id,r),this.nsps.set(i.name,r),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0)})}_disconnect(){for(const e of this.sockets.values())e.disconnect();this.sockets.clear(),this.close()}_remove(e){var t;this.sockets.has(e.id)?(t=this.sockets.get(e.id).nsp.name,this.sockets.delete(e.id),this.nsps.delete(t)):a("ignoring remove for %s",e.id)}close(){"open"===this.conn.readyState&&(a("forcing transport close"),this.conn.close(),this.onclose("forced server close"))}_packet(e,t={}){"open"!==this.conn.readyState?a("ignoring packet write %j",e):(e=t.preEncoded?e:this.encoder.encode(e),this.writeToEngine(e,t))}writeToEngine(e,t){if(t.volatile&&!this.conn.transport.writable)a("volatile packet is discarded since the transport is not currently writable");else for(const i of Array.isArray(e)?e:[e])this.conn.write(i,t)}ondata(e){try{this.decoder.add(e)}catch(e){a("invalid packet format"),this.onerror(e)}}ondecoded(e){let t,i;var s;i=3===this.conn.protocol?(t=(s=n.parse(e.nsp,!0)).pathname,s.query):(t=e.nsp,e.data);const o=this.nsps.get(t);o||e.type!==r.PacketType.CONNECT?o&&e.type!==r.PacketType.CONNECT&&e.type!==r.PacketType.CONNECT_ERROR?process.nextTick((function(){o._onpacket(e)})):(a("invalid state (packet type: %s)",e.type),this.close()):this.connect(t,i)}onerror(e){for(const t of this.sockets.values())t._onerror(e);this.conn.close()}onclose(e){a("client close with reason %s",e),this.destroy();for(const t of this.sockets.values())t._onclose(e);this.sockets.clear(),this.decoder.destroy()}destroy(){this.conn.removeListener("data",this.ondata),this.conn.removeListener("error",this.onerror),this.conn.removeListener("close",this.onclose),this.decoder.removeListener("decoded",this.ondecoded),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0)}}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ParentNamespace=void 0;const r=i(669);class s extends r.Namespace{constructor(e){super(e,"/_"+s.count++),this.children=new Set}_initAdapter(){this.adapter={broadcast:(e,t)=>{this.children.forEach(i=>{i.adapter.broadcast(e,t)})}}}emit(e,...t){return this.children.forEach(i=>{i.emit(e,...t)}),!0}createChild(e){const t=new r.Namespace(this.server,e);return t._fns=this._fns.slice(0),this.listeners("connect").forEach(e=>t.on("connect",e)),this.listeners("connection").forEach(e=>t.on("connection",e)),this.children.add(t),this.server._nsps.set(e,t),t}fetchSockets(){throw new Error("fetchSockets() is not supported on parent namespaces")}}(t.ParentNamespace=s).count=0},function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.serveFile=t.restoreAdapter=t.patchAdapter=void 0;const s=i(671),n=i(88),a=(0,r(i(93)).default)("socket.io:adapter-uws"),{addAll:o,del:c,broadcast:h}=s.Adapter.prototype;function u(e,t,i,r){const s=t.conn.id,n=t.conn.transport.socket;i&&(a("subscribe connection %s to topic %s",s,e),n.subscribe(e)),r.forEach(t=>{a("subscribe connection %s to topic %s",s,t=e+""+t),n.subscribe(t)})}t.patchAdapter=function(e){s.Adapter.prototype.addAll=function(e,t){const i=!this.sids.has(e),r=(o.call(this,e,t),this.nsp.sockets.get(e));r&&("websocket"===r.conn.transport.name?u(this.nsp.name,r,i,t):i&&r.conn.on("upgrade",()=>{var t=this.sids.get(e);t&&u(this.nsp.name,r,i,t)}))},s.Adapter.prototype.del=function(e,t){var i;c.call(this,e,t),(e=this.nsp.sockets.get(e))&&"websocket"===e.conn.transport.name&&(i=e.conn.id,e=e.conn.transport.socket,t=this.nsp.name+""+t,a("unsubscribe connection %s from topic %s",i,t),e.unsubscribe(t))},s.Adapter.prototype.broadcast=function(t,i){if(i.rooms.size<=1&&0===i.except.size){var r=i.flags||{};const s={preEncoded:!0,volatile:r.volatile,compress:r.compress},n=(t.nsp=this.nsp.name,this.encoder.encode(t)),o=0===i.rooms.size?this.nsp.name:this.nsp.name+""+i.rooms.keys().next().value;a("fast publish to %s",o),n.forEach(t=>{var i="string"!=typeof t;e.publish(o,i?t:"4"+t,i)}),this.apply(i,e=>{"websocket"!==e.conn.transport.name&&e.client.writeToEngine(n,s)})}else h.call(this,t,i)}},t.restoreAdapter=function(){s.Adapter.prototype.addAll=o,s.Adapter.prototype.del=c,s.Adapter.prototype.broadcast=h};t.serveFile=function(e,t){const i=(0,n.statSync)(t).size,r=(0,n.createReadStream)(t),s=()=>!r.destroyed&&r.destroy();e.onAborted(s),r.on("data",t=>{const s=(e=>{var{buffer:e,byteOffset:t,byteLength:i}=e;return e.slice(t,t+i)})(t),n=e.getWriteOffset();var[t,a]=e.tryEnd(s,i);a||t||(r.pause(),e.onWritable(t=>{var[t,a]=e.tryEnd(s.slice(t-n),i);return!a&&t&&r.resume(),t}))}).on("error",e=>{throw s(),e}).on("end",s)}},function(e){e.exports=JSON.parse('{"name":"socket.io","version":"4.5.4","description":"node.js realtime framework server","keywords":["realtime","framework","websocket","tcp","events","socket","io"],"files":["dist/","client-dist/","wrapper.mjs","!**/*.tsbuildinfo"],"directories":{"doc":"docs/","example":"example/","lib":"lib/","test":"test/"},"type":"commonjs","main":"./dist/index.js","exports":{"import":"./wrapper.mjs","require":"./dist/index.js","types":"./dist/index.d.ts"},"types":"./dist/index.d.ts","license":"MIT","repository":{"type":"git","url":"git://github.com/socketio/socket.io"},"scripts":{"compile":"rimraf ./dist && tsc","test":"npm run format:check && npm run compile && npm run test:types && npm run test:unit","test:types":"tsd","test:unit":"nyc mocha --require ts-node/register --reporter spec --slow 200 --bail --timeout 10000 test/index.ts","format:check":"prettier --check \\"lib/**/*.ts\\" \\"test/**/*.ts\\"","format:fix":"prettier --write \\"lib/**/*.ts\\" \\"test/**/*.ts\\"","prepack":"npm run compile"},"dependencies":{"accepts":"~1.3.4","base64id":"~2.0.0","debug":"~4.3.2","engine.io":"~6.2.1","socket.io-adapter":"~2.4.0","socket.io-parser":"~4.2.1"},"devDependencies":{"@types/mocha":"^9.0.0","expect.js":"0.3.1","mocha":"^10.0.0","nyc":"^15.1.0","prettier":"^2.3.2","rimraf":"^3.0.2","socket.io-client":"4.5.4","socket.io-client-v2":"npm:socket.io-client@^2.4.0","superagent":"^8.0.0","supertest":"^6.1.6","ts-node":"^10.2.1","tsd":"^0.21.0","typescript":"^4.4.2","uWebSockets.js":"github:uNetworking/uWebSockets.js#v20.0.0"},"contributors":[{"name":"Guillermo Rauch","email":"rauchg@gmail.com"},{"name":"Arnout Kazemier","email":"info@3rd-eden.com"},{"name":"Vladimir Dronnikov","email":"dronnikov@gmail.com"},{"name":"Einar Otto Stangvik","email":"einaros@gmail.com"}],"engines":{"node":">=10.0.0"},"tsd":{"directory":"test"}}')},function(e,t,i){const r=i(0);e.exports=class{constructor(e){this.keyLimit=100,this.bodyLimit=20<<20,this.contentType=null,this.timeout=1e4,e&&this.fromOptions(e)}fromOptions(e){return r(e),null!=e.keyLimit&&(r("number"==typeof e.keyLimit),this.keyLimit=e.keyLimit),null!=e.bodyLimit&&(r("number"==typeof e.bodyLimit),this.bodyLimit=e.bodyLimit),null!=e.contentType&&(r("string"==typeof e.contentType),this.contentType=e.contentType),this}}},function(e,t,i){const r=i(674),s=i(620).StringDecoder;e.exports=async function(e,t){let i=Object.create(null);if("GET"!==e.method){let h=e.contentType;if("bin"!==(h=t.contentType?t.contentType:h)){var n=await(a=e,o="utf8",c=t,new Promise((e,t)=>{{var i=a,r=c,n=e,h=t;const u=new s(o);let l=!1,p=0,d="";const f=()=>{i.removeListener("data",m),i.removeListener("error",g),i.removeListener("end",y),null!=v&&(v=null,clearTimeout(v))},m=e=>{p+=e.length,l=!0,p>r.bodyLimit?h(new Error("Request body overflow.")):d+=u.write(e)},g=e=>{f(),h(e)},y=()=>{f(),n(l?d:null)};let v=setTimeout(()=>{v=null,f(),h(new Error("Request body timed out."))},r.timeout);i.on("data",m),i.on("error",g),i.on("end",y)}}));if(n)switch(h){case"json":if(!(i=JSON.parse(n))||"object"!=typeof i||Array.isArray(i))throw new Error("JSON body must be an object.");break;case"form":i=r.parsePairs(n,t.keyLimit)}}}var a,o,c;return i}},function(e,t,i){const{generateKey:r,verifyObj:s}=i(72),n=i(67),a=i(6);e.exports=class{constructor(e){this.wdb=e}async call(e,t,i){try{var o,c=t.body.sig,h=n.getHmac(t.options.cid||"",this.wdb.keys.hmacSalt).token,u=r(a.hash256(Buffer.from(h)));if(!this.wdb.options.devMode&&!s({method:t.body.method,params:t.body.params,cid:t.body.cid,wid:t.body.wid},c,u.public))return o={result:null,code:404,error:{type:"HmacError",message:"Verify Error"}},i.send(404,o,"json"),{interrupt:!0,result:null};if(!(t.options.auth&&t.options.authWid==t.options.wid||(this.wdb.options.devMode||await this.wdb.auth(t.options.cid,t.options.token),t.body.method&&"wallet.create"===t.body.method))){var l=await this.wdb.get(t.options.wid);if(!l)return i.send(404,{result:null,code:404,error:{type:"HmacError",message:"Not Found Wallet"}},"json"),{interrupt:!0,result:null};this.wdb.logger.info("Successful auth for %s on %s.",t.options.cid,t.options.wid),t.options.auth=!0,t.options.authWid=t.options.wid,t.wallet=l}return{interrupt:!1}}catch(e){return this.wdb.logger.info("Auth failure for %s on %s: %s.",t.options.cid,t.options.wid,e.message),i.send(403,{result:null,code:403,error:{type:"HmacError",message:"Hmac Auth failure."}},"json"),{interrupt:!0,result:null}}}}},function(e,t){e.exports=class{async call(e,t,i){return e.node.config.devMode||e.node.acl.canAccess(t.body.method,t.options.cid)?{interrupt:!1}:(i.send(407,{result:null,code:407,error:{type:"ACLError",message:"TerminalNo Authentication Required."}},"json"),{interrupt:!0,result:null})}}},function(e,t){e.exports=class{constructor(e,t){this.routes=e,this.openapi=t}async call(e,t,i){switch(t.options.mode){case"web":if(0===t.pathname.indexOf("/public/")){var r=this.routes.getHandlers(t.method);if(!r)return{interrupt:!0,result:null};for(const n of r){var s=n.match(t.pathname);if(s){t.params=s;try{return{interrupt:!0,result:{code:0,error:null,result:await n.call(t,i)}}}catch(e){i.error(500,e)}return{interrupt:!0,result:null}}}}else if(r=this.openapi[t.body.method]){try{return{interrupt:!0,result:{code:0,error:null,result:await e.node.conn_s2local.execute(r.name,t.body.params,t)}}}catch(e){i.error(500,e)}return{interrupt:!0,result:null}}break;case"ws":if(r=this.openapi[t.body.method])return{interrupt:!0,result:{code:0,error:null,result:await e.node.conn_s2local.execute(r.name,t.body.params,t)}}}return{interrupt:!1}}}},function(e,t,i){const r=i(0),s=i(2),n=i(6),a=i(158);e.exports=class{constructor(e){r(e,"Basic auth requires options."),this.user=e.username,this.pass=e.password,this.realm=e.realm,null!=this.user&&(r("string"==typeof this.user),r(this.user.length<=255,"Username too long."),r(s.isAscii(this.user),"Username must be ASCII."),this.user=n.hash256(Buffer.from(this.user,"ascii"))),r("string"==typeof this.pass),r(this.pass.length<=255,"Password too long."),r(s.isAscii(this.pass),"Password must be ASCII."),this.pass=n.hash256(Buffer.from(this.pass,"ascii")),this.realm||(this.realm="server"),r("string"==typeof this.realm)}fail(e){e.setHeader("WWW-Authenticate",`Basic realm="${this.realm}"`),e.send(401,{result:null,code:401,error:{type:"AuthError",message:"Unauthorized."}},"json"),e.end()}async call(e,t,i){if(!e.node.config.devMode&&!t.options.auth){if(this.user){if(255<t.options.user.username.length)return this.fail(i),{interrupt:!0,result:null};const e=Buffer.from(t.options.user.username,"ascii"),r=n.hash256(e);if(!a(r,this.user))return this.fail(i),{interrupt:!0,result:null}}if(!t.options.user||!t.options.user.password||255<t.options.user.password.length)return this.fail(i),{interrupt:!0,result:null};const e=Buffer.from(t.options.user.password,"ascii"),r=n.hash256(e);if(!a(r,this.pass))return this.fail(i),{interrupt:!0,result:null};t.options.auth=!0}return{interrupt:!1}}}},function(e,t,i){const r=i(2),s=i(77),n=i(78).errors,a=i(84),o=i(120),{getBlockOverview:c,getBlockByHash:h,formatTimestamp:u}=i(621);e.exports=[{name:"blocks",method:"get",path:"/public/blocks",callback:async function(e,t){var i,r=(e=e.valid()).str("blockDate"),s=e.str("startTimestamp",""),n=(e=e.uint("limit",10),u(new Date));if(r){if(!/\d{4}-\d{2}-\d{2}/.test(r))throw new Error("Please use yyyy-mm-dd format");i=r===n}else r=n,i=!0;n=Math.round(new Date(r).getTime()/1e3),s=parseInt(s)||n+86400;var a=u(new Date(1e3*(n-86400))),o=s?u(new Date(1e3*s)):null,c=(e=parseInt(e||200),!1),l=s;try{var p,d=await this.chain.db.getTimestampHashes(s,n);let u=[];for(p of d)u.push(p.hash);u.reverse(),u.length>e&&(c=!0,u=u.slice(0,e));var f,m={blocks:[],length:u.length,pagination:{next:o,prev:a,currentTs:s-1,current:r,isToday:i,more:c,moreTs:c?l:void 0}};for(f of u){var g=await h(this,f,t);m.blocks.push(g)}return m.blocks.sort((e,t)=>t.height-e.height),m}catch(e){throw e}}},{name:"block-index",method:"get",path:"/public/block-index/:height",callback:async function(e,t){var i=this;if(-1===(e=(e=e.valid()).uint("height")))throw new s(n.TYPE_ERROR,"Invalid block height.");if(!(e=await i.chain.getEntry(e)))throw new s(n.MISC_ERROR,"Block not found");if(i=await h(i.node,e.hash,t))return i}},{name:"block-tip",method:"get",path:"/public/block-tip",callback:async function(e,t){var i=this;if(e.valid(),!(e=await i.chain.tip))throw new s(n.MISC_ERROR,"Block not found");if(i=await h(i.node,e.hash,t))return i}},{name:"block",method:"get",path:"/public/block/:blockHash",callback:async function(e,t){var i=this;if(e=(e=e.valid()).str("blockHash"),i=await h(i.node,e,t))return i}},{name:"getBlock",method:"jsonp",path:"/",callback:async function(e,t){return t=(t=new a([t])).str(0),h(e,t)}},{name:"rawblock",method:"get",path:"/public/rawblock/:param",callback:async function(e,t){var i=this;let a=(e=e.valid()).str("param");if(a=r.checkNum(a)?parseInt(a):r.revHex(a),e=await i.chain.getBlock(a))return e.toRaw().toString("hex");if(i.chain.options.spv)throw new s(n.MISC_ERROR,"Block not available (spv mode)");if(i.chain.options.prune)throw new s(n.MISC_ERROR,"Block not available (pruned data)");throw new s(n.DATABASE_ERROR,"Can't read block from disk")}},{name:"getRawBlock",method:"jsonp",path:"/",callback:async function(e,t){let i=(t=new a([t])).str(0);return r.checkNum(i)&&(i=parseInt(i)),(t=await e.chain.getBlock(i))?t.toRaw().toString("hex"):null}},{name:"isSynced",method:"jsonp",path:"/",callback:async function(e,t){return e.chain.synced}},{name:"getBlockOverview",method:"jsonp",path:"/",callback:async function(e,t){return t=(t=new a([t])).str(0),c(e,t)}},{name:"getInfo",method:"jsonp",path:"/",callback:async function(e,t){var i=await e.rpc.execute({corba:!0,method:"miner.difficulty"});return{blocks:e.chain.height,connections:e.pool.peers.size(),timeoffset:0,proxy:"",testnet:"main"!==e.network.type,errors:"",network:e.network.type,relayFee:0,version:"bitcore-1.1.2",protocolversion:700001,difficulty:i}}},{name:"getBestHeight",method:"jsonp",path:"/",callback:async function(e,t){return e.chain.height}},{name:"getBlockHeader",method:"jsonp",path:"/",callback:async function(e,t){var i=(t=new a([t])).hash(0);t=t.bool(1,!0);if(!i)throw new s(n.MISC_ERROR,"Invalid block hash.");if(!(i=await e.chain.getEntry(i)))throw new s(n.MISC_ERROR,"Block not found");if(!t)return i.toRaw().toString("hex",0,80);t=await e.chain.getMedianTime(i);var c=await e.chain.getNextHash(i.hash);return{hash:i.rhash(),confirmations:e.chain.height-i.height+1,height:i.height,version:i.version,versionHex:r.hex32(i.version),merkleroot:r.revHex(i.merkleRoot),time:i.time,mediantime:t,bits:i.bits,difficulty:o.bits2Diff(i.bits),chainwork:i.chainwork.toString("hex",64),previousblockhash:i.prevBlock!==encoding.NULL_HASH?r.revHex(i.prevBlock):null,nextblockhash:c?r.revHex(c):null}}}]},function(e){e.exports=JSON.parse('[{"poolName":"50BTC","url":"https://50btc.com/","searchStrings":["50BTC.com","50btc.com"]},{"poolName":"175btc","url":"http://www.175btc.com/","searchStrings":["Mined By 175btc.com"]},{"poolName":"ASICminer","url":"https://bitcointalk.org/index.php?topic=99497.0","searchStrings":["Mined By ASICMiner"]},{"poolName":"AntMiner","url":"https://bitmaintech.com/","searchStrings":["AntPool"]},{"poolName":"agentD","url":"http://","searchStrings":["agentD"]},{"poolName":"Bitfury","url":"http://bitfury.org/","searchStrings":["2av0id51pct"]},{"poolName":"BitMinter","url":"https://bitminter.com/","searchStrings":["BitMinter"]},{"poolName":"Bitparking","url":"http://bitparking.com/","searchStrings":["bitparking"]},{"poolName":"BTC Guild","url":"https://www.btcguild.com/","searchStrings":["Mined by BTC Guild","BTC Guild"]},{"poolName":"bcpool.io","url":"https://bcpool.io/","searchStrings":["bcpool"]},{"poolName":"Discus Fish","url":"http://f2pool.com/","searchStrings":["七彩神仙鱼","Made in China","Mined by user"]},{"poolName":"Discus Fish Solo","url":"http://f2pool.com/","searchStrings":["For Pierce and Paul"]},{"poolName":"Cointerra","url":"http://cointerra.com/","searchStrings":["cointerra"]},{"poolName":"Eligius","url":"http://eligius.st/","searchStrings":["Eligius"]},{"poolName":"EclipseMC","url":"https://eclipsemc.com/","searchStrings":["Josh Zerlan was here!","EclipseMC","Aluminum Falcon"]},{"poolName":"GIVE-ME-COINS","url":"https://give-me-coins.com/","searchStrings":["Mined at GIVE-ME-COINS.com"]},{"poolName":"ghash.io","url":"https://ghash.io/","searchStrings":["ghash.io","GHash.IO"]},{"poolName":"HHTT","url":"http://hhtt.1209k.com/","searchStrings":["HHTT"]},{"poolName":"KNCminer","url":"https://www.kncminer.com/","searchStrings":["KnCMiner"]},{"poolName":"Megabigpower","url":"http://megabigpower.com/","searchStrings":["megabigpower.com"]},{"poolName":"MultiCoin","url":"https://multicoin.co/","searchStrings":["MultiCoin.co"]},{"poolName":"Mt Red","url":"https://mtred.com/","searchStrings":["/mtred/"]},{"poolName":"MaxBTC","url":"https://www.maxbtc.com","searchStrings":["MaxBTC"]},{"poolName":"NMCbit","url":"http://nmcbit.com/","searchStrings":["nmcbit.com"]},{"poolName":"ozcoin","url":"https://ozco.in/","searchStrings":["ozco.in","ozcoin"]},{"poolName":"Polmine.pl","url":"https://polmine.pl","searchStrings":["by polmine.pl"]},{"poolName":"simplecoin","url":"http://simplecoin.us/","searchStrings":["simplecoin.us ftw"]},{"poolName":"SlushPool","url":"https://slushpool.com/","searchStrings":["/slush/"]},{"poolName":"TripleMining","url":"https://www.triplemining.com/","searchStrings":["Triplemining.com"]},{"poolName":"wizkid057","url":"http://wizkid057.com/btc","searchStrings":["wizkid057"]},{"poolName":"Yourbtc.net","url":"http://yourbtc.net/","searchStrings":["yourbtc.net"]},{"poolName":"BTCChina Pool","url":"https://pool.btcchina.com/","searchStrings":["BTCChina Pool","btcchina.com"]},{"poolName":"BTCC Pool","url":"https://pool.btcc.com/","searchStrings":["/BTCC/"]}]')},function(e,t,i){const{utxo:r,_setOutputResults:s,_setInputResults:n,transformTransaction:a,getDetailFromMeta:o,translateOutputAddress:c}=i(621),h=i(32),u=i(84),l=i(2);async function p(e,t){var i=(t=new u([t])).array(0,[]),r=t.obj(1,{}),s=(r.from=r.from||0,r.to=r.to||4294967295,[]);t=await e.getMetaByAddress(i);let n=0;for(const i of t){if(n<r.from);else{if(n>=r.to)break;var a=await o(e,i);s.push(a)}n++}return{totalCount:t.length,items:s}}async function d(e,t){let i=(r=e.valid()).str("addr");i=i||r.str("addrs");var r,s=((r={from:parseInt(e.query.from)||parseInt(e.body.from)||0}).to=parseInt(e.query.to)||parseInt(e.body.to)||parseInt(r.from)+10,e=e,{noAsm:!!parseInt(e.query.noAsm),noScriptSig:!!parseInt(e.query.noScriptSig),noSpent:!!parseInt(e.query.noSpent)});try{var n,c=await this.node.getMetaByAddress(i.split(",")),h=[];for(n of c){var u=await o(this.node,n);h.push(await a(this.node,u,s))}return{totalItems:c.length,from:r.from,to:Math.min(r.to,c.length),items:h}}catch(e){throw e}}async function f(e,t){var i=e.valid();let s=i.str("addr");s=s||i.str("addrs"),e.query.from&&e.query.to&&(parseInt(e.query.from),parseInt(e.query.to));try{var n,a=[];for(n of await r(this.node,s.split(",")))a.push(function(e,t){var i={address:c(t.address),txid:l.revHex(t.txid),vout:t.vout,scriptPubKey:t.scriptPubKey,amount:t.satoshis/1e8,satoshis:t.satoshis};return t.height&&0<t.height?(i.height=t.height,i.confirmations=e.chain.height-t.height+1):i.confirmations=0,t.timestamp&&(i.ts=t.timestamp),i}(this,n));return a}catch(e){throw e}}async function m(e,t){var i=(e=e.valid()).str("id"),r=(e=e.uint("index",1),this.node.require("walletdb"));if(r&&(r=await r.get("primary"),await r.ensureAccount({name:i,witness:!0}),r=await r.createReceive(i,e)))return r.toJSON().address}async function g(e,t,i){i=i||{};var r={totalCount:0,items:[]};let a=0;for(const s of await e.node.getMetaByAddress(t)){if(i.from&&a<i.from);else{if(i.to&&a>=i.to)break;var u=await o(e.node,s);r.items.push(u)}a++}r.totalCount=r.items.length;for(var p={addrStr:t,balance:0,balanceSat:0,totalReceived:0,totalReceivedSat:0,totalSent:0,totalSentSat:0,unconfirmedBalance:0,unconfirmedBalanceSat:0,unconfirmedTxApperances:0,txApperances:0},d=0;d<r.items.length;d++){var f=r.items[d];s(e,f,t,p),n(e,f,t,p),i.noTxList||(p.transactions||(p.transactions=[]),p.transactions.push(l.revHex(f.txid())))}return p.balance=h.fromSatoshis(p.balanceSat).toBTC(),p.totalReceived=h.fromSatoshis(p.totalReceivedSat).toBTC(),p.totalSent=h.fromSatoshis(p.totalSentSat).toBTC(),p.unconfirmedBalance=h.fromSatoshis(p.unconfirmedBalanceSat).toBTC(),p.addrStr&&(p.addrStr=c(p.addrStr)),p}e.exports=[{name:"address.reflect",method:"get",path:"/public/addr/reflect/:id",callback:m},{name:"address.reflect.index",method:"get",path:"/public/addr/reflect/:id/:index",callback:m},{name:"getInfo",method:"get",path:"/public/addr/:addr",callback:async function(e,t){var i=(i=e.valid()).str("addr"),r={noTxList:parseInt(e.query.noTxList)};e.query.from&&e.query.to?(r.from=parseInt(e.query.from),r.to=parseInt(e.query.to)):(r.from=0,r.to=10);try{return await g(this,i,r)}catch(e){throw e}}},{name:"getUTXOByAddress",method:"get",path:"/public/addr/:addr/utxo",callback:f},{name:"getUTXOByAddresses",method:"get",path:"/public/addrs/:addr/utxo",callback:f},{name:"postUTXOByAddresses",method:"post",path:"/public/addrs/utxo",callback:f},{name:"getTXSByAddresses",method:"get",path:"/public/addrs/:addrs/txs",callback:d},{name:"postTXSByAddresses",method:"post",path:"/public/addrs/txs",callback:d},{name:"getBalanceByAddress",method:"get",path:"/public/addr/:addr/balance",callback:async function(e,t){var i=this;let r=(e=e.valid()).str("addr");r=r||e.str("addrs"),e=await i.node.getCoinsByAddress(r.split(","));var s=(i=e.reduce((e,t)=>e+t.value,0))-(e=e.reduce((e,t)=>(-1==t.height&&(e+=t.value),e),0));return{confirmed:h.fromSatoshis(s).toBTC(),unconfirmed:h.fromSatoshis(e).toBTC(),balance:h.fromSatoshis(i).toBTC()}}},{name:"getUnconfirmedBalance",method:"get",path:"/public/addr/:addr/unconfirmedBalance",callback:async function(e,t){var i=this;let r=(e=e.valid()).str("addr");return r=r||e.str("addrs"),e=await i.node.getCoinsByAddress(r.split(",")),i=e.reduce((e,t)=>(-1==t.height&&(e+=t.value),e),0),h.fromSatoshis(i).toBTC()}},{name:"getTotalReceived",method:"get",path:"/public/addr/:addr/totalReceived",callback:async function(e,t){let i=(e=e.valid()).str("addr");i=i||e.str("addrs");try{return(await g(this,i)).totalReceivedSat}catch(e){throw e}}},{name:"getTotalSent",method:"get",path:"/public/addr/:addr/totalSent",callback:async function(e,t){let i=(e=e.valid()).str("addr");i=i||e.str("addrs");try{return(await g(this,i)).totalSent}catch(e){throw e}}},{name:"getAddressHistory",method:"jsonp",path:"/",callback:p},{name:"getAddressSummary",method:"jsonp",path:"/",callback:async function(e,t){var i=new u([t]),r=i.array(0,[]),a=i.obj(1,{});a.from=a.from||0,a.to=a.to||4294967295;for(var o={addrStr:r,balance:0,balanceSat:0,totalReceived:0,totalReceivedSat:0,totalSent:0,totalSentSat:0,unconfirmedBalance:0,unconfirmedBalanceSat:0,unconfirmedTxApperances:0,txApperances:0},c=(i=await p(e,t)).items,l=0;l<c.length;l++){var d=c[l];s(e,d,r,o),n(e,d,r,o),a.noTxList||(o.transactions||(o.transactions=[]),o.transactions.push(d.txid()))}return o.balance=h.fromSatoshis(o.balanceSat).toBTC(),o.totalReceived=h.fromSatoshis(o.totalReceivedSat).toBTC(),o.totalSent=h.fromSatoshis(o.totalSentSat).toBTC(),o.unconfirmedBalance=h.fromSatoshis(o.unconfirmedBalanceSat).toBTC(),o}},{name:"getAddressUnspentOutputs",method:"jsonp",path:"/",callback:async function(e,t){return t=(t=new u([t])).array(0,[]),e=await r(e,t)}},{name:"getTxidsByAddress",method:"jsonp",path:"/",callback:async function(e,t){var i=(t=new u([t])).array(0);t=t.str(1,"both");return e.chain.getHashesByAddress(i,t)}}]},function(e,t,i){var r=i(82);const s=i(32),n=i(84);var a=i(329),o=0,c=Date.now();async function h(e){var t=await e.rpc.execute({corba:!0,method:"miner.difficulty"});return{blocks:e.chain.height,connections:e.node.pool.peers.size,timeoffset:0,proxy:"",testnet:"main"!==e.node.network.type,errors:"",network:e.node.network.type,relayFee:0,version:"gamegold-"+r.version,protocolversion:700001,difficulty:t}}e.exports=[{name:"getStatus",method:"get",path:"/public/status",callback:async function(e,t){switch(e.query.q){case"getDifficulty":try{return{difficulty:(await h(this)).difficulty}}catch(e){throw e}break;case"getLastBlockHash":var i=await this.chain.db.getTip();return{syncTipHash:i.hash,lastblockhash:i.hash};case"getBestBlockHash":try{return{bestblockhash:await this.rpc.execute({corba:!0,method:"block.best"})}}catch(e){throw e}break;default:try{return{info:await h(this)}}catch(e){throw e}}}},{name:"getSync",method:"get",path:"/public/sync",callback:async function(e,t){var i="syncing";try{this.chain.synced&&(i="finished");var r=(100*this.chain.getProgress()).toFixed(2);return{status:i,blockChainHeight:this.chain.height,syncPercentage:Math.round(r),height:this.chain.height,error:null,type:"gamegold node"}}catch(e){throw e}}},{name:"getVersion",method:"get",path:"/public/version",callback:async function(e,t){return{version:r.version}}},{name:"getPeer",method:"get",path:"/public/peer",callback:function(e,t){var i=this.pool.getLoader()||{connected:!1,address:{host:null,port:null}};return{connected:i.connected,host:i.address.host,port:i.address.port}}},{name:"getEstimateFee",method:"get",path:"/public/utils/estimatefee",callback:function(e,t){e=(e.query.nbBlocks||"2").split(",");try{var i,r={};for(i of e){var n=parseInt(i);let e=this.fees.estimateFee(n,!1);0===e&&(e=-1),e=s.btc(e,!0),r[n]=e}return r}catch(e){throw e}}},{name:"estimateFee",method:"jsonp",path:"/",callback:function(e,t){t=(t=new n([t])).array(0,["2"]);try{var i,r={};for(i of t){var a=parseInt(i);let t=e.fees.estimateFee(a,!1);0===t&&(t=-1),t=s.btc(t,!0),r[a]=t}return r}catch(t){throw t}}},{name:"currency",method:"get",path:"/public/currency",callback:async function(e,t){var i=Date.now();if(!(0===o||c+6e5<=i))return{status:200,data:{bitstamp:o}};c=i;try{var r=await new Promise((e,t)=>{a("https://www.bitstamp.net/api/ticker/",(function(i,r,s){i&&t(i),i||200!==r.statusCode||e(s)}))});return{status:200,data:{bitstamp:o=parseFloat(JSON.parse(r).last)}}}catch(e){throw e}}},{name:"explorers",method:"get",path:"/public/explorers",callback:async function(e,t){return[{name:"gamegold",ticker:"GG",url:"https://insight.gamegold.xin"}]}},{name:"syncPercentage",method:"jsonp",path:"/",callback:async function(e,t){return Math.round((100*e.chain.getProgress()).toFixed(2))}},{name:"sysEcho",method:"jsonp",path:"/",callback:function(e,t){return 0}},{name:"getBestBlockHash",method:"jsonp",path:"/",callback:async function(e,t){return{bestblockhash:e=await e.rpc.execute({corba:!0,method:"block.best"})}}}]},function(e,t,i){const r=i(677),s=i(0),n=i(2),{handleErrors:a,getDetailedTransaction:o,transformTransaction:c,getDetailFromMeta:h,getBlockOverview:u,translateInputAddresses:l}=i(621),p=i(84);e.exports=[{name:"getTx",method:"get",path:"/public/tx/:txid",callback:async function(e,t){return e=(e=e.valid()).hash("txid"),(e=await o(this.node,e))?await c(this.node,e,{}):null}},{name:"getRawTx",method:"get",path:"/public/rawtx/:txid",callback:async function(e,t){return e=(e=e.valid()).str("txid"),{rawtx:e=await this.rpc.execute({method:"tx.raw.get",params:[e]})}}},{name:"getList",method:"get",path:"/public/txs",callback:async function(e,t){s(!this.chain.options.spv,"Cannot get TX in SPV mode.");var i,p=e.query.blockHash,d=l(e.query.address),f=(e=parseInt(e.query.pageNum)||0,1);if(p){if(!(p=await u(this.node,p,t)))return a(null,t);t=p.txids.length;var m,g,y=(r.isUndefined(e)?i=p.txids:(m=10*e,i=p.txids.slice(m,10+m),f=Math.ceil(t/10)),[]);for(g of i){var v=await o(this.node,n.revHex(g));v&&y.push(await c(this.node,v,{}))}return{pagesTotal:f,txs:y}}if(d){var b=10*e,w=10*(e+1),k=[];p=await this.node.getMetaByAddress(d);let t=0;for(const e of p){if(t<b);else{if(t>=w)break;var x=await h(this.node,e);k.push(await c(this.node,x,{}))}t++}return{pagesTotal:Math.ceil(p.length/10),txs:k}}throw new Error("Block hash or address expected")}},{name:"getDetailedTransaction",method:"jsonp",path:"/",callback:async function(e,t){return t=(t=new p([t])).hash(0),o(e,t,!0)}},{name:"getTransaction",method:"jsonp",path:"/",callback:async function(e,t){return t=(t=new p([t])).hash(0),e=await o(e,t,!1)}},{name:"getRawTransaction",method:"jsonp",path:"/",callback:async function(e,t){return t=(t=new p([t])).str(0),e=await e.rpc.execute({method:"tx.raw.get",params:[t]})}},{name:"getMempoolTransaction",method:"jsonp",path:"/",callback:async function(e,t){return t=(t=new p([t])).hash(0),e.mempool.getTX(t)}}]},function(e,t,i){const r=i(20).opcodes,s=i(2).revHex;e.exports=[{name:"prop.get",method:"get",path:"/public/prop/:pid",callback:async function(e,t){var i=[];e=e.valid().str("pid");if(e=await this.node.chain.db.propList.getVp(e)){var n=e.current.hash;e.oper="exchange",i.push({oper:"exchange",pid:e.pid,oid:e.oid,cid:e.cid,current:{hash:s(e.current.hash),index:e.current.index,address:e.current.address},height:e.height});let t=[n,e.current.index];for(;;){var a=await this.node.getMeta(t[0]),o=a.tx;if(!o)break;if(!(o=o.outputs[t[1]]))break;var c=o.getReturnData([r.OP_PROPCREATE,r.OP_PROPEXCHANGE]);if(!c)break;if("new"==c.oper){c.current={hash:s(t[0]),index:t[1],address:o.getAddress().toString()},c.height=a.height,i.push(c);break}if(!c.prev)break;t=[c.prev.hash,c.prev.index]}}return i}},{name:"queryProps",method:"post",path:"/public/prop/query",callback:async function(e,t){var i=(e=e.valid()).str("game_id");e=e.str("user_addr");return await this.node.queryProps(i,e)}},{name:"queryProps",method:"get",path:"/public/prop/:game_id/addr/:user_addr",callback:async function(e,t){var i=(e=e.valid()).str("game_id");e=e.str("user_addr");return await this.node.queryProps(i,e)}},{name:"queryProps",method:"get",path:"/public/props/query",callback:async function(e,t){var i=(e=e.valid()).str("pid"),r=e.str("cid"),s=e.str("oid"),n=e.str("addr");e=e.str("page");return await this.node.queryProps(r,n,i,s,e)}}]},function(e,t,i){const r=i(84);e.exports=[{name:"cp.remoteQuery",method:"jsonp",path:"/",callback:async function(e,t){return t=(t=new r([t])).array(0,[]),e.chain.db.cpList.query(t)},remoteCb:async function(e){if(e&&Array.isArray(e.list))for(var t of e.list)this.wdb.cpList.getItem(t.cid)||await this.wdb.cpList.addItem(t);return e}},{name:"cps",method:"get",path:"/public/cps",callback:async function(e,t){return e={page:e.valid().u32("page",1),pageCount:0},{list:this.chain.db.cpList.getCPList([],e),cur:e.page,page:e.pageCount}}},{name:"cpById",method:"get",path:"/public/cp/:id",callback:async function(e,t){var i=(e=e.valid()).u32("page",1);e=e.str("id");return(e=this.chain.db.cpList.getCPList(e?[e]:[],{page:i}))&&0<e.length?e[0]:null}},{name:"cpByName",method:"get",path:"/public/cp/name/:name",callback:async function(e,t){var i=(e=e.valid()).u32("page",1);e=decodeURIComponent(e.str("name"));return(e=this.chain.db.cpList.getCPListByName(e?[e]:[],{page:i}))&&0<e.length?e[0]:null}}]},function(e,t,i){const r=i(84),s=i(100),n=i(77),a=i(78).errors,o=i(67),c=i(5).ContractStatus,h=i(19),u=i(32);e.exports=[{name:"token.random",local:!0,method:"jsonp",path:"/",callback:async function(e,t,i){if(1!==t.length)throw new n(a.MISC_ERROR,"token.random clientNo: 生成令牌随机量 终端编码");return t=new r([t]).str(0),t=o.getHmac(t,e.keys.hmacSalt).random}},{name:"mempool.watch",method:"jsonp",path:"/",callback:async function(e,t,i){i&&i.join("mempool")}},{name:"mempool.unwatch",method:"jsonp",path:"/",callback:async function(e,t,i){i&&i.leave("mempool")}},{name:"chain.watch",method:"jsonp",path:"/",callback:async function(e,t,i){i&&i.join("chain")}},{name:"chain.unwatch",method:"jsonp",path:"/",callback:async function(e,t,i){i&&i.leave("chain")}},{name:"chain.rescan",method:"jsonp",path:"/",callback:async function(e,t,i){if(null==(t=new r([t]).numhash(0)))throw new Error("Invalid parameter.");return e.http.scan(i,t)}},{name:"subscribe",local:!0,method:"jsonp",path:"/",callback:async function(e,t,i){if(i&&Array.isArray(t))for(var r of t)i.bus.subscribe(r);return!0}},{name:"unsubscribe",local:!0,method:"jsonp",path:"/",callback:async function(e,t,i){if(i&&Array.isArray(t))for(var r of t)i.bus.unsubscribe(r);return!0}},{name:"filter.set",local:!0,method:"jsonp",path:"/",callback:async function(e,t,i){if(i){if(t=new r([t]).buf(0))return i.filter=s.fromRaw(t),null;throw new Error("Invalid parameter.")}}},{name:"filter.reset",local:!0,method:"jsonp",path:"/",callback:async function(e,t,i){i&&(i.filter=null)}},{name:"filter.add",local:!0,method:"jsonp",path:"/",callback:async function(e,t,i){if(i){var s=new r([t]).array(0);if(!s)throw new Error("Invalid parameter.");if(!i.filter)throw new Error("No filter set.");for(let t=0;t<s.length;t++){var n=s[t];if(!n)throw new Error("Bad data chunk.");i.filter.add(n),e.spv&&e.pool.watch(n)}}}},{name:"canExecute",method:"jsonp",path:"/",callback:async function(e,t){return(t=new r([t]).obj(0,{})).confirm||"cpChange"==t.oper?e.chain.db.cpList.canExecute(t):await e.mempool.cpMemList.canExecute(t)&&await e.chain.db.cpList.canExecute(t)}},{name:"contract.list",method:"jsonp",path:"/",callback:async function(e,t){var i,s,n,a;return 0==t.length?"contract.list type page ids size: 查询并返回交易对 交易类型 指定查询的ID数组 页码":(a=(t=new r([t])).uint(0,1),i=t.uint(1,1),s=t.array(2,[]),t=t.int(3,10),(n=[]).push(["transStatus",c.CreatedOnMem]),a&&n.push(["type",a]),0<s.length&&n.push(["id","include",s]),{pageNum:(a=e.chain.db.transactionList.where(n).paginate(t,i)).pageNum,pageCur:a.pageCur,list:a.records()})},remoteCb:async function(e){if(e&&Array.isArray(e.list))for(var t of e.list)this.wdb.transactionList.saveContract(t,!0);return e}},{name:"queryProps",method:"jsonp",path:"/",callback:async function(e,t){var i=(t=new r([t])).str(0,"");t=t.str(1,"");return e.queryProps(i,t)}},{name:"block.tip",method:"jsonp",path:"/",callback:async function(e,t){return e.chain.tip.toRaw()}},{name:"block.entry",method:"jsonp",path:"/",callback:async function(e,t){if(null==(t=new r([t]).numhash(0)))throw new Error("Invalid parameter.");return(t=await e.chain.getEntry(t))&&await e.chain.isMainChain(t)?t.toRaw():null}},{name:"$tx.broadcast",method:"jsonp",path:"/",callback:async function(e,t,i){t=new r([t]).buf(0),t=h.fromRaw(t),await e.sendTX(t)}},{name:"$estimate.fee",method:"jsonp",path:"/",callback:async function(e,t){if(t=new r([t]).u32(0,1),e.fees)return 0===(e=e.fees.estimateFee(t,!1))?-1:u.btc(e,!0);throw new n(a.MISC_ERROR,"Fee estimation not available.")}}]},function(e,t,i){const r=i(84),s=i(779);e.exports=[{name:"ca.get",method:"get",path:"/public/ca/:erid",callback:async function(e,t){return e=e.valid().str("erid"),(e=await this.node.chain.db.erList.query([["erid",e]])).height=this.node.chain.height,e}},{name:"ca.rank",method:"jsonp",path:"/",callback:async function(e,t){return t=(t=new r([t])).str(0,""),(e=await(async e=>new Promise((t,i)=>{s(e,.85,1e-4,(function(e,r){e?i(e):t(r)}))}))(e.chain.db.enCpList.rank))[t]},remoteCb:async function(e){return e}},{name:"ca.list",method:"jsonp",path:"/",callback:async function(e,t){return t=(t=new r([t])).array(0,[]),(t=await e.chain.db.erList.query(t)).height=e.chain.height,t}},{name:"ca.verify",method:"jsonp",path:"/",callback:async function(e,t){return t=(t=new r([t])).str(0,""),(t=await e.chain.db.caVerify(t))&&(t.curHeight=e.chain.height),t},remoteCb:async function(e){return e}},{name:"ca.list.ab",method:"jsonp",path:"/",callback:async function(e,t){return t=(t=new r([t])).array(0,[]),e.chain.db.erAbList.query(t)},remoteCb:async function(e){return e}}]},function(e,t,i){"use strict";class r{constructor(e,t,i,r,s){this.outgoingNodes=e,this.linkProb=t,this.tolerance=i,this.callback=r,this.pageCount=Object.keys(this.outgoingNodes).length,this.coeff=(1-t)/this.pageCount,this.probabilityNodes=e instanceof Array?[]:{},this.incomingNodes=e instanceof Array?[]:{},this.debug=s,this.startRanking()}startRanking(){var e,t,i,r=1/this.pageCount,s=this.outgoingNodes;for(e in s)for(t in this.probabilityNodes[e]=r,s[e])i=s[e][t],this.incomingNodes[i]||(this.incomingNodes[i]=[]),this.incomingNodes[i].push(e);this.debug&&this.reportDebug(1),this.iterate(1)}reportDebug(e){console.log("____ITERATION "+e+"____"),console.log("Pages: "+Object.keys(this.outgoingNodes).length),console.log("outgoing %j",this.outgoingNodes),console.log("incoming %j",this.incomingNodes),console.log("probability %j",this.probabilityNodes)}iterate(e){var t,i,r,s,n,a=[],o={};for(t in this.probabilityNodes){if(r=0,this.incomingNodes[t])for(i=0;i<this.incomingNodes[t].length;i++)r+=this.probabilityNodes[this.incomingNodes[t][i]]/this.outgoingNodes[this.incomingNodes[t][i]].length;s=this.coeff+this.linkProb*r,n=this.probabilityNodes[t]+this.tolerance,this.probabilityNodes[t]-this.tolerance<=s&&s<=n&&a.push(o[t]=s),this.probabilityNodes[t]=s}return a.length==this.pageCount?this.outgoingNodes instanceof Array?this.callback(null,a):this.callback(null,o):(this.debug&&this.reportDebug(e),this.iterate(++e))}}e.exports=function(e,t,i,s,n=!1){if(e&&t&&i&&s)return new r(e,t,i,s,n);throw new Error("Provide 4 arguments: nodeMatrix, link probability, tolerance, callback")}},function(e,t,i){"use strict";e.exports=class{constructor(e){this.config=e,this.hmacConnection=this.config.array("hmac-connection")||[],this.config.hmacConnection=this.hmacConnection}add(e){-1==this.hmacConnection.indexOf(e)&&this.hmacConnection.push(e),this.config.hmacConnection=this.hmacConnection}del(e){-1!=(e=this.hmacConnection.indexOf(e))&&(this.hmacConnection.splice(e,1),this.config.hmacConnection=this.hmacConnection)}clear(){this.hmacConnection=[],this.config.hmacConnection=this.hmacConnection}content(){return this.hmacConnection}has(e){return-1!=this.hmacConnection.indexOf(e)}}},function(e,t,i){"use strict";
|
|
1694
1694
|
/*!
|
|
1695
1695
|
* mempool/index.js - mempool for vallnet
|
|
1696
1696
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|