gamegold 5.6.9 → 5.6.12
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
|
@@ -154,7 +154,7 @@ let r=[];[i(558),i(559),i(560),i(561),i(562),i(563),i(564),i(565),i(566),i(567),
|
|
|
154
154
|
* private.js - hd private keys for vallnet
|
|
155
155
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
156
156
|
* https://github.com/bookmansoft/gamegold
|
|
157
|
-
*/const r=i(0),a=i(2),s=i(6),n=i(94),o=i(70),c=i(26),u=i(15),h=i(4),l=i(1),p=i(69),d=i(3),f=i(140),m=i(197),g=i(304);class v{constructor(e){if(!(this instanceof v))return new v(e);this.disableCache=!1,this.network=u.primary,this.depth=0,this.parentFingerPrint=0,this.childIndex=0,this.chainCode=d.ZERO_HASH,this.privateKey=d.ZERO_HASH,this.publicKey=d.ZERO_KEY,this.fingerPrint=-1,this._xprivkey=null,this._hdPublicKey=null,e&&this.fromOptions(e)}static getHmac(e,t){t=t||d.DefaultChainCode;t=v.fromKey(s.sha256(Buffer.concat([Buffer.from(e),t])),t);var i={id:"primary"};i.cid=e,i.pubkey=t.publicKey.toString("hex"),i.time=a.now()/3600|0,e=s.hash256(Buffer.from(a.stringify(i))),e=c.sign(e,t.privateKey).toString("hex");return{token:i.pubkey,random:e}}fromOptions(e){return r(e,"No options for HD private key."),r(a.isU8(e.depth)),r(a.isU32(e.parentFingerPrint)),r(a.isU32(e.childIndex)),r(Buffer.isBuffer(e.chainCode)),r(Buffer.isBuffer(e.privateKey)),e.network&&(this.network=u.get(e.network)),this.depth=e.depth,this.parentFingerPrint=e.parentFingerPrint,this.childIndex=e.childIndex,this.chainCode=e.chainCode,this.privateKey=e.privateKey,this.publicKey=c.publicKeyCreate(e.privateKey,!0),this}static fromOptions(e){return(new v).fromOptions(e)}toPublic(){let e=this._hdPublicKey;return e||((e=new g).network=this.network,e.depth=this.depth,e.parentFingerPrint=this.parentFingerPrint,e.childIndex=this.childIndex,e.chainCode=this.chainCode,e.publicKey=this.publicKey,this._hdPublicKey=e),e}xprivkey(){return this._xprivkey||(this._xprivkey=this.toBase58()),this._xprivkey}xpubkey(){return this.toPublic().xpubkey()}destroy(e){this.depth=0,this.childIndex=0,this.parentFingerPrint=0,n(this.chainCode),n(this.privateKey),n(this.publicKey),this.fingerPrint=-1,this._hdPublicKey&&(e&&this._hdPublicKey.destroy(),this._hdPublicKey=null),this._xprivkey=null}derive(e,t){if(r("number"==typeof e),e>>>0!==e)throw new Error("Index out of range.");if(255<=this.depth)throw new Error("Depth too high.");if((t&&(e=(e|f.HARDENED)>>>0),t=this.getID(e),!this.disableCache)&&(i=f.cache.get(t)))return i;var i=h.pool(37),a=(i=(e&f.HARDENED?(i.writeU8(0),i.writeBytes(this.privateKey)):i.writeBytes(this.publicKey),i.writeU32BE(e),i.render()),(i=s.hmac("sha512",i,this.chainCode)).slice(0,32));i=i.slice(32,64);let n;try{n=c.privateKeyTweakAdd(this.privateKey,a)}catch(t){return this.derive(e+1)}return-1===this.fingerPrint&&(a=s.hash160(this.publicKey),this.fingerPrint=a.readUInt32BE(0,!0)),(a=new v).disableCache=this.disableCache,a.network=this.network,a.depth=this.depth+1,a.parentFingerPrint=this.fingerPrint,a.childIndex=e,a.chainCode=i,a.privateKey=n,a.publicKey=c.publicKeyCreate(n,!0),this.disableCache||f.cache.set(t,a),a}getID(e){return this.network.keyPrefix.xprivkey58+this.publicKey.toString("hex")+e}deriveAccount(e,t){return r(a.isU32(e),"Purpose must be a number."),r(a.isU32(t),"Account index must be a number."),r(this.isMaster(),"Cannot derive account index."),this.derive(e,!0).derive(this.network.keyPrefix.coinType,!0).derive(t,!0)}isMaster(){return f.isMaster(this)}isAccount(e){return f.isAccount(this,e)}static isBase58(e,t){if("string"!=typeof e)return!1;if(e.length<4)return!1;e=e.substring(0,4);try{return u.fromPrivate58(e,t),!0}catch(e){return!1}}static isRaw(e,t){if(!Buffer.isBuffer(e))return!1;if(e.length<4)return!1;e=e.readUInt32BE(0,!0);try{return u.fromPrivate(e,t),!0}catch(e){return!1}}static isValidPath(e){try{return f.parsePath(e,!0),!0}catch(e){return!1}}derivePath(e){let t=this;for(const i of f.parsePath(e,!0))t=t.derive(i);return t}equals(e){return r(v.isHDPrivateKey(e)),this.network===e.network&&this.depth===e.depth&&this.parentFingerPrint===e.parentFingerPrint&&this.childIndex===e.childIndex&&this.chainCode.equals(e.chainCode)&&this.privateKey.equals(e.privateKey)}compare(e){r(v.isHDPrivateKey(e));var t=this.depth-e.depth;return 0!=t||0!=(t=this.parentFingerPrint-e.parentFingerPrint)||0!=(t=this.childIndex-e.childIndex)||0!==(t=this.chainCode.compare(e.chainCode))||0!==(t=this.privateKey.compare(e.privateKey))?t:0}fromSeed(e,t){if(r(Buffer.isBuffer(e)),8*e.length<f.MIN_ENTROPY||8*e.length>f.MAX_ENTROPY)throw new Error("Entropy not in range.");var i=(e=s.hmac("sha512",e,d.SEED_SALT)).slice(0,32);e=e.slice(32,64);if(c.privateKeyVerify(i))return this.network=u.get(t),this.depth=0,this.parentFingerPrint=0,this.childIndex=0,this.chainCode=e,this.privateKey=i,this.publicKey=c.publicKeyCreate(i,!0),this;throw new Error("Master private key is invalid.")}static fromSeed(e,t){return(new v).fromSeed(e,t)}fromMnemonic(e,t){return r(e instanceof m),this.fromSeed(e.toSeed(),t)}static fromMnemonic(e,t){return(new v).fromMnemonic(e,t)}fromPhrase(e,t){return e=m.fromPhrase(e),this.fromMnemonic(e,t),this}static fromPhrase(e,t){return(new v).fromPhrase(e,t)}static getAes(e,t){var i=Buffer.from(e),r=Buffer.alloc(32);for(let e=0;e<Math.max(32,i.length);e++){var a=e%32;r[a]=i[a]^d.RANDOM_HASH[a]}return v.fromKey(d.RANDOM_HASH,r,t).getAes(e)}fromKey(e,t,i){return r(Buffer.isBuffer(e)&&32===e.length),r(Buffer.isBuffer(t)&&32===t.length),this.network=u.get(i),this.depth=0,this.parentFingerPrint=0,this.childIndex=0,this.chainCode=t,this.privateKey=e,this.publicKey=c.publicKeyCreate(e,!0),this}getAes(e){e=v.getHmac(e,this.chainCode).token;let t=s.hash256(Buffer.from(e));return{aeskey:t.toString("base64").slice(0,32),aesiv:(t=s.hash256(t)).toString("base64").slice(0,16)}}static fromKey(e,t,i){return(new v).fromKey(e,t,i)}static eccEncrypt(e,t){var i=v.generate(),{aeskey:t,aesiv:r}=(t=c.ecdh(t,i.privateKey),v.getAes(t.toString()));return{pub:i.publicKey,msg:a.encrypt(t,r,Buffer.from(e).toString("hex"))}}static eccDecrypt(e,t){t=c.ecdh(e.pub,t);var{aeskey:t,aesiv:i}=v.getAes(t.toString());return Buffer.from(a.decrypt(t,i,e.msg),"hex").toString()}static generate(e){var t=c.generatePrivateKey(),i=o.randomBytes(32);return v.fromKey(t,i,e)}fromBase58(e,t){return r("string"==typeof e),this._xprivkey=e,this.fromRaw(p.decode(e),t)}fromReader(e,t){var i=e.readU32BE();return this.network=u.fromPrivate(i,t),this.depth=e.readU8(),this.parentFingerPrint=e.readU32BE(),this.childIndex=e.readU32BE(),this.chainCode=e.readBytes(32),r(0===e.readU8()),this.privateKey=e.readBytes(32),this.publicKey=c.publicKeyCreate(this.privateKey,!0),e.verifyChecksum(),this}fromRaw(e,t){return this.fromReader(new l(e),t)}toBase58(e){return p.encode(this.toRaw(e))}getSize(){return 82}toWriter(e,t){return t=t||this.network,t=u.get(t),e.writeU32BE(t.keyPrefix.xprivkey),e.writeU8(this.depth),e.writeU32BE(this.parentFingerPrint),e.writeU32BE(this.childIndex),e.writeBytes(this.chainCode),e.writeU8(0),e.writeBytes(this.privateKey),e.writeChecksum(),e}toRaw(e){return this.toWriter(new h(82),e).render()}static fromBase58(e,t){return(new v).fromBase58(e,t)}static fromReader(e,t){return(new v).fromReader(e,t)}static fromRaw(e,t){return(new v).fromRaw(e,t)}toJSON(){return{xprivkey:this.xprivkey(),pubkey:this.publicKey.toString("hex")}}fromJSON(e,t){return r(e.xprivkey,"Could not handle key JSON."),this.fromBase58(e.xprivkey,t),this}static fromJSON(e,t){return(new v).fromJSON(e,t)}static isHDPrivateKey(e){return e instanceof v}}e.exports=v},function(e,t,i){"use strict";
|
|
157
|
+
*/const r=i(0),a=i(2),s=i(6),n=i(94),o=i(70),c=i(26),u=i(15),h=i(4),l=i(1),p=i(69),d=i(3),f=i(140),m=i(197),g=i(304);class v{constructor(e){if(!(this instanceof v))return new v(e);this.disableCache=!1,this.network=u.primary,this.depth=0,this.parentFingerPrint=0,this.childIndex=0,this.chainCode=d.ZERO_HASH,this.privateKey=d.ZERO_HASH,this.publicKey=d.ZERO_KEY,this.fingerPrint=-1,this._xprivkey=null,this._hdPublicKey=null,e&&this.fromOptions(e)}static getHmac(e,t){t=t||d.DefaultChainCode;t=v.fromKey(s.sha256(Buffer.concat([Buffer.from(e),t])),t);var i={id:"primary"};i.cid=e,i.pubkey=t.publicKey.toString("hex"),i.time=a.now()/3600|0,e=s.hash256(Buffer.from(a.stringify(i))),e=c.sign(e,t.privateKey).toString("hex");return{token:i.pubkey,random:e}}fromOptions(e){return r(e,"No options for HD private key."),r(a.isU8(e.depth)),r(a.isU32(e.parentFingerPrint)),r(a.isU32(e.childIndex)),r(Buffer.isBuffer(e.chainCode)),r(Buffer.isBuffer(e.privateKey)),e.network&&(this.network=u.get(e.network)),this.depth=e.depth,this.parentFingerPrint=e.parentFingerPrint,this.childIndex=e.childIndex,this.chainCode=e.chainCode,this.privateKey=e.privateKey,this.publicKey=c.publicKeyCreate(e.privateKey,!0),this}static fromOptions(e){return(new v).fromOptions(e)}toPublic(){let e=this._hdPublicKey;return e||((e=new g).network=this.network,e.depth=this.depth,e.parentFingerPrint=this.parentFingerPrint,e.childIndex=this.childIndex,e.chainCode=this.chainCode,e.publicKey=this.publicKey,this._hdPublicKey=e),e}xprivkey(){return this._xprivkey||(this._xprivkey=this.toBase58()),this._xprivkey}xpubkey(){return this.toPublic().xpubkey()}destroy(e){this.depth=0,this.childIndex=0,this.parentFingerPrint=0,n(this.chainCode),n(this.privateKey),n(this.publicKey),this.fingerPrint=-1,this._hdPublicKey&&(e&&this._hdPublicKey.destroy(),this._hdPublicKey=null),this._xprivkey=null}derive(e,t){if(r("number"==typeof e),e>>>0!==e)throw new Error("Index out of range.");if(255<=this.depth)throw new Error("Depth too high.");if((t&&(e=(e|f.HARDENED)>>>0),t=this.getID(e),!this.disableCache)&&(i=f.cache.get(t)))return i;var i=h.pool(37),a=(i=(e&f.HARDENED?(i.writeU8(0),i.writeBytes(this.privateKey)):i.writeBytes(this.publicKey),i.writeU32BE(e),i.render()),(i=s.hmac("sha512",i,this.chainCode)).slice(0,32));i=i.slice(32,64);let n;try{n=c.privateKeyTweakAdd(this.privateKey,a)}catch(t){return this.derive(e+1)}return-1===this.fingerPrint&&(a=s.hash160(this.publicKey),this.fingerPrint=a.readUInt32BE(0,!0)),(a=new v).disableCache=this.disableCache,a.network=this.network,a.depth=this.depth+1,a.parentFingerPrint=this.fingerPrint,a.childIndex=e,a.chainCode=i,a.privateKey=n,a.publicKey=c.publicKeyCreate(n,!0),this.disableCache||f.cache.set(t,a),a}getID(e){return this.network.keyPrefix.xprivkey58+this.publicKey.toString("hex")+e}deriveAccount(e,t){return r(a.isU32(e),"Purpose must be a number."),r(a.isU32(t),"Account index must be a number."),r(this.isMaster(),"Cannot derive account index."),this.derive(e,!0).derive(this.network.keyPrefix.coinType,!0).derive(t,!0)}isMaster(){return f.isMaster(this)}isAccount(e){return f.isAccount(this,e)}static isBase58(e,t){if("string"!=typeof e)return!1;if(e.length<4)return!1;e=e.substring(0,4);try{return u.fromPrivate58(e,t),!0}catch(e){return!1}}static isRaw(e,t){if(!Buffer.isBuffer(e))return!1;if(e.length<4)return!1;e=e.readUInt32BE(0,!0);try{return u.fromPrivate(e,t),!0}catch(e){return!1}}static isValidPath(e){try{return f.parsePath(e,!0),!0}catch(e){return!1}}derivePath(e){let t=this;for(const i of f.parsePath(e,!0))t=t.derive(i);return t}equals(e){return r(v.isHDPrivateKey(e)),this.network===e.network&&this.depth===e.depth&&this.parentFingerPrint===e.parentFingerPrint&&this.childIndex===e.childIndex&&this.chainCode.equals(e.chainCode)&&this.privateKey.equals(e.privateKey)}compare(e){r(v.isHDPrivateKey(e));var t=this.depth-e.depth;return 0!=t||0!=(t=this.parentFingerPrint-e.parentFingerPrint)||0!=(t=this.childIndex-e.childIndex)||0!==(t=this.chainCode.compare(e.chainCode))||0!==(t=this.privateKey.compare(e.privateKey))?t:0}fromSeed(e,t){if(e instanceof Buffer?r(Buffer.isBuffer(e)):(r("object"==typeof e&&0<e.length),e=Buffer.from(e)),8*e.length<f.MIN_ENTROPY||8*e.length>f.MAX_ENTROPY)throw new Error("Entropy not in range.");var i=(e=s.hmac("sha512",e,d.SEED_SALT)).slice(0,32);e=e.slice(32,64);if(c.privateKeyVerify(i))return this.network=u.get(t),this.depth=0,this.parentFingerPrint=0,this.childIndex=0,this.chainCode=e,this.privateKey=i,this.publicKey=c.publicKeyCreate(i,!0),this;throw new Error("Master private key is invalid.")}static fromSeed(e,t){return(new v).fromSeed(e,t)}fromMnemonic(e,t){return r(e instanceof m),this.fromSeed(e.toSeed(),t)}static fromMnemonic(e,t){return(new v).fromMnemonic(e,t)}fromPhrase(e,t){return e=m.fromPhrase(e),this.fromMnemonic(e,t),this}static fromPhrase(e,t){return(new v).fromPhrase(e,t)}static getAes(e,t){var i=Buffer.from(e),r=Buffer.alloc(32);for(let e=0;e<Math.max(32,i.length);e++){var a=e%32;r[a]=i[a]^d.RANDOM_HASH[a]}return v.fromKey(d.RANDOM_HASH,r,t).getAes(e)}fromKey(e,t,i){return r(Buffer.isBuffer(e)&&32===e.length),r(Buffer.isBuffer(t)&&32===t.length),this.network=u.get(i),this.depth=0,this.parentFingerPrint=0,this.childIndex=0,this.chainCode=t,this.privateKey=e,this.publicKey=c.publicKeyCreate(e,!0),this}getAes(e){e=v.getHmac(e,this.chainCode).token;let t=s.hash256(Buffer.from(e));return{aeskey:t.toString("base64").slice(0,32),aesiv:(t=s.hash256(t)).toString("base64").slice(0,16)}}static fromKey(e,t,i){return(new v).fromKey(e,t,i)}static eccEncrypt(e,t){var i=v.generate(),{aeskey:t,aesiv:r}=(t=c.ecdh(t,i.privateKey),v.getAes(t.toString()));return{pub:i.publicKey,msg:a.encrypt(t,r,Buffer.from(e).toString("hex"))}}static eccDecrypt(e,t){t=c.ecdh(e.pub,t);var{aeskey:t,aesiv:i}=v.getAes(t.toString());return Buffer.from(a.decrypt(t,i,e.msg),"hex").toString()}static generate(e){var t=c.generatePrivateKey(),i=o.randomBytes(32);return v.fromKey(t,i,e)}fromBase58(e,t){return r("string"==typeof e),this._xprivkey=e,this.fromRaw(p.decode(e),t)}fromReader(e,t){var i=e.readU32BE();return this.network=u.fromPrivate(i,t),this.depth=e.readU8(),this.parentFingerPrint=e.readU32BE(),this.childIndex=e.readU32BE(),this.chainCode=e.readBytes(32),r(0===e.readU8()),this.privateKey=e.readBytes(32),this.publicKey=c.publicKeyCreate(this.privateKey,!0),e.verifyChecksum(),this}fromRaw(e,t){return this.fromReader(new l(e),t)}toBase58(e){return p.encode(this.toRaw(e))}getSize(){return 82}toWriter(e,t){return t=t||this.network,t=u.get(t),e.writeU32BE(t.keyPrefix.xprivkey),e.writeU8(this.depth),e.writeU32BE(this.parentFingerPrint),e.writeU32BE(this.childIndex),e.writeBytes(this.chainCode),e.writeU8(0),e.writeBytes(this.privateKey),e.writeChecksum(),e}toRaw(e){return this.toWriter(new h(82),e).render()}static fromBase58(e,t){return(new v).fromBase58(e,t)}static fromReader(e,t){return(new v).fromReader(e,t)}static fromRaw(e,t){return(new v).fromRaw(e,t)}toJSON(){return{xprivkey:this.xprivkey(),pubkey:this.publicKey.toString("hex")}}fromJSON(e,t){return r(e.xprivkey,"Could not handle key JSON."),this.fromBase58(e.xprivkey,t),this}static fromJSON(e,t){return(new v).fromJSON(e,t)}static isHDPrivateKey(e){return e instanceof v}}e.exports=v},function(e,t,i){"use strict";
|
|
158
158
|
/*!
|
|
159
159
|
* mtx.js - mutable transaction object for vallnet
|
|
160
160
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -201,7 +201,7 @@ let r=[];[i(558),i(559),i(560),i(561),i(562),i(563),i(564),i(565),i(566),i(567),
|
|
|
201
201
|
* pkg.js - package constants
|
|
202
202
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
203
203
|
* https://github.com/bookmansoft/gamegold
|
|
204
|
-
*/t.protocol="vallnet",t.version="5.6.
|
|
204
|
+
*/t.protocol="vallnet",t.version="5.6.11",t.url="https://github.com/bookmansoft/gamegold"},function(e,t,i){"use strict";
|
|
205
205
|
/*!
|
|
206
206
|
* common.js - p2p constants for vallnet
|
|
207
207
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -282,7 +282,7 @@ const r=i(19).opcodes;function a(e){let t=null;return new(0,(a.list[e.type]||a.l
|
|
|
282
282
|
/*!
|
|
283
283
|
* wallet.js - wallet object for vallnet
|
|
284
284
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
285
|
-
*/const r=i(0);var a=i(16);const s=i(15),n=i(2),o=i(3),c=i(35),u=i(198),h=i(141).sortWithSeq,l=i(6),p=i(94),d=i(1),f=i(4),m=i(69),g=i(334);i(218);const v=i(109),y=i(73),b=i(13),w=i(68),x=i(17),k=i(219),S=i(156),_=i(28),E=i(157),j=i(337),A=i(63),R=i(26),I=i(29),O=i(7),C=i(310),P=i(38),T=S.Mnemonic,{opcodes:B,hashType:N}=i(19),z=i(165),F=i(77),L=i(78),M=i(142),D=i(46),H=i(20),U=i(42),q=i(54),{NotifyMsg:V,ContractStatus:K,ContractType:W,PropStatus:$}=i(5),Y=i(37).VerifyError,G=i(153).ErItem,X=i(154).ErAbolishItem,J=i(228).EnchancementItem,Q=i(67),Z=i(59),ee=i(83),te=i(85).txdb,ie=i(31);class re extends a{constructor(e,t){super(),r(e,"DB required."),this.db=e,this.network=e.network,this.logger=e.logger,this.readLock=new u,this.writeLock=new c,this.sendLock=new c,this.indexCache=new A(1e4),this.accountCache=new A(1e4),this.pathCache=new A(1e5),this.current=null,this.wid=0,this.id=null,this.initialized=!1,this.watchOnly=!1,this.accountDepth=0,this.token=o.ZERO_HASH,this.tokenDepth=0,this.master=new j,this.txdb=new g(this),this.account=null,t&&this.fromOptions(t)}fromOptions(e){let t,i,a=e.master;return a?("string"==typeof a&&(a=S.PrivateKey.fromBase58(a,this.network)),r(S.isPrivate(a),"Must create wallet with hd private key.")):(i=new T(e.mnemonic),a=S.fromMnemonic(i,this.network)),r(a.network===this.network,"Network mismatch for master key."),this.master.fromKey(a,i),null!=e.wid&&(r(n.isU32(e.wid)),this.wid=e.wid),e.id&&(r(y.isName(e.id),"Bad wallet ID."),t=e.id),null!=e.initialized&&(r("boolean"==typeof e.initialized),this.initialized=e.initialized),null!=e.watchOnly&&(r("boolean"==typeof e.watchOnly),this.watchOnly=e.watchOnly),null!=e.accountDepth&&(r(n.isU32(e.accountDepth)),this.accountDepth=e.accountDepth),e.token&&(r(Buffer.isBuffer(e.token)),r(32===e.token.length),this.token=e.token),t=t||this.getID(),this.id=t,this}static fromOptions(e,t){return new re(e).fromOptions(t)}async init(e){var t=e.passphrase;r(!this.initialized),this.initialized=!0,t&&await this.master.encrypt(t),e=await this._createAccount(e,t);r(e),this.account=e,this.logger.info("Wallet initialized (%s).",this.id),await this.txdb.open()}async open(){r(this.initialized);var e=await this.getAccount(0);if(!e)throw new Error("Default account not found.");this.account=e,this.logger.info("Wallet opened (%s).",this.id),await this.txdb.open()}async ensureNotifyKey(){this.notifyKey||(await this.ensureAccount({name:"alliance",witness:!0}),this.notifyKey=await this.createReceive("alliance",1,this.master),this.notifyAddress=this.notifyKey.getAddress("string"))}async createAllianceInfo(e,t,i){var r={alliancename:e,nodeid:t};return e?(r.alliancePrivateKey=l.hash256(Buffer.concat([Buffer.from(e),this.master.key.privateKey])),i?(r.prv=Buffer.alloc(0),r.pub=Buffer.from(i,"hex"),r.awardAddress=b.fromWitnessPubkeyhash(l.hash160(r.pub),this.network.type).toString(this.network.type),r.mnemonic=new T):(i=l.hash256(Buffer.concat([Buffer.from(e+"-"+t),this.master.key.privateKey])),r.mnemonic=new T({entropy:i,language:this.master.mnemonic.language,passphrase:this.master.mnemonic.passphrase}),r.prv=l.hash256(Buffer.from(r.mnemonic.toSeed().toString("hex"))),r.pub=R.publicKeyCreate(r.prv,!0),e=j.fromKey(S.fromMnemonic(r.mnemonic),this.network.type).key.deriveAccount(44,0).derive(9).derive(1),r.awardAddress=b.fromWitnessPubkeyhash(l.hash160(e.publicKey),this.network.type).toString(this.network.type))):(r.mnemonic=T.fromOptions(this.master.mnemonic),r.prv=l.hash256(Buffer.from(r.mnemonic.toSeed().toString("hex"))),r.pub=R.publicKeyCreate(r.prv,!0),r.awardAddress=b.fromWitnessPubkeyhash(l.hash160(r.pub),this.network.type).toString(this.network.type)),r.address=b.fromWitnessPubkeyhash(l.hash160(r.pub),this.network.type).toString(),r}async destroy(){var e=await this.writeLock.lock(),t=await this.sendLock.lock();try{this.db.unregister(this),await this.master.destroy(),this.readLock.destroy(),this.writeLock.destroy(),this.sendLock.destroy()}finally{t(),e()}}async addSharedKey(e,t){var i=await this.writeLock.lock();try{return await this._addSharedKey(e,t)}finally{i()}}async _addSharedKey(e,t){if(t||(t=e,e=null),!(e=await this.getAccount(e=null==e?0:e)))throw new Error("Account not found.");let i;this.start();try{i=await e.addSharedKey(t)}catch(e){throw this.drop(),e}return await this.commit(),i}async removeSharedKey(e,t){var i=await this.writeLock.lock();try{return await this._removeSharedKey(e,t)}finally{i()}}async _removeSharedKey(e,t){if(t||(t=e,e=null),!(e=await this.getAccount(e=null==e?0:e)))throw new Error("Account not found.");let i;this.start();try{i=await e.removeSharedKey(t)}catch(e){throw this.drop(),e}return await this.commit(),i}async setPassphrase(e,t){e&&await this.decrypt(e),t&&await this.encrypt(t)}async encrypt(e){var t=await this.writeLock.lock();try{return await this._encrypt(e)}finally{t()}}async _encrypt(e){e=await this.master.encrypt(e,!0),this.start();try{await this.db.encryptKeys(this,e)}catch(t){throw p(e),this.drop(),t}p(e),this.save(),await this.commit()}async decrypt(e){var t=await this.writeLock.lock();try{return await this._decrypt(e)}finally{t()}}async _decrypt(e){e=await this.master.decrypt(e,!0),this.start();try{await this.db.decryptKeys(this,e)}catch(t){throw p(e),this.drop(),t}p(e),this.save(),await this.commit()}async rename(e){var t=await this.writeLock.lock();try{return await this.db.rename(this,e)}finally{t()}}async writeBalanceLog(e){var t=await this.writeLock.lock();try{return await this.db.writeBalanceLog(this,e)}finally{t()}}async renameAccount(e,t){var i=await this.writeLock.lock();try{return await this._renameAccount(e,t)}finally{i()}}async _renameAccount(e,t){if(!y.isName(t))throw new Error("Bad account name.");var i=await this.getAccount(e);if(!i)throw new Error("Account not found.");if(0===i.accountIndex)throw new Error("Cannot rename default account.");if(await this.hasAccount(t))throw new Error("Account name not available.");e=i.name,this.start(),this.db.renameAccount(i,t),await this.commit(),this.indexCache.remove(e),e=this.pathCache.values();for(const r of e)r.account===i.accountIndex&&(r.name=t)}async lock(){var e=await this.writeLock.lock(),t=await this.sendLock.lock();try{await this.master.lock()}finally{t(),e()}}unlock(e,t){return this.master.unlock(e,t)}getID(){r(this.master.key,"Cannot derive id.");var e,t=this.master.key.derive(44);(e=new f(37)).writeBytes(t.publicKey),e.writeU32(this.network.magic),t=l.hash160(e.render());return(e=new f(27)).writeU8(3),e.writeU8(190),e.writeU8(4),e.writeBytes(t),e.writeChecksum(),m.encode(e.render())}async createAccount(e,t){var i=await this.writeLock.lock();try{return await this._createAccount(e,t)}finally{i()}}async _createAccount(e,t){let i,a,s=e.name,o=(s=s||this.accountDepth.toString(10),0);if(0!=this.accountDepth&&(o=n.hashInt(s)),await this.hasAccountIndex(o))throw new Error("Account Index Conflict.");if(await this.hasAccount(s))throw new Error("Account already exists.");if(await this.unlock(t),this.watchOnly&&e.accountKey){if("string"==typeof(i=e.accountKey)&&(i=S.PublicKey.fromBase58(i,this.network)),!S.isPublic(i))throw new Error("Must add HD public keys to watch only wallet.");r(i.network===this.network,"Network mismatch for watch only key.")}else r(this.master.key),i=(i=this.master.key.deriveAccount(44,o)).toPublic();t={wid:this.wid,id:this.id,name:0===this.accountDepth?"default":s,witness:e.witness,watchOnly:this.watchOnly,accountKey:i,accountIndex:o,type:e.type,m:e.m,n:e.n,keys:e.keys},this.start();try{(a=E.fromOptions(this.db,t)).wallet=this,await a.init()}catch(e){throw this.drop(),e}return this.logger.info("Created account %s/%s/%d.",a.id,a.name,a.accountIndex),this.accountDepth++,this.save(),await this.commit(),a}async ensureAccount(e,t){var i=e.name;return(i=await this.getAccount(i))||this.createAccount(e,t)}getAccounts(){return this.db.getAccounts(this.wid)}getAccountMap(){return this.db.getAccountMap(this.wid)}getAddressHashes(e){return null!=e?this.getAccountHashes(e):this.db.getWalletHashes(this.wid)}async getAccountHashes(e){return e=await this.ensureIndex(e,!0),this.db.getAccountHashes(this.wid,e)}async getAccount(e){if(this.account&&(null==e||"default"===e||"number"==typeof e&&0===e||"string"==typeof e&&0===e.length))return this.account;if(-1===(e=await this.getAccountIndex(e)))return null;var t=await this.readLock.lock(e);try{return await this._getAccount(e)}finally{t()}}async _getAccount(e){var t=this.accountCache.get(e);return t||((t=await this.db.getAccount(this.wid,e))?(t.wallet=this,t.wid=this.wid,t.id=this.id,t.watchOnly=this.watchOnly,await t.open(),this.accountCache.set(e,t),t):null)}async getAccountIndex(e){var t;return null==e?-1:"number"==typeof e?e:null!=(t=this.indexCache.get(e))?t:-1===(t=await this.db.getAccountIndex(this.wid,e))?-1:(this.indexCache.set(e,t),t)}async getAccountName(e){var t;return"string"==typeof e?e:(t=this.accountCache.get(e))?t.name:this.db.getAccountName(this.wid,e)}async hasAccount(e){return-1!==(e=await this.getAccountIndex(e))&&(!!this.accountCache.has(e)||this.db.hasAccount(this.wid,e))}async hasAccountIndex(e){return!!this.accountCache.has(e)||this.db.hasAccount(this.wid,e)}createReceive(e,t=0,i=null){return this.createKey(e,0,t,i)}createChange(e){return this.createKey(e,1)}createNested(e){return this.createKey(e,2)}async createKey(e,t,i=0,r=null){var a=await this.writeLock.lock();try{return await this._createKey(e,t,i,r)}finally{a()}}async _createKey(e,t,i=0,r=null){if(null==t&&(t=e,e=null),!(e=await this.getAccount(e=e||0)))throw new Error("Account not found.");let a;this.start();try{a=await e.createKey(t,i,r)}catch(e){throw this.drop(),e}return await this.commit(),a}async deriveKey(e,t,i,r=null){let a=null;var s=await this.writeLock.lock();try{this.start(),a=await this._deriveKey(e,t,i,r),await this.commit()}catch(e){throw this.drop(),e}finally{s()}return a}async _deriveKey(e,t,i=0,r=null){if(null==t&&(t=e,e=null),e=e||0,e=parseInt(e),e=await this.getAccount(e))return t=await e.deriveKey(t,i,r),await e.saveKey(t),t;throw new Error("Account not found.")}save(){return this.db.save(this)}async saveAccount(e){var t=await this.writeLock.lock();try{this.start(),e._save(),await this.commit(),0==e.accountIndex&&(this.account=e)}finally{t()}}start(){return this.db.start(this)}drop(){return this.db.drop(this)}clear(){return this.db.clear(this)}commit(){return this.db.commit(this)}async hasAddress(e){return e=b.getHash(e,"hex"),null!=await this.getPath(e)}async ownedAddress(e){return!!await this.getKey(e)}async getPath(e){return(e=await this.readPath(e))?(e.name=await this.getAccountName(e.account),r(e.name),this.pathCache.set(e.hash,e),e):null}async readPath(e){e=b.getHash(e,"hex");var t=this.pathCache.get(e);return t||((t=await this.db.getPath(this.wid,e))?(t.id=this.id,t):null)}async hasPath(e){return e=b.getHash(e,"hex"),!!this.pathCache.has(e)||this.db.hasPath(this.wid,e)}async getPaths(e){if(null!=e)return this.getAccountPaths(e);var t=[];for(const e of await this.db.getWalletPaths(this.wid))e.id=this.id,e.name=await this.getAccountName(e.account),r(e.name),this.pathCache.set(e.hash,e),t.push(e);return t}async getAccountPaths(e){var t=await this.ensureIndex(e,!0),i=await this.getAccountHashes(t),a=await this.getAccountName(e),s=(r(a),[]);for(const e of i){var n=await this.readPath(e);r(n),r(n.account===t),n.name=a,this.pathCache.set(n.hash,n),s.push(n)}return s}async importKey(e,t,i){var r=await this.writeLock.lock();try{return await this._importKey(e,t,i)}finally{r()}}async _importKey(e,t,i){if(e&&"object"==typeof e&&(i=t,t=e,e=null),null==e&&(e=0),r(t.network===this.network,"Network mismatch for key."),this.watchOnly){if(t.privateKey)throw new Error("Cannot import privkey into watch-only wallet.")}else if(!t.privateKey)throw new Error("Cannot import pubkey into non watch-only wallet.");var a=t.getHash("hex");if(await this.getPath(a))throw new Error("Key already exists.");if(!(a=await this.getAccount(e)))throw new Error("Account not found.");if(a.type!==E.types.PUBKEYHASH)throw new Error("Cannot import into non-pkh account.");await this.unlock(i),e=k.fromRing(a,t).toPath(),this.master.encrypted&&(e.data=this.master.encipher(e.data,e.hash),r(e.data),e.encrypted=!0),this.start();try{await a.savePath(e)}catch(e){throw this.drop(),e}await this.commit()}async importAddress(e,t){var i=await this.writeLock.lock();try{return await this._importAddress(e,t)}finally{i()}}async _importAddress(e,t){if(t||(t=e,e=null),null==e&&(e=0),t.network!==this.network)throw new Error("Network mismatch for address.");if(!this.watchOnly)throw new Error("Cannot import address into non watch-only wallet.");if(await this.getPath(t))throw new Error("Address already exists.");if(!(e=await this.getAccount(e)))throw new Error("Account not found.");if(e.type!==E.types.PUBKEYHASH)throw new Error("Cannot import into non-pkh account.");t=v.fromAddress(e,t),this.start();try{await e.savePath(t)}catch(e){throw this.drop(),e}await this.commit()}async fund(e,t){var i=await this.writeLock.lock();try{return await this._fund(e,t)}finally{i()}}async _fund(e,t){if(t=t||{},!this.initialized)throw new Error("Wallet is not initialized.");if(this.watchOnly)throw new Error("Cannot fund from watch-only wallet.");let i;if(null!=t.account){if(!(i=await this.getAccount(t.account)))throw new Error("Account not found.")}else i=this.account;if(!i.initialized)throw new Error("Account is not initialized.");let a,s=t.rate;return null==s&&(s=await this.db.estimateFee(t.blocks)),a=t.smart?await this.getSmartCoins(i.name):(a=await this.getCoins(i.name),this.txdb.filterConserved(a)),await e.fund(a,{allowPreInput:t.allowPreInput,noChange:t.noChange,selection:t.selection,round:t.round,depth:t.depth,hardFee:t.hardFee,subtractFee:t.subtractFee,subtractIndex:t.subtractIndex,changeAddress:i.change.getAddress(),height:this.db.curHeight,rate:s,maxFee:t.maxFee,estimate:e=>this.estimateSize(e),network:this.network}),!t.allowInfiniteFee&&t.noChange&&r(e.getFee()<=C.MAX_FEE,"TX exceeds MAX_FEE."),a}async getAccountByAddress(e){return e=b.getHash(e,"hex"),(e=await this.getPath(e))?this.getAccount(e.account):null}async estimateSize(e){var t=O.WITNESS_SCALE_FACTOR,i=b.fromScript(e);if(!i)return-1;var r=await this.getAccountByAddress(i);if(!r)return-1;let a=0;if(e.isScripthash()&&r.witness)switch(r.type){case E.types.PUBKEYHASH:a=4*(a+23);break;case E.types.MULTISIG:a=4*(a+35)}switch(r.type){case E.types.PUBKEYHASH:a=a+74+34;break;case E.types.MULTISIG:a=(a=(a=(a=(a+=1)+74*r.m)+3+1)+34*r.n)+1+1}return r.witness?a=((a+=1)+t-1)/t|0:a+=o.sizeVarint(a),a}async createTX(e){var t=e.outputs,i=new w;r(Array.isArray(t),"Outputs must be an array."),r(0<t.length,"No outputs available."),e.comment&&("object"==typeof e.comment&&(e.comment=JSON.stringify(e.comment)),i.outputs.push(_.fromScript(x.createScript(Buffer.from(e.comment),x.types.NULLDATA),0)));for(const e of t){var a=new _(e),s=a.getAddress();if(a.isDust())throw new Error("Output is dust.");if(0<a.value){if(!s)throw new Error("Cannot send to unknown address.");if(s.isNull())throw new Error("Cannot send to null address.")}i.outputs.push(a)}let n=null;if(e.inputs)for(const t of e.inputs){var o=await this.getTX(t.hash);o&&(o=q.fromTX(o.tx,t.index,-1,0))&&(n=o.getAddress(),e.allowPreInput=!0,i.addCoin(o))}else await this.fund(i,e);if(n&&((t=new _).value=i.getFee()-C.MIN_FEE,t.script.fromAddress(n),i.outputs.push(t),i.changeIndex=i.outputs.length-1),!1!==e.sort&&i.sortMembers(),null!=e.locktime&&i.setLocktime(e.locktime),r(i.isSane(),"TX failed sanity check."),r(i.verifyInputs(this.db.curHeight+1),"TX failed context check."),0===await this.template(i))throw new Error("Templating failed.");return i}async send(e,t){var i=await this.sendLock.lock();try{return await this._send(e,t)}finally{i()}}async _send(e,t){return t&&(e.account=t),t=await this.createTX(e,!0),await this.sign(t),this.sendMTX(t,{sendafter:e.sendafter})}async sendMTX(e,t={}){if(!e.isSigned())throw new Error("TX could not be fully signed.");var i=e.toTX();if(i.getSigopsCost(e.view)>I.MAX_TX_SIGOPS_COST)throw new Error("TX exceeds policy sigops.");if(i.getWeight()>I.MAX_TX_WEIGHT)throw new Error("TX exceeds policy weight.");return t.sendafter||(this.logger.debug("Sending wallet tx (%s): %s",this.id,i.txid()),await this.db.addTX(i),await this.db.send(i)),i}async resend(){var e=await this.getPending(),t=(0<e.length&&this.logger.info("Rebroadcasting %d transactions.",e.length),[]);for(const i of e)t.push(i.tx);for(const e of h(t))await this.db.send(e);return t}async deriveInputs(e){r(e.mutable);var t=[];for(const r of await this.getInputPaths(e)){var i=await this.getAccount(r.account);i&&(i=i.derivePath(r,this.master))&&t.push(i)}return t}async getKey(e){try{var t,i=b.getHash(e,"hex",this.network.type),r=await this.getPath(i);return r&&(t=await this.getAccount(r.account))?t.derivePath(r,this.master):null}catch{return null}}async exportToFile(e){if(!Z.unsupported){var t=await this.db.getTip(),i=n.date();let o="",c=[n.fmt("# Wallet Dump created by %s %s",ee.protocol,ee.version),n.fmt("# * Created on %s",i),n.fmt("# * Best block at time of backup was %d (%s).",t.height,n.revHex(t.hash)),n.fmt("# * File: %s",e.file),""];var r,a;t=n.fmt("W %s wid= %s",this.toRaw().toString("base64"),this.wid),t=(c.push(t),await this.getAccounts());for(const e of t){var s=await this.getAccount(e);s=n.fmt("C %s name= %s index= %d",s.toRaw().toString("base64"),s.name,s.accountIndex);c.push(s)}for(const t of await this.getAddressHashes())this.watchOnly?(r=b.fromWitnessPubkeyhash(Buffer.from(t,"hex"),this.network.type).toString(),r=n.fmt("A %s %s label= account= %s branch= %s index= %s addr= %s","S",i,0,-1,-1,r),c.push(r)):(r=await this.getPrivateKey(t))&&(a=r.getAddress("string"),a=n.fmt("A %s %s label= account= %s branch= %s index= %s addr= %s",r.toSecret(),i,r.account,r.branch,r.index,a),c.push(a),e.fragment)&&1e5<c.length&&(o=c.join("\n"),await Z.writeFile(e.file.split(".").reduce((e,t)=>(e?e+="."+t:e=t+"-1",e),""),o,"utf8"),c=[]);c.push(""),c.push("# End of dump"),c.push(""),o=c.join("\n"),await Z.writeFile(e.file,o,"utf8")}}async getPrivateKey(e,t){if(e=b.getHash(e,"hex"),!(e=await this.getPath(e)))return null;var i=await this.getAccount(e.account);return i?(await this.unlock(t),(t=i.derivePath(e,this.master)).privateKey?t:null):null}async getInputPaths(e){if(r(e.mutable),!e.hasCoins())throw new Error("Not all coins available.");var t=[];for(const r of e.getInputHashes("hex")){var i=await this.getPath(r);i&&t.push(i)}return t}async getOutputPaths(e){var t=[];for(const r of e.getOutputHashes("hex")){var i=await this.getPath(r);i&&t.push(i)}return t}async setLookahead(e,t){var i=await this.writeLock.lock();try{return this._setLookahead(e,t)}finally{i()}}async _setLookahead(e,t){if(null==t&&(t=e,e=null),!(e=await this.getAccount(e=null==e?0:e)))throw new Error("Account not found.");this.start();try{await e.setLookahead(t)}catch(e){throw this.drop(),e}await this.commit()}async syncOutputDepth(e){var t=new Map;for(const r of e.outputs){var i=r.path;i&&-1!==i.index&&(t.has(i.account)||t.set(i.account,[]),t.get(i.account).push(i))}var a,s,n=[];for([a,s]of t){let e=-1,t=-1,i=-1;for(const r of s)switch(r.branch){case 0:r.index>e&&(e=r.index);break;case 1:r.index>t&&(t=r.index);break;case 2:r.index>i&&(i=r.index)}e+=2,t+=2,i+=2;var o=await this.getAccount(a);(o=(r(o),await o.syncDepth(e,t,i)))&&n.push(o)}return n}async getRedeem(e){"string"==typeof e&&(e=Buffer.from(e,"hex"));var t=await this.getKey(e.toString("hex"));return t?t.getRedeem(e):null}async template(e){var t=await this.deriveInputs(e);return e.sign(t)}async onSaleList(e,t){return(await(await this.getPropList()).predict(async(e,i)=>!!i.bid&&await this.belongToAccount(t,i.bid.address))).where([["pst",$.Sale]]).paginate(10,e).records()}async mySaleList(e,t){return(await(await this.getPropList()).predict(async(e,i)=>this.belongToAccount(t,i.current.address))).where([["pst",$.Sale]]).paginate(10,e).records()}async getPropList(){const e=await this.db.loadVpList();var t=[];for(let i=0;i<e.length;i++){let r=e[i];t.push((async()=>{await this.getPrivateKey(r.current.address)&&(e[i]=[r.pid,r])})())}return await Promise.all(t),new ie(e)}async propCreate(e,t){var i,a=new w;for(i of e){var s=await this.ensureCp(i.cid,!0);!s||i.cid==this.network.genesisId||(i.gold=(0|i.gold)>>>0,i.gold<O.MINPROPVALUE)||(i.pid||(i.pid=M()),i.oid||(i.oid=i.pid),a.propCreate(s.current.address,i),i.index=a.outputs.length-1)}if(0<a.outputs.length){t?await this.fund(a,{account:t}):await this.fund(a),await this.sign(a);var n,o=a.commit();for(n of(await this.db.addTX(o[0]),await this.db.send(o[0]),r(o[0].verify(o[1],x.flags.STANDARD_VERIFY_FLAGS)),e))n.hash=o[0].hash("hex"),n.txid=o[0].txid();return o}return[]}async attach(e,t){var i,a=new w;for(i of e)a.attach(i.address,i.value,i.data);if(0<a.outputs.length){t?await this.fund(a,{account:t}):await this.fund(a),await this.sign(a);var s,n=a.commit();for(s of(await this.db.addTX(n[0]),await this.db.send(n[0]),r(n[0].verify(n[1],x.flags.STANDARD_VERIFY_FLAGS)),e))s.hash=n[0].hash("hex"),s.txid=n[0].txid();return n}return[]}async sendSecret(e,t,i){let r=this.db.$contacts.get(e);if(!r||!r.sender){var a=(await this.createReceive(i)).getAddress("string");if(e==a)throw new F(L.errors.TYPE_ERROR,"Forbid Sending to Self Address.");r=await this.db.ensureContact({contact:e,messenger:a,wallet:this,account:i})}if(r)return r.send(t);throw new F(L.errors.TYPE_ERROR,"Invalid Address.")}async commNotify(e){r(!!e),r(!!e.dst),r(!!e.content);var t=new w,i=e.src||this.getReceive().toString(),a=(i=new V(W.notify,M(),this.db.curHeight,{src:i,content:e.content}),_.fromScript(x.createScript(i.toRaw(),x.types.NULLDATA),0));t.outputs.push(a),a={address:e.dst,locktime:O.BLOCK_DAY,locktype:"csb",value:.1*O.COIN},t.outputs.push(new _(a)),e.account?await this.fund(t,{account:e.account,noChange:!0,allowInfiniteFee:!0}):await this.fund(t,{noChange:!0,allowInfiniteFee:!0}),await this.sign(t),a=t.commit();return r(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(a[0]),this.logger.debug("Sending tx on wallet(%s): %s",this.id,a[0].txid()),await this.db.send(a[0]),i.hash=a[0].hash("hex"),i.height=-1,i}async cpRegister(e,t,i,a){if(r(!!t&&"object"==typeof t),!await this.db.client.execute("canExecute",[{confirm:!1,cid:t.cid,name:t.name,oper:W.cpRegister}]))throw new F(L.errors.TYPE_ERROR,"Invalid CP Register Info.");const s=new w;e||(n=await this.createReceive(i),e=n.getAddress());var n=await this.getKey(e);if(!n)throw new F(L.errors.TYPE_ERROR,"Invalid CP Register Address, Not along to this wallet.");if(t.pubAddress=e.toString(),t.pubKey=n.getPublicKey("hex"),t.signMethod="secp256k1",n=await this.createAllianceInfo(),t.register=n.pub.toString("hex"),s.cpRegister(e,O.registerFee,t),n=async()=>{i?await this.fund(s,{account:i}):await this.fund(s),await this.sign(s);var a=s.commit();return r(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(a[0]),await this.db.send(a[0]),t.txid=a[0].txid(),t.addr=e.toString(),a},!a)return n();n()}getSCAddress(e){return e=Q.fromMnemonic(T.fromOptions(O.SmartContractMnemonic),this.network).deriveAccount(44,e).derive(9).derive(1),b.fromWitnessPubkeyhash(l.hash160(e.publicKey),this.network)}async cpChange(e,t){var i=await this.ensureCp(e.cid);if(i.cid==this.network.genesisId||"ATHENA"==i.name)throw new F(L.errors.TYPE_ERROR,"Invalid cp name.");var a=await this.getTX(i.current.hash);if(!a)throw new F(L.errors.TYPE_ERROR,"Do not have permission to change this info.");if(a=a.tx,!await this.belongToAccount(t,a.outputs[0].getAddress()))throw new F(L.errors.TYPE_ERROR,"Invalid account info.");if(e.newName){if(!await this.db.client.execute("canExecute",[{confirm:!1,cid:i.cid,name:e.newName,oper:W.cpChange}]))throw new F(L.errors.TYPE_ERROR,"Invalid CP Change Info.")}else e.newName=i.name;return e.addr||(e.addr=b.fromString(i.current.address)),i=w.cpChange(a,e),t?await this.fund(i,{allowPreInput:!0,account:t}):await this.fund(i,{allowPreInput:!0}),await this.sign(i),a=i.commit(),await this.db.send(a[0]),r(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),e.txid=a[0].txid(),a}async propExchangeList(e,t,i=!1){var a,s,n,o=new w,c=[];for([a,s,n]of e){var u,h=null;if(h=await this.getTX(a.hash)){if(h=h.tx,u=a.index,h&&h.outputs&&!(h.outputs.length<=u)){if(i){if(!await this.ownedAddress(h.outputs[u].getAddress())){this.logger.error("not owned prop:",a.hash,a.index);continue}}else if(!await this.belongToAccount(t,h.outputs[u].getAddress())){this.logger.error("not owned prop:",a.hash,a.index);continue}var l=h.outputs[u].getReturnData();l&&(o.propExchange(h,u,s),l.index=o.outputs.length-1,l.addr=s.toString(),c.push(l))}}else this.logger.error("tx not find:",a.hash,n)}return t?await this.fund(o,{allowPreInput:!0,account:t}):await this.fund(o,{allowPreInput:!0}),await this.sign(o),e=o.commit(),await this.db.addTX(e[0]),await this.db.send(e[0]),r(e[0].verify(e[1],x.flags.STANDARD_VERIFY_FLAGS)),e.push(c),e}async propDonate(e,t){var i=e.index;if(!(e=await this.getTX(e.hash))||!e.tx||!e.tx.outputs||e.tx.outputs.length<=i)throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");if(!await this.belongToAccount(t,e.tx.outputs[i].getAddress()))throw new F(L.errors.TYPE_ERROR,"Props that do not belong to you.");if(!(t=e.tx.outputs[i].getReturnData()))throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");if(t.cid&&t.cid==this.network.genesisId)throw new Y(e.tx,"invalid","Special props that can not to donate",100);var r=new w;return(e=(r.addInputFromTx(e.tx,i),r.addOutput(x.createScript(Buffer.from(JSON.stringify({value:e.tx.outputs[i].value,cid:t.cid,pid:t.pid,oid:t.oid,gaddr:this.getAddress().toString(this.network)})),x.types.NULLDATA),0),await this.sign(r,null,N.NONE|N.ANYONECANPAY),r.commit())).push(t),e}async propReceive(e,t){var i=(e=w.fromTX(e,1)).inputs[0].prevout,r=e.outputs[0].getReturnData();e.view.addOutput({hash:e.inputs[0].prevout.hash,index:e.inputs[0].prevout.index},new _({value:r.value})),e.outputs.pop();let a=this.getAddress().toString(this.network);t&&(s={cid:r.cid,uid:t},a=(s=await this.tokenCreate(s,t)).data.addr),e.outputs.push(_.fromScript(a,r.value,{oper:W.propExchange,pid:r.pid,cid:r.cid,oid:r.oid,prev:{hash:i.hash,index:i.index}})),t?await this.fund(e,{allowPreInput:!0,account:t}):await this.fund(e,{allowPreInput:!0}),await this.sign(e,null,N.ALL,[0]);var s=e.commit();return await this.db.send(s[0]),r.simAddr=a,[s[0],null,r]}async belongToAccount(e,t){return!!t&&!(!(t=await this.getAccountByAddress(t))||e&&t.name!==e)}async propExchange(e,t,i){let a=null,s=0;var n;return Array.isArray(e)?(a=e[0],s=e[1]):(n=await this.getTX(e.hash))&&(a=n.tx,s=e.index),!a||!a.outputs||a.outputs.length<=s?(this.logger.error("Invalid tx info."),null):await this.ownedAddress(a.outputs[s].getAddress())?(n=a.outputs[s].getReturnData())?(e=(new w).propExchange(a,s,t),n.index=e.outputs.length-1,i?await this.fund(e,{allowPreInput:!0,account:i}):await this.fund(e,{allowPreInput:!0}),await this.sign(e),t=e.commit(),await this.db.addTX(t[0]),await this.db.send(t[0]),r(t[0].verify(t[1],x.flags.STANDARD_VERIFY_FLAGS)),t.push(n),t):(this.logger.error("Invalid tx info."),null):(this.logger.error("Invalid user."),null)}async propFound(e,t,i){if(e=await this.getTX(e),r(e),!(e=e.tx))throw new F(L.errors.TYPE_ERROR,"Invalid hex string.");var a=e.outputs[t],s=a.getReturnData();if(!s||s.oper!==W.propExchange&&s.oper!==W.propCreate)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");if(s.cid==this.network.genesisId)throw new Y(block,"invalid","prop found supertoken",100);var n=new w;n.addInputFromTx(e,t),e=_.fromScript(a.getAddress(),a.value),n.outputs.push(e),i?await this.fund(n,{allowPreInput:!0,subtractFee:!0,account:i}):await this.fund(n,{allowPreInput:!0,subtractFee:!0}),await this.sign(n),t=n.commit();return await this.db.send(t[0]),r(t[0].verify(t[1],x.flags.STANDARD_VERIFY_FLAGS)),t.push(s),t}async propSale(e,t,i,a){let s=await this.getTX(e);if(!s)throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");if(s.getDepth(this.db.curHeight)<=0)throw new F(L.errors.TYPE_ERROR,"No enough confirmations.");if(!(s=s.tx))throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");var n=s.outputs[t].getReturnData([x.opcodes.OP_PROPEXCHANGE,x.opcodes.OP_PROPCREATE]);if(!n)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");if(!await this.ownedAddress(s.outputs[t].getAddress()))throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");var o=await this.getCoin(e,t);if(!o||-1===o.height)throw new F(L.errors.WALLET_INSUFFICIENT_FUNDS,"Invalid coin.");if(await this.txdb.isSpent(e,t))throw new F(L.errors.WALLET_INSUFFICIENT_FUNDS,"Invalid coin.");if(i<=s.outputs[t].value)throw new F(L.errors.TYPE_ERROR,"Invalid fixed price.");if(n.cid==this.network.genesisId)throw new Y(s,"invalid","prop not for sale",100);return e=(o=new w).addInputFromTx(s,t),t={oper:W.propSale,pid:n.pid,prev:{hash:e.prevout.hash,index:e.prevout.index},fixed:i,period:this.db.curHeight+O.BLOCK_DAY},n=_.fromScript(x.createScript(Buffer.from(JSON.stringify(t)),x.types.NULLDATA),0),o.outputs.push(n),await this.sign(o,null,N.SINGLE|N.ANYONECANPAY),e=o.commit(),r(e[0].verify(e[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.send(e[0]),e}async propBuy(e,t,i){if(!(e=this.db.propList.get(e))||e.pst!=$.Sale||!e.bid||!e.bid.raw)throw new F(L.errors.INVALID_PARAMS,"Invalid Tx Hash.");var r=H.fromRaw(Buffer.from(e.bid.raw,"hex")),a=(await this.createReceive(i)).getAddress(),s=e.gold,n=b.fromString(e.current.address,this.network).getHash();if(t<s)throw new Error("wrong price");if(1<r.outputs.length&&t<r.outputs[1].value)throw new Error("low bid price than before");var o=w.fromTX(r,1);if(!o.outputs[0].getReturnType(B.OP_RETURN))throw new Error("not a sale order");return await this.remove(r.hash("hex")),o.view.addOutput({hash:o.inputs[0].prevout.hash,index:o.inputs[0].prevout.index},new _({value:e.gold})),n=_.fromScript(x.createScript(n),t),o.outputs.push(n),t={oper:W.propExchange,pid:e.pid,cid:e.cid,oid:e.oid,prev:{hash:o.inputs[0].prevout.hash,index:o.inputs[0].prevout.index}},n=_.fromScript(a,s,t),o.outputs.push(n),i?await this.fund(o,{allowPreInput:!0,account:i}):await this.fund(o,{allowPreInput:!0}),await this.sign(o,null,N.ALL,[0]),a=o.commit(),e.owned||this.db.client.watchOutpoint((new D).fromOptions(r.inputs[0].prevout)),await this.db.send(a[0]),a}async getTXByAmount(e,t){let i=null;var r;for(r of await this.getCoins(t))if(!(r.height<=0)&&r.value==e){i=r;break}return i&&(t=await this.getTX(i.hash))?[t.tx,i.index,i.height]:[]}async contractCreate(e,t,i,a,s){if(this.db.transactionList.query(e,a)!=K.None)throw new F(L.errors.TYPE_ERROR,"Contract with the same address finded.");if(0!=parseInt(t%1e3,10))throw new F(L.errors.TYPE_ERROR,"Contract source should an integer multiple of 1000.");if(!await U.checkSum(this.network,e,a))throw new F(L.errors.TYPE_ERROR,"Create contract with an invalid Address or a Address with old transations.");let n=!1,[o,c,u]=await this.getTXByAmount(t,s);if(!o){n=!0;var h=new w;let e="";e=(s?await this.createReceive(s):this).getAddress(),h.outputs.push(_.fromScript(e,t)),s?await this.fund(h,{allowPreInput:!0,account:s}):await this.fund(h,{allowPreInput:!0}),await this.sign(h),h=h.commit(),r(h[0].verify(h[1],x.flags.STANDARD_VERIFY_FLAGS)),o=h[0],c=0,u=-1}(h=new w).addInputFromTx(o,c,u);let l="";l=(s?await this.createReceive(s):this).getAddress();var p=await this.getKey(l);e={oper:W.contractCreate,type:e,addr:a,src:t,dst:i,srcact:s,alice:p.getPublicKey("hex"),period:this.db.curHeight+O.TRANSACTION_PERIOD},a=_.fromScript(x.createScript(Buffer.from(JSON.stringify(e)),x.types.NULLDATA),0),h.outputs.push(a),await this.sign(h,null,N.SINGLE|N.ANYONECANPAY),t=h.commit();return n&&await this.db.send(o),await this.db.send(t[0]),t}async contractPromise(e,t){if(!(e=this.db.transactionList.get(e))||e.transStatus!=K.CreatedOnMem)throw new F(L.errors.INVALID_PARAMS,"Invalid Tx id.");if(!(e=H.fromRaw(Buffer.from(e.raw,"hex"))))throw new F(L.errors.TYPE_ERROR,"Invalid Tx id.");var i=U.parseContract(e);if(!i||i.oper!==W.contractCreate)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");var r=w.fromTX(e,1);if(!r.outputs[0].getReturnType(B.OP_RETURN))throw new Error("not a valid contract");r.view.addOutput({hash:r.inputs[0].prevout.hash,index:r.inputs[0].prevout.index},new _({value:i.src}));let a="";a=(t?await this.createReceive(t):this).getAddress();var s=await this.getKey(a);e={oper:W.contractPromise,prevhash:e.hash("hex"),type:i.type,addr:i.addr,dst:i.dst,srcact:i.srcact,dstact:t,bob:s.getPublicKey("hex"),period:i.period},t=new x([z.fromSymbol("promise"),z.fromData(Buffer.from(JSON.stringify(e))),z.fromSymbol("drop"),z.fromSymbol("greaterthan"),z.fromSymbol("drop"),z.fromSymbol("if"),z.fromData(l.hash160(Buffer.from(e.bob,"hex"))),z.fromSymbol("else"),z.fromData(l.hash160(Buffer.from(i.alice,"hex"))),z.fromSymbol("endif"),z.fromSymbol("checksig")]),r.outputs.push(_.fromScript(t,i.src)),await this.remove(e.prevhash),await this.sign(r,null,N.ALL,[0]),s=r.commit();return await this.db.send(s[0]),e.current={hash:s[0].hash("hex"),index:0},e.raw=s[0].toRaw().toString("hex"),e.transStatus=K.Promised,this.db.transactionList.saveContract(e,!0),s}async contractExecute(e,t){if(!(e=this.db.transactionList.get(e))||e.transStatus!=K.Confirmed&&e.transStatus!=K.Expired)throw new F(L.errors.INVALID_PARAMS,"Invalid Tx id.");if(!(e=H.fromRaw(Buffer.from(e.raw,"hex"))))throw new F(L.errors.TYPE_ERROR,"Invalid Tx id.");t=t||1;var i=U.parseContract(e);if(!i||i.oper!==W.contractPromise)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");var a=e.outputs[1].getReturnData();if(!a||a.oper!==W.contractPromise)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");r.strictEqual(i.addr,a.addr),r.strictEqual(i.type,a.type),r.strictEqual(i.dst,a.dst),r.strictEqual(i.period,a.period),r.strictEqual(i.srcact,a.srcact),r.strictEqual(i.dstact,a.dstact);var s=this.db.transactionList.query(i.type,i.addr);if(s!=K.Confirmed&&s!=K.Expired)throw new F(L.errors.TYPE_ERROR,"Contract Promise not Check yet.");if(s==K.Expired&&1!=t||s==K.Confirmed&&2!=t)throw new F(L.errors.TYPE_ERROR,"Invalid Executor.");let n=i.srcact,o=(2==t&&(n=i.dstact),"");o=(n?await this.createReceive(n):this).getAddress();var c=new w,u=(c.addInputFromTx(e,1),{oper:W.contractExecute,type:i.type,addr:i.addr,master:t});u=_.fromScript(x.createScript(Buffer.from(JSON.stringify(u)),x.types.NULLDATA),0),c.outputs.push(u),u=_.fromScript(o,e.outputs[1].value),c.outputs.push(u),e=1==t?await P.fromPublic(Buffer.from(i.ori.alice,"hex")):await P.fromPublic(Buffer.from(a.bob,"hex")),u=await this.getKey(e.getAddress()),await c.signAsync(u,x.hashType.ALL,this.db.workers),t=c.commit();return r(t[0].verify(t[1],x.flags.STANDARD_VERIFY_FLAGS,s)),await this.db.send(t[0]),t}async htlcDeal(e,t){var i=await this.getTX(e.hash);let r=null;if(t){if(!(t=await this.getAccount(t)))throw new F(L.errors.TYPE_ERROR,"Invalid Account.");r=t.getReceive().toString()}else r=this.getReceive().toString();t=new w;var a=(new x).pushOp(B.OP_1);e.suggest&&a.pushData(Buffer.from(e.sa,"hex")),t.addInput({prevout:{hash:e.hash,index:e.index},script:a}),t.addOutput(r,i.tx.outputs[e.index].value-1e4),t.view.addOutput({hash:e.hash,index:e.index},new _(i.tx.outputs[e.index])),await this.sign(t,null,N.ALL),a=t.commit();return await this.db.send(a[0]),a}async htlcCancel(e,t){let i=null;var r=await this.getTX(e.hash);if(!(i=r?r.tx.outputs[e.index]:i))throw new F(L.errors.TYPE_ERROR,"Invalid Input.");let a=null;if(t){if(!(r=await this.getAccount(t)))throw new F(L.errors.TYPE_ERROR,"Invalid Account.");a=r.getReceive().toString()}else a=this.getReceive().toString();return t=new w,r=(new x).pushOp(B.OP_0),e.suggest&&r.pushData(Buffer.from(e.sa,"hex")),t.addInput({prevout:{hash:e.hash,index:e.index},script:r}),e.suggest?t.setSequence(0,2*O.HTLC_CANCEL_PERIOD,!1):t.setSequence(0,O.HTLC_CANCEL_PERIOD,!1),t.addOutput(a,i.value-1e4),t.view.addOutput({hash:e.hash,index:e.index},new _(i)),r=await this.getKey(e.master),await t.signAsync(r,x.hashType.ALL,this.db.workers),e=t.commit(),await this.db.send(e[0]),e}async sendContracts(e,t,i){var r,a=new w;for(r of e)a.outputs.push(i.create(r));return t?await this.fund(a,{account:t}):await this.fund(a),await this.sign(a),e=a.commit(),await this.db.addTX(e[0]),await this.db.send(e[0]),e}async tokenCreate(e,t="",i){r(e&&"object"==typeof e,"Token data should be a object"),r(e.cid,"Token data should has a cid property"),r(e.uid,"Token data should has a uid property"),e.time=!0,await this.ensureAccount({name:t,witness:!0});let a=null;if(i){if(!await this.belongToAccount(t,i))throw new F(L.errors.TYPE_ERROR,`tokenCreate address error: addr:${i} is not belongs to account:`+t);a=await this.getKey(i)}else a=await this.createReceive(t,n.hashInt(e.cid),this.master);return a.signData(e)}async sign(e,t,i=x.hashType.ALL,r){if(this.watchOnly)throw new Error("Cannot sign from a watch-only wallet.");return await this.unlock(t),t=await this.deriveInputs(e),e.signAsync(t,i,this.db.workers,r)}getCoinView(e){return this.txdb.getCoinView(e)}getSpentView(e){return this.txdb.getSpentView(e)}toDetails(e){return this.txdb.toDetails(e)}getDetails(e){return this.txdb.getDetails(e)}async getCoin(e,t){return this.txdb.getCoin(e,t)}async getCredit(e,t){return this.txdb.getCredit(e,t)}async getStatusOfSC(e){return this.txdb.getStatusOfSC(e)}async setStatusOfSC(e,t){var i=await this.writeLock.lock();try{this.txdb.start();try{await this.txdb._setStatusOfSC(e,t),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}}finally{i()}}getLockedCoins(){return this.txdb.lockedCoins.values}getTX(e){return this.txdb.getTX(e)}getBlocks(){return this.txdb.getBlocks()}getBlock(e){return this.txdb.getBlock(e)}async add(e,t,i){var r=await this.writeLock.lock();try{return await this._add(e,t,i)}finally{r()}}async _add(e,t,i){let r,a;this.txdb.start();try{(r=await this.txdb._add(e,t,i))&&(a=await this.syncOutputDepth(r)),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}return a&&0<a.length&&(this.db.emit("address",this.id,a),this.emit("address",a)),r}async resetBalance(){var e=await this.writeLock.lock();try{this.txdb.start();try{this.txdb.pending.unconfirmed=0,this.txdb.pending.confirmed=0;for(const e of await this.getAccounts()){var t=await this.getBalance(e);this.txdb.pending.unconfirmed+=t.unconfirmed,this.txdb.pending.confirmed+=t.confirmed}this.txdb.put(te.R,this.txdb.pending.commit()),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}}finally{e()}return this.txdb.state.toBalance()}async unconfirm(e){var t=await this.writeLock.lock();try{return await this.txdb.unconfirm(e)}finally{t()}}async remove(e){var t=await this.writeLock.lock();try{return await this.txdb.remove(e)}finally{t()}}async zap(e,t){var i=await this.writeLock.lock();try{return await this._zap(e,t)}finally{i()}}async _zap(e,t){return e=await this.ensureIndex(e),this.txdb.zap(e,t)}async abandon(e){var t=await this.writeLock.lock();try{return await this._abandon(e)}finally{t()}}_abandon(e){return this.txdb.abandon(e)}conserveCoin(e){return this.txdb.conserveCoin(e)}unConserveCoin(e){return this.txdb.unConserveCoin(e)}isConserved(e){return this.txdb.isConserved(e)}getConserved(){return this.txdb.getConserved()}async getHistory(e){return e=await this.ensureIndex(e),this.txdb.getHistory(e)}async getCoins(e){return e=await this.ensureIndex(e),this.txdb.getCoins(e)}async getCredits(e){return e=await this.ensureIndex(e),this.txdb.getCredits(e)}async getSmartCoins(e){var t=[];for(const r of await this.getCredits(e)){var i=r.coin;r.spent||this.txdb.isConserved(i)||-1===i.height&&!r.own||t.push(i)}return t}async getPending(e){return e=await this.ensureIndex(e),this.txdb.getPending(e)}async getBalance(e){return e=await this.ensureIndex(e),this.txdb.getBalance(e)}async queryBalanceLog(e,t=0){return(e=await this.ensureIndex(e))?this.db.queryBalanceLog(this.wid,e,t):[]}async getRange(e,t){return e&&"object"==typeof e&&(t=e,e=null),e=await this.ensureIndex(e),this.txdb.getRange(e,t)}async getLast(e,t){return e=await this.ensureIndex(e),this.txdb.getLast(e,t)}async ensureIndex(e,t){if(null==e){if(t)throw new Error("No account provided.");return null}if(-1===(t=await this.getAccountIndex(e)))throw new Error("Account not found.");return t}getAddress(e){return this.account.getAddress(e)}getReceive(e){return this.account.getReceive(e)}getChange(e){return this.account.getChange(e)}getNested(e){return this.account.getNested(e)}inspect(){return{wid:this.wid,id:this.id,network:this.network.type,initialized:this.initialized,accountDepth:this.accountDepth,token:this.token.toString("hex"),tokenDepth:this.tokenDepth,state:this.txdb.state?this.txdb.state.toJSON(!0):null,master:this.master,account:this.account}}toJSON(e){return{network:this.network.type,wid:this.wid,id:this.id,initialized:this.initialized,watchOnly:this.watchOnly,accountDepth:this.accountDepth,token:this.token.toString("hex"),tokenDepth:this.tokenDepth,height:this.db.curHeight,state:this.txdb.state.toJSON(!0),master:this.master.toJSON(e),account:this.account.toJSON(!0)}}getSize(){var e=0;return(e+=50)+o.sizeVarString(this.id,"ascii")+o.sizeVarlen(this.master.getSize())}toRaw(){var e=this.getSize();return(e=new f(e)).writeU32(this.network.magic),e.writeU32(this.wid),e.writeVarString(this.id,"ascii"),e.writeU8(this.initialized?1:0),e.writeU8(this.watchOnly?1:0),e.writeU32(this.accountDepth),e.writeBytes(this.token),e.writeU32(this.tokenDepth),e.writeVarBytes(this.master.toRaw()),e.render()}fromRaw(e){e=new d(e);var t=s.fromMagic(e.readU32());return this.wid=e.readU32(),this.id=e.readVarString("ascii"),this.initialized=1===e.readU8(),this.watchOnly=1===e.readU8(),this.accountDepth=e.readU32(),this.token=e.readBytes(32),this.tokenDepth=e.readU32(),this.master.fromRaw(e.readVarBytes()),r(t===this.db.network,"Wallet network mismatch."),this}static fromRaw(e,t){return new re(e).fromRaw(t)}static isWallet(e){return e instanceof re}async issueCreate(e,t,i){var r=new G(e),a=((a=(r.source.subjectName||(r.source.subjectName=r.erid),P.fromPrivate(Buffer.from(e.key,"hex"),!0,this.network))).witness=!0,r.sign(a,!0,this.network),r.toOptions(!0));return i?this.send({outputs:[{address:e.address,value:1e4}],comment:a},t):(r=await this.send({outputs:[{address:e.address,value:1e4}],comment:a},t),a.txid=r.txid()),a}async caAbolish(e,t,i){var r=P.fromPrivate(Buffer.from(e.key,"hex"),!0,this.network),a=(r.witness=!0,await this.db.client.execute("ca.byId",[e.erid]));if(!a)throw new F(L.errors.TYPE_ERROR,"ca.abolish: Invalid erid.");if(a.source.cid!=e.cid)throw new F(L.errors.TYPE_ERROR,"ca.abolish: Invalid cid.");if(a.source.uid!=e.uid)throw new F(L.errors.TYPE_ERROR,"ca.abolish: Invalid uid.");var s=a.signature;if(a.sign(r,!0,this.network),a.witness!=e.witness||a.signature!=s)throw new F(L.errors.TYPE_ERROR,"ca.abolish: You have no permission to abolish this witness.");return(a=new X(e)).sign(r),s=a.toOptions(!0),i?this.send({outputs:[{address:e.address,value:1e4}],comment:s},t):await this.send({outputs:[{address:e.address,value:1e4}],comment:s},t),s}async enchanceCp(e,t){var i=((e=new J(e)).oper="enchanceCp",await this.ensureCp(e.to)),r=await this.ensureCp(e.from);if(!(r=await this.getKey(r.pubAddress)))throw new F(L.errors.TYPE_ERROR,"Invalid cid, Not along to this wallet.");return e.sign(r),r=e.toOptions(!0),[await this.send({outputs:[{address:i.pubAddress,value:1e4}],comment:r},t),r]}async ensureCp(e,t=!1){if(await this.db.flushCP([e]),(e=this.db.cpList.getItem(e))||t)return e;throw new F(L.errors.TYPE_ERROR,"Invalid cid, cannot find cp.")}}e.exports=re},function(e,t,i){"use strict";
|
|
285
|
+
*/const r=i(0);var a=i(16);const s=i(15),n=i(2),o=i(3),c=i(35),u=i(198),h=i(141).sortWithSeq,l=i(6),p=i(94),d=i(1),f=i(4),m=i(69),g=i(334);i(218);const v=i(109),y=i(73),b=i(13),w=i(68),x=i(17),k=i(219),S=i(156),_=i(28),E=i(157),j=i(337),A=i(63),R=i(26),I=i(29),O=i(7),C=i(310),P=i(38),T=S.Mnemonic,{opcodes:B,hashType:N}=i(19),z=i(165),F=i(77),L=i(78),M=i(142),D=i(46),H=i(20),U=i(42),q=i(54),{NotifyMsg:V,ContractStatus:K,ContractType:W,PropStatus:$}=i(5),Y=i(37).VerifyError,G=i(153).ErItem,X=i(154).ErAbolishItem,J=i(228).EnchancementItem,Q=i(67),Z=i(59),ee=i(83),te=i(85).txdb,ie=i(31);class re extends a{constructor(e,t){super(),r(e,"DB required."),this.db=e,this.network=e.network,this.logger=e.logger,this.readLock=new u,this.writeLock=new c,this.sendLock=new c,this.indexCache=new A(1e4),this.accountCache=new A(1e4),this.pathCache=new A(1e5),this.current=null,this.wid=0,this.id=null,this.initialized=!1,this.watchOnly=!1,this.accountDepth=0,this.token=o.ZERO_HASH,this.tokenDepth=0,this.master=new j,this.txdb=new g(this),this.account=null,t&&this.fromOptions(t)}fromOptions(e){let t,i,a=e.master;return a?("string"==typeof a&&(a=S.PrivateKey.fromBase58(a,this.network)),r(S.isPrivate(a),"Must create wallet with hd private key.")):(i=new T(e.mnemonic),a=S.fromMnemonic(i,this.network)),r(a.network===this.network,"Network mismatch for master key."),this.master.fromKey(a,i),null!=e.wid&&(r(n.isU32(e.wid)),this.wid=e.wid),e.id&&(r(y.isName(e.id),"Bad wallet ID."),t=e.id),null!=e.initialized&&(r("boolean"==typeof e.initialized),this.initialized=e.initialized),null!=e.watchOnly&&(r("boolean"==typeof e.watchOnly),this.watchOnly=e.watchOnly),null!=e.accountDepth&&(r(n.isU32(e.accountDepth)),this.accountDepth=e.accountDepth),e.token&&(r(Buffer.isBuffer(e.token)),r(32===e.token.length),this.token=e.token),t=t||this.getID(),this.id=t,this}static fromOptions(e,t){return new re(e).fromOptions(t)}async init(e){var t=e.passphrase;r(!this.initialized),this.initialized=!0,t&&await this.master.encrypt(t),e=await this._createAccount(e,t);r(e),this.account=e,this.logger.info("Wallet initialized (%s).",this.id),await this.txdb.open()}async open(){r(this.initialized);var e=await this.getAccount(0);if(!e)throw new Error("Default account not found.");this.account=e,this.logger.info("Wallet opened (%s).",this.id),await this.txdb.open()}async ensureNotifyKey(){this.notifyKey||(await this.ensureAccount({name:"alliance",witness:!0}),this.notifyKey=await this.createReceive("alliance",1,this.master),this.notifyAddress=this.notifyKey.getAddress("string"))}async createAllianceInfo(e,t,i){var r={alliancename:e,nodeid:t};return e?(r.alliancePrivateKey=l.hash256(Buffer.concat([Buffer.from(e),this.master.key.privateKey])),i?(r.prv=Buffer.alloc(0),r.pub=Buffer.from(i,"hex"),r.awardAddress=b.fromWitnessPubkeyhash(l.hash160(r.pub),this.network.type).toString(this.network.type),r.mnemonic=new T):(i=l.hash256(Buffer.concat([Buffer.from(e+"-"+t),this.master.key.privateKey])),r.mnemonic=new T({entropy:i,language:this.master.mnemonic.language,passphrase:this.master.mnemonic.passphrase}),r.prv=l.hash256(Buffer.from(r.mnemonic.toSeed().toString("hex"))),r.pub=R.publicKeyCreate(r.prv,!0),e=j.fromKey(S.fromMnemonic(r.mnemonic),this.network.type).key.deriveAccount(44,0).derive(9).derive(1),r.awardAddress=b.fromWitnessPubkeyhash(l.hash160(e.publicKey),this.network.type).toString(this.network.type))):(r.mnemonic=T.fromOptions(this.master.mnemonic),r.prv=l.hash256(Buffer.from(r.mnemonic.toSeed().toString("hex"))),r.pub=R.publicKeyCreate(r.prv,!0),r.awardAddress=b.fromWitnessPubkeyhash(l.hash160(r.pub),this.network.type).toString(this.network.type)),r.address=b.fromWitnessPubkeyhash(l.hash160(r.pub),this.network.type).toString(),r}async destroy(){var e=await this.writeLock.lock(),t=await this.sendLock.lock();try{this.db.unregister(this),await this.master.destroy(),this.readLock.destroy(),this.writeLock.destroy(),this.sendLock.destroy()}finally{t(),e()}}async addSharedKey(e,t){var i=await this.writeLock.lock();try{return await this._addSharedKey(e,t)}finally{i()}}async _addSharedKey(e,t){if(t||(t=e,e=null),!(e=await this.getAccount(e=null==e?0:e)))throw new Error("Account not found.");let i;this.start();try{i=await e.addSharedKey(t)}catch(e){throw this.drop(),e}return await this.commit(),i}async removeSharedKey(e,t){var i=await this.writeLock.lock();try{return await this._removeSharedKey(e,t)}finally{i()}}async _removeSharedKey(e,t){if(t||(t=e,e=null),!(e=await this.getAccount(e=null==e?0:e)))throw new Error("Account not found.");let i;this.start();try{i=await e.removeSharedKey(t)}catch(e){throw this.drop(),e}return await this.commit(),i}async setPassphrase(e,t){e&&await this.decrypt(e),t&&await this.encrypt(t)}async encrypt(e){var t=await this.writeLock.lock();try{return await this._encrypt(e)}finally{t()}}async _encrypt(e){e=await this.master.encrypt(e,!0),this.start();try{await this.db.encryptKeys(this,e)}catch(t){throw p(e),this.drop(),t}p(e),this.save(),await this.commit()}async decrypt(e){var t=await this.writeLock.lock();try{return await this._decrypt(e)}finally{t()}}async _decrypt(e){e=await this.master.decrypt(e,!0),this.start();try{await this.db.decryptKeys(this,e)}catch(t){throw p(e),this.drop(),t}p(e),this.save(),await this.commit()}async rename(e){var t=await this.writeLock.lock();try{return await this.db.rename(this,e)}finally{t()}}async writeBalanceLog(e){var t=await this.writeLock.lock();try{return await this.db.writeBalanceLog(this,e)}finally{t()}}async renameAccount(e,t){var i=await this.writeLock.lock();try{return await this._renameAccount(e,t)}finally{i()}}async _renameAccount(e,t){if(!y.isName(t))throw new Error("Bad account name.");var i=await this.getAccount(e);if(!i)throw new Error("Account not found.");if(0===i.accountIndex)throw new Error("Cannot rename default account.");if(await this.hasAccount(t))throw new Error("Account name not available.");e=i.name,this.start(),this.db.renameAccount(i,t),await this.commit(),this.indexCache.remove(e),e=this.pathCache.values();for(const r of e)r.account===i.accountIndex&&(r.name=t)}async lock(){var e=await this.writeLock.lock(),t=await this.sendLock.lock();try{await this.master.lock()}finally{t(),e()}}unlock(e,t){return this.master.unlock(e,t)}getID(){r(this.master.key,"Cannot derive id.");var e,t=this.master.key.derive(44);(e=new f(37)).writeBytes(t.publicKey),e.writeU32(this.network.magic),t=l.hash160(e.render());return(e=new f(27)).writeU8(3),e.writeU8(190),e.writeU8(4),e.writeBytes(t),e.writeChecksum(),m.encode(e.render())}async createAccount(e,t){var i=await this.writeLock.lock();try{return await this._createAccount(e,t)}finally{i()}}async _createAccount(e,t){let i,a,s=e.name,o=(s=s||this.accountDepth.toString(10),0);if(0!=this.accountDepth&&(o=n.hashInt(s)),await this.hasAccountIndex(o))throw new Error("Account Index Conflict.");if(await this.hasAccount(s))throw new Error("Account already exists.");if(await this.unlock(t),this.watchOnly&&e.accountKey){if("string"==typeof(i=e.accountKey)&&(i=S.PublicKey.fromBase58(i,this.network)),!S.isPublic(i))throw new Error("Must add HD public keys to watch only wallet.");r(i.network===this.network,"Network mismatch for watch only key.")}else r(this.master.key),i=(i=this.master.key.deriveAccount(44,o)).toPublic();t={wid:this.wid,id:this.id,name:0===this.accountDepth?"default":s,witness:e.witness,watchOnly:this.watchOnly,accountKey:i,accountIndex:o,type:e.type,m:e.m,n:e.n,keys:e.keys},this.start();try{(a=E.fromOptions(this.db,t)).wallet=this,await a.init()}catch(e){throw this.drop(),e}return this.logger.info("Created account %s/%s/%d.",a.id,a.name,a.accountIndex),this.accountDepth++,this.save(),await this.commit(),a}async ensureAccount(e,t){var i=e.name;return(i=await this.getAccount(i))||this.createAccount(e,t)}getAccounts(){return this.db.getAccounts(this.wid)}getAccountMap(){return this.db.getAccountMap(this.wid)}getAddressHashes(e){return null!=e?this.getAccountHashes(e):this.db.getWalletHashes(this.wid)}async getAccountHashes(e){return e=await this.ensureIndex(e,!0),this.db.getAccountHashes(this.wid,e)}async getAccount(e){if(this.account&&(null==e||"default"===e||"number"==typeof e&&0===e||"string"==typeof e&&0===e.length))return this.account;if(-1===(e=await this.getAccountIndex(e)))return null;var t=await this.readLock.lock(e);try{return await this._getAccount(e)}finally{t()}}async _getAccount(e){var t=this.accountCache.get(e);return t||((t=await this.db.getAccount(this.wid,e))?(t.wallet=this,t.wid=this.wid,t.id=this.id,t.watchOnly=this.watchOnly,await t.open(),this.accountCache.set(e,t),t):null)}async getAccountIndex(e){var t;return null==e?-1:"number"==typeof e?e:null!=(t=this.indexCache.get(e))?t:-1===(t=await this.db.getAccountIndex(this.wid,e))?-1:(this.indexCache.set(e,t),t)}async getAccountName(e){var t;return"string"==typeof e?e:(t=this.accountCache.get(e))?t.name:this.db.getAccountName(this.wid,e)}async hasAccount(e){return-1!==(e=await this.getAccountIndex(e))&&(!!this.accountCache.has(e)||this.db.hasAccount(this.wid,e))}async hasAccountIndex(e){return!!this.accountCache.has(e)||this.db.hasAccount(this.wid,e)}createReceive(e,t=0,i=null){return this.createKey(e,0,t,i)}createChange(e){return this.createKey(e,1)}createNested(e){return this.createKey(e,2)}async createKey(e,t,i=0,r=null){var a=await this.writeLock.lock();try{return await this._createKey(e,t,i,r)}finally{a()}}async _createKey(e,t,i=0,r=null){if(null==t&&(t=e,e=null),!(e=await this.getAccount(e=e||0)))throw new Error("Account not found.");let a;this.start();try{a=await e.createKey(t,i,r)}catch(e){throw this.drop(),e}return await this.commit(),a}async deriveKey(e,t,i,r=null){let a=null;var s=await this.writeLock.lock();try{this.start(),a=await this._deriveKey(e,t,i,r),await this.commit()}catch(e){throw this.drop(),e}finally{s()}return a}async _deriveKey(e,t,i=0,r=null){if(null==t&&(t=e,e=null),e=e||0,e=parseInt(e),e=await this.getAccount(e))return t=await e.deriveKey(t,i,r),await e.saveKey(t),t;throw new Error("Account not found.")}save(){return this.db.save(this)}async saveAccount(e){var t=await this.writeLock.lock();try{this.start(),e._save(),await this.commit(),0==e.accountIndex&&(this.account=e)}finally{t()}}start(){return this.db.start(this)}drop(){return this.db.drop(this)}clear(){return this.db.clear(this)}commit(){return this.db.commit(this)}async hasAddress(e){return e=b.getHash(e,"hex"),null!=await this.getPath(e)}async ownedAddress(e){return!!await this.getKey(e)}async getPath(e){return(e=await this.readPath(e))?(e.name=await this.getAccountName(e.account),r(e.name),this.pathCache.set(e.hash,e),e):null}async readPath(e){e=b.getHash(e,"hex");var t=this.pathCache.get(e);return t||((t=await this.db.getPath(this.wid,e))?(t.id=this.id,t):null)}async hasPath(e){return e=b.getHash(e,"hex"),!!this.pathCache.has(e)||this.db.hasPath(this.wid,e)}async getPaths(e){if(null!=e)return this.getAccountPaths(e);var t=[];for(const e of await this.db.getWalletPaths(this.wid))e.id=this.id,e.name=await this.getAccountName(e.account),r(e.name),this.pathCache.set(e.hash,e),t.push(e);return t}async getAccountPaths(e){var t=await this.ensureIndex(e,!0),i=await this.getAccountHashes(t),a=await this.getAccountName(e),s=(r(a),[]);for(const e of i){var n=await this.readPath(e);r(n),r(n.account===t),n.name=a,this.pathCache.set(n.hash,n),s.push(n)}return s}async importKey(e,t,i){var r=await this.writeLock.lock();try{return await this._importKey(e,t,i)}finally{r()}}async _importKey(e,t,i){if(e&&"object"==typeof e&&(i=t,t=e,e=null),null==e&&(e=0),r(t.network===this.network,"Network mismatch for key."),this.watchOnly){if(t.privateKey)throw new Error("Cannot import privkey into watch-only wallet.")}else if(!t.privateKey)throw new Error("Cannot import pubkey into non watch-only wallet.");var a=t.getHash("hex");if(await this.getPath(a))throw new Error("Key already exists.");if(!(a=await this.getAccount(e)))throw new Error("Account not found.");if(a.type!==E.types.PUBKEYHASH)throw new Error("Cannot import into non-pkh account.");await this.unlock(i),e=k.fromRing(a,t).toPath(),this.master.encrypted&&(e.data=this.master.encipher(e.data,e.hash),r(e.data),e.encrypted=!0),this.start();try{await a.savePath(e)}catch(e){throw this.drop(),e}await this.commit()}async importAddress(e,t){var i=await this.writeLock.lock();try{return await this._importAddress(e,t)}finally{i()}}async _importAddress(e,t){if(t||(t=e,e=null),null==e&&(e=0),t.network!==this.network)throw new Error("Network mismatch for address.");if(!this.watchOnly)throw new Error("Cannot import address into non watch-only wallet.");if(await this.getPath(t))throw new Error("Address already exists.");if(!(e=await this.getAccount(e)))throw new Error("Account not found.");if(e.type!==E.types.PUBKEYHASH)throw new Error("Cannot import into non-pkh account.");t=v.fromAddress(e,t),this.start();try{await e.savePath(t)}catch(e){throw this.drop(),e}await this.commit()}async fund(e,t){var i=await this.writeLock.lock();try{return await this._fund(e,t)}finally{i()}}async _fund(e,t){if(t=t||{},!this.initialized)throw new Error("Wallet is not initialized.");if(this.watchOnly)throw new Error("Cannot fund from watch-only wallet.");let i;if(null!=t.account){if(!(i=await this.getAccount(t.account)))throw new Error("Account not found.")}else i=this.account;if(!i.initialized)throw new Error("Account is not initialized.");let a,s=t.rate;return null==s&&(s=await this.db.estimateFee(t.blocks)),a=t.smart?await this.getSmartCoins(i.name):(a=await this.getCoins(i.name),this.txdb.filterConserved(a)),await e.fund(a,{allowPreInput:t.allowPreInput,noChange:t.noChange,selection:t.selection,round:t.round,depth:t.depth,hardFee:t.hardFee,subtractFee:t.subtractFee,subtractIndex:t.subtractIndex,changeAddress:i.change.getAddress(),height:this.db.curHeight,rate:s,maxFee:t.maxFee,estimate:e=>this.estimateSize(e),network:this.network}),!t.allowInfiniteFee&&t.noChange&&r(e.getFee()<=C.MAX_FEE,"TX exceeds MAX_FEE."),a}async getAccountByAddress(e){return e=b.getHash(e,"hex"),(e=await this.getPath(e))?this.getAccount(e.account):null}async estimateSize(e){var t=O.WITNESS_SCALE_FACTOR,i=b.fromScript(e);if(!i)return-1;var r=await this.getAccountByAddress(i);if(!r)return-1;let a=0;if(e.isScripthash()&&r.witness)switch(r.type){case E.types.PUBKEYHASH:a=4*(a+23);break;case E.types.MULTISIG:a=4*(a+35)}switch(r.type){case E.types.PUBKEYHASH:a=a+74+34;break;case E.types.MULTISIG:a=(a=(a=(a=(a+=1)+74*r.m)+3+1)+34*r.n)+1+1}return r.witness?a=((a+=1)+t-1)/t|0:a+=o.sizeVarint(a),a}async createTX(e){var t=e.outputs,i=new w;r(Array.isArray(t),"Outputs must be an array."),r(0<t.length,"No outputs available."),e.comment&&("object"==typeof e.comment&&(e.comment=JSON.stringify(e.comment)),i.outputs.push(_.fromScript(x.createScript(Buffer.from(e.comment),x.types.NULLDATA),0)));for(const e of t){var a=new _(e),s=a.getAddress();if(a.isDust())throw new Error("Output is dust.");if(0<a.value){if(!s)throw new Error("Cannot send to unknown address.");if(s.isNull())throw new Error("Cannot send to null address.")}i.outputs.push(a)}let n=null;if(e.inputs)for(const t of e.inputs){var o=await this.getTX(t.hash);o&&(o=q.fromTX(o.tx,t.index,-1,0))&&(n=o.getAddress(),e.allowPreInput=!0,i.addCoin(o))}else await this.fund(i,e);if(n&&((t=new _).value=i.getFee()-C.MIN_FEE,t.script.fromAddress(n),i.outputs.push(t),i.changeIndex=i.outputs.length-1),!1!==e.sort&&i.sortMembers(),null!=e.locktime&&i.setLocktime(e.locktime),r(i.isSane(),"TX failed sanity check."),r(i.verifyInputs(this.db.curHeight+1),"TX failed context check."),0===await this.template(i))throw new Error("Templating failed.");return i}async send(e,t){var i=await this.sendLock.lock();try{return await this._send(e,t)}finally{i()}}async _send(e,t){return t&&(e.account=t),t=await this.createTX(e,!0),await this.sign(t),this.sendMTX(t,{sendafter:e.sendafter})}async sendMTX(e,t={}){if(!e.isSigned())throw new Error("TX could not be fully signed.");var i=e.toTX();if(i.getSigopsCost(e.view)>I.MAX_TX_SIGOPS_COST)throw new Error("TX exceeds policy sigops.");if(i.getWeight()>I.MAX_TX_WEIGHT)throw new Error("TX exceeds policy weight.");return t.sendafter||(this.logger.debug("Sending wallet tx (%s): %s",this.id,i.txid()),await this.db.addTX(i),await this.db.send(i)),i}async resend(){var e=await this.getPending(),t=(0<e.length&&this.logger.info("Rebroadcasting %d transactions.",e.length),[]);for(const i of e)t.push(i.tx);for(const e of h(t))await this.db.send(e);return t}async deriveInputs(e){r(e.mutable);var t=[];for(const r of await this.getInputPaths(e)){var i=await this.getAccount(r.account);i&&(i=i.derivePath(r,this.master))&&t.push(i)}return t}async getKey(e){try{var t,i=b.getHash(e,"hex",this.network.type),r=await this.getPath(i);return r&&(t=await this.getAccount(r.account))?t.derivePath(r,this.master):null}catch{return null}}async exportToFile(e){if(!Z.unsupported){var t=await this.db.getTip(),i=n.date();let o="",c=[n.fmt("# Wallet Dump created by %s %s",ee.protocol,ee.version),n.fmt("# * Created on %s",i),n.fmt("# * Best block at time of backup was %d (%s).",t.height,n.revHex(t.hash)),n.fmt("# * File: %s",e.file),""];var r,a;t=n.fmt("W %s wid= %s",this.toRaw().toString("base64"),this.wid),t=(c.push(t),await this.getAccounts());for(const e of t){var s=await this.getAccount(e);s=n.fmt("C %s name= %s index= %d",s.toRaw().toString("base64"),s.name,s.accountIndex);c.push(s)}for(const t of await this.getAddressHashes())this.watchOnly?(r=b.fromWitnessPubkeyhash(Buffer.from(t,"hex"),this.network.type).toString(),r=n.fmt("A %s %s label= account= %s branch= %s index= %s addr= %s","S",i,0,-1,-1,r),c.push(r)):(r=await this.getPrivateKey(t))&&(a=r.getAddress("string"),a=n.fmt("A %s %s label= account= %s branch= %s index= %s addr= %s",r.toSecret(),i,r.account,r.branch,r.index,a),c.push(a),e.fragment)&&1e5<c.length&&(o=c.join("\n"),await Z.writeFile(e.file.split(".").reduce((e,t)=>(e?e+="."+t:e=t+"-1",e),""),o,"utf8"),c=[]);c.push(""),c.push("# End of dump"),c.push(""),o=c.join("\n"),await Z.writeFile(e.file,o,"utf8")}}async getPrivateKey(e,t){if(e=b.getHash(e,"hex"),!(e=await this.getPath(e)))return null;var i=await this.getAccount(e.account);return i?(await this.unlock(t),(t=i.derivePath(e,this.master)).privateKey?t:null):null}async getInputPaths(e){if(r(e.mutable),!e.hasCoins())throw new Error("Not all coins available.");var t=[];for(const r of e.getInputHashes("hex")){var i=await this.getPath(r);i&&t.push(i)}return t}async getOutputPaths(e){var t=[];for(const r of e.getOutputHashes("hex")){var i=await this.getPath(r);i&&t.push(i)}return t}async setLookahead(e,t){var i=await this.writeLock.lock();try{return this._setLookahead(e,t)}finally{i()}}async _setLookahead(e,t){if(null==t&&(t=e,e=null),!(e=await this.getAccount(e=null==e?0:e)))throw new Error("Account not found.");this.start();try{await e.setLookahead(t)}catch(e){throw this.drop(),e}await this.commit()}async syncOutputDepth(e){var t=new Map;for(const r of e.outputs){var i=r.path;i&&-1!==i.index&&(t.has(i.account)||t.set(i.account,[]),t.get(i.account).push(i))}var a,s,n=[];for([a,s]of t){let e=-1,t=-1,i=-1;for(const r of s)switch(r.branch){case 0:r.index>e&&(e=r.index);break;case 1:r.index>t&&(t=r.index);break;case 2:r.index>i&&(i=r.index)}e+=2,t+=2,i+=2;var o=await this.getAccount(a);(o=(r(o),await o.syncDepth(e,t,i)))&&n.push(o)}return n}async getRedeem(e){"string"==typeof e&&(e=Buffer.from(e,"hex"));var t=await this.getKey(e.toString("hex"));return t?t.getRedeem(e):null}async template(e){var t=await this.deriveInputs(e);return e.sign(t)}async onSaleList(e,t){return(await(await this.getPropList()).predict(async(e,i)=>!!i.bid&&await this.belongToAccount(t,i.bid.address))).where([["pst",$.Sale]]).paginate(10,e).records()}async mySaleList(e,t){return(await(await this.getPropList()).predict(async(e,i)=>this.belongToAccount(t,i.current.address))).where([["pst",$.Sale]]).paginate(10,e).records()}async getPropList(){const e=await this.db.loadVpList();var t=[];for(let i=0;i<e.length;i++){let r=e[i];t.push((async()=>{await this.getPrivateKey(r.current.address)&&(e[i]=[r.pid,r])})())}return await Promise.all(t),new ie(e)}async propCreate(e,t){var i,a=new w;for(i of e){var s=await this.ensureCp(i.cid,!0);!s||i.cid==this.network.genesisId||(i.gold=(0|i.gold)>>>0,i.gold<O.MINPROPVALUE)||(i.pid||(i.pid=M()),i.oid||(i.oid=i.pid),a.propCreate(s.current.address,i),i.index=a.outputs.length-1)}if(0<a.outputs.length){t?await this.fund(a,{account:t}):await this.fund(a),await this.sign(a);var n,o=a.commit();for(n of(await this.db.addTX(o[0]),await this.db.send(o[0]),r(o[0].verify(o[1],x.flags.STANDARD_VERIFY_FLAGS)),e))n.hash=o[0].hash("hex"),n.txid=o[0].txid();return o}return[]}async attach(e,t){var i,a=new w;for(i of e)a.attach(i.address,i.value,i.data);if(0<a.outputs.length){t?await this.fund(a,{account:t}):await this.fund(a),await this.sign(a);var s,n=a.commit();for(s of(await this.db.addTX(n[0]),await this.db.send(n[0]),r(n[0].verify(n[1],x.flags.STANDARD_VERIFY_FLAGS)),e))s.hash=n[0].hash("hex"),s.txid=n[0].txid();return n}return[]}async sendSecret(e,t,i){let r=this.db.$contacts.get(e);if(!r||!r.sender){var a=(await this.createReceive(i)).getAddress("string");if(e==a)throw new F(L.errors.TYPE_ERROR,"Forbid Sending to Self Address.");r=await this.db.ensureContact({contact:e,messenger:a,wallet:this,account:i})}if(r)return r.send(t);throw new F(L.errors.TYPE_ERROR,"Invalid Address.")}async commNotify(e){r(!!e),r(!!e.dst),r(!!e.content);var t=new w,i=e.src||this.getReceive().toString(),a=(i=new V(W.notify,M(),this.db.curHeight,{src:i,content:e.content}),_.fromScript(x.createScript(i.toRaw(),x.types.NULLDATA),0));t.outputs.push(a),a={address:e.dst,locktime:O.BLOCK_DAY,locktype:"csb",value:.1*O.COIN},t.outputs.push(new _(a)),e.account?await this.fund(t,{account:e.account,noChange:!0,allowInfiniteFee:!0}):await this.fund(t,{noChange:!0,allowInfiniteFee:!0}),await this.sign(t),a=t.commit();return r(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(a[0]),this.logger.debug("Sending tx on wallet(%s): %s",this.id,a[0].txid()),await this.db.send(a[0]),i.hash=a[0].hash("hex"),i.height=-1,i}async cpRegister(e,t,i,a){if(r(!!t&&"object"==typeof t),!await this.db.client.execute("canExecute",[{confirm:!1,cid:t.cid,name:t.name,oper:W.cpRegister}]))throw new F(L.errors.TYPE_ERROR,"Invalid CP Register Info.");const s=new w;e||(n=await this.createReceive(i),e=n.getAddress());var n=await this.getKey(e);if(!n)throw new F(L.errors.TYPE_ERROR,"Invalid CP Register Address, Not along to this wallet.");if(t.pubAddress=e.toString(),t.pubKey=n.getPublicKey("hex"),t.signMethod="secp256k1",n=await this.createAllianceInfo(),t.register=n.pub.toString("hex"),s.cpRegister(e,O.registerFee,t),n=async()=>{i?await this.fund(s,{account:i}):await this.fund(s),await this.sign(s);var a=s.commit();return r(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(a[0]),await this.db.send(a[0]),t.txid=a[0].txid(),t.addr=e.toString(),a},!a)return n();n()}getSCAddress(e){return e=Q.fromMnemonic(T.fromOptions(O.SmartContractMnemonic),this.network).deriveAccount(44,e).derive(9).derive(1),b.fromWitnessPubkeyhash(l.hash160(e.publicKey),this.network)}async cpChange(e,t){var i=await this.ensureCp(e.cid);if(i.cid==this.network.genesisId||"ATHENA"==i.name)throw new F(L.errors.TYPE_ERROR,"Invalid cp name.");var a=await this.getTX(i.current.hash);if(!a)throw new F(L.errors.TYPE_ERROR,"Do not have permission to change this info.");if(a=a.tx,!await this.belongToAccount(t,a.outputs[0].getAddress()))throw new F(L.errors.TYPE_ERROR,"Invalid account info.");if(e.newName){if(!await this.db.client.execute("canExecute",[{confirm:!1,cid:i.cid,name:e.newName,oper:W.cpChange}]))throw new F(L.errors.TYPE_ERROR,"Invalid CP Change Info.")}else e.newName=i.name;return e.addr||(e.addr=b.fromString(i.current.address)),i=w.cpChange(a,e),t?await this.fund(i,{allowPreInput:!0,account:t}):await this.fund(i,{allowPreInput:!0}),await this.sign(i),a=i.commit(),await this.db.send(a[0]),r(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),e.txid=a[0].txid(),a}async propExchangeList(e,t,i=!1){var a,s,n,o=new w,c=[];for([a,s,n]of e){var u,h=null;if(h=await this.getTX(a.hash)){if(h=h.tx,u=a.index,h&&h.outputs&&!(h.outputs.length<=u)){if(i){if(!await this.ownedAddress(h.outputs[u].getAddress())){this.logger.error("not owned prop:",a.hash,a.index);continue}}else if(!await this.belongToAccount(t,h.outputs[u].getAddress())){this.logger.error("not owned prop:",a.hash,a.index);continue}var l=h.outputs[u].getReturnData();l&&(o.propExchange(h,u,s),l.index=o.outputs.length-1,l.addr=s.toString(),c.push(l))}}else this.logger.error("tx not find:",a.hash,n)}return t?await this.fund(o,{allowPreInput:!0,account:t}):await this.fund(o,{allowPreInput:!0}),await this.sign(o),e=o.commit(),await this.db.addTX(e[0]),await this.db.send(e[0]),r(e[0].verify(e[1],x.flags.STANDARD_VERIFY_FLAGS)),e.push(c),e}async propDonate(e,t){var i=e.index;if(!(e=await this.getTX(e.hash))||!e.tx||!e.tx.outputs||e.tx.outputs.length<=i)throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");if(!await this.belongToAccount(t,e.tx.outputs[i].getAddress()))throw new F(L.errors.TYPE_ERROR,"Props that do not belong to you.");if(!(t=e.tx.outputs[i].getReturnData()))throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");if(t.cid&&t.cid==this.network.genesisId)throw new Y(e.tx,"invalid","Special props that can not to donate",100);var r=new w;return(e=(r.addInputFromTx(e.tx,i),r.addOutput(x.createScript(Buffer.from(JSON.stringify({value:e.tx.outputs[i].value,cid:t.cid,pid:t.pid,oid:t.oid,gaddr:this.getAddress().toString(this.network)})),x.types.NULLDATA),0),await this.sign(r,null,N.NONE|N.ANYONECANPAY),r.commit())).push(t),e}async propReceive(e,t){var i=(e=w.fromTX(e,1)).inputs[0].prevout,r=e.outputs[0].getReturnData();e.view.addOutput({hash:e.inputs[0].prevout.hash,index:e.inputs[0].prevout.index},new _({value:r.value})),e.outputs.pop();let a=this.getAddress().toString(this.network);t&&(s={cid:r.cid,uid:t},a=(s=await this.tokenCreate(s,t)).data.addr),e.outputs.push(_.fromScript(a,r.value,{oper:W.propExchange,pid:r.pid,cid:r.cid,oid:r.oid,prev:{hash:i.hash,index:i.index}})),t?await this.fund(e,{allowPreInput:!0,account:t}):await this.fund(e,{allowPreInput:!0}),await this.sign(e,null,N.ALL,[0]);var s=e.commit();return await this.db.send(s[0]),r.simAddr=a,[s[0],null,r]}async belongToAccount(e,t){return!!t&&!(!(t=await this.getAccountByAddress(t))||e&&t.name!==e)}async propExchange(e,t,i){let a=null,s=0;var n;return Array.isArray(e)?(a=e[0],s=e[1]):(n=await this.getTX(e.hash))&&(a=n.tx,s=e.index),!a||!a.outputs||a.outputs.length<=s?(this.logger.error("Invalid tx info."),null):await this.ownedAddress(a.outputs[s].getAddress())?(n=a.outputs[s].getReturnData())?(e=(new w).propExchange(a,s,t),n.index=e.outputs.length-1,i?await this.fund(e,{allowPreInput:!0,account:i}):await this.fund(e,{allowPreInput:!0}),await this.sign(e),t=e.commit(),await this.db.addTX(t[0]),await this.db.send(t[0]),r(t[0].verify(t[1],x.flags.STANDARD_VERIFY_FLAGS)),t.push(n),t):(this.logger.error("Invalid tx info."),null):(this.logger.error("Invalid user."),null)}async propFound(e,t,i){if(e=await this.getTX(e),r(e),!(e=e.tx))throw new F(L.errors.TYPE_ERROR,"Invalid hex string.");var a=e.outputs[t],s=a.getReturnData();if(!s||s.oper!==W.propExchange&&s.oper!==W.propCreate)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");if(s.cid==this.network.genesisId)throw new Y(block,"invalid","prop found supertoken",100);var n=new w;n.addInputFromTx(e,t),e=_.fromScript(a.getAddress(),a.value),n.outputs.push(e),i?await this.fund(n,{allowPreInput:!0,subtractFee:!0,account:i}):await this.fund(n,{allowPreInput:!0,subtractFee:!0}),await this.sign(n),t=n.commit();return await this.db.send(t[0]),r(t[0].verify(t[1],x.flags.STANDARD_VERIFY_FLAGS)),t.push(s),t}async propSale(e,t,i,a){let s=await this.getTX(e);if(!s)throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");if(s.getDepth(this.db.curHeight)<=0)throw new F(L.errors.TYPE_ERROR,"No enough confirmations.");if(!(s=s.tx))throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");var n=s.outputs[t].getReturnData([x.opcodes.OP_PROPEXCHANGE,x.opcodes.OP_PROPCREATE]);if(!n)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");if(!await this.ownedAddress(s.outputs[t].getAddress()))throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");var o=await this.getCoin(e,t);if(!o||-1===o.height)throw new F(L.errors.WALLET_INSUFFICIENT_FUNDS,"Invalid coin.");if(await this.txdb.isSpent(e,t))throw new F(L.errors.WALLET_INSUFFICIENT_FUNDS,"Invalid coin.");if(i<=s.outputs[t].value)throw new F(L.errors.TYPE_ERROR,"Invalid fixed price.");if(n.cid==this.network.genesisId)throw new Y(s,"invalid","prop not for sale",100);return e=(o=new w).addInputFromTx(s,t),t={oper:W.propSale,pid:n.pid,prev:{hash:e.prevout.hash,index:e.prevout.index},fixed:i,period:this.db.curHeight+O.BLOCK_DAY},n=_.fromScript(x.createScript(Buffer.from(JSON.stringify(t)),x.types.NULLDATA),0),o.outputs.push(n),await this.sign(o,null,N.SINGLE|N.ANYONECANPAY),e=o.commit(),r(e[0].verify(e[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.send(e[0]),e}async propBuy(e,t,i){if(!(e=this.db.propList.get(e))||e.pst!=$.Sale||!e.bid||!e.bid.raw)throw new F(L.errors.INVALID_PARAMS,"Invalid Tx Hash.");var r=H.fromRaw(Buffer.from(e.bid.raw,"hex")),a=(await this.createReceive(i)).getAddress(),s=e.gold;if(t<s)throw new Error("wrong price");if(1<r.outputs.length&&t<r.outputs[1].value)throw new Error("low bid price than before");var n=w.fromTX(r,1);if(!n.outputs[0].getReturnType(B.OP_RETURN))throw new Error("not a sale order");return await this.remove(r.hash("hex")),n.view.addOutput({hash:n.inputs[0].prevout.hash,index:n.inputs[0].prevout.index},new _({value:e.gold})),t=new _({address:e.current.address,value:t}),n.outputs.push(t),t={oper:W.propExchange,pid:e.pid,cid:e.cid,oid:e.oid,prev:{hash:n.inputs[0].prevout.hash,index:n.inputs[0].prevout.index}},a=_.fromScript(a,s,t),n.outputs.push(a),i?await this.fund(n,{allowPreInput:!0,account:i}):await this.fund(n,{allowPreInput:!0}),await this.sign(n,null,N.ALL,[0]),s=n.commit(),e.owned||this.db.client.watchOutpoint((new D).fromOptions(r.inputs[0].prevout)),await this.db.send(s[0]),s}async getTXByAmount(e,t){let i=null;var r;for(r of await this.getCoins(t))if(!(r.height<=0)&&r.value==e){i=r;break}return i&&(t=await this.getTX(i.hash))?[t.tx,i.index,i.height]:[]}async contractCreate(e,t,i,a,s){if(this.db.transactionList.query(e,a)!=K.None)throw new F(L.errors.TYPE_ERROR,"Contract with the same address finded.");if(0!=parseInt(t%1e3,10))throw new F(L.errors.TYPE_ERROR,"Contract source should an integer multiple of 1000.");if(!await U.checkSum(this.network,e,a))throw new F(L.errors.TYPE_ERROR,"Create contract with an invalid Address or a Address with old transations.");let n=!1,[o,c,u]=await this.getTXByAmount(t,s);if(!o){n=!0;var h=new w;let e="";e=(s?await this.createReceive(s):this).getAddress(),h.outputs.push(_.fromScript(e,t)),s?await this.fund(h,{allowPreInput:!0,account:s}):await this.fund(h,{allowPreInput:!0}),await this.sign(h),h=h.commit(),r(h[0].verify(h[1],x.flags.STANDARD_VERIFY_FLAGS)),o=h[0],c=0,u=-1}(h=new w).addInputFromTx(o,c,u);let l="";l=(s?await this.createReceive(s):this).getAddress();var p=await this.getKey(l);e={oper:W.contractCreate,type:e,addr:a,src:t,dst:i,srcact:s,alice:p.getPublicKey("hex"),period:this.db.curHeight+O.TRANSACTION_PERIOD},a=_.fromScript(x.createScript(Buffer.from(JSON.stringify(e)),x.types.NULLDATA),0),h.outputs.push(a),await this.sign(h,null,N.SINGLE|N.ANYONECANPAY),t=h.commit();return n&&await this.db.send(o),await this.db.send(t[0]),t}async contractPromise(e,t){if(!(e=this.db.transactionList.get(e))||e.transStatus!=K.CreatedOnMem)throw new F(L.errors.INVALID_PARAMS,"Invalid Tx id.");if(!(e=H.fromRaw(Buffer.from(e.raw,"hex"))))throw new F(L.errors.TYPE_ERROR,"Invalid Tx id.");var i=U.parseContract(e);if(!i||i.oper!==W.contractCreate)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");var r=w.fromTX(e,1);if(!r.outputs[0].getReturnType(B.OP_RETURN))throw new Error("not a valid contract");r.view.addOutput({hash:r.inputs[0].prevout.hash,index:r.inputs[0].prevout.index},new _({value:i.src}));let a="";a=(t?await this.createReceive(t):this).getAddress();var s=await this.getKey(a);e={oper:W.contractPromise,prevhash:e.hash("hex"),type:i.type,addr:i.addr,dst:i.dst,srcact:i.srcact,dstact:t,bob:s.getPublicKey("hex"),period:i.period},t=new x([z.fromSymbol("promise"),z.fromData(Buffer.from(JSON.stringify(e))),z.fromSymbol("drop"),z.fromSymbol("greaterthan"),z.fromSymbol("drop"),z.fromSymbol("if"),z.fromData(l.hash160(Buffer.from(e.bob,"hex"))),z.fromSymbol("else"),z.fromData(l.hash160(Buffer.from(i.alice,"hex"))),z.fromSymbol("endif"),z.fromSymbol("checksig")]),r.outputs.push(_.fromScript(t,i.src)),await this.remove(e.prevhash),await this.sign(r,null,N.ALL,[0]),s=r.commit();return await this.db.send(s[0]),e.current={hash:s[0].hash("hex"),index:0},e.raw=s[0].toRaw().toString("hex"),e.transStatus=K.Promised,this.db.transactionList.saveContract(e,!0),s}async contractExecute(e,t){if(!(e=this.db.transactionList.get(e))||e.transStatus!=K.Confirmed&&e.transStatus!=K.Expired)throw new F(L.errors.INVALID_PARAMS,"Invalid Tx id.");if(!(e=H.fromRaw(Buffer.from(e.raw,"hex"))))throw new F(L.errors.TYPE_ERROR,"Invalid Tx id.");t=t||1;var i=U.parseContract(e);if(!i||i.oper!==W.contractPromise)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");var a=e.outputs[1].getReturnData();if(!a||a.oper!==W.contractPromise)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");r.strictEqual(i.addr,a.addr),r.strictEqual(i.type,a.type),r.strictEqual(i.dst,a.dst),r.strictEqual(i.period,a.period),r.strictEqual(i.srcact,a.srcact),r.strictEqual(i.dstact,a.dstact);var s=this.db.transactionList.query(i.type,i.addr);if(s!=K.Confirmed&&s!=K.Expired)throw new F(L.errors.TYPE_ERROR,"Contract Promise not Check yet.");if(s==K.Expired&&1!=t||s==K.Confirmed&&2!=t)throw new F(L.errors.TYPE_ERROR,"Invalid Executor.");let n=i.srcact,o=(2==t&&(n=i.dstact),"");o=(n?await this.createReceive(n):this).getAddress();var c=new w,u=(c.addInputFromTx(e,1),{oper:W.contractExecute,type:i.type,addr:i.addr,master:t});u=_.fromScript(x.createScript(Buffer.from(JSON.stringify(u)),x.types.NULLDATA),0),c.outputs.push(u),u=_.fromScript(o,e.outputs[1].value),c.outputs.push(u),e=1==t?await P.fromPublic(Buffer.from(i.ori.alice,"hex")):await P.fromPublic(Buffer.from(a.bob,"hex")),u=await this.getKey(e.getAddress()),await c.signAsync(u,x.hashType.ALL,this.db.workers),t=c.commit();return r(t[0].verify(t[1],x.flags.STANDARD_VERIFY_FLAGS,s)),await this.db.send(t[0]),t}async htlcDeal(e,t){var i=await this.getTX(e.hash);let r=null;if(t){if(!(t=await this.getAccount(t)))throw new F(L.errors.TYPE_ERROR,"Invalid Account.");r=t.getReceive().toString()}else r=this.getReceive().toString();t=new w;var a=(new x).pushOp(B.OP_1);e.suggest&&a.pushData(Buffer.from(e.sa,"hex")),t.addInput({prevout:{hash:e.hash,index:e.index},script:a}),t.addOutput(r,i.tx.outputs[e.index].value-1e4),t.view.addOutput({hash:e.hash,index:e.index},new _(i.tx.outputs[e.index])),await this.sign(t,null,N.ALL),a=t.commit();return await this.db.send(a[0]),a}async htlcCancel(e,t){let i=null;var r=await this.getTX(e.hash);if(!(i=r?r.tx.outputs[e.index]:i))throw new F(L.errors.TYPE_ERROR,"Invalid Input.");let a=null;if(t){if(!(r=await this.getAccount(t)))throw new F(L.errors.TYPE_ERROR,"Invalid Account.");a=r.getReceive().toString()}else a=this.getReceive().toString();return t=new w,r=(new x).pushOp(B.OP_0),e.suggest&&r.pushData(Buffer.from(e.sa,"hex")),t.addInput({prevout:{hash:e.hash,index:e.index},script:r}),e.suggest?t.setSequence(0,2*O.HTLC_CANCEL_PERIOD,!1):t.setSequence(0,O.HTLC_CANCEL_PERIOD,!1),t.addOutput(a,i.value-1e4),t.view.addOutput({hash:e.hash,index:e.index},new _(i)),r=await this.getKey(e.master),await t.signAsync(r,x.hashType.ALL,this.db.workers),e=t.commit(),await this.db.send(e[0]),e}async sendContracts(e,t,i){var r,a=new w;for(r of e)a.outputs.push(i.create(r));return t?await this.fund(a,{account:t}):await this.fund(a),await this.sign(a),e=a.commit(),await this.db.addTX(e[0]),await this.db.send(e[0]),e}async tokenCreate(e,t="",i){r(e&&"object"==typeof e,"Token data should be a object"),r(e.cid,"Token data should has a cid property"),r(e.uid,"Token data should has a uid property"),e.time=!0,await this.ensureAccount({name:t,witness:!0});let a=null;if(i){if(!await this.belongToAccount(t,i))throw new F(L.errors.TYPE_ERROR,`tokenCreate address error: addr:${i} is not belongs to account:`+t);a=await this.getKey(i)}else a=await this.createReceive(t,n.hashInt(e.cid),this.master);return a.signData(e)}async sign(e,t,i=x.hashType.ALL,r){if(this.watchOnly)throw new Error("Cannot sign from a watch-only wallet.");return await this.unlock(t),t=await this.deriveInputs(e),e.signAsync(t,i,this.db.workers,r)}getCoinView(e){return this.txdb.getCoinView(e)}getSpentView(e){return this.txdb.getSpentView(e)}toDetails(e){return this.txdb.toDetails(e)}getDetails(e){return this.txdb.getDetails(e)}async getCoin(e,t){return this.txdb.getCoin(e,t)}async getCredit(e,t){return this.txdb.getCredit(e,t)}async getStatusOfSC(e){return this.txdb.getStatusOfSC(e)}async setStatusOfSC(e,t){var i=await this.writeLock.lock();try{this.txdb.start();try{await this.txdb._setStatusOfSC(e,t),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}}finally{i()}}getLockedCoins(){return this.txdb.lockedCoins.values}getTX(e){return this.txdb.getTX(e)}getBlocks(){return this.txdb.getBlocks()}getBlock(e){return this.txdb.getBlock(e)}async add(e,t,i){var r=await this.writeLock.lock();try{return await this._add(e,t,i)}finally{r()}}async _add(e,t,i){let r,a;this.txdb.start();try{(r=await this.txdb._add(e,t,i))&&(a=await this.syncOutputDepth(r)),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}return a&&0<a.length&&(this.db.emit("address",this.id,a),this.emit("address",a)),r}async resetBalance(){var e=await this.writeLock.lock();try{this.txdb.start();try{this.txdb.pending.unconfirmed=0,this.txdb.pending.confirmed=0;for(const e of await this.getAccounts()){var t=await this.getBalance(e);this.txdb.pending.unconfirmed+=t.unconfirmed,this.txdb.pending.confirmed+=t.confirmed}this.txdb.put(te.R,this.txdb.pending.commit()),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}}finally{e()}return this.txdb.state.toBalance()}async unconfirm(e){var t=await this.writeLock.lock();try{return await this.txdb.unconfirm(e)}finally{t()}}async remove(e){var t=await this.writeLock.lock();try{return await this.txdb.remove(e)}finally{t()}}async zap(e,t){var i=await this.writeLock.lock();try{return await this._zap(e,t)}finally{i()}}async _zap(e,t){return e=await this.ensureIndex(e),this.txdb.zap(e,t)}async abandon(e){var t=await this.writeLock.lock();try{return await this._abandon(e)}finally{t()}}_abandon(e){return this.txdb.abandon(e)}conserveCoin(e){return this.txdb.conserveCoin(e)}unConserveCoin(e){return this.txdb.unConserveCoin(e)}isConserved(e){return this.txdb.isConserved(e)}getConserved(){return this.txdb.getConserved()}async getHistory(e){return e=await this.ensureIndex(e),this.txdb.getHistory(e)}async getCoins(e){return e=await this.ensureIndex(e),this.txdb.getCoins(e)}async getCredits(e){return e=await this.ensureIndex(e),this.txdb.getCredits(e)}async getSmartCoins(e){var t=[];for(const r of await this.getCredits(e)){var i=r.coin;r.spent||this.txdb.isConserved(i)||-1===i.height&&!r.own||t.push(i)}return t}async getPending(e){return e=await this.ensureIndex(e),this.txdb.getPending(e)}async getBalance(e){return e=await this.ensureIndex(e),this.txdb.getBalance(e)}async queryBalanceLog(e,t=0){return(e=await this.ensureIndex(e))?this.db.queryBalanceLog(this.wid,e,t):[]}async getRange(e,t){return e&&"object"==typeof e&&(t=e,e=null),e=await this.ensureIndex(e),this.txdb.getRange(e,t)}async getLast(e,t){return e=await this.ensureIndex(e),this.txdb.getLast(e,t)}async ensureIndex(e,t){if(null==e){if(t)throw new Error("No account provided.");return null}if(-1===(t=await this.getAccountIndex(e)))throw new Error("Account not found.");return t}getAddress(e){return this.account.getAddress(e)}getReceive(e){return this.account.getReceive(e)}getChange(e){return this.account.getChange(e)}getNested(e){return this.account.getNested(e)}inspect(){return{wid:this.wid,id:this.id,network:this.network.type,initialized:this.initialized,accountDepth:this.accountDepth,token:this.token.toString("hex"),tokenDepth:this.tokenDepth,state:this.txdb.state?this.txdb.state.toJSON(!0):null,master:this.master,account:this.account}}toJSON(e){return{network:this.network.type,wid:this.wid,id:this.id,initialized:this.initialized,watchOnly:this.watchOnly,accountDepth:this.accountDepth,token:this.token.toString("hex"),tokenDepth:this.tokenDepth,height:this.db.curHeight,state:this.txdb.state.toJSON(!0),master:this.master.toJSON(e),account:this.account.toJSON(!0)}}getSize(){var e=0;return(e+=50)+o.sizeVarString(this.id,"ascii")+o.sizeVarlen(this.master.getSize())}toRaw(){var e=this.getSize();return(e=new f(e)).writeU32(this.network.magic),e.writeU32(this.wid),e.writeVarString(this.id,"ascii"),e.writeU8(this.initialized?1:0),e.writeU8(this.watchOnly?1:0),e.writeU32(this.accountDepth),e.writeBytes(this.token),e.writeU32(this.tokenDepth),e.writeVarBytes(this.master.toRaw()),e.render()}fromRaw(e){e=new d(e);var t=s.fromMagic(e.readU32());return this.wid=e.readU32(),this.id=e.readVarString("ascii"),this.initialized=1===e.readU8(),this.watchOnly=1===e.readU8(),this.accountDepth=e.readU32(),this.token=e.readBytes(32),this.tokenDepth=e.readU32(),this.master.fromRaw(e.readVarBytes()),r(t===this.db.network,"Wallet network mismatch."),this}static fromRaw(e,t){return new re(e).fromRaw(t)}static isWallet(e){return e instanceof re}async issueCreate(e,t,i){var r=new G(e),a=((a=(r.source.subjectName||(r.source.subjectName=r.erid),P.fromPrivate(Buffer.from(e.key,"hex"),!0,this.network))).witness=!0,r.sign(a,!0,this.network),r.toOptions(!0));return i?this.send({outputs:[{address:e.address,value:1e4}],comment:a},t):(r=await this.send({outputs:[{address:e.address,value:1e4}],comment:a},t),a.txid=r.txid()),a}async caAbolish(e,t,i){var r=P.fromPrivate(Buffer.from(e.key,"hex"),!0,this.network),a=(r.witness=!0,await this.db.client.execute("ca.byId",[e.erid]));if(!a)throw new F(L.errors.TYPE_ERROR,"ca.abolish: Invalid erid.");if(a.source.cid!=e.cid)throw new F(L.errors.TYPE_ERROR,"ca.abolish: Invalid cid.");if(a.source.uid!=e.uid)throw new F(L.errors.TYPE_ERROR,"ca.abolish: Invalid uid.");var s=a.signature;if(a.sign(r,!0,this.network),a.witness!=e.witness||a.signature!=s)throw new F(L.errors.TYPE_ERROR,"ca.abolish: You have no permission to abolish this witness.");return(a=new X(e)).sign(r),s=a.toOptions(!0),i?this.send({outputs:[{address:e.address,value:1e4}],comment:s},t):await this.send({outputs:[{address:e.address,value:1e4}],comment:s},t),s}async enchanceCp(e,t){var i=((e=new J(e)).oper="enchanceCp",await this.ensureCp(e.to)),r=await this.ensureCp(e.from);if(!(r=await this.getKey(r.pubAddress)))throw new F(L.errors.TYPE_ERROR,"Invalid cid, Not along to this wallet.");return e.sign(r),r=e.toOptions(!0),[await this.send({outputs:[{address:i.pubAddress,value:1e4}],comment:r},t),r]}async ensureCp(e,t=!1){if(await this.db.flushCP([e]),(e=this.db.cpList.getItem(e))||t)return e;throw new F(L.errors.TYPE_ERROR,"Invalid cid, cannot find cp.")}}e.exports=re},function(e,t,i){"use strict";
|
|
286
286
|
/*!
|
|
287
287
|
* BlockMeta.js - walletdb records
|
|
288
288
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
package/lib/gamegold.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const path = require('path');var gpath = path.join(__dirname, '../../../', 'node_modules'); module.exports=function(e){var t={};function i(r){var s;return(t[r]||(s=t[r]={i:r,l:!1,exports:{}},e[r].call(s.exports,s,s.exports,i),s.l=!0,s)).exports}return i.m=e,i.c=t,i.d=function(e,t,r){i.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(i.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var s in e)i.d(r,s,function(t){return e[t]}.bind(null,s));return r},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,"a",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p="",i(i.s=723)}([function(e,t){e.exports=require("assert")},function(e,t,i){"use strict";
|
|
1
|
+
const path = require('path');var gpath = path.join(__dirname, '../../../', 'node_modules'); const path = require('path');var gpath = path.join(__dirname, '../../../', 'node_modules'); module.exports=function(e){var t={};function i(r){var s;return(t[r]||(s=t[r]={i:r,l:!1,exports:{}},e[r].call(s.exports,s,s.exports,i),s.l=!0,s)).exports}return i.m=e,i.c=t,i.d=function(e,t,r){i.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(i.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var s in e)i.d(r,s,function(t){return e[t]}.bind(null,s));return r},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,"a",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p="",i(i.s=723)}([function(e,t){e.exports=require("assert")},function(e,t,i){"use strict";
|
|
2
2
|
/*!
|
|
3
3
|
* reader.js - buffer reader for vallnet
|
|
4
4
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -164,7 +164,7 @@ let r=[];[i(558),i(559),i(560),i(561),i(562),i(563),i(564),i(565),i(566),i(567),
|
|
|
164
164
|
* private.js - hd private keys for vallnet
|
|
165
165
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
166
166
|
* https://github.com/bookmansoft/gamegold
|
|
167
|
-
*/const r=i(0),s=i(2),n=i(6),a=i(94),o=i(70),c=i(26),h=i(15),u=i(4),l=i(1),p=i(69),d=i(3),f=i(140),m=i(197),g=i(304);class y{constructor(e){if(!(this instanceof y))return new y(e);this.disableCache=!1,this.network=h.primary,this.depth=0,this.parentFingerPrint=0,this.childIndex=0,this.chainCode=d.ZERO_HASH,this.privateKey=d.ZERO_HASH,this.publicKey=d.ZERO_KEY,this.fingerPrint=-1,this._xprivkey=null,this._hdPublicKey=null,e&&this.fromOptions(e)}static getHmac(e,t){t=t||d.DefaultChainCode;t=y.fromKey(n.sha256(Buffer.concat([Buffer.from(e),t])),t);var i={id:"primary"};i.cid=e,i.pubkey=t.publicKey.toString("hex"),i.time=s.now()/3600|0,e=n.hash256(Buffer.from(s.stringify(i))),e=c.sign(e,t.privateKey).toString("hex");return{token:i.pubkey,random:e}}fromOptions(e){return r(e,"No options for HD private key."),r(s.isU8(e.depth)),r(s.isU32(e.parentFingerPrint)),r(s.isU32(e.childIndex)),r(Buffer.isBuffer(e.chainCode)),r(Buffer.isBuffer(e.privateKey)),e.network&&(this.network=h.get(e.network)),this.depth=e.depth,this.parentFingerPrint=e.parentFingerPrint,this.childIndex=e.childIndex,this.chainCode=e.chainCode,this.privateKey=e.privateKey,this.publicKey=c.publicKeyCreate(e.privateKey,!0),this}static fromOptions(e){return(new y).fromOptions(e)}toPublic(){let e=this._hdPublicKey;return e||((e=new g).network=this.network,e.depth=this.depth,e.parentFingerPrint=this.parentFingerPrint,e.childIndex=this.childIndex,e.chainCode=this.chainCode,e.publicKey=this.publicKey,this._hdPublicKey=e),e}xprivkey(){return this._xprivkey||(this._xprivkey=this.toBase58()),this._xprivkey}xpubkey(){return this.toPublic().xpubkey()}destroy(e){this.depth=0,this.childIndex=0,this.parentFingerPrint=0,a(this.chainCode),a(this.privateKey),a(this.publicKey),this.fingerPrint=-1,this._hdPublicKey&&(e&&this._hdPublicKey.destroy(),this._hdPublicKey=null),this._xprivkey=null}derive(e,t){if(r("number"==typeof e),e>>>0!==e)throw new Error("Index out of range.");if(255<=this.depth)throw new Error("Depth too high.");if((t&&(e=(e|f.HARDENED)>>>0),t=this.getID(e),!this.disableCache)&&(i=f.cache.get(t)))return i;var i=u.pool(37),s=(i=(e&f.HARDENED?(i.writeU8(0),i.writeBytes(this.privateKey)):i.writeBytes(this.publicKey),i.writeU32BE(e),i.render()),(i=n.hmac("sha512",i,this.chainCode)).slice(0,32));i=i.slice(32,64);let a;try{a=c.privateKeyTweakAdd(this.privateKey,s)}catch(t){return this.derive(e+1)}return-1===this.fingerPrint&&(s=n.hash160(this.publicKey),this.fingerPrint=s.readUInt32BE(0,!0)),(s=new y).disableCache=this.disableCache,s.network=this.network,s.depth=this.depth+1,s.parentFingerPrint=this.fingerPrint,s.childIndex=e,s.chainCode=i,s.privateKey=a,s.publicKey=c.publicKeyCreate(a,!0),this.disableCache||f.cache.set(t,s),s}getID(e){return this.network.keyPrefix.xprivkey58+this.publicKey.toString("hex")+e}deriveAccount(e,t){return r(s.isU32(e),"Purpose must be a number."),r(s.isU32(t),"Account index must be a number."),r(this.isMaster(),"Cannot derive account index."),this.derive(e,!0).derive(this.network.keyPrefix.coinType,!0).derive(t,!0)}isMaster(){return f.isMaster(this)}isAccount(e){return f.isAccount(this,e)}static isBase58(e,t){if("string"!=typeof e)return!1;if(e.length<4)return!1;e=e.substring(0,4);try{return h.fromPrivate58(e,t),!0}catch(e){return!1}}static isRaw(e,t){if(!Buffer.isBuffer(e))return!1;if(e.length<4)return!1;e=e.readUInt32BE(0,!0);try{return h.fromPrivate(e,t),!0}catch(e){return!1}}static isValidPath(e){try{return f.parsePath(e,!0),!0}catch(e){return!1}}derivePath(e){let t=this;for(const i of f.parsePath(e,!0))t=t.derive(i);return t}equals(e){return r(y.isHDPrivateKey(e)),this.network===e.network&&this.depth===e.depth&&this.parentFingerPrint===e.parentFingerPrint&&this.childIndex===e.childIndex&&this.chainCode.equals(e.chainCode)&&this.privateKey.equals(e.privateKey)}compare(e){r(y.isHDPrivateKey(e));var t=this.depth-e.depth;return 0!=t||0!=(t=this.parentFingerPrint-e.parentFingerPrint)||0!=(t=this.childIndex-e.childIndex)||0!==(t=this.chainCode.compare(e.chainCode))||0!==(t=this.privateKey.compare(e.privateKey))?t:0}fromSeed(e,t){if(r(Buffer.isBuffer(e)),8*e.length<f.MIN_ENTROPY||8*e.length>f.MAX_ENTROPY)throw new Error("Entropy not in range.");var i=(e=n.hmac("sha512",e,d.SEED_SALT)).slice(0,32);e=e.slice(32,64);if(c.privateKeyVerify(i))return this.network=h.get(t),this.depth=0,this.parentFingerPrint=0,this.childIndex=0,this.chainCode=e,this.privateKey=i,this.publicKey=c.publicKeyCreate(i,!0),this;throw new Error("Master private key is invalid.")}static fromSeed(e,t){return(new y).fromSeed(e,t)}fromMnemonic(e,t){return r(e instanceof m),this.fromSeed(e.toSeed(),t)}static fromMnemonic(e,t){return(new y).fromMnemonic(e,t)}fromPhrase(e,t){return e=m.fromPhrase(e),this.fromMnemonic(e,t),this}static fromPhrase(e,t){return(new y).fromPhrase(e,t)}static getAes(e,t){var i=Buffer.from(e),r=Buffer.alloc(32);for(let e=0;e<Math.max(32,i.length);e++){var s=e%32;r[s]=i[s]^d.RANDOM_HASH[s]}return y.fromKey(d.RANDOM_HASH,r,t).getAes(e)}fromKey(e,t,i){return r(Buffer.isBuffer(e)&&32===e.length),r(Buffer.isBuffer(t)&&32===t.length),this.network=h.get(i),this.depth=0,this.parentFingerPrint=0,this.childIndex=0,this.chainCode=t,this.privateKey=e,this.publicKey=c.publicKeyCreate(e,!0),this}getAes(e){e=y.getHmac(e,this.chainCode).token;let t=n.hash256(Buffer.from(e));return{aeskey:t.toString("base64").slice(0,32),aesiv:(t=n.hash256(t)).toString("base64").slice(0,16)}}static fromKey(e,t,i){return(new y).fromKey(e,t,i)}static eccEncrypt(e,t){var i=y.generate(),{aeskey:t,aesiv:r}=(t=c.ecdh(t,i.privateKey),y.getAes(t.toString()));return{pub:i.publicKey,msg:s.encrypt(t,r,Buffer.from(e).toString("hex"))}}static eccDecrypt(e,t){t=c.ecdh(e.pub,t);var{aeskey:t,aesiv:i}=y.getAes(t.toString());return Buffer.from(s.decrypt(t,i,e.msg),"hex").toString()}static generate(e){var t=c.generatePrivateKey(),i=o.randomBytes(32);return y.fromKey(t,i,e)}fromBase58(e,t){return r("string"==typeof e),this._xprivkey=e,this.fromRaw(p.decode(e),t)}fromReader(e,t){var i=e.readU32BE();return this.network=h.fromPrivate(i,t),this.depth=e.readU8(),this.parentFingerPrint=e.readU32BE(),this.childIndex=e.readU32BE(),this.chainCode=e.readBytes(32),r(0===e.readU8()),this.privateKey=e.readBytes(32),this.publicKey=c.publicKeyCreate(this.privateKey,!0),e.verifyChecksum(),this}fromRaw(e,t){return this.fromReader(new l(e),t)}toBase58(e){return p.encode(this.toRaw(e))}getSize(){return 82}toWriter(e,t){return t=t||this.network,t=h.get(t),e.writeU32BE(t.keyPrefix.xprivkey),e.writeU8(this.depth),e.writeU32BE(this.parentFingerPrint),e.writeU32BE(this.childIndex),e.writeBytes(this.chainCode),e.writeU8(0),e.writeBytes(this.privateKey),e.writeChecksum(),e}toRaw(e){return this.toWriter(new u(82),e).render()}static fromBase58(e,t){return(new y).fromBase58(e,t)}static fromReader(e,t){return(new y).fromReader(e,t)}static fromRaw(e,t){return(new y).fromRaw(e,t)}toJSON(){return{xprivkey:this.xprivkey(),pubkey:this.publicKey.toString("hex")}}fromJSON(e,t){return r(e.xprivkey,"Could not handle key JSON."),this.fromBase58(e.xprivkey,t),this}static fromJSON(e,t){return(new y).fromJSON(e,t)}static isHDPrivateKey(e){return e instanceof y}}e.exports=y},function(e,t,i){"use strict";
|
|
167
|
+
*/const r=i(0),s=i(2),n=i(6),a=i(94),o=i(70),c=i(26),h=i(15),u=i(4),l=i(1),p=i(69),d=i(3),f=i(140),m=i(197),g=i(304);class y{constructor(e){if(!(this instanceof y))return new y(e);this.disableCache=!1,this.network=h.primary,this.depth=0,this.parentFingerPrint=0,this.childIndex=0,this.chainCode=d.ZERO_HASH,this.privateKey=d.ZERO_HASH,this.publicKey=d.ZERO_KEY,this.fingerPrint=-1,this._xprivkey=null,this._hdPublicKey=null,e&&this.fromOptions(e)}static getHmac(e,t){t=t||d.DefaultChainCode;t=y.fromKey(n.sha256(Buffer.concat([Buffer.from(e),t])),t);var i={id:"primary"};i.cid=e,i.pubkey=t.publicKey.toString("hex"),i.time=s.now()/3600|0,e=n.hash256(Buffer.from(s.stringify(i))),e=c.sign(e,t.privateKey).toString("hex");return{token:i.pubkey,random:e}}fromOptions(e){return r(e,"No options for HD private key."),r(s.isU8(e.depth)),r(s.isU32(e.parentFingerPrint)),r(s.isU32(e.childIndex)),r(Buffer.isBuffer(e.chainCode)),r(Buffer.isBuffer(e.privateKey)),e.network&&(this.network=h.get(e.network)),this.depth=e.depth,this.parentFingerPrint=e.parentFingerPrint,this.childIndex=e.childIndex,this.chainCode=e.chainCode,this.privateKey=e.privateKey,this.publicKey=c.publicKeyCreate(e.privateKey,!0),this}static fromOptions(e){return(new y).fromOptions(e)}toPublic(){let e=this._hdPublicKey;return e||((e=new g).network=this.network,e.depth=this.depth,e.parentFingerPrint=this.parentFingerPrint,e.childIndex=this.childIndex,e.chainCode=this.chainCode,e.publicKey=this.publicKey,this._hdPublicKey=e),e}xprivkey(){return this._xprivkey||(this._xprivkey=this.toBase58()),this._xprivkey}xpubkey(){return this.toPublic().xpubkey()}destroy(e){this.depth=0,this.childIndex=0,this.parentFingerPrint=0,a(this.chainCode),a(this.privateKey),a(this.publicKey),this.fingerPrint=-1,this._hdPublicKey&&(e&&this._hdPublicKey.destroy(),this._hdPublicKey=null),this._xprivkey=null}derive(e,t){if(r("number"==typeof e),e>>>0!==e)throw new Error("Index out of range.");if(255<=this.depth)throw new Error("Depth too high.");if((t&&(e=(e|f.HARDENED)>>>0),t=this.getID(e),!this.disableCache)&&(i=f.cache.get(t)))return i;var i=u.pool(37),s=(i=(e&f.HARDENED?(i.writeU8(0),i.writeBytes(this.privateKey)):i.writeBytes(this.publicKey),i.writeU32BE(e),i.render()),(i=n.hmac("sha512",i,this.chainCode)).slice(0,32));i=i.slice(32,64);let a;try{a=c.privateKeyTweakAdd(this.privateKey,s)}catch(t){return this.derive(e+1)}return-1===this.fingerPrint&&(s=n.hash160(this.publicKey),this.fingerPrint=s.readUInt32BE(0,!0)),(s=new y).disableCache=this.disableCache,s.network=this.network,s.depth=this.depth+1,s.parentFingerPrint=this.fingerPrint,s.childIndex=e,s.chainCode=i,s.privateKey=a,s.publicKey=c.publicKeyCreate(a,!0),this.disableCache||f.cache.set(t,s),s}getID(e){return this.network.keyPrefix.xprivkey58+this.publicKey.toString("hex")+e}deriveAccount(e,t){return r(s.isU32(e),"Purpose must be a number."),r(s.isU32(t),"Account index must be a number."),r(this.isMaster(),"Cannot derive account index."),this.derive(e,!0).derive(this.network.keyPrefix.coinType,!0).derive(t,!0)}isMaster(){return f.isMaster(this)}isAccount(e){return f.isAccount(this,e)}static isBase58(e,t){if("string"!=typeof e)return!1;if(e.length<4)return!1;e=e.substring(0,4);try{return h.fromPrivate58(e,t),!0}catch(e){return!1}}static isRaw(e,t){if(!Buffer.isBuffer(e))return!1;if(e.length<4)return!1;e=e.readUInt32BE(0,!0);try{return h.fromPrivate(e,t),!0}catch(e){return!1}}static isValidPath(e){try{return f.parsePath(e,!0),!0}catch(e){return!1}}derivePath(e){let t=this;for(const i of f.parsePath(e,!0))t=t.derive(i);return t}equals(e){return r(y.isHDPrivateKey(e)),this.network===e.network&&this.depth===e.depth&&this.parentFingerPrint===e.parentFingerPrint&&this.childIndex===e.childIndex&&this.chainCode.equals(e.chainCode)&&this.privateKey.equals(e.privateKey)}compare(e){r(y.isHDPrivateKey(e));var t=this.depth-e.depth;return 0!=t||0!=(t=this.parentFingerPrint-e.parentFingerPrint)||0!=(t=this.childIndex-e.childIndex)||0!==(t=this.chainCode.compare(e.chainCode))||0!==(t=this.privateKey.compare(e.privateKey))?t:0}fromSeed(e,t){if(e instanceof Buffer?r(Buffer.isBuffer(e)):(r("object"==typeof e&&0<e.length),e=Buffer.from(e)),8*e.length<f.MIN_ENTROPY||8*e.length>f.MAX_ENTROPY)throw new Error("Entropy not in range.");var i=(e=n.hmac("sha512",e,d.SEED_SALT)).slice(0,32);e=e.slice(32,64);if(c.privateKeyVerify(i))return this.network=h.get(t),this.depth=0,this.parentFingerPrint=0,this.childIndex=0,this.chainCode=e,this.privateKey=i,this.publicKey=c.publicKeyCreate(i,!0),this;throw new Error("Master private key is invalid.")}static fromSeed(e,t){return(new y).fromSeed(e,t)}fromMnemonic(e,t){return r(e instanceof m),this.fromSeed(e.toSeed(),t)}static fromMnemonic(e,t){return(new y).fromMnemonic(e,t)}fromPhrase(e,t){return e=m.fromPhrase(e),this.fromMnemonic(e,t),this}static fromPhrase(e,t){return(new y).fromPhrase(e,t)}static getAes(e,t){var i=Buffer.from(e),r=Buffer.alloc(32);for(let e=0;e<Math.max(32,i.length);e++){var s=e%32;r[s]=i[s]^d.RANDOM_HASH[s]}return y.fromKey(d.RANDOM_HASH,r,t).getAes(e)}fromKey(e,t,i){return r(Buffer.isBuffer(e)&&32===e.length),r(Buffer.isBuffer(t)&&32===t.length),this.network=h.get(i),this.depth=0,this.parentFingerPrint=0,this.childIndex=0,this.chainCode=t,this.privateKey=e,this.publicKey=c.publicKeyCreate(e,!0),this}getAes(e){e=y.getHmac(e,this.chainCode).token;let t=n.hash256(Buffer.from(e));return{aeskey:t.toString("base64").slice(0,32),aesiv:(t=n.hash256(t)).toString("base64").slice(0,16)}}static fromKey(e,t,i){return(new y).fromKey(e,t,i)}static eccEncrypt(e,t){var i=y.generate(),{aeskey:t,aesiv:r}=(t=c.ecdh(t,i.privateKey),y.getAes(t.toString()));return{pub:i.publicKey,msg:s.encrypt(t,r,Buffer.from(e).toString("hex"))}}static eccDecrypt(e,t){t=c.ecdh(e.pub,t);var{aeskey:t,aesiv:i}=y.getAes(t.toString());return Buffer.from(s.decrypt(t,i,e.msg),"hex").toString()}static generate(e){var t=c.generatePrivateKey(),i=o.randomBytes(32);return y.fromKey(t,i,e)}fromBase58(e,t){return r("string"==typeof e),this._xprivkey=e,this.fromRaw(p.decode(e),t)}fromReader(e,t){var i=e.readU32BE();return this.network=h.fromPrivate(i,t),this.depth=e.readU8(),this.parentFingerPrint=e.readU32BE(),this.childIndex=e.readU32BE(),this.chainCode=e.readBytes(32),r(0===e.readU8()),this.privateKey=e.readBytes(32),this.publicKey=c.publicKeyCreate(this.privateKey,!0),e.verifyChecksum(),this}fromRaw(e,t){return this.fromReader(new l(e),t)}toBase58(e){return p.encode(this.toRaw(e))}getSize(){return 82}toWriter(e,t){return t=t||this.network,t=h.get(t),e.writeU32BE(t.keyPrefix.xprivkey),e.writeU8(this.depth),e.writeU32BE(this.parentFingerPrint),e.writeU32BE(this.childIndex),e.writeBytes(this.chainCode),e.writeU8(0),e.writeBytes(this.privateKey),e.writeChecksum(),e}toRaw(e){return this.toWriter(new u(82),e).render()}static fromBase58(e,t){return(new y).fromBase58(e,t)}static fromReader(e,t){return(new y).fromReader(e,t)}static fromRaw(e,t){return(new y).fromRaw(e,t)}toJSON(){return{xprivkey:this.xprivkey(),pubkey:this.publicKey.toString("hex")}}fromJSON(e,t){return r(e.xprivkey,"Could not handle key JSON."),this.fromBase58(e.xprivkey,t),this}static fromJSON(e,t){return(new y).fromJSON(e,t)}static isHDPrivateKey(e){return e instanceof y}}e.exports=y},function(e,t,i){"use strict";
|
|
168
168
|
/*!
|
|
169
169
|
* mtx.js - mutable transaction object for vallnet
|
|
170
170
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -211,7 +211,7 @@ let r=[];[i(558),i(559),i(560),i(561),i(562),i(563),i(564),i(565),i(566),i(567),
|
|
|
211
211
|
* pkg.js - package constants
|
|
212
212
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
213
213
|
* https://github.com/bookmansoft/gamegold
|
|
214
|
-
*/t.protocol="vallnet",t.version="5.6.
|
|
214
|
+
*/t.protocol="vallnet",t.version="5.6.11",t.url="https://github.com/bookmansoft/gamegold"},function(e,t,i){"use strict";
|
|
215
215
|
/*!
|
|
216
216
|
* common.js - p2p constants for vallnet
|
|
217
217
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -292,7 +292,7 @@ const r=i(19).opcodes;function s(e){let t=null;return new(0,(s.list[e.type]||s.l
|
|
|
292
292
|
/*!
|
|
293
293
|
* wallet.js - wallet object for vallnet
|
|
294
294
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
295
|
-
*/const r=i(0);var s=i(16);const n=i(15),a=i(2),o=i(3),c=i(35),h=i(198),u=i(141).sortWithSeq,l=i(6),p=i(94),d=i(1),f=i(4),m=i(69),g=i(334);i(218);const y=i(109),v=i(73),b=i(13),w=i(68),k=i(17),x=i(219),S=i(156),_=i(28),E=i(157),R=i(337),A=i(63),O=i(26),C=i(29),I=i(7),j=i(310),P=i(38),T=S.Mnemonic,{opcodes:B,hashType:N}=i(19),M=i(165),L=i(77),F=i(78),z=i(142),H=i(46),D=i(20),U=i(42),q=i(54),{NotifyMsg:V,ContractStatus:K,ContractType:W,PropStatus:$}=i(5),X=i(37).VerifyError,G=i(153).ErItem,Y=i(154).ErAbolishItem,J=i(228).EnchancementItem,Z=i(67),Q=i(59),ee=i(83),te=i(85).txdb,ie=i(31);class re extends s{constructor(e,t){super(),r(e,"DB required."),this.db=e,this.network=e.network,this.logger=e.logger,this.readLock=new h,this.writeLock=new c,this.sendLock=new c,this.indexCache=new A(1e4),this.accountCache=new A(1e4),this.pathCache=new A(1e5),this.current=null,this.wid=0,this.id=null,this.initialized=!1,this.watchOnly=!1,this.accountDepth=0,this.token=o.ZERO_HASH,this.tokenDepth=0,this.master=new R,this.txdb=new g(this),this.account=null,t&&this.fromOptions(t)}fromOptions(e){let t,i,s=e.master;return s?("string"==typeof s&&(s=S.PrivateKey.fromBase58(s,this.network)),r(S.isPrivate(s),"Must create wallet with hd private key.")):(i=new T(e.mnemonic),s=S.fromMnemonic(i,this.network)),r(s.network===this.network,"Network mismatch for master key."),this.master.fromKey(s,i),null!=e.wid&&(r(a.isU32(e.wid)),this.wid=e.wid),e.id&&(r(v.isName(e.id),"Bad wallet ID."),t=e.id),null!=e.initialized&&(r("boolean"==typeof e.initialized),this.initialized=e.initialized),null!=e.watchOnly&&(r("boolean"==typeof e.watchOnly),this.watchOnly=e.watchOnly),null!=e.accountDepth&&(r(a.isU32(e.accountDepth)),this.accountDepth=e.accountDepth),e.token&&(r(Buffer.isBuffer(e.token)),r(32===e.token.length),this.token=e.token),t=t||this.getID(),this.id=t,this}static fromOptions(e,t){return new re(e).fromOptions(t)}async init(e){var t=e.passphrase;r(!this.initialized),this.initialized=!0,t&&await this.master.encrypt(t),e=await this._createAccount(e,t);r(e),this.account=e,this.logger.info("Wallet initialized (%s).",this.id),await this.txdb.open()}async open(){r(this.initialized);var e=await this.getAccount(0);if(!e)throw new Error("Default account not found.");this.account=e,this.logger.info("Wallet opened (%s).",this.id),await this.txdb.open()}async ensureNotifyKey(){this.notifyKey||(await this.ensureAccount({name:"alliance",witness:!0}),this.notifyKey=await this.createReceive("alliance",1,this.master),this.notifyAddress=this.notifyKey.getAddress("string"))}async createAllianceInfo(e,t,i){var r={alliancename:e,nodeid:t};return e?(r.alliancePrivateKey=l.hash256(Buffer.concat([Buffer.from(e),this.master.key.privateKey])),i?(r.prv=Buffer.alloc(0),r.pub=Buffer.from(i,"hex"),r.awardAddress=b.fromWitnessPubkeyhash(l.hash160(r.pub),this.network.type).toString(this.network.type),r.mnemonic=new T):(i=l.hash256(Buffer.concat([Buffer.from(e+"-"+t),this.master.key.privateKey])),r.mnemonic=new T({entropy:i,language:this.master.mnemonic.language,passphrase:this.master.mnemonic.passphrase}),r.prv=l.hash256(Buffer.from(r.mnemonic.toSeed().toString("hex"))),r.pub=O.publicKeyCreate(r.prv,!0),e=R.fromKey(S.fromMnemonic(r.mnemonic),this.network.type).key.deriveAccount(44,0).derive(9).derive(1),r.awardAddress=b.fromWitnessPubkeyhash(l.hash160(e.publicKey),this.network.type).toString(this.network.type))):(r.mnemonic=T.fromOptions(this.master.mnemonic),r.prv=l.hash256(Buffer.from(r.mnemonic.toSeed().toString("hex"))),r.pub=O.publicKeyCreate(r.prv,!0),r.awardAddress=b.fromWitnessPubkeyhash(l.hash160(r.pub),this.network.type).toString(this.network.type)),r.address=b.fromWitnessPubkeyhash(l.hash160(r.pub),this.network.type).toString(),r}async destroy(){var e=await this.writeLock.lock(),t=await this.sendLock.lock();try{this.db.unregister(this),await this.master.destroy(),this.readLock.destroy(),this.writeLock.destroy(),this.sendLock.destroy()}finally{t(),e()}}async addSharedKey(e,t){var i=await this.writeLock.lock();try{return await this._addSharedKey(e,t)}finally{i()}}async _addSharedKey(e,t){if(t||(t=e,e=null),!(e=await this.getAccount(e=null==e?0:e)))throw new Error("Account not found.");let i;this.start();try{i=await e.addSharedKey(t)}catch(e){throw this.drop(),e}return await this.commit(),i}async removeSharedKey(e,t){var i=await this.writeLock.lock();try{return await this._removeSharedKey(e,t)}finally{i()}}async _removeSharedKey(e,t){if(t||(t=e,e=null),!(e=await this.getAccount(e=null==e?0:e)))throw new Error("Account not found.");let i;this.start();try{i=await e.removeSharedKey(t)}catch(e){throw this.drop(),e}return await this.commit(),i}async setPassphrase(e,t){e&&await this.decrypt(e),t&&await this.encrypt(t)}async encrypt(e){var t=await this.writeLock.lock();try{return await this._encrypt(e)}finally{t()}}async _encrypt(e){e=await this.master.encrypt(e,!0),this.start();try{await this.db.encryptKeys(this,e)}catch(t){throw p(e),this.drop(),t}p(e),this.save(),await this.commit()}async decrypt(e){var t=await this.writeLock.lock();try{return await this._decrypt(e)}finally{t()}}async _decrypt(e){e=await this.master.decrypt(e,!0),this.start();try{await this.db.decryptKeys(this,e)}catch(t){throw p(e),this.drop(),t}p(e),this.save(),await this.commit()}async rename(e){var t=await this.writeLock.lock();try{return await this.db.rename(this,e)}finally{t()}}async writeBalanceLog(e){var t=await this.writeLock.lock();try{return await this.db.writeBalanceLog(this,e)}finally{t()}}async renameAccount(e,t){var i=await this.writeLock.lock();try{return await this._renameAccount(e,t)}finally{i()}}async _renameAccount(e,t){if(!v.isName(t))throw new Error("Bad account name.");var i=await this.getAccount(e);if(!i)throw new Error("Account not found.");if(0===i.accountIndex)throw new Error("Cannot rename default account.");if(await this.hasAccount(t))throw new Error("Account name not available.");e=i.name,this.start(),this.db.renameAccount(i,t),await this.commit(),this.indexCache.remove(e),e=this.pathCache.values();for(const r of e)r.account===i.accountIndex&&(r.name=t)}async lock(){var e=await this.writeLock.lock(),t=await this.sendLock.lock();try{await this.master.lock()}finally{t(),e()}}unlock(e,t){return this.master.unlock(e,t)}getID(){r(this.master.key,"Cannot derive id.");var e,t=this.master.key.derive(44);(e=new f(37)).writeBytes(t.publicKey),e.writeU32(this.network.magic),t=l.hash160(e.render());return(e=new f(27)).writeU8(3),e.writeU8(190),e.writeU8(4),e.writeBytes(t),e.writeChecksum(),m.encode(e.render())}async createAccount(e,t){var i=await this.writeLock.lock();try{return await this._createAccount(e,t)}finally{i()}}async _createAccount(e,t){let i,s,n=e.name,o=(n=n||this.accountDepth.toString(10),0);if(0!=this.accountDepth&&(o=a.hashInt(n)),await this.hasAccountIndex(o))throw new Error("Account Index Conflict.");if(await this.hasAccount(n))throw new Error("Account already exists.");if(await this.unlock(t),this.watchOnly&&e.accountKey){if("string"==typeof(i=e.accountKey)&&(i=S.PublicKey.fromBase58(i,this.network)),!S.isPublic(i))throw new Error("Must add HD public keys to watch only wallet.");r(i.network===this.network,"Network mismatch for watch only key.")}else r(this.master.key),i=(i=this.master.key.deriveAccount(44,o)).toPublic();t={wid:this.wid,id:this.id,name:0===this.accountDepth?"default":n,witness:e.witness,watchOnly:this.watchOnly,accountKey:i,accountIndex:o,type:e.type,m:e.m,n:e.n,keys:e.keys},this.start();try{(s=E.fromOptions(this.db,t)).wallet=this,await s.init()}catch(e){throw this.drop(),e}return this.logger.info("Created account %s/%s/%d.",s.id,s.name,s.accountIndex),this.accountDepth++,this.save(),await this.commit(),s}async ensureAccount(e,t){var i=e.name;return(i=await this.getAccount(i))||this.createAccount(e,t)}getAccounts(){return this.db.getAccounts(this.wid)}getAccountMap(){return this.db.getAccountMap(this.wid)}getAddressHashes(e){return null!=e?this.getAccountHashes(e):this.db.getWalletHashes(this.wid)}async getAccountHashes(e){return e=await this.ensureIndex(e,!0),this.db.getAccountHashes(this.wid,e)}async getAccount(e){if(this.account&&(null==e||"default"===e||"number"==typeof e&&0===e||"string"==typeof e&&0===e.length))return this.account;if(-1===(e=await this.getAccountIndex(e)))return null;var t=await this.readLock.lock(e);try{return await this._getAccount(e)}finally{t()}}async _getAccount(e){var t=this.accountCache.get(e);return t||((t=await this.db.getAccount(this.wid,e))?(t.wallet=this,t.wid=this.wid,t.id=this.id,t.watchOnly=this.watchOnly,await t.open(),this.accountCache.set(e,t),t):null)}async getAccountIndex(e){var t;return null==e?-1:"number"==typeof e?e:null!=(t=this.indexCache.get(e))?t:-1===(t=await this.db.getAccountIndex(this.wid,e))?-1:(this.indexCache.set(e,t),t)}async getAccountName(e){var t;return"string"==typeof e?e:(t=this.accountCache.get(e))?t.name:this.db.getAccountName(this.wid,e)}async hasAccount(e){return-1!==(e=await this.getAccountIndex(e))&&(!!this.accountCache.has(e)||this.db.hasAccount(this.wid,e))}async hasAccountIndex(e){return!!this.accountCache.has(e)||this.db.hasAccount(this.wid,e)}createReceive(e,t=0,i=null){return this.createKey(e,0,t,i)}createChange(e){return this.createKey(e,1)}createNested(e){return this.createKey(e,2)}async createKey(e,t,i=0,r=null){var s=await this.writeLock.lock();try{return await this._createKey(e,t,i,r)}finally{s()}}async _createKey(e,t,i=0,r=null){if(null==t&&(t=e,e=null),!(e=await this.getAccount(e=e||0)))throw new Error("Account not found.");let s;this.start();try{s=await e.createKey(t,i,r)}catch(e){throw this.drop(),e}return await this.commit(),s}async deriveKey(e,t,i,r=null){let s=null;var n=await this.writeLock.lock();try{this.start(),s=await this._deriveKey(e,t,i,r),await this.commit()}catch(e){throw this.drop(),e}finally{n()}return s}async _deriveKey(e,t,i=0,r=null){if(null==t&&(t=e,e=null),e=e||0,e=parseInt(e),e=await this.getAccount(e))return t=await e.deriveKey(t,i,r),await e.saveKey(t),t;throw new Error("Account not found.")}save(){return this.db.save(this)}async saveAccount(e){var t=await this.writeLock.lock();try{this.start(),e._save(),await this.commit(),0==e.accountIndex&&(this.account=e)}finally{t()}}start(){return this.db.start(this)}drop(){return this.db.drop(this)}clear(){return this.db.clear(this)}commit(){return this.db.commit(this)}async hasAddress(e){return e=b.getHash(e,"hex"),null!=await this.getPath(e)}async ownedAddress(e){return!!await this.getKey(e)}async getPath(e){return(e=await this.readPath(e))?(e.name=await this.getAccountName(e.account),r(e.name),this.pathCache.set(e.hash,e),e):null}async readPath(e){e=b.getHash(e,"hex");var t=this.pathCache.get(e);return t||((t=await this.db.getPath(this.wid,e))?(t.id=this.id,t):null)}async hasPath(e){return e=b.getHash(e,"hex"),!!this.pathCache.has(e)||this.db.hasPath(this.wid,e)}async getPaths(e){if(null!=e)return this.getAccountPaths(e);var t=[];for(const e of await this.db.getWalletPaths(this.wid))e.id=this.id,e.name=await this.getAccountName(e.account),r(e.name),this.pathCache.set(e.hash,e),t.push(e);return t}async getAccountPaths(e){var t=await this.ensureIndex(e,!0),i=await this.getAccountHashes(t),s=await this.getAccountName(e),n=(r(s),[]);for(const e of i){var a=await this.readPath(e);r(a),r(a.account===t),a.name=s,this.pathCache.set(a.hash,a),n.push(a)}return n}async importKey(e,t,i){var r=await this.writeLock.lock();try{return await this._importKey(e,t,i)}finally{r()}}async _importKey(e,t,i){if(e&&"object"==typeof e&&(i=t,t=e,e=null),null==e&&(e=0),r(t.network===this.network,"Network mismatch for key."),this.watchOnly){if(t.privateKey)throw new Error("Cannot import privkey into watch-only wallet.")}else if(!t.privateKey)throw new Error("Cannot import pubkey into non watch-only wallet.");var s=t.getHash("hex");if(await this.getPath(s))throw new Error("Key already exists.");if(!(s=await this.getAccount(e)))throw new Error("Account not found.");if(s.type!==E.types.PUBKEYHASH)throw new Error("Cannot import into non-pkh account.");await this.unlock(i),e=x.fromRing(s,t).toPath(),this.master.encrypted&&(e.data=this.master.encipher(e.data,e.hash),r(e.data),e.encrypted=!0),this.start();try{await s.savePath(e)}catch(e){throw this.drop(),e}await this.commit()}async importAddress(e,t){var i=await this.writeLock.lock();try{return await this._importAddress(e,t)}finally{i()}}async _importAddress(e,t){if(t||(t=e,e=null),null==e&&(e=0),t.network!==this.network)throw new Error("Network mismatch for address.");if(!this.watchOnly)throw new Error("Cannot import address into non watch-only wallet.");if(await this.getPath(t))throw new Error("Address already exists.");if(!(e=await this.getAccount(e)))throw new Error("Account not found.");if(e.type!==E.types.PUBKEYHASH)throw new Error("Cannot import into non-pkh account.");t=y.fromAddress(e,t),this.start();try{await e.savePath(t)}catch(e){throw this.drop(),e}await this.commit()}async fund(e,t){var i=await this.writeLock.lock();try{return await this._fund(e,t)}finally{i()}}async _fund(e,t){if(t=t||{},!this.initialized)throw new Error("Wallet is not initialized.");if(this.watchOnly)throw new Error("Cannot fund from watch-only wallet.");let i;if(null!=t.account){if(!(i=await this.getAccount(t.account)))throw new Error("Account not found.")}else i=this.account;if(!i.initialized)throw new Error("Account is not initialized.");let s,n=t.rate;return null==n&&(n=await this.db.estimateFee(t.blocks)),s=t.smart?await this.getSmartCoins(i.name):(s=await this.getCoins(i.name),this.txdb.filterConserved(s)),await e.fund(s,{allowPreInput:t.allowPreInput,noChange:t.noChange,selection:t.selection,round:t.round,depth:t.depth,hardFee:t.hardFee,subtractFee:t.subtractFee,subtractIndex:t.subtractIndex,changeAddress:i.change.getAddress(),height:this.db.curHeight,rate:n,maxFee:t.maxFee,estimate:e=>this.estimateSize(e),network:this.network}),!t.allowInfiniteFee&&t.noChange&&r(e.getFee()<=j.MAX_FEE,"TX exceeds MAX_FEE."),s}async getAccountByAddress(e){return e=b.getHash(e,"hex"),(e=await this.getPath(e))?this.getAccount(e.account):null}async estimateSize(e){var t=I.WITNESS_SCALE_FACTOR,i=b.fromScript(e);if(!i)return-1;var r=await this.getAccountByAddress(i);if(!r)return-1;let s=0;if(e.isScripthash()&&r.witness)switch(r.type){case E.types.PUBKEYHASH:s=4*(s+23);break;case E.types.MULTISIG:s=4*(s+35)}switch(r.type){case E.types.PUBKEYHASH:s=s+74+34;break;case E.types.MULTISIG:s=(s=(s=(s=(s+=1)+74*r.m)+3+1)+34*r.n)+1+1}return r.witness?s=((s+=1)+t-1)/t|0:s+=o.sizeVarint(s),s}async createTX(e){var t=e.outputs,i=new w;r(Array.isArray(t),"Outputs must be an array."),r(0<t.length,"No outputs available."),e.comment&&("object"==typeof e.comment&&(e.comment=JSON.stringify(e.comment)),i.outputs.push(_.fromScript(k.createScript(Buffer.from(e.comment),k.types.NULLDATA),0)));for(const e of t){var s=new _(e),n=s.getAddress();if(s.isDust())throw new Error("Output is dust.");if(0<s.value){if(!n)throw new Error("Cannot send to unknown address.");if(n.isNull())throw new Error("Cannot send to null address.")}i.outputs.push(s)}let a=null;if(e.inputs)for(const t of e.inputs){var o=await this.getTX(t.hash);o&&(o=q.fromTX(o.tx,t.index,-1,0))&&(a=o.getAddress(),e.allowPreInput=!0,i.addCoin(o))}else await this.fund(i,e);if(a&&((t=new _).value=i.getFee()-j.MIN_FEE,t.script.fromAddress(a),i.outputs.push(t),i.changeIndex=i.outputs.length-1),!1!==e.sort&&i.sortMembers(),null!=e.locktime&&i.setLocktime(e.locktime),r(i.isSane(),"TX failed sanity check."),r(i.verifyInputs(this.db.curHeight+1),"TX failed context check."),0===await this.template(i))throw new Error("Templating failed.");return i}async send(e,t){var i=await this.sendLock.lock();try{return await this._send(e,t)}finally{i()}}async _send(e,t){return t&&(e.account=t),t=await this.createTX(e,!0),await this.sign(t),this.sendMTX(t,{sendafter:e.sendafter})}async sendMTX(e,t={}){if(!e.isSigned())throw new Error("TX could not be fully signed.");var i=e.toTX();if(i.getSigopsCost(e.view)>C.MAX_TX_SIGOPS_COST)throw new Error("TX exceeds policy sigops.");if(i.getWeight()>C.MAX_TX_WEIGHT)throw new Error("TX exceeds policy weight.");return t.sendafter||(this.logger.debug("Sending wallet tx (%s): %s",this.id,i.txid()),await this.db.addTX(i),await this.db.send(i)),i}async resend(){var e=await this.getPending(),t=(0<e.length&&this.logger.info("Rebroadcasting %d transactions.",e.length),[]);for(const i of e)t.push(i.tx);for(const e of u(t))await this.db.send(e);return t}async deriveInputs(e){r(e.mutable);var t=[];for(const r of await this.getInputPaths(e)){var i=await this.getAccount(r.account);i&&(i=i.derivePath(r,this.master))&&t.push(i)}return t}async getKey(e){try{var t,i=b.getHash(e,"hex",this.network.type),r=await this.getPath(i);return r&&(t=await this.getAccount(r.account))?t.derivePath(r,this.master):null}catch{return null}}async exportToFile(e){if(!Q.unsupported){var t=await this.db.getTip(),i=a.date();let o="",c=[a.fmt("# Wallet Dump created by %s %s",ee.protocol,ee.version),a.fmt("# * Created on %s",i),a.fmt("# * Best block at time of backup was %d (%s).",t.height,a.revHex(t.hash)),a.fmt("# * File: %s",e.file),""];var r,s;t=a.fmt("W %s wid= %s",this.toRaw().toString("base64"),this.wid),t=(c.push(t),await this.getAccounts());for(const e of t){var n=await this.getAccount(e);n=a.fmt("C %s name= %s index= %d",n.toRaw().toString("base64"),n.name,n.accountIndex);c.push(n)}for(const t of await this.getAddressHashes())this.watchOnly?(r=b.fromWitnessPubkeyhash(Buffer.from(t,"hex"),this.network.type).toString(),r=a.fmt("A %s %s label= account= %s branch= %s index= %s addr= %s","S",i,0,-1,-1,r),c.push(r)):(r=await this.getPrivateKey(t))&&(s=r.getAddress("string"),s=a.fmt("A %s %s label= account= %s branch= %s index= %s addr= %s",r.toSecret(),i,r.account,r.branch,r.index,s),c.push(s),e.fragment)&&1e5<c.length&&(o=c.join("\n"),await Q.writeFile(e.file.split(".").reduce((e,t)=>(e?e+="."+t:e=t+"-1",e),""),o,"utf8"),c=[]);c.push(""),c.push("# End of dump"),c.push(""),o=c.join("\n"),await Q.writeFile(e.file,o,"utf8")}}async getPrivateKey(e,t){if(e=b.getHash(e,"hex"),!(e=await this.getPath(e)))return null;var i=await this.getAccount(e.account);return i?(await this.unlock(t),(t=i.derivePath(e,this.master)).privateKey?t:null):null}async getInputPaths(e){if(r(e.mutable),!e.hasCoins())throw new Error("Not all coins available.");var t=[];for(const r of e.getInputHashes("hex")){var i=await this.getPath(r);i&&t.push(i)}return t}async getOutputPaths(e){var t=[];for(const r of e.getOutputHashes("hex")){var i=await this.getPath(r);i&&t.push(i)}return t}async setLookahead(e,t){var i=await this.writeLock.lock();try{return this._setLookahead(e,t)}finally{i()}}async _setLookahead(e,t){if(null==t&&(t=e,e=null),!(e=await this.getAccount(e=null==e?0:e)))throw new Error("Account not found.");this.start();try{await e.setLookahead(t)}catch(e){throw this.drop(),e}await this.commit()}async syncOutputDepth(e){var t=new Map;for(const r of e.outputs){var i=r.path;i&&-1!==i.index&&(t.has(i.account)||t.set(i.account,[]),t.get(i.account).push(i))}var s,n,a=[];for([s,n]of t){let e=-1,t=-1,i=-1;for(const r of n)switch(r.branch){case 0:r.index>e&&(e=r.index);break;case 1:r.index>t&&(t=r.index);break;case 2:r.index>i&&(i=r.index)}e+=2,t+=2,i+=2;var o=await this.getAccount(s);(o=(r(o),await o.syncDepth(e,t,i)))&&a.push(o)}return a}async getRedeem(e){"string"==typeof e&&(e=Buffer.from(e,"hex"));var t=await this.getKey(e.toString("hex"));return t?t.getRedeem(e):null}async template(e){var t=await this.deriveInputs(e);return e.sign(t)}async onSaleList(e,t){return(await(await this.getPropList()).predict(async(e,i)=>!!i.bid&&await this.belongToAccount(t,i.bid.address))).where([["pst",$.Sale]]).paginate(10,e).records()}async mySaleList(e,t){return(await(await this.getPropList()).predict(async(e,i)=>this.belongToAccount(t,i.current.address))).where([["pst",$.Sale]]).paginate(10,e).records()}async getPropList(){const e=await this.db.loadVpList();var t=[];for(let i=0;i<e.length;i++){let r=e[i];t.push((async()=>{await this.getPrivateKey(r.current.address)&&(e[i]=[r.pid,r])})())}return await Promise.all(t),new ie(e)}async propCreate(e,t){var i,s=new w;for(i of e){var n=await this.ensureCp(i.cid,!0);!n||i.cid==this.network.genesisId||(i.gold=(0|i.gold)>>>0,i.gold<I.MINPROPVALUE)||(i.pid||(i.pid=z()),i.oid||(i.oid=i.pid),s.propCreate(n.current.address,i),i.index=s.outputs.length-1)}if(0<s.outputs.length){t?await this.fund(s,{account:t}):await this.fund(s),await this.sign(s);var a,o=s.commit();for(a of(await this.db.addTX(o[0]),await this.db.send(o[0]),r(o[0].verify(o[1],k.flags.STANDARD_VERIFY_FLAGS)),e))a.hash=o[0].hash("hex"),a.txid=o[0].txid();return o}return[]}async attach(e,t){var i,s=new w;for(i of e)s.attach(i.address,i.value,i.data);if(0<s.outputs.length){t?await this.fund(s,{account:t}):await this.fund(s),await this.sign(s);var n,a=s.commit();for(n of(await this.db.addTX(a[0]),await this.db.send(a[0]),r(a[0].verify(a[1],k.flags.STANDARD_VERIFY_FLAGS)),e))n.hash=a[0].hash("hex"),n.txid=a[0].txid();return a}return[]}async sendSecret(e,t,i){let r=this.db.$contacts.get(e);if(!r||!r.sender){var s=(await this.createReceive(i)).getAddress("string");if(e==s)throw new L(F.errors.TYPE_ERROR,"Forbid Sending to Self Address.");r=await this.db.ensureContact({contact:e,messenger:s,wallet:this,account:i})}if(r)return r.send(t);throw new L(F.errors.TYPE_ERROR,"Invalid Address.")}async commNotify(e){r(!!e),r(!!e.dst),r(!!e.content);var t=new w,i=e.src||this.getReceive().toString(),s=(i=new V(W.notify,z(),this.db.curHeight,{src:i,content:e.content}),_.fromScript(k.createScript(i.toRaw(),k.types.NULLDATA),0));t.outputs.push(s),s={address:e.dst,locktime:I.BLOCK_DAY,locktype:"csb",value:.1*I.COIN},t.outputs.push(new _(s)),e.account?await this.fund(t,{account:e.account,noChange:!0,allowInfiniteFee:!0}):await this.fund(t,{noChange:!0,allowInfiniteFee:!0}),await this.sign(t),s=t.commit();return r(s[0].verify(s[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(s[0]),this.logger.debug("Sending tx on wallet(%s): %s",this.id,s[0].txid()),await this.db.send(s[0]),i.hash=s[0].hash("hex"),i.height=-1,i}async cpRegister(e,t,i,s){if(r(!!t&&"object"==typeof t),!await this.db.client.execute("canExecute",[{confirm:!1,cid:t.cid,name:t.name,oper:W.cpRegister}]))throw new L(F.errors.TYPE_ERROR,"Invalid CP Register Info.");const n=new w;e||(a=await this.createReceive(i),e=a.getAddress());var a=await this.getKey(e);if(!a)throw new L(F.errors.TYPE_ERROR,"Invalid CP Register Address, Not along to this wallet.");if(t.pubAddress=e.toString(),t.pubKey=a.getPublicKey("hex"),t.signMethod="secp256k1",a=await this.createAllianceInfo(),t.register=a.pub.toString("hex"),n.cpRegister(e,I.registerFee,t),a=async()=>{i?await this.fund(n,{account:i}):await this.fund(n),await this.sign(n);var s=n.commit();return r(s[0].verify(s[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(s[0]),await this.db.send(s[0]),t.txid=s[0].txid(),t.addr=e.toString(),s},!s)return a();a()}getSCAddress(e){return e=Z.fromMnemonic(T.fromOptions(I.SmartContractMnemonic),this.network).deriveAccount(44,e).derive(9).derive(1),b.fromWitnessPubkeyhash(l.hash160(e.publicKey),this.network)}async cpChange(e,t){var i=await this.ensureCp(e.cid);if(i.cid==this.network.genesisId||"ATHENA"==i.name)throw new L(F.errors.TYPE_ERROR,"Invalid cp name.");var s=await this.getTX(i.current.hash);if(!s)throw new L(F.errors.TYPE_ERROR,"Do not have permission to change this info.");if(s=s.tx,!await this.belongToAccount(t,s.outputs[0].getAddress()))throw new L(F.errors.TYPE_ERROR,"Invalid account info.");if(e.newName){if(!await this.db.client.execute("canExecute",[{confirm:!1,cid:i.cid,name:e.newName,oper:W.cpChange}]))throw new L(F.errors.TYPE_ERROR,"Invalid CP Change Info.")}else e.newName=i.name;return e.addr||(e.addr=b.fromString(i.current.address)),i=w.cpChange(s,e),t?await this.fund(i,{allowPreInput:!0,account:t}):await this.fund(i,{allowPreInput:!0}),await this.sign(i),s=i.commit(),await this.db.send(s[0]),r(s[0].verify(s[1],k.flags.STANDARD_VERIFY_FLAGS)),e.txid=s[0].txid(),s}async propExchangeList(e,t,i=!1){var s,n,a,o=new w,c=[];for([s,n,a]of e){var h,u=null;if(u=await this.getTX(s.hash)){if(u=u.tx,h=s.index,u&&u.outputs&&!(u.outputs.length<=h)){if(i){if(!await this.ownedAddress(u.outputs[h].getAddress())){this.logger.error("not owned prop:",s.hash,s.index);continue}}else if(!await this.belongToAccount(t,u.outputs[h].getAddress())){this.logger.error("not owned prop:",s.hash,s.index);continue}var l=u.outputs[h].getReturnData();l&&(o.propExchange(u,h,n),l.index=o.outputs.length-1,l.addr=n.toString(),c.push(l))}}else this.logger.error("tx not find:",s.hash,a)}return t?await this.fund(o,{allowPreInput:!0,account:t}):await this.fund(o,{allowPreInput:!0}),await this.sign(o),e=o.commit(),await this.db.addTX(e[0]),await this.db.send(e[0]),r(e[0].verify(e[1],k.flags.STANDARD_VERIFY_FLAGS)),e.push(c),e}async propDonate(e,t){var i=e.index;if(!(e=await this.getTX(e.hash))||!e.tx||!e.tx.outputs||e.tx.outputs.length<=i)throw new L(F.errors.TYPE_ERROR,"Invalid tx info.");if(!await this.belongToAccount(t,e.tx.outputs[i].getAddress()))throw new L(F.errors.TYPE_ERROR,"Props that do not belong to you.");if(!(t=e.tx.outputs[i].getReturnData()))throw new L(F.errors.TYPE_ERROR,"Invalid tx info.");if(t.cid&&t.cid==this.network.genesisId)throw new X(e.tx,"invalid","Special props that can not to donate",100);var r=new w;return(e=(r.addInputFromTx(e.tx,i),r.addOutput(k.createScript(Buffer.from(JSON.stringify({value:e.tx.outputs[i].value,cid:t.cid,pid:t.pid,oid:t.oid,gaddr:this.getAddress().toString(this.network)})),k.types.NULLDATA),0),await this.sign(r,null,N.NONE|N.ANYONECANPAY),r.commit())).push(t),e}async propReceive(e,t){var i=(e=w.fromTX(e,1)).inputs[0].prevout,r=e.outputs[0].getReturnData();e.view.addOutput({hash:e.inputs[0].prevout.hash,index:e.inputs[0].prevout.index},new _({value:r.value})),e.outputs.pop();let s=this.getAddress().toString(this.network);t&&(n={cid:r.cid,uid:t},s=(n=await this.tokenCreate(n,t)).data.addr),e.outputs.push(_.fromScript(s,r.value,{oper:W.propExchange,pid:r.pid,cid:r.cid,oid:r.oid,prev:{hash:i.hash,index:i.index}})),t?await this.fund(e,{allowPreInput:!0,account:t}):await this.fund(e,{allowPreInput:!0}),await this.sign(e,null,N.ALL,[0]);var n=e.commit();return await this.db.send(n[0]),r.simAddr=s,[n[0],null,r]}async belongToAccount(e,t){return!!t&&!(!(t=await this.getAccountByAddress(t))||e&&t.name!==e)}async propExchange(e,t,i){let s=null,n=0;var a;return Array.isArray(e)?(s=e[0],n=e[1]):(a=await this.getTX(e.hash))&&(s=a.tx,n=e.index),!s||!s.outputs||s.outputs.length<=n?(this.logger.error("Invalid tx info."),null):await this.ownedAddress(s.outputs[n].getAddress())?(a=s.outputs[n].getReturnData())?(e=(new w).propExchange(s,n,t),a.index=e.outputs.length-1,i?await this.fund(e,{allowPreInput:!0,account:i}):await this.fund(e,{allowPreInput:!0}),await this.sign(e),t=e.commit(),await this.db.addTX(t[0]),await this.db.send(t[0]),r(t[0].verify(t[1],k.flags.STANDARD_VERIFY_FLAGS)),t.push(a),t):(this.logger.error("Invalid tx info."),null):(this.logger.error("Invalid user."),null)}async propFound(e,t,i){if(e=await this.getTX(e),r(e),!(e=e.tx))throw new L(F.errors.TYPE_ERROR,"Invalid hex string.");var s=e.outputs[t],n=s.getReturnData();if(!n||n.oper!==W.propExchange&&n.oper!==W.propCreate)throw new L(F.errors.TYPE_ERROR,"Invalid tx type.");if(n.cid==this.network.genesisId)throw new X(block,"invalid","prop found supertoken",100);var a=new w;a.addInputFromTx(e,t),e=_.fromScript(s.getAddress(),s.value),a.outputs.push(e),i?await this.fund(a,{allowPreInput:!0,subtractFee:!0,account:i}):await this.fund(a,{allowPreInput:!0,subtractFee:!0}),await this.sign(a),t=a.commit();return await this.db.send(t[0]),r(t[0].verify(t[1],k.flags.STANDARD_VERIFY_FLAGS)),t.push(n),t}async propSale(e,t,i,s){let n=await this.getTX(e);if(!n)throw new L(F.errors.TYPE_ERROR,"Invalid tx info.");if(n.getDepth(this.db.curHeight)<=0)throw new L(F.errors.TYPE_ERROR,"No enough confirmations.");if(!(n=n.tx))throw new L(F.errors.TYPE_ERROR,"Invalid tx info.");var a=n.outputs[t].getReturnData([k.opcodes.OP_PROPEXCHANGE,k.opcodes.OP_PROPCREATE]);if(!a)throw new L(F.errors.TYPE_ERROR,"Invalid tx type.");if(!await this.ownedAddress(n.outputs[t].getAddress()))throw new L(F.errors.TYPE_ERROR,"Invalid tx info.");var o=await this.getCoin(e,t);if(!o||-1===o.height)throw new L(F.errors.WALLET_INSUFFICIENT_FUNDS,"Invalid coin.");if(await this.txdb.isSpent(e,t))throw new L(F.errors.WALLET_INSUFFICIENT_FUNDS,"Invalid coin.");if(i<=n.outputs[t].value)throw new L(F.errors.TYPE_ERROR,"Invalid fixed price.");if(a.cid==this.network.genesisId)throw new X(n,"invalid","prop not for sale",100);return e=(o=new w).addInputFromTx(n,t),t={oper:W.propSale,pid:a.pid,prev:{hash:e.prevout.hash,index:e.prevout.index},fixed:i,period:this.db.curHeight+I.BLOCK_DAY},a=_.fromScript(k.createScript(Buffer.from(JSON.stringify(t)),k.types.NULLDATA),0),o.outputs.push(a),await this.sign(o,null,N.SINGLE|N.ANYONECANPAY),e=o.commit(),r(e[0].verify(e[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.send(e[0]),e}async propBuy(e,t,i){if(!(e=this.db.propList.get(e))||e.pst!=$.Sale||!e.bid||!e.bid.raw)throw new L(F.errors.INVALID_PARAMS,"Invalid Tx Hash.");var r=D.fromRaw(Buffer.from(e.bid.raw,"hex")),s=(await this.createReceive(i)).getAddress(),n=e.gold,a=b.fromString(e.current.address,this.network).getHash();if(t<n)throw new Error("wrong price");if(1<r.outputs.length&&t<r.outputs[1].value)throw new Error("low bid price than before");var o=w.fromTX(r,1);if(!o.outputs[0].getReturnType(B.OP_RETURN))throw new Error("not a sale order");return await this.remove(r.hash("hex")),o.view.addOutput({hash:o.inputs[0].prevout.hash,index:o.inputs[0].prevout.index},new _({value:e.gold})),a=_.fromScript(k.createScript(a),t),o.outputs.push(a),t={oper:W.propExchange,pid:e.pid,cid:e.cid,oid:e.oid,prev:{hash:o.inputs[0].prevout.hash,index:o.inputs[0].prevout.index}},a=_.fromScript(s,n,t),o.outputs.push(a),i?await this.fund(o,{allowPreInput:!0,account:i}):await this.fund(o,{allowPreInput:!0}),await this.sign(o,null,N.ALL,[0]),s=o.commit(),e.owned||this.db.client.watchOutpoint((new H).fromOptions(r.inputs[0].prevout)),await this.db.send(s[0]),s}async getTXByAmount(e,t){let i=null;var r;for(r of await this.getCoins(t))if(!(r.height<=0)&&r.value==e){i=r;break}return i&&(t=await this.getTX(i.hash))?[t.tx,i.index,i.height]:[]}async contractCreate(e,t,i,s,n){if(this.db.transactionList.query(e,s)!=K.None)throw new L(F.errors.TYPE_ERROR,"Contract with the same address finded.");if(0!=parseInt(t%1e3,10))throw new L(F.errors.TYPE_ERROR,"Contract source should an integer multiple of 1000.");if(!await U.checkSum(this.network,e,s))throw new L(F.errors.TYPE_ERROR,"Create contract with an invalid Address or a Address with old transations.");let a=!1,[o,c,h]=await this.getTXByAmount(t,n);if(!o){a=!0;var u=new w;let e="";e=(n?await this.createReceive(n):this).getAddress(),u.outputs.push(_.fromScript(e,t)),n?await this.fund(u,{allowPreInput:!0,account:n}):await this.fund(u,{allowPreInput:!0}),await this.sign(u),u=u.commit(),r(u[0].verify(u[1],k.flags.STANDARD_VERIFY_FLAGS)),o=u[0],c=0,h=-1}(u=new w).addInputFromTx(o,c,h);let l="";l=(n?await this.createReceive(n):this).getAddress();var p=await this.getKey(l);e={oper:W.contractCreate,type:e,addr:s,src:t,dst:i,srcact:n,alice:p.getPublicKey("hex"),period:this.db.curHeight+I.TRANSACTION_PERIOD},s=_.fromScript(k.createScript(Buffer.from(JSON.stringify(e)),k.types.NULLDATA),0),u.outputs.push(s),await this.sign(u,null,N.SINGLE|N.ANYONECANPAY),t=u.commit();return a&&await this.db.send(o),await this.db.send(t[0]),t}async contractPromise(e,t){if(!(e=this.db.transactionList.get(e))||e.transStatus!=K.CreatedOnMem)throw new L(F.errors.INVALID_PARAMS,"Invalid Tx id.");if(!(e=D.fromRaw(Buffer.from(e.raw,"hex"))))throw new L(F.errors.TYPE_ERROR,"Invalid Tx id.");var i=U.parseContract(e);if(!i||i.oper!==W.contractCreate)throw new L(F.errors.TYPE_ERROR,"Invalid tx type.");var r=w.fromTX(e,1);if(!r.outputs[0].getReturnType(B.OP_RETURN))throw new Error("not a valid contract");r.view.addOutput({hash:r.inputs[0].prevout.hash,index:r.inputs[0].prevout.index},new _({value:i.src}));let s="";s=(t?await this.createReceive(t):this).getAddress();var n=await this.getKey(s);e={oper:W.contractPromise,prevhash:e.hash("hex"),type:i.type,addr:i.addr,dst:i.dst,srcact:i.srcact,dstact:t,bob:n.getPublicKey("hex"),period:i.period},t=new k([M.fromSymbol("promise"),M.fromData(Buffer.from(JSON.stringify(e))),M.fromSymbol("drop"),M.fromSymbol("greaterthan"),M.fromSymbol("drop"),M.fromSymbol("if"),M.fromData(l.hash160(Buffer.from(e.bob,"hex"))),M.fromSymbol("else"),M.fromData(l.hash160(Buffer.from(i.alice,"hex"))),M.fromSymbol("endif"),M.fromSymbol("checksig")]),r.outputs.push(_.fromScript(t,i.src)),await this.remove(e.prevhash),await this.sign(r,null,N.ALL,[0]),n=r.commit();return await this.db.send(n[0]),e.current={hash:n[0].hash("hex"),index:0},e.raw=n[0].toRaw().toString("hex"),e.transStatus=K.Promised,this.db.transactionList.saveContract(e,!0),n}async contractExecute(e,t){if(!(e=this.db.transactionList.get(e))||e.transStatus!=K.Confirmed&&e.transStatus!=K.Expired)throw new L(F.errors.INVALID_PARAMS,"Invalid Tx id.");if(!(e=D.fromRaw(Buffer.from(e.raw,"hex"))))throw new L(F.errors.TYPE_ERROR,"Invalid Tx id.");t=t||1;var i=U.parseContract(e);if(!i||i.oper!==W.contractPromise)throw new L(F.errors.TYPE_ERROR,"Invalid tx type.");var s=e.outputs[1].getReturnData();if(!s||s.oper!==W.contractPromise)throw new L(F.errors.TYPE_ERROR,"Invalid tx type.");r.strictEqual(i.addr,s.addr),r.strictEqual(i.type,s.type),r.strictEqual(i.dst,s.dst),r.strictEqual(i.period,s.period),r.strictEqual(i.srcact,s.srcact),r.strictEqual(i.dstact,s.dstact);var n=this.db.transactionList.query(i.type,i.addr);if(n!=K.Confirmed&&n!=K.Expired)throw new L(F.errors.TYPE_ERROR,"Contract Promise not Check yet.");if(n==K.Expired&&1!=t||n==K.Confirmed&&2!=t)throw new L(F.errors.TYPE_ERROR,"Invalid Executor.");let a=i.srcact,o=(2==t&&(a=i.dstact),"");o=(a?await this.createReceive(a):this).getAddress();var c=new w,h=(c.addInputFromTx(e,1),{oper:W.contractExecute,type:i.type,addr:i.addr,master:t});h=_.fromScript(k.createScript(Buffer.from(JSON.stringify(h)),k.types.NULLDATA),0),c.outputs.push(h),h=_.fromScript(o,e.outputs[1].value),c.outputs.push(h),e=1==t?await P.fromPublic(Buffer.from(i.ori.alice,"hex")):await P.fromPublic(Buffer.from(s.bob,"hex")),h=await this.getKey(e.getAddress()),await c.signAsync(h,k.hashType.ALL,this.db.workers),t=c.commit();return r(t[0].verify(t[1],k.flags.STANDARD_VERIFY_FLAGS,n)),await this.db.send(t[0]),t}async htlcDeal(e,t){var i=await this.getTX(e.hash);let r=null;if(t){if(!(t=await this.getAccount(t)))throw new L(F.errors.TYPE_ERROR,"Invalid Account.");r=t.getReceive().toString()}else r=this.getReceive().toString();t=new w;var s=(new k).pushOp(B.OP_1);e.suggest&&s.pushData(Buffer.from(e.sa,"hex")),t.addInput({prevout:{hash:e.hash,index:e.index},script:s}),t.addOutput(r,i.tx.outputs[e.index].value-1e4),t.view.addOutput({hash:e.hash,index:e.index},new _(i.tx.outputs[e.index])),await this.sign(t,null,N.ALL),s=t.commit();return await this.db.send(s[0]),s}async htlcCancel(e,t){let i=null;var r=await this.getTX(e.hash);if(!(i=r?r.tx.outputs[e.index]:i))throw new L(F.errors.TYPE_ERROR,"Invalid Input.");let s=null;if(t){if(!(r=await this.getAccount(t)))throw new L(F.errors.TYPE_ERROR,"Invalid Account.");s=r.getReceive().toString()}else s=this.getReceive().toString();return t=new w,r=(new k).pushOp(B.OP_0),e.suggest&&r.pushData(Buffer.from(e.sa,"hex")),t.addInput({prevout:{hash:e.hash,index:e.index},script:r}),e.suggest?t.setSequence(0,2*I.HTLC_CANCEL_PERIOD,!1):t.setSequence(0,I.HTLC_CANCEL_PERIOD,!1),t.addOutput(s,i.value-1e4),t.view.addOutput({hash:e.hash,index:e.index},new _(i)),r=await this.getKey(e.master),await t.signAsync(r,k.hashType.ALL,this.db.workers),e=t.commit(),await this.db.send(e[0]),e}async sendContracts(e,t,i){var r,s=new w;for(r of e)s.outputs.push(i.create(r));return t?await this.fund(s,{account:t}):await this.fund(s),await this.sign(s),e=s.commit(),await this.db.addTX(e[0]),await this.db.send(e[0]),e}async tokenCreate(e,t="",i){r(e&&"object"==typeof e,"Token data should be a object"),r(e.cid,"Token data should has a cid property"),r(e.uid,"Token data should has a uid property"),e.time=!0,await this.ensureAccount({name:t,witness:!0});let s=null;if(i){if(!await this.belongToAccount(t,i))throw new L(F.errors.TYPE_ERROR,`tokenCreate address error: addr:${i} is not belongs to account:`+t);s=await this.getKey(i)}else s=await this.createReceive(t,a.hashInt(e.cid),this.master);return s.signData(e)}async sign(e,t,i=k.hashType.ALL,r){if(this.watchOnly)throw new Error("Cannot sign from a watch-only wallet.");return await this.unlock(t),t=await this.deriveInputs(e),e.signAsync(t,i,this.db.workers,r)}getCoinView(e){return this.txdb.getCoinView(e)}getSpentView(e){return this.txdb.getSpentView(e)}toDetails(e){return this.txdb.toDetails(e)}getDetails(e){return this.txdb.getDetails(e)}async getCoin(e,t){return this.txdb.getCoin(e,t)}async getCredit(e,t){return this.txdb.getCredit(e,t)}async getStatusOfSC(e){return this.txdb.getStatusOfSC(e)}async setStatusOfSC(e,t){var i=await this.writeLock.lock();try{this.txdb.start();try{await this.txdb._setStatusOfSC(e,t),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}}finally{i()}}getLockedCoins(){return this.txdb.lockedCoins.values}getTX(e){return this.txdb.getTX(e)}getBlocks(){return this.txdb.getBlocks()}getBlock(e){return this.txdb.getBlock(e)}async add(e,t,i){var r=await this.writeLock.lock();try{return await this._add(e,t,i)}finally{r()}}async _add(e,t,i){let r,s;this.txdb.start();try{(r=await this.txdb._add(e,t,i))&&(s=await this.syncOutputDepth(r)),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}return s&&0<s.length&&(this.db.emit("address",this.id,s),this.emit("address",s)),r}async resetBalance(){var e=await this.writeLock.lock();try{this.txdb.start();try{this.txdb.pending.unconfirmed=0,this.txdb.pending.confirmed=0;for(const e of await this.getAccounts()){var t=await this.getBalance(e);this.txdb.pending.unconfirmed+=t.unconfirmed,this.txdb.pending.confirmed+=t.confirmed}this.txdb.put(te.R,this.txdb.pending.commit()),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}}finally{e()}return this.txdb.state.toBalance()}async unconfirm(e){var t=await this.writeLock.lock();try{return await this.txdb.unconfirm(e)}finally{t()}}async remove(e){var t=await this.writeLock.lock();try{return await this.txdb.remove(e)}finally{t()}}async zap(e,t){var i=await this.writeLock.lock();try{return await this._zap(e,t)}finally{i()}}async _zap(e,t){return e=await this.ensureIndex(e),this.txdb.zap(e,t)}async abandon(e){var t=await this.writeLock.lock();try{return await this._abandon(e)}finally{t()}}_abandon(e){return this.txdb.abandon(e)}conserveCoin(e){return this.txdb.conserveCoin(e)}unConserveCoin(e){return this.txdb.unConserveCoin(e)}isConserved(e){return this.txdb.isConserved(e)}getConserved(){return this.txdb.getConserved()}async getHistory(e){return e=await this.ensureIndex(e),this.txdb.getHistory(e)}async getCoins(e){return e=await this.ensureIndex(e),this.txdb.getCoins(e)}async getCredits(e){return e=await this.ensureIndex(e),this.txdb.getCredits(e)}async getSmartCoins(e){var t=[];for(const r of await this.getCredits(e)){var i=r.coin;r.spent||this.txdb.isConserved(i)||-1===i.height&&!r.own||t.push(i)}return t}async getPending(e){return e=await this.ensureIndex(e),this.txdb.getPending(e)}async getBalance(e){return e=await this.ensureIndex(e),this.txdb.getBalance(e)}async queryBalanceLog(e,t=0){return(e=await this.ensureIndex(e))?this.db.queryBalanceLog(this.wid,e,t):[]}async getRange(e,t){return e&&"object"==typeof e&&(t=e,e=null),e=await this.ensureIndex(e),this.txdb.getRange(e,t)}async getLast(e,t){return e=await this.ensureIndex(e),this.txdb.getLast(e,t)}async ensureIndex(e,t){if(null==e){if(t)throw new Error("No account provided.");return null}if(-1===(t=await this.getAccountIndex(e)))throw new Error("Account not found.");return t}getAddress(e){return this.account.getAddress(e)}getReceive(e){return this.account.getReceive(e)}getChange(e){return this.account.getChange(e)}getNested(e){return this.account.getNested(e)}inspect(){return{wid:this.wid,id:this.id,network:this.network.type,initialized:this.initialized,accountDepth:this.accountDepth,token:this.token.toString("hex"),tokenDepth:this.tokenDepth,state:this.txdb.state?this.txdb.state.toJSON(!0):null,master:this.master,account:this.account}}toJSON(e){return{network:this.network.type,wid:this.wid,id:this.id,initialized:this.initialized,watchOnly:this.watchOnly,accountDepth:this.accountDepth,token:this.token.toString("hex"),tokenDepth:this.tokenDepth,height:this.db.curHeight,state:this.txdb.state.toJSON(!0),master:this.master.toJSON(e),account:this.account.toJSON(!0)}}getSize(){var e=0;return(e+=50)+o.sizeVarString(this.id,"ascii")+o.sizeVarlen(this.master.getSize())}toRaw(){var e=this.getSize();return(e=new f(e)).writeU32(this.network.magic),e.writeU32(this.wid),e.writeVarString(this.id,"ascii"),e.writeU8(this.initialized?1:0),e.writeU8(this.watchOnly?1:0),e.writeU32(this.accountDepth),e.writeBytes(this.token),e.writeU32(this.tokenDepth),e.writeVarBytes(this.master.toRaw()),e.render()}fromRaw(e){e=new d(e);var t=n.fromMagic(e.readU32());return this.wid=e.readU32(),this.id=e.readVarString("ascii"),this.initialized=1===e.readU8(),this.watchOnly=1===e.readU8(),this.accountDepth=e.readU32(),this.token=e.readBytes(32),this.tokenDepth=e.readU32(),this.master.fromRaw(e.readVarBytes()),r(t===this.db.network,"Wallet network mismatch."),this}static fromRaw(e,t){return new re(e).fromRaw(t)}static isWallet(e){return e instanceof re}async issueCreate(e,t,i){var r=new G(e),s=((s=(r.source.subjectName||(r.source.subjectName=r.erid),P.fromPrivate(Buffer.from(e.key,"hex"),!0,this.network))).witness=!0,r.sign(s,!0,this.network),r.toOptions(!0));return i?this.send({outputs:[{address:e.address,value:1e4}],comment:s},t):(r=await this.send({outputs:[{address:e.address,value:1e4}],comment:s},t),s.txid=r.txid()),s}async caAbolish(e,t,i){var r=P.fromPrivate(Buffer.from(e.key,"hex"),!0,this.network),s=(r.witness=!0,await this.db.client.execute("ca.byId",[e.erid]));if(!s)throw new L(F.errors.TYPE_ERROR,"ca.abolish: Invalid erid.");if(s.source.cid!=e.cid)throw new L(F.errors.TYPE_ERROR,"ca.abolish: Invalid cid.");if(s.source.uid!=e.uid)throw new L(F.errors.TYPE_ERROR,"ca.abolish: Invalid uid.");var n=s.signature;if(s.sign(r,!0,this.network),s.witness!=e.witness||s.signature!=n)throw new L(F.errors.TYPE_ERROR,"ca.abolish: You have no permission to abolish this witness.");return(s=new Y(e)).sign(r),n=s.toOptions(!0),i?this.send({outputs:[{address:e.address,value:1e4}],comment:n},t):await this.send({outputs:[{address:e.address,value:1e4}],comment:n},t),n}async enchanceCp(e,t){var i=((e=new J(e)).oper="enchanceCp",await this.ensureCp(e.to)),r=await this.ensureCp(e.from);if(!(r=await this.getKey(r.pubAddress)))throw new L(F.errors.TYPE_ERROR,"Invalid cid, Not along to this wallet.");return e.sign(r),r=e.toOptions(!0),[await this.send({outputs:[{address:i.pubAddress,value:1e4}],comment:r},t),r]}async ensureCp(e,t=!1){if(await this.db.flushCP([e]),(e=this.db.cpList.getItem(e))||t)return e;throw new L(F.errors.TYPE_ERROR,"Invalid cid, cannot find cp.")}}e.exports=re},function(e,t,i){"use strict";
|
|
295
|
+
*/const r=i(0);var s=i(16);const n=i(15),a=i(2),o=i(3),c=i(35),h=i(198),u=i(141).sortWithSeq,l=i(6),p=i(94),d=i(1),f=i(4),m=i(69),g=i(334);i(218);const y=i(109),v=i(73),b=i(13),w=i(68),k=i(17),x=i(219),S=i(156),_=i(28),E=i(157),R=i(337),A=i(63),O=i(26),C=i(29),I=i(7),j=i(310),P=i(38),T=S.Mnemonic,{opcodes:B,hashType:N}=i(19),M=i(165),L=i(77),F=i(78),z=i(142),H=i(46),D=i(20),U=i(42),q=i(54),{NotifyMsg:V,ContractStatus:K,ContractType:W,PropStatus:$}=i(5),X=i(37).VerifyError,G=i(153).ErItem,Y=i(154).ErAbolishItem,J=i(228).EnchancementItem,Z=i(67),Q=i(59),ee=i(83),te=i(85).txdb,ie=i(31);class re extends s{constructor(e,t){super(),r(e,"DB required."),this.db=e,this.network=e.network,this.logger=e.logger,this.readLock=new h,this.writeLock=new c,this.sendLock=new c,this.indexCache=new A(1e4),this.accountCache=new A(1e4),this.pathCache=new A(1e5),this.current=null,this.wid=0,this.id=null,this.initialized=!1,this.watchOnly=!1,this.accountDepth=0,this.token=o.ZERO_HASH,this.tokenDepth=0,this.master=new R,this.txdb=new g(this),this.account=null,t&&this.fromOptions(t)}fromOptions(e){let t,i,s=e.master;return s?("string"==typeof s&&(s=S.PrivateKey.fromBase58(s,this.network)),r(S.isPrivate(s),"Must create wallet with hd private key.")):(i=new T(e.mnemonic),s=S.fromMnemonic(i,this.network)),r(s.network===this.network,"Network mismatch for master key."),this.master.fromKey(s,i),null!=e.wid&&(r(a.isU32(e.wid)),this.wid=e.wid),e.id&&(r(v.isName(e.id),"Bad wallet ID."),t=e.id),null!=e.initialized&&(r("boolean"==typeof e.initialized),this.initialized=e.initialized),null!=e.watchOnly&&(r("boolean"==typeof e.watchOnly),this.watchOnly=e.watchOnly),null!=e.accountDepth&&(r(a.isU32(e.accountDepth)),this.accountDepth=e.accountDepth),e.token&&(r(Buffer.isBuffer(e.token)),r(32===e.token.length),this.token=e.token),t=t||this.getID(),this.id=t,this}static fromOptions(e,t){return new re(e).fromOptions(t)}async init(e){var t=e.passphrase;r(!this.initialized),this.initialized=!0,t&&await this.master.encrypt(t),e=await this._createAccount(e,t);r(e),this.account=e,this.logger.info("Wallet initialized (%s).",this.id),await this.txdb.open()}async open(){r(this.initialized);var e=await this.getAccount(0);if(!e)throw new Error("Default account not found.");this.account=e,this.logger.info("Wallet opened (%s).",this.id),await this.txdb.open()}async ensureNotifyKey(){this.notifyKey||(await this.ensureAccount({name:"alliance",witness:!0}),this.notifyKey=await this.createReceive("alliance",1,this.master),this.notifyAddress=this.notifyKey.getAddress("string"))}async createAllianceInfo(e,t,i){var r={alliancename:e,nodeid:t};return e?(r.alliancePrivateKey=l.hash256(Buffer.concat([Buffer.from(e),this.master.key.privateKey])),i?(r.prv=Buffer.alloc(0),r.pub=Buffer.from(i,"hex"),r.awardAddress=b.fromWitnessPubkeyhash(l.hash160(r.pub),this.network.type).toString(this.network.type),r.mnemonic=new T):(i=l.hash256(Buffer.concat([Buffer.from(e+"-"+t),this.master.key.privateKey])),r.mnemonic=new T({entropy:i,language:this.master.mnemonic.language,passphrase:this.master.mnemonic.passphrase}),r.prv=l.hash256(Buffer.from(r.mnemonic.toSeed().toString("hex"))),r.pub=O.publicKeyCreate(r.prv,!0),e=R.fromKey(S.fromMnemonic(r.mnemonic),this.network.type).key.deriveAccount(44,0).derive(9).derive(1),r.awardAddress=b.fromWitnessPubkeyhash(l.hash160(e.publicKey),this.network.type).toString(this.network.type))):(r.mnemonic=T.fromOptions(this.master.mnemonic),r.prv=l.hash256(Buffer.from(r.mnemonic.toSeed().toString("hex"))),r.pub=O.publicKeyCreate(r.prv,!0),r.awardAddress=b.fromWitnessPubkeyhash(l.hash160(r.pub),this.network.type).toString(this.network.type)),r.address=b.fromWitnessPubkeyhash(l.hash160(r.pub),this.network.type).toString(),r}async destroy(){var e=await this.writeLock.lock(),t=await this.sendLock.lock();try{this.db.unregister(this),await this.master.destroy(),this.readLock.destroy(),this.writeLock.destroy(),this.sendLock.destroy()}finally{t(),e()}}async addSharedKey(e,t){var i=await this.writeLock.lock();try{return await this._addSharedKey(e,t)}finally{i()}}async _addSharedKey(e,t){if(t||(t=e,e=null),!(e=await this.getAccount(e=null==e?0:e)))throw new Error("Account not found.");let i;this.start();try{i=await e.addSharedKey(t)}catch(e){throw this.drop(),e}return await this.commit(),i}async removeSharedKey(e,t){var i=await this.writeLock.lock();try{return await this._removeSharedKey(e,t)}finally{i()}}async _removeSharedKey(e,t){if(t||(t=e,e=null),!(e=await this.getAccount(e=null==e?0:e)))throw new Error("Account not found.");let i;this.start();try{i=await e.removeSharedKey(t)}catch(e){throw this.drop(),e}return await this.commit(),i}async setPassphrase(e,t){e&&await this.decrypt(e),t&&await this.encrypt(t)}async encrypt(e){var t=await this.writeLock.lock();try{return await this._encrypt(e)}finally{t()}}async _encrypt(e){e=await this.master.encrypt(e,!0),this.start();try{await this.db.encryptKeys(this,e)}catch(t){throw p(e),this.drop(),t}p(e),this.save(),await this.commit()}async decrypt(e){var t=await this.writeLock.lock();try{return await this._decrypt(e)}finally{t()}}async _decrypt(e){e=await this.master.decrypt(e,!0),this.start();try{await this.db.decryptKeys(this,e)}catch(t){throw p(e),this.drop(),t}p(e),this.save(),await this.commit()}async rename(e){var t=await this.writeLock.lock();try{return await this.db.rename(this,e)}finally{t()}}async writeBalanceLog(e){var t=await this.writeLock.lock();try{return await this.db.writeBalanceLog(this,e)}finally{t()}}async renameAccount(e,t){var i=await this.writeLock.lock();try{return await this._renameAccount(e,t)}finally{i()}}async _renameAccount(e,t){if(!v.isName(t))throw new Error("Bad account name.");var i=await this.getAccount(e);if(!i)throw new Error("Account not found.");if(0===i.accountIndex)throw new Error("Cannot rename default account.");if(await this.hasAccount(t))throw new Error("Account name not available.");e=i.name,this.start(),this.db.renameAccount(i,t),await this.commit(),this.indexCache.remove(e),e=this.pathCache.values();for(const r of e)r.account===i.accountIndex&&(r.name=t)}async lock(){var e=await this.writeLock.lock(),t=await this.sendLock.lock();try{await this.master.lock()}finally{t(),e()}}unlock(e,t){return this.master.unlock(e,t)}getID(){r(this.master.key,"Cannot derive id.");var e,t=this.master.key.derive(44);(e=new f(37)).writeBytes(t.publicKey),e.writeU32(this.network.magic),t=l.hash160(e.render());return(e=new f(27)).writeU8(3),e.writeU8(190),e.writeU8(4),e.writeBytes(t),e.writeChecksum(),m.encode(e.render())}async createAccount(e,t){var i=await this.writeLock.lock();try{return await this._createAccount(e,t)}finally{i()}}async _createAccount(e,t){let i,s,n=e.name,o=(n=n||this.accountDepth.toString(10),0);if(0!=this.accountDepth&&(o=a.hashInt(n)),await this.hasAccountIndex(o))throw new Error("Account Index Conflict.");if(await this.hasAccount(n))throw new Error("Account already exists.");if(await this.unlock(t),this.watchOnly&&e.accountKey){if("string"==typeof(i=e.accountKey)&&(i=S.PublicKey.fromBase58(i,this.network)),!S.isPublic(i))throw new Error("Must add HD public keys to watch only wallet.");r(i.network===this.network,"Network mismatch for watch only key.")}else r(this.master.key),i=(i=this.master.key.deriveAccount(44,o)).toPublic();t={wid:this.wid,id:this.id,name:0===this.accountDepth?"default":n,witness:e.witness,watchOnly:this.watchOnly,accountKey:i,accountIndex:o,type:e.type,m:e.m,n:e.n,keys:e.keys},this.start();try{(s=E.fromOptions(this.db,t)).wallet=this,await s.init()}catch(e){throw this.drop(),e}return this.logger.info("Created account %s/%s/%d.",s.id,s.name,s.accountIndex),this.accountDepth++,this.save(),await this.commit(),s}async ensureAccount(e,t){var i=e.name;return(i=await this.getAccount(i))||this.createAccount(e,t)}getAccounts(){return this.db.getAccounts(this.wid)}getAccountMap(){return this.db.getAccountMap(this.wid)}getAddressHashes(e){return null!=e?this.getAccountHashes(e):this.db.getWalletHashes(this.wid)}async getAccountHashes(e){return e=await this.ensureIndex(e,!0),this.db.getAccountHashes(this.wid,e)}async getAccount(e){if(this.account&&(null==e||"default"===e||"number"==typeof e&&0===e||"string"==typeof e&&0===e.length))return this.account;if(-1===(e=await this.getAccountIndex(e)))return null;var t=await this.readLock.lock(e);try{return await this._getAccount(e)}finally{t()}}async _getAccount(e){var t=this.accountCache.get(e);return t||((t=await this.db.getAccount(this.wid,e))?(t.wallet=this,t.wid=this.wid,t.id=this.id,t.watchOnly=this.watchOnly,await t.open(),this.accountCache.set(e,t),t):null)}async getAccountIndex(e){var t;return null==e?-1:"number"==typeof e?e:null!=(t=this.indexCache.get(e))?t:-1===(t=await this.db.getAccountIndex(this.wid,e))?-1:(this.indexCache.set(e,t),t)}async getAccountName(e){var t;return"string"==typeof e?e:(t=this.accountCache.get(e))?t.name:this.db.getAccountName(this.wid,e)}async hasAccount(e){return-1!==(e=await this.getAccountIndex(e))&&(!!this.accountCache.has(e)||this.db.hasAccount(this.wid,e))}async hasAccountIndex(e){return!!this.accountCache.has(e)||this.db.hasAccount(this.wid,e)}createReceive(e,t=0,i=null){return this.createKey(e,0,t,i)}createChange(e){return this.createKey(e,1)}createNested(e){return this.createKey(e,2)}async createKey(e,t,i=0,r=null){var s=await this.writeLock.lock();try{return await this._createKey(e,t,i,r)}finally{s()}}async _createKey(e,t,i=0,r=null){if(null==t&&(t=e,e=null),!(e=await this.getAccount(e=e||0)))throw new Error("Account not found.");let s;this.start();try{s=await e.createKey(t,i,r)}catch(e){throw this.drop(),e}return await this.commit(),s}async deriveKey(e,t,i,r=null){let s=null;var n=await this.writeLock.lock();try{this.start(),s=await this._deriveKey(e,t,i,r),await this.commit()}catch(e){throw this.drop(),e}finally{n()}return s}async _deriveKey(e,t,i=0,r=null){if(null==t&&(t=e,e=null),e=e||0,e=parseInt(e),e=await this.getAccount(e))return t=await e.deriveKey(t,i,r),await e.saveKey(t),t;throw new Error("Account not found.")}save(){return this.db.save(this)}async saveAccount(e){var t=await this.writeLock.lock();try{this.start(),e._save(),await this.commit(),0==e.accountIndex&&(this.account=e)}finally{t()}}start(){return this.db.start(this)}drop(){return this.db.drop(this)}clear(){return this.db.clear(this)}commit(){return this.db.commit(this)}async hasAddress(e){return e=b.getHash(e,"hex"),null!=await this.getPath(e)}async ownedAddress(e){return!!await this.getKey(e)}async getPath(e){return(e=await this.readPath(e))?(e.name=await this.getAccountName(e.account),r(e.name),this.pathCache.set(e.hash,e),e):null}async readPath(e){e=b.getHash(e,"hex");var t=this.pathCache.get(e);return t||((t=await this.db.getPath(this.wid,e))?(t.id=this.id,t):null)}async hasPath(e){return e=b.getHash(e,"hex"),!!this.pathCache.has(e)||this.db.hasPath(this.wid,e)}async getPaths(e){if(null!=e)return this.getAccountPaths(e);var t=[];for(const e of await this.db.getWalletPaths(this.wid))e.id=this.id,e.name=await this.getAccountName(e.account),r(e.name),this.pathCache.set(e.hash,e),t.push(e);return t}async getAccountPaths(e){var t=await this.ensureIndex(e,!0),i=await this.getAccountHashes(t),s=await this.getAccountName(e),n=(r(s),[]);for(const e of i){var a=await this.readPath(e);r(a),r(a.account===t),a.name=s,this.pathCache.set(a.hash,a),n.push(a)}return n}async importKey(e,t,i){var r=await this.writeLock.lock();try{return await this._importKey(e,t,i)}finally{r()}}async _importKey(e,t,i){if(e&&"object"==typeof e&&(i=t,t=e,e=null),null==e&&(e=0),r(t.network===this.network,"Network mismatch for key."),this.watchOnly){if(t.privateKey)throw new Error("Cannot import privkey into watch-only wallet.")}else if(!t.privateKey)throw new Error("Cannot import pubkey into non watch-only wallet.");var s=t.getHash("hex");if(await this.getPath(s))throw new Error("Key already exists.");if(!(s=await this.getAccount(e)))throw new Error("Account not found.");if(s.type!==E.types.PUBKEYHASH)throw new Error("Cannot import into non-pkh account.");await this.unlock(i),e=x.fromRing(s,t).toPath(),this.master.encrypted&&(e.data=this.master.encipher(e.data,e.hash),r(e.data),e.encrypted=!0),this.start();try{await s.savePath(e)}catch(e){throw this.drop(),e}await this.commit()}async importAddress(e,t){var i=await this.writeLock.lock();try{return await this._importAddress(e,t)}finally{i()}}async _importAddress(e,t){if(t||(t=e,e=null),null==e&&(e=0),t.network!==this.network)throw new Error("Network mismatch for address.");if(!this.watchOnly)throw new Error("Cannot import address into non watch-only wallet.");if(await this.getPath(t))throw new Error("Address already exists.");if(!(e=await this.getAccount(e)))throw new Error("Account not found.");if(e.type!==E.types.PUBKEYHASH)throw new Error("Cannot import into non-pkh account.");t=y.fromAddress(e,t),this.start();try{await e.savePath(t)}catch(e){throw this.drop(),e}await this.commit()}async fund(e,t){var i=await this.writeLock.lock();try{return await this._fund(e,t)}finally{i()}}async _fund(e,t){if(t=t||{},!this.initialized)throw new Error("Wallet is not initialized.");if(this.watchOnly)throw new Error("Cannot fund from watch-only wallet.");let i;if(null!=t.account){if(!(i=await this.getAccount(t.account)))throw new Error("Account not found.")}else i=this.account;if(!i.initialized)throw new Error("Account is not initialized.");let s,n=t.rate;return null==n&&(n=await this.db.estimateFee(t.blocks)),s=t.smart?await this.getSmartCoins(i.name):(s=await this.getCoins(i.name),this.txdb.filterConserved(s)),await e.fund(s,{allowPreInput:t.allowPreInput,noChange:t.noChange,selection:t.selection,round:t.round,depth:t.depth,hardFee:t.hardFee,subtractFee:t.subtractFee,subtractIndex:t.subtractIndex,changeAddress:i.change.getAddress(),height:this.db.curHeight,rate:n,maxFee:t.maxFee,estimate:e=>this.estimateSize(e),network:this.network}),!t.allowInfiniteFee&&t.noChange&&r(e.getFee()<=j.MAX_FEE,"TX exceeds MAX_FEE."),s}async getAccountByAddress(e){return e=b.getHash(e,"hex"),(e=await this.getPath(e))?this.getAccount(e.account):null}async estimateSize(e){var t=I.WITNESS_SCALE_FACTOR,i=b.fromScript(e);if(!i)return-1;var r=await this.getAccountByAddress(i);if(!r)return-1;let s=0;if(e.isScripthash()&&r.witness)switch(r.type){case E.types.PUBKEYHASH:s=4*(s+23);break;case E.types.MULTISIG:s=4*(s+35)}switch(r.type){case E.types.PUBKEYHASH:s=s+74+34;break;case E.types.MULTISIG:s=(s=(s=(s=(s+=1)+74*r.m)+3+1)+34*r.n)+1+1}return r.witness?s=((s+=1)+t-1)/t|0:s+=o.sizeVarint(s),s}async createTX(e){var t=e.outputs,i=new w;r(Array.isArray(t),"Outputs must be an array."),r(0<t.length,"No outputs available."),e.comment&&("object"==typeof e.comment&&(e.comment=JSON.stringify(e.comment)),i.outputs.push(_.fromScript(k.createScript(Buffer.from(e.comment),k.types.NULLDATA),0)));for(const e of t){var s=new _(e),n=s.getAddress();if(s.isDust())throw new Error("Output is dust.");if(0<s.value){if(!n)throw new Error("Cannot send to unknown address.");if(n.isNull())throw new Error("Cannot send to null address.")}i.outputs.push(s)}let a=null;if(e.inputs)for(const t of e.inputs){var o=await this.getTX(t.hash);o&&(o=q.fromTX(o.tx,t.index,-1,0))&&(a=o.getAddress(),e.allowPreInput=!0,i.addCoin(o))}else await this.fund(i,e);if(a&&((t=new _).value=i.getFee()-j.MIN_FEE,t.script.fromAddress(a),i.outputs.push(t),i.changeIndex=i.outputs.length-1),!1!==e.sort&&i.sortMembers(),null!=e.locktime&&i.setLocktime(e.locktime),r(i.isSane(),"TX failed sanity check."),r(i.verifyInputs(this.db.curHeight+1),"TX failed context check."),0===await this.template(i))throw new Error("Templating failed.");return i}async send(e,t){var i=await this.sendLock.lock();try{return await this._send(e,t)}finally{i()}}async _send(e,t){return t&&(e.account=t),t=await this.createTX(e,!0),await this.sign(t),this.sendMTX(t,{sendafter:e.sendafter})}async sendMTX(e,t={}){if(!e.isSigned())throw new Error("TX could not be fully signed.");var i=e.toTX();if(i.getSigopsCost(e.view)>C.MAX_TX_SIGOPS_COST)throw new Error("TX exceeds policy sigops.");if(i.getWeight()>C.MAX_TX_WEIGHT)throw new Error("TX exceeds policy weight.");return t.sendafter||(this.logger.debug("Sending wallet tx (%s): %s",this.id,i.txid()),await this.db.addTX(i),await this.db.send(i)),i}async resend(){var e=await this.getPending(),t=(0<e.length&&this.logger.info("Rebroadcasting %d transactions.",e.length),[]);for(const i of e)t.push(i.tx);for(const e of u(t))await this.db.send(e);return t}async deriveInputs(e){r(e.mutable);var t=[];for(const r of await this.getInputPaths(e)){var i=await this.getAccount(r.account);i&&(i=i.derivePath(r,this.master))&&t.push(i)}return t}async getKey(e){try{var t,i=b.getHash(e,"hex",this.network.type),r=await this.getPath(i);return r&&(t=await this.getAccount(r.account))?t.derivePath(r,this.master):null}catch{return null}}async exportToFile(e){if(!Q.unsupported){var t=await this.db.getTip(),i=a.date();let o="",c=[a.fmt("# Wallet Dump created by %s %s",ee.protocol,ee.version),a.fmt("# * Created on %s",i),a.fmt("# * Best block at time of backup was %d (%s).",t.height,a.revHex(t.hash)),a.fmt("# * File: %s",e.file),""];var r,s;t=a.fmt("W %s wid= %s",this.toRaw().toString("base64"),this.wid),t=(c.push(t),await this.getAccounts());for(const e of t){var n=await this.getAccount(e);n=a.fmt("C %s name= %s index= %d",n.toRaw().toString("base64"),n.name,n.accountIndex);c.push(n)}for(const t of await this.getAddressHashes())this.watchOnly?(r=b.fromWitnessPubkeyhash(Buffer.from(t,"hex"),this.network.type).toString(),r=a.fmt("A %s %s label= account= %s branch= %s index= %s addr= %s","S",i,0,-1,-1,r),c.push(r)):(r=await this.getPrivateKey(t))&&(s=r.getAddress("string"),s=a.fmt("A %s %s label= account= %s branch= %s index= %s addr= %s",r.toSecret(),i,r.account,r.branch,r.index,s),c.push(s),e.fragment)&&1e5<c.length&&(o=c.join("\n"),await Q.writeFile(e.file.split(".").reduce((e,t)=>(e?e+="."+t:e=t+"-1",e),""),o,"utf8"),c=[]);c.push(""),c.push("# End of dump"),c.push(""),o=c.join("\n"),await Q.writeFile(e.file,o,"utf8")}}async getPrivateKey(e,t){if(e=b.getHash(e,"hex"),!(e=await this.getPath(e)))return null;var i=await this.getAccount(e.account);return i?(await this.unlock(t),(t=i.derivePath(e,this.master)).privateKey?t:null):null}async getInputPaths(e){if(r(e.mutable),!e.hasCoins())throw new Error("Not all coins available.");var t=[];for(const r of e.getInputHashes("hex")){var i=await this.getPath(r);i&&t.push(i)}return t}async getOutputPaths(e){var t=[];for(const r of e.getOutputHashes("hex")){var i=await this.getPath(r);i&&t.push(i)}return t}async setLookahead(e,t){var i=await this.writeLock.lock();try{return this._setLookahead(e,t)}finally{i()}}async _setLookahead(e,t){if(null==t&&(t=e,e=null),!(e=await this.getAccount(e=null==e?0:e)))throw new Error("Account not found.");this.start();try{await e.setLookahead(t)}catch(e){throw this.drop(),e}await this.commit()}async syncOutputDepth(e){var t=new Map;for(const r of e.outputs){var i=r.path;i&&-1!==i.index&&(t.has(i.account)||t.set(i.account,[]),t.get(i.account).push(i))}var s,n,a=[];for([s,n]of t){let e=-1,t=-1,i=-1;for(const r of n)switch(r.branch){case 0:r.index>e&&(e=r.index);break;case 1:r.index>t&&(t=r.index);break;case 2:r.index>i&&(i=r.index)}e+=2,t+=2,i+=2;var o=await this.getAccount(s);(o=(r(o),await o.syncDepth(e,t,i)))&&a.push(o)}return a}async getRedeem(e){"string"==typeof e&&(e=Buffer.from(e,"hex"));var t=await this.getKey(e.toString("hex"));return t?t.getRedeem(e):null}async template(e){var t=await this.deriveInputs(e);return e.sign(t)}async onSaleList(e,t){return(await(await this.getPropList()).predict(async(e,i)=>!!i.bid&&await this.belongToAccount(t,i.bid.address))).where([["pst",$.Sale]]).paginate(10,e).records()}async mySaleList(e,t){return(await(await this.getPropList()).predict(async(e,i)=>this.belongToAccount(t,i.current.address))).where([["pst",$.Sale]]).paginate(10,e).records()}async getPropList(){const e=await this.db.loadVpList();var t=[];for(let i=0;i<e.length;i++){let r=e[i];t.push((async()=>{await this.getPrivateKey(r.current.address)&&(e[i]=[r.pid,r])})())}return await Promise.all(t),new ie(e)}async propCreate(e,t){var i,s=new w;for(i of e){var n=await this.ensureCp(i.cid,!0);!n||i.cid==this.network.genesisId||(i.gold=(0|i.gold)>>>0,i.gold<I.MINPROPVALUE)||(i.pid||(i.pid=z()),i.oid||(i.oid=i.pid),s.propCreate(n.current.address,i),i.index=s.outputs.length-1)}if(0<s.outputs.length){t?await this.fund(s,{account:t}):await this.fund(s),await this.sign(s);var a,o=s.commit();for(a of(await this.db.addTX(o[0]),await this.db.send(o[0]),r(o[0].verify(o[1],k.flags.STANDARD_VERIFY_FLAGS)),e))a.hash=o[0].hash("hex"),a.txid=o[0].txid();return o}return[]}async attach(e,t){var i,s=new w;for(i of e)s.attach(i.address,i.value,i.data);if(0<s.outputs.length){t?await this.fund(s,{account:t}):await this.fund(s),await this.sign(s);var n,a=s.commit();for(n of(await this.db.addTX(a[0]),await this.db.send(a[0]),r(a[0].verify(a[1],k.flags.STANDARD_VERIFY_FLAGS)),e))n.hash=a[0].hash("hex"),n.txid=a[0].txid();return a}return[]}async sendSecret(e,t,i){let r=this.db.$contacts.get(e);if(!r||!r.sender){var s=(await this.createReceive(i)).getAddress("string");if(e==s)throw new L(F.errors.TYPE_ERROR,"Forbid Sending to Self Address.");r=await this.db.ensureContact({contact:e,messenger:s,wallet:this,account:i})}if(r)return r.send(t);throw new L(F.errors.TYPE_ERROR,"Invalid Address.")}async commNotify(e){r(!!e),r(!!e.dst),r(!!e.content);var t=new w,i=e.src||this.getReceive().toString(),s=(i=new V(W.notify,z(),this.db.curHeight,{src:i,content:e.content}),_.fromScript(k.createScript(i.toRaw(),k.types.NULLDATA),0));t.outputs.push(s),s={address:e.dst,locktime:I.BLOCK_DAY,locktype:"csb",value:.1*I.COIN},t.outputs.push(new _(s)),e.account?await this.fund(t,{account:e.account,noChange:!0,allowInfiniteFee:!0}):await this.fund(t,{noChange:!0,allowInfiniteFee:!0}),await this.sign(t),s=t.commit();return r(s[0].verify(s[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(s[0]),this.logger.debug("Sending tx on wallet(%s): %s",this.id,s[0].txid()),await this.db.send(s[0]),i.hash=s[0].hash("hex"),i.height=-1,i}async cpRegister(e,t,i,s){if(r(!!t&&"object"==typeof t),!await this.db.client.execute("canExecute",[{confirm:!1,cid:t.cid,name:t.name,oper:W.cpRegister}]))throw new L(F.errors.TYPE_ERROR,"Invalid CP Register Info.");const n=new w;e||(a=await this.createReceive(i),e=a.getAddress());var a=await this.getKey(e);if(!a)throw new L(F.errors.TYPE_ERROR,"Invalid CP Register Address, Not along to this wallet.");if(t.pubAddress=e.toString(),t.pubKey=a.getPublicKey("hex"),t.signMethod="secp256k1",a=await this.createAllianceInfo(),t.register=a.pub.toString("hex"),n.cpRegister(e,I.registerFee,t),a=async()=>{i?await this.fund(n,{account:i}):await this.fund(n),await this.sign(n);var s=n.commit();return r(s[0].verify(s[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(s[0]),await this.db.send(s[0]),t.txid=s[0].txid(),t.addr=e.toString(),s},!s)return a();a()}getSCAddress(e){return e=Z.fromMnemonic(T.fromOptions(I.SmartContractMnemonic),this.network).deriveAccount(44,e).derive(9).derive(1),b.fromWitnessPubkeyhash(l.hash160(e.publicKey),this.network)}async cpChange(e,t){var i=await this.ensureCp(e.cid);if(i.cid==this.network.genesisId||"ATHENA"==i.name)throw new L(F.errors.TYPE_ERROR,"Invalid cp name.");var s=await this.getTX(i.current.hash);if(!s)throw new L(F.errors.TYPE_ERROR,"Do not have permission to change this info.");if(s=s.tx,!await this.belongToAccount(t,s.outputs[0].getAddress()))throw new L(F.errors.TYPE_ERROR,"Invalid account info.");if(e.newName){if(!await this.db.client.execute("canExecute",[{confirm:!1,cid:i.cid,name:e.newName,oper:W.cpChange}]))throw new L(F.errors.TYPE_ERROR,"Invalid CP Change Info.")}else e.newName=i.name;return e.addr||(e.addr=b.fromString(i.current.address)),i=w.cpChange(s,e),t?await this.fund(i,{allowPreInput:!0,account:t}):await this.fund(i,{allowPreInput:!0}),await this.sign(i),s=i.commit(),await this.db.send(s[0]),r(s[0].verify(s[1],k.flags.STANDARD_VERIFY_FLAGS)),e.txid=s[0].txid(),s}async propExchangeList(e,t,i=!1){var s,n,a,o=new w,c=[];for([s,n,a]of e){var h,u=null;if(u=await this.getTX(s.hash)){if(u=u.tx,h=s.index,u&&u.outputs&&!(u.outputs.length<=h)){if(i){if(!await this.ownedAddress(u.outputs[h].getAddress())){this.logger.error("not owned prop:",s.hash,s.index);continue}}else if(!await this.belongToAccount(t,u.outputs[h].getAddress())){this.logger.error("not owned prop:",s.hash,s.index);continue}var l=u.outputs[h].getReturnData();l&&(o.propExchange(u,h,n),l.index=o.outputs.length-1,l.addr=n.toString(),c.push(l))}}else this.logger.error("tx not find:",s.hash,a)}return t?await this.fund(o,{allowPreInput:!0,account:t}):await this.fund(o,{allowPreInput:!0}),await this.sign(o),e=o.commit(),await this.db.addTX(e[0]),await this.db.send(e[0]),r(e[0].verify(e[1],k.flags.STANDARD_VERIFY_FLAGS)),e.push(c),e}async propDonate(e,t){var i=e.index;if(!(e=await this.getTX(e.hash))||!e.tx||!e.tx.outputs||e.tx.outputs.length<=i)throw new L(F.errors.TYPE_ERROR,"Invalid tx info.");if(!await this.belongToAccount(t,e.tx.outputs[i].getAddress()))throw new L(F.errors.TYPE_ERROR,"Props that do not belong to you.");if(!(t=e.tx.outputs[i].getReturnData()))throw new L(F.errors.TYPE_ERROR,"Invalid tx info.");if(t.cid&&t.cid==this.network.genesisId)throw new X(e.tx,"invalid","Special props that can not to donate",100);var r=new w;return(e=(r.addInputFromTx(e.tx,i),r.addOutput(k.createScript(Buffer.from(JSON.stringify({value:e.tx.outputs[i].value,cid:t.cid,pid:t.pid,oid:t.oid,gaddr:this.getAddress().toString(this.network)})),k.types.NULLDATA),0),await this.sign(r,null,N.NONE|N.ANYONECANPAY),r.commit())).push(t),e}async propReceive(e,t){var i=(e=w.fromTX(e,1)).inputs[0].prevout,r=e.outputs[0].getReturnData();e.view.addOutput({hash:e.inputs[0].prevout.hash,index:e.inputs[0].prevout.index},new _({value:r.value})),e.outputs.pop();let s=this.getAddress().toString(this.network);t&&(n={cid:r.cid,uid:t},s=(n=await this.tokenCreate(n,t)).data.addr),e.outputs.push(_.fromScript(s,r.value,{oper:W.propExchange,pid:r.pid,cid:r.cid,oid:r.oid,prev:{hash:i.hash,index:i.index}})),t?await this.fund(e,{allowPreInput:!0,account:t}):await this.fund(e,{allowPreInput:!0}),await this.sign(e,null,N.ALL,[0]);var n=e.commit();return await this.db.send(n[0]),r.simAddr=s,[n[0],null,r]}async belongToAccount(e,t){return!!t&&!(!(t=await this.getAccountByAddress(t))||e&&t.name!==e)}async propExchange(e,t,i){let s=null,n=0;var a;return Array.isArray(e)?(s=e[0],n=e[1]):(a=await this.getTX(e.hash))&&(s=a.tx,n=e.index),!s||!s.outputs||s.outputs.length<=n?(this.logger.error("Invalid tx info."),null):await this.ownedAddress(s.outputs[n].getAddress())?(a=s.outputs[n].getReturnData())?(e=(new w).propExchange(s,n,t),a.index=e.outputs.length-1,i?await this.fund(e,{allowPreInput:!0,account:i}):await this.fund(e,{allowPreInput:!0}),await this.sign(e),t=e.commit(),await this.db.addTX(t[0]),await this.db.send(t[0]),r(t[0].verify(t[1],k.flags.STANDARD_VERIFY_FLAGS)),t.push(a),t):(this.logger.error("Invalid tx info."),null):(this.logger.error("Invalid user."),null)}async propFound(e,t,i){if(e=await this.getTX(e),r(e),!(e=e.tx))throw new L(F.errors.TYPE_ERROR,"Invalid hex string.");var s=e.outputs[t],n=s.getReturnData();if(!n||n.oper!==W.propExchange&&n.oper!==W.propCreate)throw new L(F.errors.TYPE_ERROR,"Invalid tx type.");if(n.cid==this.network.genesisId)throw new X(block,"invalid","prop found supertoken",100);var a=new w;a.addInputFromTx(e,t),e=_.fromScript(s.getAddress(),s.value),a.outputs.push(e),i?await this.fund(a,{allowPreInput:!0,subtractFee:!0,account:i}):await this.fund(a,{allowPreInput:!0,subtractFee:!0}),await this.sign(a),t=a.commit();return await this.db.send(t[0]),r(t[0].verify(t[1],k.flags.STANDARD_VERIFY_FLAGS)),t.push(n),t}async propSale(e,t,i,s){let n=await this.getTX(e);if(!n)throw new L(F.errors.TYPE_ERROR,"Invalid tx info.");if(n.getDepth(this.db.curHeight)<=0)throw new L(F.errors.TYPE_ERROR,"No enough confirmations.");if(!(n=n.tx))throw new L(F.errors.TYPE_ERROR,"Invalid tx info.");var a=n.outputs[t].getReturnData([k.opcodes.OP_PROPEXCHANGE,k.opcodes.OP_PROPCREATE]);if(!a)throw new L(F.errors.TYPE_ERROR,"Invalid tx type.");if(!await this.ownedAddress(n.outputs[t].getAddress()))throw new L(F.errors.TYPE_ERROR,"Invalid tx info.");var o=await this.getCoin(e,t);if(!o||-1===o.height)throw new L(F.errors.WALLET_INSUFFICIENT_FUNDS,"Invalid coin.");if(await this.txdb.isSpent(e,t))throw new L(F.errors.WALLET_INSUFFICIENT_FUNDS,"Invalid coin.");if(i<=n.outputs[t].value)throw new L(F.errors.TYPE_ERROR,"Invalid fixed price.");if(a.cid==this.network.genesisId)throw new X(n,"invalid","prop not for sale",100);return e=(o=new w).addInputFromTx(n,t),t={oper:W.propSale,pid:a.pid,prev:{hash:e.prevout.hash,index:e.prevout.index},fixed:i,period:this.db.curHeight+I.BLOCK_DAY},a=_.fromScript(k.createScript(Buffer.from(JSON.stringify(t)),k.types.NULLDATA),0),o.outputs.push(a),await this.sign(o,null,N.SINGLE|N.ANYONECANPAY),e=o.commit(),r(e[0].verify(e[1],k.flags.STANDARD_VERIFY_FLAGS)),await this.db.send(e[0]),e}async propBuy(e,t,i){if(!(e=this.db.propList.get(e))||e.pst!=$.Sale||!e.bid||!e.bid.raw)throw new L(F.errors.INVALID_PARAMS,"Invalid Tx Hash.");var r=D.fromRaw(Buffer.from(e.bid.raw,"hex")),s=(await this.createReceive(i)).getAddress(),n=e.gold;if(t<n)throw new Error("wrong price");if(1<r.outputs.length&&t<r.outputs[1].value)throw new Error("low bid price than before");var a=w.fromTX(r,1);if(!a.outputs[0].getReturnType(B.OP_RETURN))throw new Error("not a sale order");return await this.remove(r.hash("hex")),a.view.addOutput({hash:a.inputs[0].prevout.hash,index:a.inputs[0].prevout.index},new _({value:e.gold})),t=new _({address:e.current.address,value:t}),a.outputs.push(t),t={oper:W.propExchange,pid:e.pid,cid:e.cid,oid:e.oid,prev:{hash:a.inputs[0].prevout.hash,index:a.inputs[0].prevout.index}},s=_.fromScript(s,n,t),a.outputs.push(s),i?await this.fund(a,{allowPreInput:!0,account:i}):await this.fund(a,{allowPreInput:!0}),await this.sign(a,null,N.ALL,[0]),n=a.commit(),e.owned||this.db.client.watchOutpoint((new H).fromOptions(r.inputs[0].prevout)),await this.db.send(n[0]),n}async getTXByAmount(e,t){let i=null;var r;for(r of await this.getCoins(t))if(!(r.height<=0)&&r.value==e){i=r;break}return i&&(t=await this.getTX(i.hash))?[t.tx,i.index,i.height]:[]}async contractCreate(e,t,i,s,n){if(this.db.transactionList.query(e,s)!=K.None)throw new L(F.errors.TYPE_ERROR,"Contract with the same address finded.");if(0!=parseInt(t%1e3,10))throw new L(F.errors.TYPE_ERROR,"Contract source should an integer multiple of 1000.");if(!await U.checkSum(this.network,e,s))throw new L(F.errors.TYPE_ERROR,"Create contract with an invalid Address or a Address with old transations.");let a=!1,[o,c,h]=await this.getTXByAmount(t,n);if(!o){a=!0;var u=new w;let e="";e=(n?await this.createReceive(n):this).getAddress(),u.outputs.push(_.fromScript(e,t)),n?await this.fund(u,{allowPreInput:!0,account:n}):await this.fund(u,{allowPreInput:!0}),await this.sign(u),u=u.commit(),r(u[0].verify(u[1],k.flags.STANDARD_VERIFY_FLAGS)),o=u[0],c=0,h=-1}(u=new w).addInputFromTx(o,c,h);let l="";l=(n?await this.createReceive(n):this).getAddress();var p=await this.getKey(l);e={oper:W.contractCreate,type:e,addr:s,src:t,dst:i,srcact:n,alice:p.getPublicKey("hex"),period:this.db.curHeight+I.TRANSACTION_PERIOD},s=_.fromScript(k.createScript(Buffer.from(JSON.stringify(e)),k.types.NULLDATA),0),u.outputs.push(s),await this.sign(u,null,N.SINGLE|N.ANYONECANPAY),t=u.commit();return a&&await this.db.send(o),await this.db.send(t[0]),t}async contractPromise(e,t){if(!(e=this.db.transactionList.get(e))||e.transStatus!=K.CreatedOnMem)throw new L(F.errors.INVALID_PARAMS,"Invalid Tx id.");if(!(e=D.fromRaw(Buffer.from(e.raw,"hex"))))throw new L(F.errors.TYPE_ERROR,"Invalid Tx id.");var i=U.parseContract(e);if(!i||i.oper!==W.contractCreate)throw new L(F.errors.TYPE_ERROR,"Invalid tx type.");var r=w.fromTX(e,1);if(!r.outputs[0].getReturnType(B.OP_RETURN))throw new Error("not a valid contract");r.view.addOutput({hash:r.inputs[0].prevout.hash,index:r.inputs[0].prevout.index},new _({value:i.src}));let s="";s=(t?await this.createReceive(t):this).getAddress();var n=await this.getKey(s);e={oper:W.contractPromise,prevhash:e.hash("hex"),type:i.type,addr:i.addr,dst:i.dst,srcact:i.srcact,dstact:t,bob:n.getPublicKey("hex"),period:i.period},t=new k([M.fromSymbol("promise"),M.fromData(Buffer.from(JSON.stringify(e))),M.fromSymbol("drop"),M.fromSymbol("greaterthan"),M.fromSymbol("drop"),M.fromSymbol("if"),M.fromData(l.hash160(Buffer.from(e.bob,"hex"))),M.fromSymbol("else"),M.fromData(l.hash160(Buffer.from(i.alice,"hex"))),M.fromSymbol("endif"),M.fromSymbol("checksig")]),r.outputs.push(_.fromScript(t,i.src)),await this.remove(e.prevhash),await this.sign(r,null,N.ALL,[0]),n=r.commit();return await this.db.send(n[0]),e.current={hash:n[0].hash("hex"),index:0},e.raw=n[0].toRaw().toString("hex"),e.transStatus=K.Promised,this.db.transactionList.saveContract(e,!0),n}async contractExecute(e,t){if(!(e=this.db.transactionList.get(e))||e.transStatus!=K.Confirmed&&e.transStatus!=K.Expired)throw new L(F.errors.INVALID_PARAMS,"Invalid Tx id.");if(!(e=D.fromRaw(Buffer.from(e.raw,"hex"))))throw new L(F.errors.TYPE_ERROR,"Invalid Tx id.");t=t||1;var i=U.parseContract(e);if(!i||i.oper!==W.contractPromise)throw new L(F.errors.TYPE_ERROR,"Invalid tx type.");var s=e.outputs[1].getReturnData();if(!s||s.oper!==W.contractPromise)throw new L(F.errors.TYPE_ERROR,"Invalid tx type.");r.strictEqual(i.addr,s.addr),r.strictEqual(i.type,s.type),r.strictEqual(i.dst,s.dst),r.strictEqual(i.period,s.period),r.strictEqual(i.srcact,s.srcact),r.strictEqual(i.dstact,s.dstact);var n=this.db.transactionList.query(i.type,i.addr);if(n!=K.Confirmed&&n!=K.Expired)throw new L(F.errors.TYPE_ERROR,"Contract Promise not Check yet.");if(n==K.Expired&&1!=t||n==K.Confirmed&&2!=t)throw new L(F.errors.TYPE_ERROR,"Invalid Executor.");let a=i.srcact,o=(2==t&&(a=i.dstact),"");o=(a?await this.createReceive(a):this).getAddress();var c=new w,h=(c.addInputFromTx(e,1),{oper:W.contractExecute,type:i.type,addr:i.addr,master:t});h=_.fromScript(k.createScript(Buffer.from(JSON.stringify(h)),k.types.NULLDATA),0),c.outputs.push(h),h=_.fromScript(o,e.outputs[1].value),c.outputs.push(h),e=1==t?await P.fromPublic(Buffer.from(i.ori.alice,"hex")):await P.fromPublic(Buffer.from(s.bob,"hex")),h=await this.getKey(e.getAddress()),await c.signAsync(h,k.hashType.ALL,this.db.workers),t=c.commit();return r(t[0].verify(t[1],k.flags.STANDARD_VERIFY_FLAGS,n)),await this.db.send(t[0]),t}async htlcDeal(e,t){var i=await this.getTX(e.hash);let r=null;if(t){if(!(t=await this.getAccount(t)))throw new L(F.errors.TYPE_ERROR,"Invalid Account.");r=t.getReceive().toString()}else r=this.getReceive().toString();t=new w;var s=(new k).pushOp(B.OP_1);e.suggest&&s.pushData(Buffer.from(e.sa,"hex")),t.addInput({prevout:{hash:e.hash,index:e.index},script:s}),t.addOutput(r,i.tx.outputs[e.index].value-1e4),t.view.addOutput({hash:e.hash,index:e.index},new _(i.tx.outputs[e.index])),await this.sign(t,null,N.ALL),s=t.commit();return await this.db.send(s[0]),s}async htlcCancel(e,t){let i=null;var r=await this.getTX(e.hash);if(!(i=r?r.tx.outputs[e.index]:i))throw new L(F.errors.TYPE_ERROR,"Invalid Input.");let s=null;if(t){if(!(r=await this.getAccount(t)))throw new L(F.errors.TYPE_ERROR,"Invalid Account.");s=r.getReceive().toString()}else s=this.getReceive().toString();return t=new w,r=(new k).pushOp(B.OP_0),e.suggest&&r.pushData(Buffer.from(e.sa,"hex")),t.addInput({prevout:{hash:e.hash,index:e.index},script:r}),e.suggest?t.setSequence(0,2*I.HTLC_CANCEL_PERIOD,!1):t.setSequence(0,I.HTLC_CANCEL_PERIOD,!1),t.addOutput(s,i.value-1e4),t.view.addOutput({hash:e.hash,index:e.index},new _(i)),r=await this.getKey(e.master),await t.signAsync(r,k.hashType.ALL,this.db.workers),e=t.commit(),await this.db.send(e[0]),e}async sendContracts(e,t,i){var r,s=new w;for(r of e)s.outputs.push(i.create(r));return t?await this.fund(s,{account:t}):await this.fund(s),await this.sign(s),e=s.commit(),await this.db.addTX(e[0]),await this.db.send(e[0]),e}async tokenCreate(e,t="",i){r(e&&"object"==typeof e,"Token data should be a object"),r(e.cid,"Token data should has a cid property"),r(e.uid,"Token data should has a uid property"),e.time=!0,await this.ensureAccount({name:t,witness:!0});let s=null;if(i){if(!await this.belongToAccount(t,i))throw new L(F.errors.TYPE_ERROR,`tokenCreate address error: addr:${i} is not belongs to account:`+t);s=await this.getKey(i)}else s=await this.createReceive(t,a.hashInt(e.cid),this.master);return s.signData(e)}async sign(e,t,i=k.hashType.ALL,r){if(this.watchOnly)throw new Error("Cannot sign from a watch-only wallet.");return await this.unlock(t),t=await this.deriveInputs(e),e.signAsync(t,i,this.db.workers,r)}getCoinView(e){return this.txdb.getCoinView(e)}getSpentView(e){return this.txdb.getSpentView(e)}toDetails(e){return this.txdb.toDetails(e)}getDetails(e){return this.txdb.getDetails(e)}async getCoin(e,t){return this.txdb.getCoin(e,t)}async getCredit(e,t){return this.txdb.getCredit(e,t)}async getStatusOfSC(e){return this.txdb.getStatusOfSC(e)}async setStatusOfSC(e,t){var i=await this.writeLock.lock();try{this.txdb.start();try{await this.txdb._setStatusOfSC(e,t),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}}finally{i()}}getLockedCoins(){return this.txdb.lockedCoins.values}getTX(e){return this.txdb.getTX(e)}getBlocks(){return this.txdb.getBlocks()}getBlock(e){return this.txdb.getBlock(e)}async add(e,t,i){var r=await this.writeLock.lock();try{return await this._add(e,t,i)}finally{r()}}async _add(e,t,i){let r,s;this.txdb.start();try{(r=await this.txdb._add(e,t,i))&&(s=await this.syncOutputDepth(r)),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}return s&&0<s.length&&(this.db.emit("address",this.id,s),this.emit("address",s)),r}async resetBalance(){var e=await this.writeLock.lock();try{this.txdb.start();try{this.txdb.pending.unconfirmed=0,this.txdb.pending.confirmed=0;for(const e of await this.getAccounts()){var t=await this.getBalance(e);this.txdb.pending.unconfirmed+=t.unconfirmed,this.txdb.pending.confirmed+=t.confirmed}this.txdb.put(te.R,this.txdb.pending.commit()),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}}finally{e()}return this.txdb.state.toBalance()}async unconfirm(e){var t=await this.writeLock.lock();try{return await this.txdb.unconfirm(e)}finally{t()}}async remove(e){var t=await this.writeLock.lock();try{return await this.txdb.remove(e)}finally{t()}}async zap(e,t){var i=await this.writeLock.lock();try{return await this._zap(e,t)}finally{i()}}async _zap(e,t){return e=await this.ensureIndex(e),this.txdb.zap(e,t)}async abandon(e){var t=await this.writeLock.lock();try{return await this._abandon(e)}finally{t()}}_abandon(e){return this.txdb.abandon(e)}conserveCoin(e){return this.txdb.conserveCoin(e)}unConserveCoin(e){return this.txdb.unConserveCoin(e)}isConserved(e){return this.txdb.isConserved(e)}getConserved(){return this.txdb.getConserved()}async getHistory(e){return e=await this.ensureIndex(e),this.txdb.getHistory(e)}async getCoins(e){return e=await this.ensureIndex(e),this.txdb.getCoins(e)}async getCredits(e){return e=await this.ensureIndex(e),this.txdb.getCredits(e)}async getSmartCoins(e){var t=[];for(const r of await this.getCredits(e)){var i=r.coin;r.spent||this.txdb.isConserved(i)||-1===i.height&&!r.own||t.push(i)}return t}async getPending(e){return e=await this.ensureIndex(e),this.txdb.getPending(e)}async getBalance(e){return e=await this.ensureIndex(e),this.txdb.getBalance(e)}async queryBalanceLog(e,t=0){return(e=await this.ensureIndex(e))?this.db.queryBalanceLog(this.wid,e,t):[]}async getRange(e,t){return e&&"object"==typeof e&&(t=e,e=null),e=await this.ensureIndex(e),this.txdb.getRange(e,t)}async getLast(e,t){return e=await this.ensureIndex(e),this.txdb.getLast(e,t)}async ensureIndex(e,t){if(null==e){if(t)throw new Error("No account provided.");return null}if(-1===(t=await this.getAccountIndex(e)))throw new Error("Account not found.");return t}getAddress(e){return this.account.getAddress(e)}getReceive(e){return this.account.getReceive(e)}getChange(e){return this.account.getChange(e)}getNested(e){return this.account.getNested(e)}inspect(){return{wid:this.wid,id:this.id,network:this.network.type,initialized:this.initialized,accountDepth:this.accountDepth,token:this.token.toString("hex"),tokenDepth:this.tokenDepth,state:this.txdb.state?this.txdb.state.toJSON(!0):null,master:this.master,account:this.account}}toJSON(e){return{network:this.network.type,wid:this.wid,id:this.id,initialized:this.initialized,watchOnly:this.watchOnly,accountDepth:this.accountDepth,token:this.token.toString("hex"),tokenDepth:this.tokenDepth,height:this.db.curHeight,state:this.txdb.state.toJSON(!0),master:this.master.toJSON(e),account:this.account.toJSON(!0)}}getSize(){var e=0;return(e+=50)+o.sizeVarString(this.id,"ascii")+o.sizeVarlen(this.master.getSize())}toRaw(){var e=this.getSize();return(e=new f(e)).writeU32(this.network.magic),e.writeU32(this.wid),e.writeVarString(this.id,"ascii"),e.writeU8(this.initialized?1:0),e.writeU8(this.watchOnly?1:0),e.writeU32(this.accountDepth),e.writeBytes(this.token),e.writeU32(this.tokenDepth),e.writeVarBytes(this.master.toRaw()),e.render()}fromRaw(e){e=new d(e);var t=n.fromMagic(e.readU32());return this.wid=e.readU32(),this.id=e.readVarString("ascii"),this.initialized=1===e.readU8(),this.watchOnly=1===e.readU8(),this.accountDepth=e.readU32(),this.token=e.readBytes(32),this.tokenDepth=e.readU32(),this.master.fromRaw(e.readVarBytes()),r(t===this.db.network,"Wallet network mismatch."),this}static fromRaw(e,t){return new re(e).fromRaw(t)}static isWallet(e){return e instanceof re}async issueCreate(e,t,i){var r=new G(e),s=((s=(r.source.subjectName||(r.source.subjectName=r.erid),P.fromPrivate(Buffer.from(e.key,"hex"),!0,this.network))).witness=!0,r.sign(s,!0,this.network),r.toOptions(!0));return i?this.send({outputs:[{address:e.address,value:1e4}],comment:s},t):(r=await this.send({outputs:[{address:e.address,value:1e4}],comment:s},t),s.txid=r.txid()),s}async caAbolish(e,t,i){var r=P.fromPrivate(Buffer.from(e.key,"hex"),!0,this.network),s=(r.witness=!0,await this.db.client.execute("ca.byId",[e.erid]));if(!s)throw new L(F.errors.TYPE_ERROR,"ca.abolish: Invalid erid.");if(s.source.cid!=e.cid)throw new L(F.errors.TYPE_ERROR,"ca.abolish: Invalid cid.");if(s.source.uid!=e.uid)throw new L(F.errors.TYPE_ERROR,"ca.abolish: Invalid uid.");var n=s.signature;if(s.sign(r,!0,this.network),s.witness!=e.witness||s.signature!=n)throw new L(F.errors.TYPE_ERROR,"ca.abolish: You have no permission to abolish this witness.");return(s=new Y(e)).sign(r),n=s.toOptions(!0),i?this.send({outputs:[{address:e.address,value:1e4}],comment:n},t):await this.send({outputs:[{address:e.address,value:1e4}],comment:n},t),n}async enchanceCp(e,t){var i=((e=new J(e)).oper="enchanceCp",await this.ensureCp(e.to)),r=await this.ensureCp(e.from);if(!(r=await this.getKey(r.pubAddress)))throw new L(F.errors.TYPE_ERROR,"Invalid cid, Not along to this wallet.");return e.sign(r),r=e.toOptions(!0),[await this.send({outputs:[{address:i.pubAddress,value:1e4}],comment:r},t),r]}async ensureCp(e,t=!1){if(await this.db.flushCP([e]),(e=this.db.cpList.getItem(e))||t)return e;throw new L(F.errors.TYPE_ERROR,"Invalid cid, cannot find cp.")}}e.exports=re},function(e,t,i){"use strict";
|
|
296
296
|
/*!
|
|
297
297
|
* BlockMeta.js - walletdb records
|
|
298
298
|
* 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(664),n=i(762),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(763);i=i(764);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(315),s=i(174);const n=i(623),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(315);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(53);var s=i(93);const n=i(43),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(674);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(676),n=i(88),a=(0,r(i(93)).default)("socket.io:adapter-uws"),{addAll:o,del:c,broadcast:h}=s.Adapter.prototype;function u(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(679),s=i(625).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(80),o=i(121),{getBlockOverview:c,getBlockByHash:h,formatTimestamp:u}=i(626);async function l(e,t){if(e.valid(),!(e=await this.chain.tip))throw new s(n.MISC_ERROR,"Block not found");if(e=await h(this.node,e.hash,t))return e.chain="VNS",e.network="main"===this.node.network.type?"mainnet":"testnet",e}e.exports=[{name:"blocks",method:"get",path:"/public/block",callback:async function(e,t){var i,r=this,s=(e=e.valid()).str("blockDate"),n=e.str("startTimestamp",""),a=(e=e.uint("limit",10),u(new Date));if(s){if(!/\d{4}-\d{2}-\d{2}/.test(s))throw new Error("Please use yyyy-mm-dd format");i=s===a}else s=a,i=!0;a=Math.round(new Date(s).getTime()/1e3),n=parseInt(n)||a+86400;var o=u(new Date(1e3*(a-86400))),c=n?u(new Date(1e3*n)):null,l=(e=parseInt(e||200),!1),p=n;try{var d,f=await r.chain.db.getTimestampHashes(n,a);let u=[];for(d of f)u.push(d.hash);u.reverse(),u.length>e&&(l=!0,u=u.slice(0,e));var m,g={blocks:[],length:u.length,pagination:{next:c,prev:o,currentTs:n-1,current:s,isToday:i,more:l,moreTs:l?p:void 0}};for(m of u){var y=await h(r,m,t);y.chain="VNS",y.network="main"===r.node.network.type?"mainnet":"testnet",g.blocks.push(y)}return g.blocks.sort((e,t)=>t.height-e.height),g.blocks}catch(e){throw e}}},{name:"block-tip",method:"get",path:"/public/block/tip",callback:l},{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:l},{name:"block",method:"get",path:"/public/block/:blockHash",callback:async function(e,t){if(e=(e=e.valid()).str("blockHash"),e=await h(this.node,e,t))return e.chain="VNS",e.network="main"===this.node.network.type?"mainnet":"testnet",e}},{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(626),h=i(33),u=i(80),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=(e=e.valid()).str("addr");i=i||e.str("addrs");var r=(e=await this.node.getCoinsByAddress(i.split(","))).reduce((e,t)=>e+t.value,0);return{confirmed:r-(e=e.reduce((e,t)=>(-1==t.height&&(e+=t.value),e),0)),unconfirmed:e,balance:r}}async function f(e,t){let i=(e=e.valid()).str("addr");var r,s=[];for(r of(i=i||e.str("addrs")).split(",")){var n=(a=await this.node.getCoinsByAddress(r)).reduce((e,t)=>e+t.value,0),a=a.reduce((e,t)=>(-1==t.height&&(e+=t.value),e),0);s.push({param:r,result:{confirmed:n-a,unconfirmed:a,balance:n}})}return s}async function m(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,y(e));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 g(e,t){var i=e.valid();let r=i.str("addr");r=r||i.str("addrs");var s=y(e),n=[];try{for(var c of r.split(",")){var h,u=await this.node.getMetaByAddress(c),l=[];for(h of u){var p=await o(this.node,h);l.push(await a(this.node,p,s))}n.push({param:c,result:l})}return n}catch(e){throw e}}function y(e){return{noAsm:!!parseInt(e.query.noAsm),noScriptSig:!!parseInt(e.query.noScriptSig),noSpent:!!parseInt(e.query.noSpent)}}async function v(e,t){let i=(e=e.valid()).str("addrs");i=i||e.str("addr","");try{var s,n=[];for(s of await r(this.node,i.split(",")))n.push(w(this,s));return n}catch(e){throw e}}async function b(e,t){let i=(e=e.valid()).str("addrs");i=i||e.str("addr","");try{var s,n=[];for(s of i.split(",")){var a,o=[];for(a of await r(this.node,s))o.push(w(this,a));n.push({param:s,result:o})}return n}catch(e){throw e}}function w(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.chain="VNS",i.network="main"===e.node.network.type?"mainnet":"testnet",i.coinbase=t.coinbase,i.mintTxid=i.txid,i.value=i.satoshis,i.mintIndex=i.vout,i.mintHeight=i.height,i.spentTxid="",i.spentHeight=-2,i.script=i.scriptPubKey,i}async function k(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 x(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:k},{name:"address.reflect.index",method:"get",path:"/public/addr/reflect/:id/:index",callback:k},{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 x(this,i,r)}catch(e){throw e}}},{name:"getUTXOByAddress",method:"get",path:"/public/addr/:addr/utxo",callback:v},{name:"getTXSByAddress",method:"get",path:"/public/address/:addr/txs",callback:m},{name:"getUTXOByAddress",method:"get",path:"/public/address/:addr/utxo",callback:v},{name:"getUTXOByAddresses",method:"get",path:"/public/addrs/:addrs/utxo",callback:v},{name:"postUTXOByAddresses",method:"post",path:"/public/addrs/utxo",callback:v},{name:"getUTXOGroupAddresses",method:"get",path:"/public/addrs/:addrs/grouputxo",callback:b},{name:"postUTXOGroupAddresses",method:"post",path:"/public/addrs/grouputxo",callback:b},{name:"getTXSByAddresses",method:"get",path:"/public/addrs/:addrs/txs",callback:m},{name:"postTXSByAddresses",method:"post",path:"/public/addrs/txs",callback:m},{name:"getTXSGroupAddresses",method:"get",path:"/public/addrs/:addrs/grouptxs",callback:g},{name:"postTXSGroupAddresses",method:"post",path:"/public/addrs/grouptxs",callback:g},{name:"getBalanceByAddress",method:"get",path:"/public/addrs/:addrs/balance",callback:d},{name:"postBalanceByAddress",method:"post",path:"/public/addrs/balance",callback:d},{name:"getBalanceGroupAddress",method:"get",path:"/public/addrs/:addrs/groupbalance",callback:f},{name:"postBalanceGroupAddress",method:"post",path:"/public/addrs/groupbalance",callback:f},{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:"getBalanceByAddress",method:"get",path:"/public/address/:addr/balance",callback:d},{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 x(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 x(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(83);const s=i(33),n=i(80);var a=i(331),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:"getPeers",method:"get",path:"/public/peers",callback:async function(e,t){return this.rpc.execute({corba:!0,method:"sys.peerinfo"})}},{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(682),s=i(0),n=i(2),{handleErrors:a,getDetailedTransaction:o,transformTransaction:c,getDetailFromMeta:h,getBlockOverview:u,translateInputAddresses:l}=i(626),p=i(80),d=i(19).opcodes,f=i(6);e.exports=[{name:"getTx",method:"get",path:"/public/tx/:txid",callback:async function(e,t){var i,r=this;return e=(e=e.valid()).hash("txid"),(e=await o(r.node,e))?((i=await c(r.node,e,{})).chain="VNS",i.coinbase=e.isCoinbase(),i.network="main"===r.node.network.type?"mainnet":"testnet",i.blockTime=i.blocktime,i.blockTimeNormalized=i.blockTime,i.fee=i.fees*Math.pow(10,8),i.blockHash=i.blockhash,i.blockHeight=i.blockheight,i.coinbase=!1,i.inputCount=i.vin.length,i.outputCount=i.vout.length,i.value=i.valueIn*Math.pow(10,8),i):null}},{name:"getSpender",method:"get",path:"/public/tx/:txid/spender/:index",callback:async function(e,t){var i=this,r=(e=e.valid()).hash("txid");e=e.u32("index",0);return s(r,"Hash is required."),s(null!=e,"Index is required."),(i=await i.node.chain.db.getSpender(r,e))&&(i.txid=n.revHex(i.txid)),i}},{name:"getTx",method:"get",path:"/public/tx/:txid/coins",callback:async function(e,t){let i=this;const r=e.valid().hash("txid");let s=await o(i.node,r),a=null;if(s){a=await c(i.node,s,{});let e={inputs:[],outputs:[]},t=0;return s.inputs.map(o=>{var c=a.vin[t];c.coinbase=o.isCoinbase(),c.chain="VNS",c.network="main"===i.node.network.type?"mainnet":"testnet",c.sequenceNumber=o.sequence,c.address=a.vin[t].address||"",c.value=a.vin[t].valueSat||0,c.mintHeight=a.vin[t].mintHeight||0,c.mintTxid=n.revHex(o.prevout.hash),c.mintIndex=o.prevout.index,c.spentTxid=r,c.spentHeight=s.height,c.confirmations=s.confirmations,c.script=o.script.raw.toString("hex"),e.inputs.push(c),t++}),t=0,s.outputs.map(n=>{var o=a.vout[t];o.chain="VNS",o.network="main"===i.node.network.type?"mainnet":"testnet",o.coinbase=s.isCoinbase(),o.mintTxid=r,o.address=a.vout[t].scriptPubKey.addresses?a.vout[t].scriptPubKey.addresses[0]:"",o.spentTxid=a.vout[t].spentTxid||"",o.spentHeight=a.vout[t].spentHeight||0,o.mintIndex=t,o.mintHeight=s.height,o.value=n.value,o.confirmations=s.confirmations,o.script=n.script.raw.toString("hex"),e.outputs.push(o),t++}),e}return 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:"getBlob",method:"get",path:"/public/blob/:txid/:index",callback:async function(e,t){var i=(e=e.valid()).hash("txid");e=e.uint("index");if(!(i=await this.node.getMeta(i))||!i.tx)return null;if(!(i=i.tx.outputs[e]))return null;if(!(e=i.getReturnData([d.OP_PROPEXCHANGE,d.OP_PROPCREATE]))||!e.oid)return null;if(!(i=await this.node.chain.db.erList.query([["erid",e.oid]]))||!i.list||!i.list[0].erid)return null;let r=i.list[0].source.blob;return"string"==typeof r&&(r=JSON.parse(r)),t.setHeader("content-type",r.type),{data:r}}},{name:"notify",method:"post",path:"/public/notify",callback:async function(e,t){return e.body.sign==(delete e.body.sign,e.body.secret=this.node.config.remotesecret,f.hash256(Buffer.from(JSON.stringify(e.body))).toString("hex"))?(delete e.body.secret,console.log("remote notify:",JSON.stringify(e.body)),{code:0}):{code:-1}}},{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:"block",method:"get",path:"/public/block/:blockHash/coins/:pageSize/:pageNum",callback:async function(e,t){var i=this,p=(s(!i.chain.options.spv,"Cannot get TX in SPV mode."),e.query.blockHash),d=e.params.pageSize?parseInt(e.params.pageSize):100,f=l(e.query.address),m=parseInt(e.params.pageNum)-1||0,g=1;if(p=p||e.params.blockHash){if(!(e=await u(i.node,p,t)))return a(null,t);t=e.txids.length;var y,v=[],b=[],w=(r.isUndefined(m)?y=e.txids:(E=m*d,y=e.txids.slice(E,E+d),g=Math.ceil(t/d)),[]);for(let e of y){let t=await o(i.node,n.revHex(e),!0),r=null;if(t){r=await c(i.node,t,{}),w.push(r);let s=0;t.inputs.map(a=>{a.isCoinbase()||v.push({coinbase:!1,chain:"VNS",network:"main"===i.node.network.type?"mainnet":"testnet",mintTxid:n.revHex(a.prevout.hash),mintIndex:a.prevout.index,spentTxid:e,spentHeight:t.height,confirmations:t.confirmations,sequenceNumber:a.sequence,script:a.script.raw.toString("hex"),address:r.vin[s].addr||"",mintHeight:r.vin[s].mintHeight||0,value:r.vin[s].valueSat||0}),s++}),s=0,t.outputs.map(n=>{b.push({coinbase:t.isCoinbase(),chain:"VNS",network:"main"===i.node.network.type?"mainnet":"testnet",mintTxid:e,address:r.vout[s].scriptPubKey.addresses?r.vout[s].scriptPubKey.addresses[0]:"",spentTxid:r.vout[s].spentTxid||"",spentHeight:r.vout[s].spentHeight||0,mintIndex:s,mintHeight:t.height,value:n.value,confirmations:t.confirmations,script:n.script.raw.toString("hex")}),s++})}}return{txids:y,previous:"",next:m+1<g?`/block/${p}/coins/${d}/`+(m+2):"",inputs:v,outputs:b}}if(f){var k=m*d,x=(m+1)*d,S=[];e=await i.node.getMetaByAddress(f);let t=0;for(const r of e){if(t<k);else{if(t>=x)break;var _=await h(i.node,r);S.push(await c(i.node,_,{}))}t++}var E=Math.ceil(e.length/d);return{txids:y,previous:"",next:`/block/${p}/coins/${d}/`+((m+1)%E+1),pagesTotal:E,inputs:[],outputs:[],txs:S}}throw new Error("Block hash or address expected")}},{name:"getTxSend",method:"get",path:"/public/rawsend/:tx",callback:async function(e,t){return e=(e=e.valid()).str("tx"),e=await this.rpc.execute({method:"tx.raw.send",params:[e]})}},{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(19).opcodes,s=i(31),n=i(2).revHex,a=i(80);e.exports=[{name:"prop.byaddress",method:"get",path:"/public/props/address/:address",callback:async function(e,t){return e=e.valid().str("address"),this.node.chain.db.getVpByAddress(e)}},{name:"prop.bidlist",method:"jsonp",path:"/",callback:async function(e,t){e.bidList||(e.bidList=new s);t=new a([t]);var i=Math.max(0,t.uint(0));return 0==i?(t=t.str(1))?e.bidList.query([["pid",t],["size",e.bidList.getSize()],["page",1]]):e.bidList.query([["size",e.bidList.getSize()],["page",1]]):e.bidList.query([["size",10],["page",i]])}},{name:"propBidlist",method:"get",path:"/public/prop/bidlist/:page",callback:async function(e,t){return this.node.bidList||(this.node.bidList=new s),e=e.valid(),(e=Math.max(0,e.uint("page",0)))?this.node.bidList.query([["size",10],["page",e]]):this.node.bidList.query([["size",this.node.bidList.getSize()],["page",1]])}},{name:"propBidOne",method:"get",path:"/public/prop/bidone/:pid",callback:async function(e,t){return this.node.bidList||(this.node.bidList=new s),(e=e.valid().str("pid"))?this.node.bidList.query([["pid",e],["page",1]]):[]}},{name:"prop.get",method:"get",path:"/public/prop/:pid",callback:async function(e,t){var i=[],s=(e=e.valid().str("pid"),await this.node.chain.db.propList.getVp(e));if(s){let e=[s.current.hash,s.current.index];for(;;){var a=await this.node.getMeta(e[0]),o=a.tx;if(!o)break;if(!(o=o.outputs[e[1]]))break;var c=o.getReturnData([r.OP_PROPCREATE,r.OP_PROPEXCHANGE]);if(!c)break;if(c.current={hash:n(e[0]),index:e[1],address:o.getAddress().toString()},c.height=a.height,c.status=s.pst,c.pst=s.pst,c.gold=s.gold,0==i.length&&s.bid&&(c.bid=s.bid),i.push(c),!c.prev)break;e=[c.prev.hash,c.prev.index]}}return i}}]},function(e,t,i){const r=i(80);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(80),s=i(100),n=i(77),a=i(78).errors,o=i(67),c=i(5).ContractStatus,h=i(20),u=i(33);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:"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(80),s=i(784);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.byId",method:"jsonp",path:"/",callback:async function(e,t){return t=new r([t]).str(0),e.chain.db.erList.getEr(t)}},{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(664),n=i(762),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(763);i=i(764);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(315),s=i(174);const n=i(623),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(315);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(53);var s=i(93);const n=i(43),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(674);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(676),n=i(88),a=(0,r(i(93)).default)("socket.io:adapter-uws"),{addAll:o,del:c,broadcast:h}=s.Adapter.prototype;function u(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(679),s=i(625).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(80),o=i(121),{getBlockOverview:c,getBlockByHash:h,formatTimestamp:u}=i(626);async function l(e,t){if(e.valid(),!(e=await this.chain.tip))throw new s(n.MISC_ERROR,"Block not found");if(e=await h(this.node,e.hash,t))return e.chain="VNS",e.network="main"===this.node.network.type?"mainnet":"testnet",e}e.exports=[{name:"blocks",method:"get",path:"/public/block",callback:async function(e,t){var i,r=this,s=(e=e.valid()).str("blockDate"),n=e.str("startTimestamp",""),a=(e=e.uint("limit",10),u(new Date));if(s){if(!/\d{4}-\d{2}-\d{2}/.test(s))throw new Error("Please use yyyy-mm-dd format");i=s===a}else s=a,i=!0;a=Math.round(new Date(s).getTime()/1e3),n=parseInt(n)||a+86400;var o=u(new Date(1e3*(a-86400))),c=n?u(new Date(1e3*n)):null,l=(e=parseInt(e||200),!1),p=n;try{var d,f=await r.chain.db.getTimestampHashes(n,a);let u=[];for(d of f)u.push(d.hash);u.reverse(),u.length>e&&(l=!0,u=u.slice(0,e));var m,g={blocks:[],length:u.length,pagination:{next:c,prev:o,currentTs:n-1,current:s,isToday:i,more:l,moreTs:l?p:void 0}};for(m of u){var y=await h(r,m,t);y.chain="VNS",y.network="main"===r.node.network.type?"mainnet":"testnet",g.blocks.push(y)}return g.blocks.sort((e,t)=>t.height-e.height),g.blocks}catch(e){throw e}}},{name:"block-tip",method:"get",path:"/public/block/tip",callback:l},{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:l},{name:"block",method:"get",path:"/public/block/:blockHash",callback:async function(e,t){if(e=(e=e.valid()).str("blockHash"),e=await h(this.node,e,t))return e.chain="VNS",e.network="main"===this.node.network.type?"mainnet":"testnet",e}},{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(626),h=i(33),u=i(80),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=(e=e.valid()).str("addr");i=i||e.str("addrs");var r=(e=await this.node.getCoinsByAddress(i.split(","))).reduce((e,t)=>e+t.value,0);return{confirmed:r-(e=e.reduce((e,t)=>(-1==t.height&&(e+=t.value),e),0)),unconfirmed:e,balance:r}}async function f(e,t){let i=(e=e.valid()).str("addr");var r,s=[];for(r of(i=i||e.str("addrs")).split(",")){var n=(a=await this.node.getCoinsByAddress(r)).reduce((e,t)=>e+t.value,0),a=a.reduce((e,t)=>(-1==t.height&&(e+=t.value),e),0);s.push({param:r,result:{confirmed:n-a,unconfirmed:a,balance:n}})}return s}async function m(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,y(e));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 g(e,t){var i=e.valid();let r=i.str("addr");r=r||i.str("addrs");var s=y(e),n=[];try{for(var c of r.split(",")){var h,u=await this.node.getMetaByAddress(c),l=[];for(h of u){var p=await o(this.node,h);l.push(await a(this.node,p,s))}n.push({param:c,result:l})}return n}catch(e){throw e}}function y(e){return{noAsm:!!parseInt(e.query.noAsm),noScriptSig:!!parseInt(e.query.noScriptSig),noSpent:!!parseInt(e.query.noSpent)}}async function v(e,t){let i=(e=e.valid()).str("addrs");i=i||e.str("addr","");try{var s,n=[];for(s of await r(this.node,i.split(",")))n.push(w(this,s));return n}catch(e){throw e}}async function b(e,t){let i=(e=e.valid()).str("addrs");i=i||e.str("addr","");try{var s,n=[];for(s of i.split(",")){var a,o=[];for(a of await r(this.node,s))o.push(w(this,a));n.push({param:s,result:o})}return n}catch(e){throw e}}function w(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.chain="VNS",i.network="main"===e.node.network.type?"mainnet":"testnet",i.coinbase=t.coinbase,i.mintTxid=i.txid,i.value=i.satoshis,i.mintIndex=i.vout,i.mintHeight=i.height,i.spentTxid="",i.spentHeight=-2,i.script=i.scriptPubKey,i}async function k(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 x(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:k},{name:"address.reflect.index",method:"get",path:"/public/addr/reflect/:id/:index",callback:k},{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 x(this,i,r)}catch(e){throw e}}},{name:"getUTXOByAddress",method:"get",path:"/public/addr/:addr/utxo",callback:v},{name:"getTXSByAddress",method:"get",path:"/public/address/:addr/txs",callback:m},{name:"getUTXOByAddress",method:"get",path:"/public/address/:addr/utxo",callback:v},{name:"getUTXOByAddresses",method:"get",path:"/public/addrs/:addrs/utxo",callback:v},{name:"postUTXOByAddresses",method:"post",path:"/public/addrs/utxo",callback:v},{name:"getUTXOGroupAddresses",method:"get",path:"/public/addrs/:addrs/grouputxo",callback:b},{name:"postUTXOGroupAddresses",method:"post",path:"/public/addrs/grouputxo",callback:b},{name:"getTXSByAddresses",method:"get",path:"/public/addrs/:addrs/txs",callback:m},{name:"postTXSByAddresses",method:"post",path:"/public/addrs/txs",callback:m},{name:"getTXSGroupAddresses",method:"get",path:"/public/addrs/:addrs/grouptxs",callback:g},{name:"postTXSGroupAddresses",method:"post",path:"/public/addrs/grouptxs",callback:g},{name:"getBalanceByAddress",method:"get",path:"/public/addrs/:addrs/balance",callback:d},{name:"postBalanceByAddress",method:"post",path:"/public/addrs/balance",callback:d},{name:"getBalanceGroupAddress",method:"get",path:"/public/addrs/:addrs/groupbalance",callback:f},{name:"postBalanceGroupAddress",method:"post",path:"/public/addrs/groupbalance",callback:f},{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:"getBalanceByAddress",method:"get",path:"/public/address/:addr/balance",callback:d},{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 x(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 x(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(83);const s=i(33),n=i(80);var a=i(331),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:"getPeers",method:"get",path:"/public/peers",callback:async function(e,t){return this.rpc.execute({corba:!0,method:"sys.peerinfo"})}},{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(682),s=i(0),n=i(2),{handleErrors:a,getDetailedTransaction:o,transformTransaction:c,getDetailFromMeta:h,getBlockOverview:u,translateInputAddresses:l}=i(626),p=i(80),d=i(19).opcodes,f=i(6);async function m(e,t){var i,r=[];for(i of e.valid().str("txids").split(","))try{i=n.revHex(i);var s=await this.rpc.execute({method:"tx.raw.get",params:[i,!0]});s&&r.push({param:i,result:s})}catch(e){}return r}async function g(e,t){var i,r=[];for(i of e.valid().str("txids").split(",")){var s,n=await o(this.node,i);n&&((s=await c(this.node,n,{})).chain="VNS",s.coinbase=n.isCoinbase(),s.network="main"===this.node.network.type?"mainnet":"testnet",s.blockTime=s.blocktime,s.blockTimeNormalized=s.blockTime,s.fee=s.fees*Math.pow(10,8),s.blockHash=s.blockhash,s.blockHeight=s.blockheight,s.coinbase=!1,s.inputCount=s.vin.length,s.outputCount=s.vout.length,s.value=s.valueIn*Math.pow(10,8),r.push({parama:i,result:s}))}return r}e.exports=[{name:"getTx",method:"get",path:"/public/tx/:txid",callback:async function(e,t){var i,r=this;return e=(e=e.valid()).hash("txid"),(e=await o(r.node,e))?((i=await c(r.node,e,{})).chain="VNS",i.coinbase=e.isCoinbase(),i.network="main"===r.node.network.type?"mainnet":"testnet",i.blockTime=i.blocktime,i.blockTimeNormalized=i.blockTime,i.fee=i.fees*Math.pow(10,8),i.blockHash=i.blockhash,i.blockHeight=i.blockheight,i.coinbase=!1,i.inputCount=i.vin.length,i.outputCount=i.vout.length,i.value=i.valueIn*Math.pow(10,8),i):null}},{name:"getTxs",method:"get",path:"/public/txids/:txids",callback:g},{name:"getTxs",method:"post",path:"/public/txids",callback:g},{name:"getRawTxs",method:"get",path:"/public/rawtxids/:txids",callback:m},{name:"getRawTxs",method:"post",path:"/public/rawtxids",callback:m},{name:"getSpender",method:"get",path:"/public/tx/:txid/spender/:index",callback:async function(e,t){var i=this,r=(e=e.valid()).hash("txid");e=e.u32("index",0);return s(r,"Hash is required."),s(null!=e,"Index is required."),(i=await i.node.chain.db.getSpender(r,e))&&(i.txid=n.revHex(i.txid)),i}},{name:"getTx",method:"get",path:"/public/tx/:txid/coins",callback:async function(e,t){let i=this;const r=e.valid().hash("txid");let s=await o(i.node,r),a=null;if(s){a=await c(i.node,s,{});let e={inputs:[],outputs:[]},t=0;return s.inputs.map(o=>{var c=a.vin[t];c.coinbase=o.isCoinbase(),c.chain="VNS",c.network="main"===i.node.network.type?"mainnet":"testnet",c.sequenceNumber=o.sequence,c.address=a.vin[t].address||"",c.value=a.vin[t].valueSat||0,c.mintHeight=a.vin[t].mintHeight||0,c.mintTxid=n.revHex(o.prevout.hash),c.mintIndex=o.prevout.index,c.spentTxid=r,c.spentHeight=s.height,c.confirmations=s.confirmations,c.script=o.script.raw.toString("hex"),e.inputs.push(c),t++}),t=0,s.outputs.map(n=>{var o=a.vout[t];o.chain="VNS",o.network="main"===i.node.network.type?"mainnet":"testnet",o.coinbase=s.isCoinbase(),o.mintTxid=r,o.address=a.vout[t].scriptPubKey.addresses?a.vout[t].scriptPubKey.addresses[0]:"",o.spentTxid=a.vout[t].spentTxid||"",o.spentHeight=a.vout[t].spentHeight||0,o.mintIndex=t,o.mintHeight=s.height,o.value=n.value,o.confirmations=s.confirmations,o.script=n.script.raw.toString("hex"),e.outputs.push(o),t++}),e}return 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:"getBlob",method:"get",path:"/public/blob/:txid/:index",callback:async function(e,t){var i=(e=e.valid()).hash("txid");e=e.uint("index");if(!(i=await this.node.getMeta(i))||!i.tx)return null;if(!(i=i.tx.outputs[e]))return null;if(!(e=i.getReturnData([d.OP_PROPEXCHANGE,d.OP_PROPCREATE]))||!e.oid)return null;if(!(i=await this.node.chain.db.erList.query([["erid",e.oid]]))||!i.list||!i.list[0].erid)return null;let r=i.list[0].source.blob;return"string"==typeof r&&(r=JSON.parse(r)),t.setHeader("content-type",r.type),{data:r}}},{name:"notify",method:"post",path:"/public/notify",callback:async function(e,t){return e.body.sign==(delete e.body.sign,e.body.secret=this.node.config.remotesecret,f.hash256(Buffer.from(JSON.stringify(e.body))).toString("hex"))?(delete e.body.secret,console.log("remote notify:",JSON.stringify(e.body)),{code:0}):{code:-1}}},{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:"block",method:"get",path:"/public/block/:blockHash/coins/:pageSize/:pageNum",callback:async function(e,t){var i=this,p=(s(!i.chain.options.spv,"Cannot get TX in SPV mode."),e.query.blockHash),d=e.params.pageSize?parseInt(e.params.pageSize):100,f=l(e.query.address),m=parseInt(e.params.pageNum)-1||0,g=1;if(p=p||e.params.blockHash){if(!(e=await u(i.node,p,t)))return a(null,t);t=e.txids.length;var y,v=[],b=[],w=(r.isUndefined(m)?y=e.txids:(E=m*d,y=e.txids.slice(E,E+d),g=Math.ceil(t/d)),[]);for(let e of y){let t=await o(i.node,n.revHex(e),!0),r=null;if(t){r=await c(i.node,t,{}),w.push(r);let s=0;t.inputs.map(a=>{a.isCoinbase()||v.push({coinbase:!1,chain:"VNS",network:"main"===i.node.network.type?"mainnet":"testnet",mintTxid:n.revHex(a.prevout.hash),mintIndex:a.prevout.index,spentTxid:e,spentHeight:t.height,confirmations:t.confirmations,sequenceNumber:a.sequence,script:a.script.raw.toString("hex"),address:r.vin[s].addr||"",mintHeight:r.vin[s].mintHeight||0,value:r.vin[s].valueSat||0}),s++}),s=0,t.outputs.map(n=>{b.push({coinbase:t.isCoinbase(),chain:"VNS",network:"main"===i.node.network.type?"mainnet":"testnet",mintTxid:e,address:r.vout[s].scriptPubKey.addresses?r.vout[s].scriptPubKey.addresses[0]:"",spentTxid:r.vout[s].spentTxid||"",spentHeight:r.vout[s].spentHeight||0,mintIndex:s,mintHeight:t.height,value:n.value,confirmations:t.confirmations,script:n.script.raw.toString("hex")}),s++})}}return{txids:y,previous:"",next:m+1<g?`/block/${p}/coins/${d}/`+(m+2):"",inputs:v,outputs:b}}if(f){var k=m*d,x=(m+1)*d,S=[];e=await i.node.getMetaByAddress(f);let t=0;for(const r of e){if(t<k);else{if(t>=x)break;var _=await h(i.node,r);S.push(await c(i.node,_,{}))}t++}var E=Math.ceil(e.length/d);return{txids:y,previous:"",next:`/block/${p}/coins/${d}/`+((m+1)%E+1),pagesTotal:E,inputs:[],outputs:[],txs:S}}throw new Error("Block hash or address expected")}},{name:"getTxSend",method:"get",path:"/public/rawsend/:tx",callback:async function(e,t){return e=(e=e.valid()).str("tx"),e=await this.rpc.execute({method:"tx.raw.send",params:[e]})}},{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){var i=(t=new p([t])).str(0);t=t.bool(1,!1);return e.rpc.execute({method:"tx.raw.get",params:[i,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(19).opcodes,s=i(31),n=i(2).revHex,a=i(80);e.exports=[{name:"prop.byaddress",method:"get",path:"/public/props/address/:address",callback:async function(e,t){return e=e.valid().str("address"),this.node.chain.db.getVpByAddress(e)}},{name:"prop.bidlist",method:"jsonp",path:"/",callback:async function(e,t){e.bidList||(e.bidList=new s);t=new a([t]);var i=Math.max(0,t.uint(0));return 0==i?(t=t.str(1))?e.bidList.query([["pid",t],["size",e.bidList.getSize()],["page",1]]):e.bidList.query([["size",e.bidList.getSize()],["page",1]]):e.bidList.query([["size",10],["page",i]])}},{name:"propBidlist",method:"get",path:"/public/prop/bidlist/:page",callback:async function(e,t){return this.node.bidList||(this.node.bidList=new s),e=e.valid(),(e=Math.max(0,e.uint("page",0)))?this.node.bidList.query([["size",10],["page",e]]):this.node.bidList.query([["size",this.node.bidList.getSize()],["page",1]])}},{name:"propBidOne",method:"get",path:"/public/prop/bidone/:pid",callback:async function(e,t){return this.node.bidList||(this.node.bidList=new s),(e=e.valid().str("pid"))?this.node.bidList.query([["pid",e],["page",1]]):[]}},{name:"prop.get",method:"get",path:"/public/prop/:pid",callback:async function(e,t){var i=[],s=(e=e.valid().str("pid"),await this.node.chain.db.propList.getVp(e));if(s){let e=[s.current.hash,s.current.index];for(;;){var a=await this.node.getMeta(e[0]),o=a.tx;if(!o)break;if(!(o=o.outputs[e[1]]))break;var c=o.getReturnData([r.OP_PROPCREATE,r.OP_PROPEXCHANGE]);if(!c)break;if(c.current={hash:n(e[0]),index:e[1],address:o.getAddress().toString()},c.height=a.height,c.status=s.pst,c.pst=s.pst,c.gold=s.gold,0==i.length&&s.bid&&(c.bid=s.bid),i.push(c),!c.prev)break;e=[c.prev.hash,c.prev.index]}}return i}}]},function(e,t,i){const r=i(80);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(80),s=i(100),n=i(77),a=i(78).errors,o=i(67),c=i(5).ContractStatus,h=i(20),u=i(33);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:"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(80),s=i(784);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.byId",method:"jsonp",path:"/",callback:async function(e,t){return t=new r([t]).str(0),e.chain.db.erList.getEr(t)}},{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).
|
|
@@ -1833,4 +1833,4 @@ const r=i(0);var s=i(78);const n=i(234).openapi;i(221);e.exports=class extends s
|
|
|
1833
1833
|
* workers/index.js - workers for vallnet
|
|
1834
1834
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
1835
1835
|
* https://github.com/bookmansoft/gamegold
|
|
1836
|
-
*/t.Framer=i(233),t.jobs=i(155),t.packets=i(122),t.Parser=i(232),t.WorkerPool=i(230)}]);;exports = module.exports; exports.setRelative = function(relative) { gpath = relative;}
|
|
1836
|
+
*/t.Framer=i(233),t.jobs=i(155),t.packets=i(122),t.Parser=i(232),t.WorkerPool=i(230)}]);;exports = module.exports; exports.setRelative = function(relative) { gpath = relative;};exports = module.exports; exports.setRelative = function(relative) { gpath = relative;}
|